From 110a9cd8db515c4d1a9ac5cd8837291da7c6c5ea Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 3 Jul 2013 04:23:44 +0200 Subject: lib, src: upgrade after v8 api change This is a big commit that touches just about every file in the src/ directory. The V8 API has changed in significant ways. The most important changes are: * Binding functions take a const v8::FunctionCallbackInfo& argument rather than a const v8::Arguments& argument. * Binding functions return void rather than v8::Handle. The return value is returned with the args.GetReturnValue().Set() family of functions. * v8::Persistent no longer derives from v8::Handle and no longer allows you to directly dereference the object that the persistent handle points to. This means that the common pattern of caching oft-used JS values in a persistent handle no longer quite works, you first need to reconstruct a v8::Local from the persistent handle with the Local::New(isolate, persistent) factory method. A handful of (internal) convenience classes and functions have been added to make dealing with the new API a little easier. The most visible one is node::Cached, which wraps a v8::Persistent with some template sugar. It can hold arbitrary types but so far it's exclusively used for v8::Strings (which was by far the most commonly cached handle type.) --- src/cares_wrap.cc | 102 +++-- src/fs_event_wrap.cc | 63 ++-- src/handle_wrap.cc | 52 ++- src/handle_wrap.h | 57 +-- src/node.cc | 502 ++++++++++++------------- src/node.h | 57 +-- src/node_buffer.cc | 160 ++++---- src/node_counters.cc | 57 ++- src/node_crypto.cc | 910 ++++++++++++++++++--------------------------- src/node_crypto.h | 193 +++++----- src/node_dtrace.cc | 146 ++++---- src/node_file.cc | 214 +++++------ src/node_http_parser.cc | 156 ++++---- src/node_internals.h | 206 +++++++++- src/node_object_wrap.h | 75 ++-- src/node_os.cc | 121 +++--- src/node_script.cc | 239 ++++++------ src/node_stat_watcher.cc | 47 +-- src/node_stat_watcher.h | 6 +- src/node_wrap.h | 6 +- src/node_zlib.cc | 62 +-- src/pipe_wrap.cc | 64 ++-- src/pipe_wrap.h | 13 +- src/process_wrap.cc | 49 +-- src/req_wrap.h | 24 +- src/signal_wrap.cc | 28 +- src/smalloc.cc | 68 ++-- src/stream_wrap.cc | 130 +++---- src/stream_wrap.h | 22 +- src/tcp_wrap.cc | 130 +++---- src/tcp_wrap.h | 25 +- src/timer_wrap.cc | 58 +-- src/tls_wrap.cc | 353 ++++++++---------- src/tls_wrap.h | 43 ++- src/tty_wrap.cc | 77 ++-- src/tty_wrap.h | 23 +- src/udp_wrap.cc | 150 ++++---- src/udp_wrap.h | 43 ++- src/v8_typed_array.cc | 874 ------------------------------------------- src/v8_typed_array.h | 35 -- src/v8_typed_array_bswap.h | 201 ---------- 41 files changed, 2238 insertions(+), 3603 deletions(-) delete mode 100644 src/v8_typed_array.cc delete mode 100644 src/v8_typed_array.h delete mode 100644 src/v8_typed_array_bswap.h (limited to 'src') diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index 0b12bce4adf..14adf545233 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -45,9 +45,9 @@ namespace node { namespace cares_wrap { -using v8::Arguments; using v8::Array; using v8::Function; +using v8::FunctionCallbackInfo; using v8::Handle; using v8::HandleScope; using v8::Integer; @@ -69,7 +69,7 @@ struct ares_task_t { }; -static Persistent oncomplete_sym; +static Cached oncomplete_sym; static ares_channel ares_channel; static uv_timer_t ares_timer; static RB_HEAD(ares_task_list, ares_task_t) ares_tasks; @@ -268,7 +268,8 @@ static void SetAresErrno(int errorno) { HandleScope scope(node_isolate); Local key = String::NewSymbol("_errno"); Local value = String::NewSymbol(AresErrnoString(errorno)); - node::process->Set(key, value); + Local process = Local::New(node_isolate, process_p); + process->Set(key, value); } @@ -276,26 +277,18 @@ class QueryWrap { public: QueryWrap() { HandleScope scope(node_isolate); - - object_ = Persistent::New(node_isolate, Object::New()); + persistent().Reset(node_isolate, Object::New()); } virtual ~QueryWrap() { - assert(!object_.IsEmpty()); - - object_->Delete(oncomplete_sym); - - object_.Dispose(node_isolate); - object_.Clear(); - } - - Handle GetObject() { - return object_; + assert(!persistent().IsEmpty()); + object()->Delete(oncomplete_sym); + persistent().Dispose(); } void SetOnComplete(Handle oncomplete) { assert(oncomplete->IsFunction()); - object_->Set(oncomplete_sym, oncomplete); + object()->Set(oncomplete_sym, oncomplete); } // Subclasses should implement the appropriate Send method. @@ -309,6 +302,14 @@ class QueryWrap { return 0; } + inline Persistent& persistent() { + return object_; + } + + inline Local object() { + return Local::New(node_isolate, persistent()); + } + protected: void* GetQueryArg() { return static_cast(this); @@ -343,13 +344,13 @@ class QueryWrap { void CallOnComplete(Local answer) { HandleScope scope(node_isolate); Local argv[2] = { Integer::New(0, node_isolate), answer }; - MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); + MakeCallback(object(), oncomplete_sym, ARRAY_SIZE(argv), argv); } void CallOnComplete(Local answer, Local family) { HandleScope scope(node_isolate); Local argv[3] = { Integer::New(0, node_isolate), answer, family }; - MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); + MakeCallback(object(), oncomplete_sym, ARRAY_SIZE(argv), argv); } void ParseError(int status) { @@ -358,7 +359,7 @@ class QueryWrap { HandleScope scope(node_isolate); Local argv[1] = { Integer::New(-1, node_isolate) }; - MakeCallback(object_, oncomplete_sym, ARRAY_SIZE(argv), argv); + MakeCallback(object(), oncomplete_sym, ARRAY_SIZE(argv), argv); } // Subclasses should implement the appropriate Parse method. @@ -730,7 +731,7 @@ class GetHostByNameWrap: public QueryWrap { template -static Handle Query(const Arguments& args) { +static void Query(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); assert(!args.IsConstructCall()); @@ -742,8 +743,8 @@ static Handle Query(const Arguments& args) { // We must cache the wrap's js object here, because cares might make the // callback from the wrap->Send stack. This will destroy the wrap's internal - // object reference, causing wrap->GetObject() to return undefined. - Local object = Local::New(node_isolate, wrap->GetObject()); + // object reference, causing wrap->object() to return an empty handle. + Local object = wrap->object(); String::Utf8Value name(args[0]); @@ -751,15 +752,14 @@ static Handle Query(const Arguments& args) { if (r) { SetAresErrno(r); delete wrap; - return scope.Close(v8::Null(node_isolate)); } else { - return scope.Close(object); + args.GetReturnValue().Set(object); } } template -static Handle QueryWithFamily(const Arguments& args) { +static void QueryWithFamily(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); assert(!args.IsConstructCall()); @@ -771,8 +771,8 @@ static Handle QueryWithFamily(const Arguments& args) { // We must cache the wrap's js object here, because cares might make the // callback from the wrap->Send stack. This will destroy the wrap's internal - // object reference, causing wrap->GetObject() to return undefined. - Local object = Local::New(node_isolate, wrap->GetObject()); + // object reference, causing wrap->object() to return an empty handle. + Local object = wrap->object(); String::Utf8Value name(args[0]); int family = args[1]->Int32Value(); @@ -781,9 +781,8 @@ static Handle QueryWithFamily(const Arguments& args) { if (r) { SetAresErrno(r); delete wrap; - return scope.Close(v8::Null(node_isolate)); } else { - return scope.Close(object); + args.GetReturnValue().Set(object); } } @@ -877,31 +876,29 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) { uv_freeaddrinfo(res); // Make the callback into JavaScript - MakeCallback(req_wrap->object_, oncomplete_sym, ARRAY_SIZE(argv), argv); + MakeCallback(req_wrap->object(), oncomplete_sym, ARRAY_SIZE(argv), argv); delete req_wrap; } -static Handle IsIP(const Arguments& args) { +static void IsIP(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); String::AsciiValue ip(args[0]); char address_buffer[sizeof(struct in6_addr)]; - if (uv_inet_pton(AF_INET, *ip, &address_buffer).code == UV_OK) { - return scope.Close(v8::Integer::New(4, node_isolate)); - } - - if (uv_inet_pton(AF_INET6, *ip, &address_buffer).code == UV_OK) { - return scope.Close(v8::Integer::New(6, node_isolate)); - } + int rc = 0; + if (uv_inet_pton(AF_INET, *ip, &address_buffer).code == UV_OK) + rc = 4; + else if (uv_inet_pton(AF_INET6, *ip, &address_buffer).code == UV_OK) + rc = 6; - return scope.Close(v8::Integer::New(0, node_isolate)); + args.GetReturnValue().Set(rc); } -static Handle GetAddrInfo(const Arguments& args) { +static void GetAddrInfo(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); String::Utf8Value hostname(args[0]); @@ -937,14 +934,13 @@ static Handle GetAddrInfo(const Arguments& args) { if (r) { SetErrno(uv_last_error(uv_default_loop())); delete req_wrap; - return scope.Close(v8::Null(node_isolate)); } else { - return scope.Close(req_wrap->object_); + args.GetReturnValue().Set(req_wrap->persistent()); } } -static Handle GetServers(const Arguments& args) { +static void GetServers(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local server_array = Array::New(); @@ -969,11 +965,11 @@ static Handle GetServers(const Arguments& args) { ares_free_data(servers); - return scope.Close(server_array); + args.GetReturnValue().Set(server_array); } -static Handle SetServers(const Arguments& args) { +static void SetServers(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); assert(args[0]->IsArray()); @@ -984,7 +980,7 @@ static Handle SetServers(const Arguments& args) { if (len == 0) { int rv = ares_set_servers(ares_channel, NULL); - return scope.Close(Integer::New(rv)); + return args.GetReturnValue().Set(rv); } ares_addr_node* servers = new ares_addr_node[len]; @@ -1039,16 +1035,14 @@ static Handle SetServers(const Arguments& args) { delete[] servers; - return scope.Close(Integer::New(r)); + args.GetReturnValue().Set(r); } -static Handle StrError(const Arguments& args) { - HandleScope scope; - - int r = args[0]->Int32Value(); - - return scope.Close(String::New(ares_strerror(r))); +static void StrError(const FunctionCallbackInfo& args) { + HandleScope scope(node_isolate); + const char* errmsg = ares_strerror(args[0]->Int32Value()); + args.GetReturnValue().Set(String::New(errmsg)); } @@ -1100,7 +1094,7 @@ static void Initialize(Handle target) { target->Set(String::NewSymbol("AF_UNSPEC"), Integer::New(AF_UNSPEC, node_isolate)); - oncomplete_sym = NODE_PSYMBOL("oncomplete"); + oncomplete_sym = String::New("oncomplete"); } diff --git a/src/fs_event_wrap.cc b/src/fs_event_wrap.cc index f767db037c3..bcac8dbab81 100644 --- a/src/fs_event_wrap.cc +++ b/src/fs_event_wrap.cc @@ -24,20 +24,28 @@ #include -using namespace v8; - namespace node { -static Persistent change_sym; -static Persistent onchange_sym; -static Persistent rename_sym; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::Handle; +using v8::HandleScope; +using v8::Integer; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + +static Cached change_sym; +static Cached onchange_sym; +static Cached rename_sym; class FSEventWrap: public HandleWrap { public: static void Initialize(Handle target); - static Handle New(const Arguments& args); - static Handle Start(const Arguments& args); - static Handle Close(const Arguments& args); + static void New(const FunctionCallbackInfo& args); + static void Start(const FunctionCallbackInfo& args); + static void Close(const FunctionCallbackInfo& args); private: FSEventWrap(Handle object); @@ -74,33 +82,28 @@ void FSEventWrap::Initialize(Handle target) { NODE_SET_PROTOTYPE_METHOD(t, "start", Start); NODE_SET_PROTOTYPE_METHOD(t, "close", Close); - target->Set(String::NewSymbol("FSEvent"), - Persistent::New(node_isolate, - t)->GetFunction()); + target->Set(String::New("FSEvent"), t->GetFunction()); - change_sym = NODE_PSYMBOL("change"); - onchange_sym = NODE_PSYMBOL("onchange"); - rename_sym = NODE_PSYMBOL("rename"); + change_sym = String::New("change"); + onchange_sym = String::New("onchange"); + rename_sym = String::New("rename"); } -Handle FSEventWrap::New(const Arguments& args) { +void FSEventWrap::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - assert(args.IsConstructCall()); new FSEventWrap(args.This()); - - return scope.Close(args.This()); } -Handle FSEventWrap::Start(const Arguments& args) { +void FSEventWrap::Start(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); UNWRAP(FSEventWrap) if (args.Length() < 1 || !args[0]->IsString()) { - return ThrowException(Exception::TypeError(String::New("Bad arguments"))); + return ThrowTypeError("Bad arguments"); } String::Utf8Value path(args[0]); @@ -116,7 +119,7 @@ Handle FSEventWrap::Start(const Arguments& args) { SetErrno(uv_last_error(uv_default_loop())); } - return scope.Close(Integer::New(r, node_isolate)); + args.GetReturnValue().Set(r); } @@ -127,7 +130,7 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, FSEventWrap* wrap = static_cast(handle->data); - assert(wrap->object_.IsEmpty() == false); + assert(wrap->persistent().IsEmpty() == false); // We're in a bind here. libuv can set both UV_RENAME and UV_CHANGE but // the Node API only lets us pass a single event to JS land. @@ -158,14 +161,18 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, Handle argv[3] = { Integer::New(status, node_isolate), eventStr, - filename ? String::New(filename) : v8::Null(node_isolate) + Null(node_isolate) }; - MakeCallback(wrap->object_, onchange_sym, ARRAY_SIZE(argv), argv); + if (filename != NULL) { + argv[2] = String::New(filename); + } + + MakeCallback(wrap->object(), onchange_sym, ARRAY_SIZE(argv), argv); } -Handle FSEventWrap::Close(const Arguments& args) { +void FSEventWrap::Close(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); // Unwrap manually here. The UNWRAP() macro asserts that wrap != NULL. @@ -176,12 +183,10 @@ Handle FSEventWrap::Close(const Arguments& args) { void* ptr = args.This()->GetAlignedPointerFromInternalField(0); FSEventWrap* wrap = static_cast(ptr); - if (wrap == NULL || wrap->initialized_ == false) { - return Undefined(node_isolate); - } + if (wrap == NULL || wrap->initialized_ == false) return; wrap->initialized_ = false; - return HandleWrap::Close(args); + HandleWrap::Close(args); } diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc index cf3768ace4c..6860231ca94 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -25,20 +25,17 @@ namespace node { -using v8::Arguments; -using v8::Function; +using v8::FunctionCallbackInfo; using v8::Handle; using v8::HandleScope; +using v8::Local; using v8::Object; -using v8::Persistent; using v8::String; -using v8::Undefined; using v8::Value; - // defined in node.cc extern QUEUE handle_wrap_queue; -static Persistent close_sym; +static Cached close_sym; void HandleWrap::Initialize(Handle target) { @@ -46,7 +43,7 @@ void HandleWrap::Initialize(Handle target) { } -Handle HandleWrap::Ref(const Arguments& args) { +void HandleWrap::Ref(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); UNWRAP_NO_ABORT(HandleWrap) @@ -55,12 +52,10 @@ Handle HandleWrap::Ref(const Arguments& args) { uv_ref(wrap->handle__); wrap->flags_ &= ~kUnref; } - - return v8::Undefined(node_isolate); } -Handle HandleWrap::Unref(const Arguments& args) { +void HandleWrap::Unref(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); UNWRAP_NO_ABORT(HandleWrap) @@ -69,33 +64,27 @@ Handle HandleWrap::Unref(const Arguments& args) { uv_unref(wrap->handle__); wrap->flags_ |= kUnref; } - - return v8::Undefined(node_isolate); } -Handle HandleWrap::Close(const Arguments& args) { +void HandleWrap::Close(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); HandleWrap *wrap = static_cast( args.This()->GetAlignedPointerFromInternalField(0)); // guard against uninitialized handle or double close - if (wrap == NULL || wrap->handle__ == NULL) { - return Undefined(node_isolate); - } + if (wrap == NULL || wrap->handle__ == NULL) return; - assert(!wrap->object_.IsEmpty()); + assert(!wrap->persistent().IsEmpty()); uv_close(wrap->handle__, OnClose); wrap->handle__ = NULL; if (args[0]->IsFunction()) { - if (close_sym.IsEmpty() == true) close_sym = NODE_PSYMBOL("close"); - wrap->object_->Set(close_sym, args[0]); + if (close_sym.IsEmpty() == true) close_sym = String::New("close"); + wrap->object()->Set(close_sym, args[0]); wrap->flags_ |= kCloseCallback; } - - return Undefined(node_isolate); } @@ -105,16 +94,16 @@ HandleWrap::HandleWrap(Handle object, uv_handle_t* h) { handle__->data = this; HandleScope scope(node_isolate); - assert(object_.IsEmpty()); + assert(persistent().IsEmpty()); assert(object->InternalFieldCount() > 0); - object_ = v8::Persistent::New(node_isolate, object); - object_->SetAlignedPointerInInternalField(0, this); + persistent().Reset(node_isolate, object); + object->SetAlignedPointerInInternalField(0, this); QUEUE_INSERT_TAIL(&handle_wrap_queue, &handle_wrap_queue_); } HandleWrap::~HandleWrap() { - assert(object_.IsEmpty()); + assert(persistent().IsEmpty()); QUEUE_REMOVE(&handle_wrap_queue_); } @@ -123,20 +112,21 @@ void HandleWrap::OnClose(uv_handle_t* handle) { HandleWrap* wrap = static_cast(handle->data); // The wrap object should still be there. - assert(wrap->object_.IsEmpty() == false); + assert(wrap->persistent().IsEmpty() == false); // But the handle pointer should be gone. assert(wrap->handle__ == NULL); + HandleScope scope(node_isolate); + Local object = wrap->object(); + if (wrap->flags_ & kCloseCallback) { assert(close_sym.IsEmpty() == false); - MakeCallback(wrap->object_, close_sym, 0, NULL); + MakeCallback(object, close_sym, 0, NULL); } - wrap->object_->SetAlignedPointerInInternalField(0, NULL); - wrap->object_.Dispose(node_isolate); - wrap->object_.Clear(); - + object->SetAlignedPointerInInternalField(0, NULL); + wrap->persistent().Dispose(); delete wrap; } diff --git a/src/handle_wrap.h b/src/handle_wrap.h index 3a42148a626..d8194b97b0a 100644 --- a/src/handle_wrap.h +++ b/src/handle_wrap.h @@ -53,31 +53,38 @@ namespace node { args.This()->GetAlignedPointerFromInternalField(0)); class HandleWrap { - public: - static void Initialize(v8::Handle target); - static v8::Handle Close(const v8::Arguments& args); - static v8::Handle Ref(const v8::Arguments& args); - static v8::Handle Unref(const v8::Arguments& args); - - inline uv_handle_t* GetHandle() { return handle__; }; - - protected: - HandleWrap(v8::Handle object, uv_handle_t* handle); - virtual ~HandleWrap(); - - v8::Persistent object_; - - private: - friend v8::Handle GetActiveHandles(const v8::Arguments&); - static void OnClose(uv_handle_t* handle); - QUEUE handle_wrap_queue_; - // Using double underscore due to handle_ member in tcp_wrap. Probably - // tcp_wrap should rename it's member to 'handle'. - uv_handle_t* handle__; - unsigned int flags_; - - static const unsigned int kUnref = 1; - static const unsigned int kCloseCallback = 2; +public: + static void Initialize(v8::Handle target); + static void Close(const v8::FunctionCallbackInfo& args); + static void Ref(const v8::FunctionCallbackInfo& args); + static void Unref(const v8::FunctionCallbackInfo& args); + + inline uv_handle_t* GetHandle() { return handle__; }; + +protected: + HandleWrap(v8::Handle object, uv_handle_t* handle); + virtual ~HandleWrap(); + + inline v8::Local object() { + return v8::Local::New(node_isolate, persistent()); + } + + inline v8::Persistent& persistent() { + return object_; + } + +private: + friend void GetActiveHandles(const v8::FunctionCallbackInfo&); + static void OnClose(uv_handle_t* handle); + v8::Persistent object_; + QUEUE handle_wrap_queue_; + // Using double underscore due to handle_ member in tcp_wrap. Probably + // tcp_wrap should rename it's member to 'handle'. + uv_handle_t* handle__; + unsigned int flags_; + + static const unsigned int kUnref = 1; + static const unsigned int kCloseCallback = 2; }; diff --git a/src/node.cc b/src/node.cc index a9c11e0bd1d..82be2f9b2bf 100644 --- a/src/node.cc +++ b/src/node.cc @@ -80,9 +80,6 @@ typedef int mode_t; #include "node_provider.h" #endif #include "node_script.h" -#include "v8_typed_array.h" - -using namespace v8; # ifdef __APPLE__ # include @@ -93,41 +90,68 @@ extern char **environ; namespace node { +using v8::Array; +using v8::Boolean; +using v8::Context; +using v8::Exception; +using v8::Function; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::HandleScope; +using v8::HeapStatistics; +using v8::Integer; +using v8::Isolate; +using v8::Locker; +using v8::Message; +using v8::Number; +using v8::Object; +using v8::ObjectTemplate; +using v8::Persistent; +using v8::PropertyCallbackInfo; +using v8::ResourceConstraints; +using v8::SetResourceConstraints; +using v8::ThrowException; +using v8::TryCatch; +using v8::Uint32; +using v8::V8; +using v8::Value; +using v8::kExternalUnsignedIntArray; + QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue }; QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue }; // declared in req_wrap.h -Persistent process_symbol; -Persistent domain_symbol; +Cached process_symbol; +Cached domain_symbol; // declared in node_internals.h -Persistent process; +Persistent process_p; -static Persistent process_tickFromSpinner; static Persistent process_tickCallback; +static Persistent binding_cache; +static Persistent module_load_list; -static Persistent exports_symbol; +static Cached exports_symbol; -static Persistent errno_symbol; -static Persistent syscall_symbol; -static Persistent errpath_symbol; -static Persistent code_symbol; +static Cached errno_symbol; +static Cached syscall_symbol; +static Cached errpath_symbol; +static Cached code_symbol; -static Persistent rss_symbol; -static Persistent heap_total_symbol; -static Persistent heap_used_symbol; +static Cached rss_symbol; +static Cached heap_total_symbol; +static Cached heap_used_symbol; -static Persistent fatal_exception_symbol; +static Cached fatal_exception_symbol; -static Persistent enter_symbol; -static Persistent exit_symbol; -static Persistent disposed_symbol; +static Cached enter_symbol; +static Cached exit_symbol; +static Cached disposed_symbol; // Essential for node_wrap.h Persistent pipeConstructorTmpl; -Persistent ttyConstructorTmpl; Persistent tcpConstructorTmpl; -Persistent udpConstructorTmpl; +Persistent ttyConstructorTmpl; static bool print_eval = false; static bool force_repl = false; @@ -149,7 +173,7 @@ static uv_idle_t tick_spinner; static uv_check_t check_immediate_watcher; static uv_idle_t idle_immediate_dummy; static bool need_immediate_cb; -static Persistent immediate_callback_sym; +static Cached immediate_callback_sym; // for quick ref to tickCallback values static struct { @@ -187,10 +211,10 @@ static void CheckImmediate(uv_check_t* handle, int status) { HandleScope scope(node_isolate); if (immediate_callback_sym.IsEmpty()) { - immediate_callback_sym = NODE_PSYMBOL("_immediateCallback"); + immediate_callback_sym = String::New("_immediateCallback"); } - MakeCallback(process, immediate_callback_sym, 0, NULL); + MakeCallback(process_p, immediate_callback_sym, 0, NULL); } @@ -695,10 +719,10 @@ Local ErrnoException(int errorno, Local cons2 = String::Concat(cons1, message); if (syscall_symbol.IsEmpty()) { - syscall_symbol = NODE_PSYMBOL("syscall"); - errno_symbol = NODE_PSYMBOL("errno"); - errpath_symbol = NODE_PSYMBOL("path"); - code_symbol = NODE_PSYMBOL("code"); + syscall_symbol = String::New("syscall"); + errno_symbol = String::New("errno"); + errpath_symbol = String::New("path"); + code_symbol = String::New("code"); } if (path) { @@ -742,10 +766,10 @@ Local UVException(int errorno, const char *msg, const char *path) { if (syscall_symbol.IsEmpty()) { - syscall_symbol = NODE_PSYMBOL("syscall"); - errno_symbol = NODE_PSYMBOL("errno"); - errpath_symbol = NODE_PSYMBOL("path"); - code_symbol = NODE_PSYMBOL("code"); + syscall_symbol = String::New("syscall"); + errno_symbol = String::New("errno"); + errpath_symbol = String::New("path"); + code_symbol = String::New("code"); } if (!msg || !msg[0]) @@ -828,10 +852,10 @@ Local WinapiErrnoException(int errorno, Local message = String::NewSymbol(msg); if (syscall_symbol.IsEmpty()) { - syscall_symbol = NODE_PSYMBOL("syscall"); - errno_symbol = NODE_PSYMBOL("errno"); - errpath_symbol = NODE_PSYMBOL("path"); - code_symbol = NODE_PSYMBOL("code"); + syscall_symbol = String::New("syscall"); + errno_symbol = String::New("errno"); + errpath_symbol = String::New("path"); + code_symbol = String::New("code"); } if (path) { @@ -853,22 +877,11 @@ Local WinapiErrnoException(int errorno, #endif -Handle FromConstructorTemplate(Persistent t, - const Arguments& args) { - HandleScope scope(node_isolate); - Local argv[32]; - unsigned argc = args.Length(); - if (argc > ARRAY_SIZE(argv)) argc = ARRAY_SIZE(argv); - for (unsigned i = 0; i < argc; ++i) argv[i] = args[i]; - return scope.Close(t->GetFunction()->NewInstance(argc, argv)); -} - - -Handle SetupDomainUse(const Arguments& args) { +void SetupDomainUse(const FunctionCallbackInfo& args) { + if (using_domains) return; HandleScope scope(node_isolate); - if (using_domains) - return Undefined(node_isolate); using_domains = true; + Local process = Local::New(node_isolate, process_p); Local tdc_v = process->Get(String::New("_tickDomainCallback")); Local ndt_v = process->Get(String::New("_nextDomainTick")); if (!tdc_v->IsFunction()) { @@ -883,9 +896,7 @@ Handle SetupDomainUse(const Arguments& args) { Local ndt = ndt_v.As(); process->Set(String::New("_tickCallback"), tdc); process->Set(String::New("nextTick"), ndt); - process_tickCallback.Dispose(node_isolate); // May be set by MakeCallback(). - process_tickCallback = Persistent::New(node_isolate, tdc); - return Undefined(node_isolate); + process_tickCallback.Reset(node_isolate, tdc); } @@ -898,9 +909,9 @@ MakeDomainCallback(const Handle object, // lazy load domain specific symbols if (enter_symbol.IsEmpty()) { - enter_symbol = NODE_PSYMBOL("enter"); - exit_symbol = NODE_PSYMBOL("exit"); - disposed_symbol = NODE_PSYMBOL("_disposed"); + enter_symbol = String::New("enter"); + exit_symbol = String::New("exit"); + disposed_symbol = String::New("_disposed"); } Local domain_v = object->Get(domain_symbol); @@ -950,7 +961,9 @@ MakeDomainCallback(const Handle object, } // process nextTicks after call - process_tickCallback->Call(process, 0, NULL); + Local process = Local::New(node_isolate, process_p); + Local fn = Local::New(node_isolate, process_tickCallback); + fn->Call(process, 0, NULL); if (try_catch.HasCaught()) { return Undefined(node_isolate); @@ -966,6 +979,7 @@ MakeCallback(const Handle object, int argc, Handle argv[]) { // TODO Hook for long stack traces to be made here. + Local process = Local::New(node_isolate, process_p); // lazy load no domain next tick callbacks if (process_tickCallback.IsEmpty()) { @@ -974,8 +988,7 @@ MakeCallback(const Handle object, fprintf(stderr, "process._tickCallback assigned to non-function\n"); abort(); } - Local cb = cb_v.As(); - process_tickCallback = Persistent::New(node_isolate, cb); + process_tickCallback.Reset(node_isolate, cb_v.As()); } TryCatch try_catch; @@ -993,7 +1006,8 @@ MakeCallback(const Handle object, } // process nextTicks after call - process_tickCallback->Call(process, 0, NULL); + Local fn = Local::New(node_isolate, process_tickCallback); + fn->Call(process, 0, NULL); if (try_catch.HasCaught()) { return Undefined(node_isolate); @@ -1034,10 +1048,11 @@ MakeCallback(const Handle object, void SetErrno(uv_err_t err) { HandleScope scope(node_isolate); + Local process = Local::New(node_isolate, process_p); - static Persistent errno_symbol; + static Cached errno_symbol; if (errno_symbol.IsEmpty()) { - errno_symbol = NODE_PSYMBOL("_errno"); + errno_symbol = String::New("_errno"); } if (err.code == UV_UNKNOWN) { @@ -1253,7 +1268,7 @@ Local ExecuteString(Handle source, Handle filename) { } -static Handle GetActiveRequests(const Arguments& args) { +static void GetActiveRequests(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local ary = Array::New(); @@ -1262,17 +1277,17 @@ static Handle GetActiveRequests(const Arguments& args) { QUEUE_FOREACH(q, &req_wrap_queue) { ReqWrap* w = container_of(q, ReqWrap, req_wrap_queue_); - if (w->object_.IsEmpty()) continue; - ary->Set(i++, w->object_); + if (w->persistent().IsEmpty()) continue; + ary->Set(i++, w->object()); } - return scope.Close(ary); + args.GetReturnValue().Set(ary); } // Non-static, friend of HandleWrap. Could have been a HandleWrap method but // implemented here for consistency with GetActiveRequests(). -Handle GetActiveHandles(const Arguments& args) { +void GetActiveHandles(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local ary = Array::New(); @@ -1283,27 +1298,27 @@ Handle GetActiveHandles(const Arguments& args) { QUEUE_FOREACH(q, &handle_wrap_queue) { HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_); - if (w->object_.IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue; - Local obj = w->object_->Get(owner_sym); - if (obj->IsUndefined()) obj = *w->object_; - ary->Set(i++, obj); + if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue; + Local object = w->object(); + Local owner = object->Get(owner_sym); + if (owner->IsUndefined()) owner = object; + ary->Set(i++, owner); } - return scope.Close(ary); + args.GetReturnValue().Set(ary); } -static Handle Abort(const Arguments& args) { +static void Abort(const FunctionCallbackInfo& args) { abort(); - return Undefined(node_isolate); } -static Handle Chdir(const Arguments& args) { +static void Chdir(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() != 1 || !args[0]->IsString()) { - return ThrowException(Exception::Error(String::New("Bad argument."))); + return ThrowError("Bad argument."); // FIXME(bnoordhuis) ThrowTypeError? } String::Utf8Value path(args[0]); @@ -1311,14 +1326,12 @@ static Handle Chdir(const Arguments& args) { uv_err_t r = uv_chdir(*path); if (r.code != UV_OK) { - return ThrowException(UVException(r.code, "uv_chdir")); + return ThrowUVException(r.code, "uv_chdir"); } - - return Undefined(node_isolate); } -static Handle Cwd(const Arguments& args) { +static void Cwd(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); #ifdef _WIN32 /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ @@ -1329,27 +1342,26 @@ static Handle Cwd(const Arguments& args) { uv_err_t r = uv_cwd(buf, ARRAY_SIZE(buf) - 1); if (r.code != UV_OK) { - return ThrowException(UVException(r.code, "uv_cwd")); + return ThrowUVException(r.code, "uv_cwd"); } buf[ARRAY_SIZE(buf) - 1] = '\0'; Local cwd = String::New(buf); - return scope.Close(cwd); + args.GetReturnValue().Set(cwd); } -static Handle Umask(const Arguments& args) { +static void Umask(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - unsigned int old; + uint32_t old; if (args.Length() < 1 || args[0]->IsUndefined()) { old = umask(0); - umask((mode_t)old); + umask(static_cast(old)); } else if(!args[0]->IsInt32() && !args[0]->IsString()) { - return ThrowException(Exception::TypeError( - String::New("argument must be an integer or octal string."))); + return ThrowTypeError("argument must be an integer or octal string."); } else { int oct; @@ -1363,8 +1375,7 @@ static Handle Umask(const Arguments& args) { for (int i = 0; i < str.length(); i++) { char c = (*str)[i]; if (c > '7' || c < '0') { - return ThrowException(Exception::TypeError( - String::New("invalid octal string"))); + return ThrowTypeError("invalid octal string"); } oct *= 8; oct += c - '0'; @@ -1373,7 +1384,7 @@ static Handle Umask(const Arguments& args) { old = umask(static_cast(oct)); } - return scope.Close(Uint32::New(old, node_isolate)); + args.GetReturnValue().Set(old); } @@ -1479,21 +1490,17 @@ static gid_t gid_by_name(Handle value) { } -static Handle GetUid(const Arguments& args) { - HandleScope scope(node_isolate); - int uid = getuid(); - return scope.Close(Integer::New(uid, node_isolate)); +static void GetUid(const FunctionCallbackInfo& args) { + args.GetReturnValue().Set(getuid()); } -static Handle GetGid(const Arguments& args) { - HandleScope scope(node_isolate); - int gid = getgid(); - return scope.Close(Integer::New(gid, node_isolate)); +static void GetGid(const FunctionCallbackInfo& args) { + args.GetReturnValue().Set(getgid()); } -static Handle SetGid(const Arguments& args) { +static void SetGid(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (!args[0]->IsUint32() && !args[0]->IsString()) { @@ -1507,14 +1514,12 @@ static Handle SetGid(const Arguments& args) { } if (setgid(gid)) { - return ThrowException(ErrnoException(errno, "setgid")); + return ThrowErrnoException(errno, "setgid"); } - - return Undefined(node_isolate); } -static Handle SetUid(const Arguments& args) { +static void SetUid(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (!args[0]->IsUint32() && !args[0]->IsString()) { @@ -1528,20 +1533,18 @@ static Handle SetUid(const Arguments& args) { } if (setuid(uid)) { - return ThrowException(ErrnoException(errno, "setuid")); + return ThrowErrnoException(errno, "setuid"); } - - return Undefined(node_isolate); } -static Handle GetGroups(const Arguments& args) { +static void GetGroups(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int ngroups = getgroups(0, NULL); if (ngroups == -1) { - return ThrowException(ErrnoException(errno, "getgroups")); + return ThrowErrnoException(errno, "getgroups"); } gid_t* groups = new gid_t[ngroups]; @@ -1550,7 +1553,7 @@ static Handle GetGroups(const Arguments& args) { if (ngroups == -1) { delete[] groups; - return ThrowException(ErrnoException(errno, "getgroups")); + return ThrowErrnoException(errno, "getgroups"); } Local groups_list = Array::New(ngroups); @@ -1568,11 +1571,11 @@ static Handle GetGroups(const Arguments& args) { groups_list->Set(ngroups, Integer::New(egid, node_isolate)); } - return scope.Close(groups_list); + args.GetReturnValue().Set(groups_list); } -static Handle SetGroups(const Arguments& args) { +static void SetGroups(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (!args[0]->IsArray()) { @@ -1598,14 +1601,12 @@ static Handle SetGroups(const Arguments& args) { delete[] groups; if (rc == -1) { - return ThrowException(ErrnoException(errno, "setgroups")); + return ThrowErrnoException(errno, "setgroups"); } - - return Undefined(node_isolate); } -static Handle InitGroups(const Arguments& args) { +static void InitGroups(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (!args[0]->IsUint32() && !args[0]->IsString()) { @@ -1647,37 +1648,28 @@ static Handle InitGroups(const Arguments& args) { } if (rc) { - return ThrowException(ErrnoException(errno, "initgroups")); + return ThrowErrnoException(errno, "initgroups"); } - - return Undefined(node_isolate); } #endif // __POSIX__ && !defined(__ANDROID__) -v8::Handle Exit(const v8::Arguments& args) { +void Exit(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); exit(args[0]->IntegerValue()); - return Undefined(node_isolate); } -static Handle Uptime(const Arguments& args) { +static void Uptime(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); double uptime; - - uv_err_t err = uv_uptime(&uptime); - - if (err.code != UV_OK) { - return Undefined(node_isolate); - } - - return scope.Close(Number::New(uptime - prog_start_time)); + if (uv_uptime(&uptime).code != UV_OK) return; + args.GetReturnValue().Set(uptime - prog_start_time); } -v8::Handle MemoryUsage(const v8::Arguments& args) { +void MemoryUsage(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); size_t rss; @@ -1685,15 +1677,15 @@ v8::Handle MemoryUsage(const v8::Arguments& args) { uv_err_t err = uv_resident_set_memory(&rss); if (err.code != UV_OK) { - return ThrowException(UVException(err.code, "uv_resident_set_memory")); + return ThrowUVException(err.code, "uv_resident_set_memory"); } Local info = Object::New(); if (rss_symbol.IsEmpty()) { - rss_symbol = NODE_PSYMBOL("rss"); - heap_total_symbol = NODE_PSYMBOL("heapTotal"); - heap_used_symbol = NODE_PSYMBOL("heapUsed"); + rss_symbol = String::New("rss"); + heap_total_symbol = String::New("heapTotal"); + heap_used_symbol = String::New("heapUsed"); } info->Set(rss_symbol, Number::New(rss)); @@ -1708,15 +1700,15 @@ v8::Handle MemoryUsage(const v8::Arguments& args) { Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate)); - return scope.Close(info); + args.GetReturnValue().Set(info); } -Handle Kill(const Arguments& args) { +void Kill(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() != 2) { - return ThrowException(Exception::Error(String::New("Bad argument."))); + return ThrowError("Bad argument."); } int pid = args[0]->IntegerValue(); @@ -1725,10 +1717,8 @@ Handle Kill(const Arguments& args) { if (err.code != UV_OK) { SetErrno(err); - return scope.Close(Integer::New(-1, node_isolate)); + args.GetReturnValue().Set(-1); } - - return Undefined(node_isolate); } // used in Hrtime() below @@ -1739,7 +1729,7 @@ Handle Kill(const Arguments& args) { // so this function instead returns an Array with 2 entries representing seconds // and nanoseconds, to avoid any integer overflow possibility. // Pass in an Array from a previous hrtime() call to instead get a time diff. -Handle Hrtime(const v8::Arguments& args) { +void Hrtime(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); uint64_t t = uv_hrtime(); @@ -1747,9 +1737,7 @@ Handle Hrtime(const v8::Arguments& args) { if (args.Length() > 0) { // return a time diff tuple if (!args[0]->IsArray()) { - Local exception = Exception::TypeError( - String::New("process.hrtime() only accepts an Array tuple.")); - return ThrowException(exception); + return ThrowTypeError("process.hrtime() only accepts an Array tuple."); } Local inArray = Local::Cast(args[0]); uint64_t seconds = inArray->Get(0)->Uint32Value(); @@ -1760,8 +1748,7 @@ Handle Hrtime(const v8::Arguments& args) { Local tuple = Array::New(2); tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate)); tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate)); - - return scope.Close(tuple); + args.GetReturnValue().Set(tuple); } @@ -1769,23 +1756,21 @@ typedef void (UV_DYNAMIC* extInit)(Handle exports); // DLOpen is process.dlopen(module, filename). // Used to load 'module.node' dynamically shared objects. -Handle DLOpen(const v8::Arguments& args) { +void DLOpen(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); char symbol[1024], *base, *pos; uv_lib_t lib; int r; if (args.Length() < 2) { - Local exception = Exception::Error( - String::New("process.dlopen takes exactly 2 arguments.")); - return ThrowException(exception); + return ThrowError("process.dlopen takes exactly 2 arguments."); } Local module = args[0]->ToObject(); // Cast String::Utf8Value filename(args[1]); // Cast if (exports_symbol.IsEmpty()) { - exports_symbol = NODE_PSYMBOL("exports"); + exports_symbol = String::New("exports"); } Local exports = module->Get(exports_symbol)->ToObject(); @@ -1795,7 +1780,8 @@ Handle DLOpen(const v8::Arguments& args) { // Windows needs to add the filename into the error message errmsg = String::Concat(errmsg, args[1]->ToString()); #endif - return ThrowException(Exception::Error(errmsg)); + ThrowException(Exception::Error(errmsg)); + return; } String::Utf8Value path(args[1]); @@ -1826,9 +1812,7 @@ Handle DLOpen(const v8::Arguments& args) { /* Add the `_module` suffix to the extension name. */ r = snprintf(symbol, sizeof symbol, "%s_module", base); if (r <= 0 || static_cast(r) >= sizeof symbol) { - Local exception = - Exception::Error(String::New("Out of memory.")); - return ThrowException(exception); + return ThrowError("Out of memory."); } /* Replace dashes with underscores. When loading foo-bar.node, @@ -1859,7 +1843,6 @@ Handle DLOpen(const v8::Arguments& args) { // Tell coverity that 'handle' should not be freed when we return. // coverity[leaked_storage] - return Undefined(node_isolate); } @@ -1884,8 +1867,9 @@ void FatalException(Handle error, Handle message) { HandleScope scope(node_isolate); if (fatal_exception_symbol.IsEmpty()) - fatal_exception_symbol = NODE_PSYMBOL("_fatalException"); + fatal_exception_symbol = String::New("_fatalException"); + Local process = Local::New(node_isolate, process_p); Local fatal_v = process->Get(fatal_exception_symbol); if (!fatal_v->IsFunction()) { @@ -1933,71 +1917,68 @@ void OnMessage(Handle message, Handle error) { } -Persistent binding_cache; -Persistent module_load_list; - -static Handle Binding(const Arguments& args) { +static void Binding(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local module = args[0]->ToString(); String::Utf8Value module_v(module); node_module_struct* modp; - if (binding_cache.IsEmpty()) { - binding_cache = Persistent::New(node_isolate, Object::New()); - } - + Local cache = Local::New(node_isolate, binding_cache); Local exports; - if (binding_cache->Has(module)) { - exports = binding_cache->Get(module)->ToObject(); - return scope.Close(exports); + if (cache->Has(module)) { + exports = cache->Get(module)->ToObject(); + args.GetReturnValue().Set(exports); + return; } // Append a string to process.moduleLoadList char buf[1024]; snprintf(buf, 1024, "Binding %s", *module_v); - uint32_t l = module_load_list->Length(); - module_load_list->Set(l, String::New(buf)); + + Local modules = Local::New(node_isolate, module_load_list); + uint32_t l = modules->Length(); + modules->Set(l, String::New(buf)); if ((modp = get_builtin_module(*module_v)) != NULL) { exports = Object::New(); // Internal bindings don't have a "module" object, // only exports. modp->register_func(exports, Undefined(node_isolate)); - binding_cache->Set(module, exports); + cache->Set(module, exports); } else if (!strcmp(*module_v, "constants")) { exports = Object::New(); DefineConstants(exports); - binding_cache->Set(module, exports); + cache->Set(module, exports); } else if (!strcmp(*module_v, "natives")) { exports = Object::New(); DefineJavaScript(exports); - binding_cache->Set(module, exports); + cache->Set(module, exports); } else { - return ThrowException(Exception::Error(String::New("No such module"))); + return ThrowError("No such module"); } - return scope.Close(exports); + args.GetReturnValue().Set(exports); } -static Handle ProcessTitleGetter(Local property, - const AccessorInfo& info) { +static void ProcessTitleGetter(Local property, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); char buffer[512]; uv_get_process_title(buffer, sizeof(buffer)); - return scope.Close(String::New(buffer)); + info.GetReturnValue().Set(String::New(buffer)); } static void ProcessTitleSetter(Local property, Local value, - const AccessorInfo& info) { + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); String::Utf8Value title(value); // TODO: protect with a lock @@ -2005,14 +1986,14 @@ static void ProcessTitleSetter(Local property, } -static Handle EnvGetter(Local property, - const AccessorInfo& info) { +static void EnvGetter(Local property, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); #ifdef __POSIX__ String::Utf8Value key(property); const char* val = getenv(*key); if (val) { - return scope.Close(String::New(val)); + return info.GetReturnValue().Set(String::New(val)); } #else // _WIN32 String::Value key(property); @@ -2025,17 +2006,19 @@ static Handle EnvGetter(Local property, // not found. if ((result > 0 || GetLastError() == ERROR_SUCCESS) && result < ARRAY_SIZE(buffer)) { - return scope.Close(String::New(reinterpret_cast(buffer), result)); + return info.GetReturnValue().Set( + String::New(reinterpret_cast(buffer), result)); } #endif // Not found. Fetch from prototype. - return scope.Close(info.Data().As()->Get(property)); + info.GetReturnValue().Set( + info.Data().As()->Get(property)); } -static Handle EnvSetter(Local property, - Local value, - const AccessorInfo& info) { +static void EnvSetter(Local property, + Local value, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); #ifdef __POSIX__ String::Utf8Value key(property); @@ -2051,63 +2034,58 @@ static Handle EnvSetter(Local property, } #endif // Whether it worked or not, always return rval. - return scope.Close(value); + info.GetReturnValue().Set(value); } -static Handle EnvQuery(Local property, - const AccessorInfo& info) { +static void EnvQuery(Local property, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); + int32_t rc = -1; // Not found unless proven otherwise. #ifdef __POSIX__ String::Utf8Value key(property); - if (getenv(*key)) { - return scope.Close(Integer::New(0, node_isolate)); - } + if (getenv(*key)) rc = 0; #else // _WIN32 String::Value key(property); WCHAR* key_ptr = reinterpret_cast(*key); if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 || GetLastError() == ERROR_SUCCESS) { + rc = 0; if (key_ptr[0] == L'=') { // Environment variables that start with '=' are hidden and read-only. - return scope.Close(Integer::New(v8::ReadOnly || - v8::DontDelete || - v8::DontEnum, - node_isolate)); - } else { - return scope.Close(Integer::New(0, node_isolate)); + rc = static_cast(v8::ReadOnly) | + static_cast(v8::DontDelete) | + static_cast(v8::DontEnum); } } #endif - // Not found - return scope.Close(Handle()); + if (rc != -1) info.GetReturnValue().Set(rc); } -static Handle EnvDeleter(Local property, - const AccessorInfo& info) { +static void EnvDeleter(Local property, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); + bool rc = true; #ifdef __POSIX__ String::Utf8Value key(property); - if (!getenv(*key)) return False(node_isolate); - unsetenv(*key); // can't check return value, it's void on some platforms - return True(node_isolate); + rc = getenv(*key) != NULL; + if (rc) unsetenv(*key); #else String::Value key(property); WCHAR* key_ptr = reinterpret_cast(*key); if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) { // Deletion failed. Return true if the key wasn't there in the first place, // false if it is still there. - bool rv = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 && - GetLastError() != ERROR_SUCCESS; - return scope.Close(Boolean::New(rv)); + rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 && + GetLastError() != ERROR_SUCCESS; } - return True(node_isolate); #endif + info.GetReturnValue().Set(rc); } -static Handle EnvEnumerator(const AccessorInfo& info) { +static void EnvEnumerator(const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); #ifdef __POSIX__ int size = 0; @@ -2123,10 +2101,7 @@ static Handle EnvEnumerator(const AccessorInfo& info) { } #else // _WIN32 WCHAR* environment = GetEnvironmentStringsW(); - if (environment == NULL) { - // This should not happen. - return scope.Close(Handle()); - } + if (environment == NULL) return; // This should not happen. Local env = Array::New(); WCHAR* p = environment; int i = 0; @@ -2147,7 +2122,8 @@ static Handle EnvEnumerator(const AccessorInfo& info) { } FreeEnvironmentStringsW(environment); #endif - return scope.Close(env); + + info.GetReturnValue().Set(env); } @@ -2174,35 +2150,35 @@ static Handle GetFeatures() { } -static Handle DebugPortGetter(Local property, - const AccessorInfo& info) { +static void DebugPortGetter(Local property, + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); - return scope.Close(Integer::NewFromUnsigned(debug_port, node_isolate)); + info.GetReturnValue().Set(debug_port); } static void DebugPortSetter(Local property, Local value, - const AccessorInfo& info) { + const PropertyCallbackInfo& info) { HandleScope scope(node_isolate); debug_port = value->NumberValue(); } -static Handle DebugProcess(const Arguments& args); -static Handle DebugPause(const Arguments& args); -static Handle DebugEnd(const Arguments& args); +static void DebugProcess(const FunctionCallbackInfo& args); +static void DebugPause(const FunctionCallbackInfo& args); +static void DebugEnd(const FunctionCallbackInfo& args); -Handle NeedImmediateCallbackGetter(Local property, - const AccessorInfo& info) { - return Boolean::New(need_immediate_cb); +void NeedImmediateCallbackGetter(Local property, + const PropertyCallbackInfo& info) { + info.GetReturnValue().Set(need_immediate_cb); } static void NeedImmediateCallbackSetter(Local property, Local value, - const AccessorInfo& info) { + const PropertyCallbackInfo&) { HandleScope scope(node_isolate); bool bool_value = value->BooleanValue(); @@ -2228,11 +2204,13 @@ Handle SetupProcessObject(int argc, char *argv[]) { int i, j; Local process_template = FunctionTemplate::New(); + process_template->SetClassName(String::New("process")); - process_template->SetClassName(String::NewSymbol("process")); + Local process = process_template->GetFunction()->NewInstance(); + assert(process.IsEmpty() == false); + assert(process->IsObject() == true); - process = Persistent::New(node_isolate, - process_template->GetFunction()->NewInstance()); + process_p.Reset(node_isolate, process); process->SetAccessor(String::New("title"), ProcessTitleGetter, @@ -2242,8 +2220,9 @@ Handle SetupProcessObject(int argc, char *argv[]) { process->Set(String::NewSymbol("version"), String::New(NODE_VERSION)); // process.moduleLoadList - module_load_list = Persistent::New(node_isolate, Array::New()); - process->Set(String::NewSymbol("moduleLoadList"), module_load_list); + Local modules = Array::New(); + module_load_list.Reset(node_isolate, modules); + process->Set(String::NewSymbol("moduleLoadList"), modules); // process.versions Local versions = Object::New(); @@ -2414,7 +2393,7 @@ Handle SetupProcessObject(int argc, char *argv[]) { // pre-set _events object for faster emit checks process->Set(String::NewSymbol("_events"), Object::New()); - return process; + return scope.Close(process); } @@ -2430,8 +2409,8 @@ static void SignalExit(int signal) { void Load(Handle process_l) { - process_symbol = NODE_PSYMBOL("process"); - domain_symbol = NODE_PSYMBOL("domain"); + process_symbol = String::New("process"); + domain_symbol = String::New("domain"); // Compile, execute the src/node.js file. (Which was included as static C // string in node_natives.h. 'natve_node' is the string containing that @@ -2466,7 +2445,6 @@ void Load(Handle process_l) { // Add a reference to the global object Local global = v8::Context::GetCurrent()->Global(); - Local args[1] = { Local::New(node_isolate, process_l) }; #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP InitDTrace(global); @@ -2484,7 +2462,8 @@ void Load(Handle process_l) { // thrown during process startup. try_catch.SetVerbose(true); - f->Call(global, 1, args); + Local arg = process_l; + f->Call(global, 1, &arg); } static void PrintHelp(); @@ -2643,7 +2622,7 @@ static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) { Local obj = Object::New(); obj->Set(String::New("cmd"), String::New("NODE_DEBUG_ENABLED")); Local args[] = { String::New("internalMessage"), obj }; - MakeCallback(process, "emit", ARRAY_SIZE(args), args); + MakeCallback(process_p, "emit", ARRAY_SIZE(args), args); } @@ -2677,7 +2656,7 @@ static void EnableDebug(bool wait_connect) { // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting // the main process (i.e. when called via `node --debug`) - if (!process.IsEmpty()) + if (!process_p.IsEmpty()) EmitDebugEnabled(); node_isolate->Exit(); @@ -2706,12 +2685,11 @@ static void RegisterSignalHandler(int signal, void (*handler)(int)) { } -Handle DebugProcess(const Arguments& args) { +void DebugProcess(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() != 1) { - return ThrowException(Exception::Error( - String::New("Invalid number of arguments."))); + return ThrowError("Invalid number of arguments."); } pid_t pid; @@ -2720,10 +2698,8 @@ Handle DebugProcess(const Arguments& args) { pid = args[0]->IntegerValue(); r = kill(pid, SIGUSR1); if (r != 0) { - return ThrowException(ErrnoException(errno, "kill")); + return ThrowErrnoException(errno, "kill"); } - - return Undefined(node_isolate); } #endif // __POSIX__ @@ -2794,9 +2770,8 @@ static int RegisterDebugSignalHandler() { } -static Handle DebugProcess(const Arguments& args) { +static void DebugProcess(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Handle rv = Undefined(node_isolate); DWORD pid; HANDLE process = NULL; HANDLE thread = NULL; @@ -2805,7 +2780,7 @@ static Handle DebugProcess(const Arguments& args) { LPTHREAD_START_ROUTINE* handler = NULL; if (args.Length() != 1) { - rv = ThrowException(Exception::Error(String::New("Invalid number of arguments."))); + ThrowError("Invalid number of arguments."); goto out; } @@ -2817,21 +2792,20 @@ static Handle DebugProcess(const Arguments& args) { FALSE, pid); if (process == NULL) { - rv = ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess")); + ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess")); goto out; } if (GetDebugSignalHandlerMappingName(pid, mapping_name, ARRAY_SIZE(mapping_name)) < 0) { - rv = ThrowException(ErrnoException(errno, "sprintf")); + ThrowErrnoException(errno, "sprintf"); goto out; } mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name); if (mapping == NULL) { - rv = ThrowException(WinapiErrnoException(GetLastError(), - "OpenFileMappingW")); + ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW")); goto out; } @@ -2842,7 +2816,7 @@ static Handle DebugProcess(const Arguments& args) { 0, sizeof *handler)); if (handler == NULL || *handler == NULL) { - rv = ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile")); + ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile")); goto out; } @@ -2854,15 +2828,13 @@ static Handle DebugProcess(const Arguments& args) { 0, NULL); if (thread == NULL) { - rv = ThrowException(WinapiErrnoException(GetLastError(), - "CreateRemoteThread")); + ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread")); goto out; } // Wait for the thread to terminate if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) { - rv = ThrowException(WinapiErrnoException(GetLastError(), - "WaitForSingleObject")); + ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject")); goto out; } @@ -2879,25 +2851,20 @@ static Handle DebugProcess(const Arguments& args) { if (mapping != NULL) { CloseHandle(mapping); } - - return Undefined(node_isolate); } #endif // _WIN32 -static Handle DebugPause(const Arguments& args) { +static void DebugPause(const FunctionCallbackInfo& args) { v8::Debug::DebugBreak(node_isolate); - return Undefined(node_isolate); } -static Handle DebugEnd(const Arguments& args) { +static void DebugEnd(const FunctionCallbackInfo& args) { if (debugger_running) { v8::Debug::DisableAgent(); debugger_running = false; } - - return Undefined(node_isolate); } @@ -3026,7 +2993,7 @@ void EmitExit(v8::Handle process_l) { // process.emit('exit') process_l->Set(String::NewSymbol("_exiting"), True(node_isolate)); Local args[] = { String::New("exit"), Integer::New(0, node_isolate) }; - MakeCallback(process, "emit", ARRAY_SIZE(args), args); + MakeCallback(process_l, "emit", ARRAY_SIZE(args), args); } static char **copy_argv(int argc, char **argv) { @@ -3081,9 +3048,10 @@ int Start(int argc, char *argv[]) { Local context = Context::New(node_isolate); Context::Scope context_scope(context); + binding_cache.Reset(node_isolate, Object::New()); + // Use original argv, as we're just copying values out of it. - Handle process_l = SetupProcessObject(argc, argv); - v8_typed_array::AttachBindings(context->Global()); + Local process_l = SetupProcessObject(argc, argv); // Create all the objects, load modules, do everything. // so your next reading stop should be node::Load()! diff --git a/src/node.h b/src/node.h index 59d03a355ae..16bfec56d82 100644 --- a/src/node.h +++ b/src/node.h @@ -95,10 +95,6 @@ v8::Handle SetupProcessObject(int argc, char *argv[]); void Load(v8::Handle process); void EmitExit(v8::Handle process); -#define NODE_PSYMBOL(s) \ - v8::Persistent::New(v8::Isolate::GetCurrent(), \ - v8::String::NewSymbol(s)) - /* Converts a unixtime to V8 Date */ #define NODE_UNIXTIME_V8(t) v8::Date::New(1000*static_cast(t)) #define NODE_V8_UNIXTIME(v) (static_cast((v)->NumberValue())/1000.0); @@ -109,25 +105,25 @@ void EmitExit(v8::Handle process); static_cast( \ v8::ReadOnly|v8::DontDelete)) -template -void SetMethod(target_t obj, const char* name, - v8::InvocationCallback callback) -{ - obj->Set(v8::String::NewSymbol(name), - v8::FunctionTemplate::New(callback)->GetFunction()); +// Used to be a macro, hence the uppercase name. +template +inline void NODE_SET_METHOD(TypeName& recv, + const char* name, + v8::FunctionCallback callback) { + v8::Local t = v8::FunctionTemplate::New(callback); + recv->Set(v8::String::New(name), t->GetFunction()); } - -template -void SetPrototypeMethod(target_t target, - const char* name, v8::InvocationCallback callback) -{ - v8::Local templ = v8::FunctionTemplate::New(callback); - target->PrototypeTemplate()->Set(v8::String::NewSymbol(name), templ); +#define NODE_SET_METHOD node::NODE_SET_METHOD + +// Used to be a macro, hence the uppercase name. +// Not a template because it only makes sense for FunctionTemplates. +inline void NODE_SET_PROTOTYPE_METHOD(v8::Handle recv, + const char* name, + v8::FunctionCallback callback) { + v8::Local t = v8::FunctionTemplate::New(callback); + recv->PrototypeTemplate()->Set(v8::String::New(name), t->GetFunction()); } - -// for backwards compatibility -#define NODE_SET_METHOD node::SetMethod -#define NODE_SET_PROTOTYPE_METHOD node::SetPrototypeMethod +#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; enum encoding ParseEncoding(v8::Handle encoding_v, @@ -151,25 +147,6 @@ NODE_EXTERN ssize_t DecodeWrite(char *buf, v8::Local BuildStatsObject(const uv_stat_t* s); -static inline v8::Persistent* cb_persist(v8::Local v) { - v8::Persistent* fn = new v8::Persistent(); - *fn = v8::Persistent::New(v8::Isolate::GetCurrent(), - v.As()); - return fn; -} - -static inline v8::Persistent* cb_unwrap(void *data) { - v8::Persistent *cb = - reinterpret_cast*>(data); - assert((*cb)->IsFunction()); - return cb; -} - -static inline void cb_destroy(v8::Persistent * cb) { - cb->Dispose(v8::Isolate::GetCurrent()); - delete cb; -} - NODE_EXTERN v8::Local ErrnoException(int errorno, const char *syscall = NULL, const char *msg = "", diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 95cfa3e928f..9ed92b09e76 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -57,9 +57,8 @@ namespace node { namespace Buffer { - -using v8::Arguments; using v8::Function; +using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Handle; using v8::HandleScope; @@ -72,8 +71,7 @@ using v8::Uint32; using v8::Undefined; using v8::Value; - -Persistent p_buffer_fn; +static Persistent p_buffer_fn; bool HasInstance(Handle val) { @@ -140,7 +138,7 @@ Local New(size_t length) { // of GC reclaiming the values prematurely. argv[0] = Undefined(node_isolate); argv[1] = Uint32::New(length, node_isolate); - Local obj = p_buffer_fn->NewInstance(2, argv); + Local obj = NewInstance(p_buffer_fn, ARRAY_SIZE(argv), argv); // TODO(trevnorris): done like this to handle HasInstance since only checks // if external array data has been set, but would like to use a better @@ -172,7 +170,7 @@ Local New(const char* data, size_t length) { // of GC reclaiming the values prematurely. argv[0] = Undefined(node_isolate); argv[1] = Uint32::New(length, node_isolate); - Local obj = p_buffer_fn->NewInstance(2, argv); + Local obj = NewInstance(p_buffer_fn, ARRAY_SIZE(argv), argv); // TODO(trevnorris): done like this to handle HasInstance since only checks // if external array data has been set, but would like to use a better @@ -206,7 +204,7 @@ Local New(char* data, // of GC reclaiming the values prematurely. argv[0] = Undefined(node_isolate); argv[1] = Uint32::New(length, node_isolate); - Local obj = p_buffer_fn->NewInstance(2, argv); + Local obj = NewInstance(p_buffer_fn, ARRAY_SIZE(argv), argv); smalloc::Alloc(obj, data, length, callback, hint); @@ -224,7 +222,7 @@ Local Use(char* data, uint32_t length) { // of GC reclaiming the values prematurely. argv[0] = Undefined(node_isolate); argv[1] = Uint32::New(length, node_isolate); - Local obj = p_buffer_fn->NewInstance(2, argv); + Local obj = NewInstance(p_buffer_fn, ARRAY_SIZE(argv), argv); smalloc::Alloc(obj, data, length); @@ -233,49 +231,49 @@ Local Use(char* data, uint32_t length) { template -Handle StringSlice(const Arguments& args) { +void StringSlice(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); ARGS_THIS(args.This()) SLICE_START_END(args[0], args[1], obj_length) - return scope.Close(StringBytes::Encode(obj_data + start, length, encoding)); + args.GetReturnValue().Set( + StringBytes::Encode(obj_data + start, length, encoding)); } -Handle BinarySlice(const Arguments& args) { - return StringSlice(args); +void BinarySlice(const FunctionCallbackInfo& args) { + StringSlice(args); } -Handle AsciiSlice(const Arguments& args) { - return StringSlice(args); +void AsciiSlice(const FunctionCallbackInfo& args) { + StringSlice(args); } -Handle Utf8Slice(const Arguments& args) { - return StringSlice(args); +void Utf8Slice(const FunctionCallbackInfo& args) { + StringSlice(args); } -Handle Ucs2Slice(const Arguments& args) { - return StringSlice(args); +void Ucs2Slice(const FunctionCallbackInfo& args) { + StringSlice(args); } - -Handle HexSlice(const Arguments& args) { - return StringSlice(args); +void HexSlice(const FunctionCallbackInfo& args) { + StringSlice(args); } -Handle Base64Slice(const Arguments& args) { - return StringSlice(args); +void Base64Slice(const FunctionCallbackInfo& args) { + StringSlice(args); } // bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]); -Handle Copy(const Arguments &args) { +void Copy(const FunctionCallbackInfo &args) { HandleScope scope(node_isolate); Local target = args[0]->ToObject(); @@ -297,7 +295,7 @@ Handle Copy(const Arguments &args) { // Copy 0 bytes; we're done if (target_start >= target_length || source_start >= source_end) - return scope.Close(Uint32::New(0, node_isolate)); + return args.GetReturnValue().Set(0); if (source_start > obj_length) return ThrowRangeError("out of range index"); @@ -305,27 +303,27 @@ Handle Copy(const Arguments &args) { if (source_end - source_start > target_length - target_start) source_end = source_start + target_length - target_start; - size_t to_copy = MIN(MIN(source_end - source_start, - target_length - target_start), - obj_length - source_start); + uint32_t to_copy = MIN(MIN(source_end - source_start, + target_length - target_start), + obj_length - source_start); memmove(target_data + target_start, obj_data + source_start, to_copy); - - return scope.Close(Uint32::New(to_copy, node_isolate)); + args.GetReturnValue().Set(to_copy); } // buffer.fill(value[, start][, end]); -Handle Fill(const Arguments &args) { +void Fill(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); ARGS_THIS(args.This()) SLICE_START_END(args[1], args[2], obj_length) + args.GetReturnValue().Set(args.This()); if (args[0]->IsNumber()) { int value = args[0]->Uint32Value() & 255; memset(obj_data + start, value, length); - return args.This(); + return; } String::Utf8Value at(args[0]); @@ -335,7 +333,7 @@ Handle Fill(const Arguments &args) { if (at_length == 1) { int value = static_cast((*at)[0]); memset(obj_data + start, value, length); - return args.This(); + return; } size_t in_there = at_length; @@ -344,7 +342,7 @@ Handle Fill(const Arguments &args) { memcpy(obj_data + start, *at, MIN(at_length, length)); if (at_length >= length) - return args.This(); + return; while (in_there < length - in_there) { memcpy(ptr, obj_data + start, in_there); @@ -356,13 +354,11 @@ Handle Fill(const Arguments &args) { memcpy(ptr, obj_data + start, length - in_there); in_there = length; } - - return args.This(); } template -Handle StringWrite(const Arguments& args) { +void StringWrite(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); ARGS_THIS(args.This()) @@ -384,7 +380,7 @@ Handle StringWrite(const Arguments& args) { max_length = MIN(obj_length - offset, max_length); if (max_length == 0) - return scope.Close(Uint32::New(0, node_isolate)); + return args.GetReturnValue().Set(0); if (encoding == UCS2) max_length = max_length / 2; @@ -392,43 +388,42 @@ Handle StringWrite(const Arguments& args) { if (offset >= obj_length) return ThrowRangeError("Offset is out of bounds"); - size_t written = StringBytes::Write(obj_data + offset, - max_length, - str, - encoding, - NULL); - - return scope.Close(Uint32::New(written, node_isolate)); + uint32_t written = StringBytes::Write(obj_data + offset, + max_length, + str, + encoding, + NULL); + args.GetReturnValue().Set(written); } -Handle Base64Write(const Arguments& args) { - return StringWrite(args); +void Base64Write(const FunctionCallbackInfo& args) { + StringWrite(args); } -Handle BinaryWrite(const Arguments& args) { - return StringWrite(args); +void BinaryWrite(const FunctionCallbackInfo& args) { + StringWrite(args); } -Handle Utf8Write(const Arguments& args) { - return StringWrite(args); +void Utf8Write(const FunctionCallbackInfo& args) { + StringWrite(args); } -Handle Ucs2Write(const Arguments& args) { - return StringWrite(args); +void Ucs2Write(const FunctionCallbackInfo& args) { + StringWrite(args); } -Handle HexWrite(const Arguments& args) { - return StringWrite(args); +void HexWrite(const FunctionCallbackInfo& args) { + StringWrite(args); } -Handle AsciiWrite(const Arguments& args) { - return StringWrite(args); +void AsciiWrite(const FunctionCallbackInfo& args) { + StringWrite(args); } @@ -443,7 +438,7 @@ static inline void Swizzle(char* start, unsigned int len) { template -Handle ReadFloatGeneric(const Arguments& args) { +void ReadFloatGeneric(const FunctionCallbackInfo& args) { bool doAssert = !args[1]->BooleanValue(); size_t offset; @@ -466,32 +461,32 @@ Handle ReadFloatGeneric(const Arguments& args) { memcpy(na.bytes, ptr, sizeof(na.bytes)); if (endianness != GetEndianness()) Swizzle(na.bytes, sizeof(na.bytes)); - return Number::New(na.val); + args.GetReturnValue().Set(na.val); } -Handle ReadFloatLE(const Arguments& args) { - return ReadFloatGeneric(args); +void ReadFloatLE(const FunctionCallbackInfo& args) { + ReadFloatGeneric(args); } -Handle ReadFloatBE(const Arguments& args) { - return ReadFloatGeneric(args); +void ReadFloatBE(const FunctionCallbackInfo& args) { + ReadFloatGeneric(args); } -Handle ReadDoubleLE(const Arguments& args) { - return ReadFloatGeneric(args); +void ReadDoubleLE(const FunctionCallbackInfo& args) { + ReadFloatGeneric(args); } -Handle ReadDoubleBE(const Arguments& args) { - return ReadFloatGeneric(args); +void ReadDoubleBE(const FunctionCallbackInfo& args) { + ReadFloatGeneric(args); } template -Handle WriteFloatGeneric(const Arguments& args) { +void WriteFloatGeneric(const FunctionCallbackInfo& args) { bool doAssert = !args[2]->BooleanValue(); T val = static_cast(args[0]->NumberValue()); @@ -515,32 +510,30 @@ Handle WriteFloatGeneric(const Arguments& args) { char* ptr = static_cast(data) + offset; if (endianness != GetEndianness()) Swizzle(na.bytes, sizeof(na.bytes)); memcpy(ptr, na.bytes, sizeof(na.bytes)); - - return Undefined(node_isolate); } -Handle WriteFloatLE(const Arguments& args) { - return WriteFloatGeneric(args); +void WriteFloatLE(const FunctionCallbackInfo& args) { + WriteFloatGeneric(args); } -Handle WriteFloatBE(const Arguments& args) { - return WriteFloatGeneric(args); +void WriteFloatBE(const FunctionCallbackInfo& args) { + WriteFloatGeneric(args); } -Handle WriteDoubleLE(const Arguments& args) { - return WriteFloatGeneric(args); +void WriteDoubleLE(const FunctionCallbackInfo& args) { + WriteFloatGeneric(args); } -Handle WriteDoubleBE(const Arguments& args) { - return WriteFloatGeneric(args); +void WriteDoubleBE(const FunctionCallbackInfo& args) { + WriteFloatGeneric(args); } -Handle ByteLength(const Arguments &args) { +void ByteLength(const FunctionCallbackInfo &args) { HandleScope scope(node_isolate); if (!args[0]->IsString()) @@ -549,18 +542,19 @@ Handle ByteLength(const Arguments &args) { Local s = args[0]->ToString(); enum encoding e = ParseEncoding(args[1], UTF8); - return scope.Close(Uint32::New(StringBytes::Size(s, e), node_isolate)); + uint32_t size = StringBytes::Size(s, e); + args.GetReturnValue().Set(size); } // pass Buffer object to load prototype methods -Handle SetupBufferJS(const Arguments& args) { +void SetupBufferJS(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); assert(args[0]->IsFunction()); Local bv = args[0].As(); - p_buffer_fn = Persistent::New(node_isolate, bv); + p_buffer_fn.Reset(node_isolate, bv); Local proto_v = bv->Get(String::New("prototype")); assert(proto_v->IsObject()); @@ -599,8 +593,6 @@ Handle SetupBufferJS(const Arguments& args) { // for backwards compatibility proto->Set(String::New("offset"), Uint32::New(0, node_isolate), v8::ReadOnly); - - return Undefined(node_isolate); } diff --git a/src/node_counters.cc b/src/node_counters.cc index 289be601862..8f6d136f462 100644 --- a/src/node_counters.cc +++ b/src/node_counters.cc @@ -20,7 +20,6 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_counters.h" - #include "uv.h" #include @@ -28,60 +27,55 @@ namespace node { -using namespace v8; - +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::GCCallbackFlags; +using v8::GCEpilogueCallback; +using v8::GCPrologueCallback; +using v8::GCType; +using v8::Handle; +using v8::HandleScope; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; static uint64_t counter_gc_start_time; static uint64_t counter_gc_end_time; -#define SLURP_OBJECT(obj, member, valp) \ - if (!(obj)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "object for " #obj " to contain object member " #member)))); \ - } \ - *valp = Local::Cast(obj->Get(String::New(#member))); - -Handle COUNTER_NET_SERVER_CONNECTION(const Arguments& args) { +void COUNTER_NET_SERVER_CONNECTION(const FunctionCallbackInfo&) { NODE_COUNT_SERVER_CONN_OPEN(); - return Undefined(node_isolate); } -Handle COUNTER_NET_SERVER_CONNECTION_CLOSE(const Arguments& args) { +void COUNTER_NET_SERVER_CONNECTION_CLOSE(const FunctionCallbackInfo&) { NODE_COUNT_SERVER_CONN_CLOSE(); - return Undefined(node_isolate); } -Handle COUNTER_HTTP_SERVER_REQUEST(const Arguments& args) { +void COUNTER_HTTP_SERVER_REQUEST(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_SERVER_REQUEST(); - return Undefined(node_isolate); } -Handle COUNTER_HTTP_SERVER_RESPONSE(const Arguments& args) { +void COUNTER_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_SERVER_RESPONSE(); - return Undefined(node_isolate); } -Handle COUNTER_HTTP_CLIENT_REQUEST(const Arguments& args) { +void COUNTER_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_CLIENT_REQUEST(); - return Undefined(node_isolate); } -Handle COUNTER_HTTP_CLIENT_RESPONSE(const Arguments& args) { +void COUNTER_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo&) { NODE_COUNT_HTTP_CLIENT_RESPONSE(); - return Undefined(node_isolate); } static void counter_gc_start(GCType type, GCCallbackFlags flags) { counter_gc_start_time = NODE_COUNT_GET_GC_RAWTIME(); - - return; } @@ -98,33 +92,30 @@ static void counter_gc_done(GCType type, GCCallbackFlags flags) { counter_gc_end_time = endgc; } } - - return; } -#define NODE_PROBE(name) #name, name - void InitPerfCounters(Handle target) { HandleScope scope(node_isolate); static struct { const char* name; - Handle (*func)(const Arguments&); - Persistent templ; + void (*func)(const FunctionCallbackInfo&); } tab[] = { +#define NODE_PROBE(name) #name, name { NODE_PROBE(COUNTER_NET_SERVER_CONNECTION) }, { NODE_PROBE(COUNTER_NET_SERVER_CONNECTION_CLOSE) }, { NODE_PROBE(COUNTER_HTTP_SERVER_REQUEST) }, { NODE_PROBE(COUNTER_HTTP_SERVER_RESPONSE) }, { NODE_PROBE(COUNTER_HTTP_CLIENT_REQUEST) }, { NODE_PROBE(COUNTER_HTTP_CLIENT_RESPONSE) } +#undef NODE_PROBE }; for (int i = 0; i < ARRAY_SIZE(tab); i++) { - tab[i].templ = Persistent::New(node_isolate, - FunctionTemplate::New(tab[i].func)); - target->Set(String::NewSymbol(tab[i].name), tab[i].templ->GetFunction()); + Local key = String::New(tab[i].name); + Local val = FunctionTemplate::New(tab[i].func)->GetFunction(); + target->Set(key, val); } // Only Windows performance counters supported diff --git a/src/node_crypto.cc b/src/node_crypto.cc index c902bcb7aa8..fc826c154fd 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -45,15 +45,13 @@ #define ASSERT_IS_STRING_OR_BUFFER(val) do { \ if (!Buffer::HasInstance(val) && !val->IsString()) { \ - return ThrowException(Exception::TypeError(String::New( \ - "Not a string or buffer"))); \ + return ThrowTypeError("Not a string or buffer"); \ } \ } while (0) #define ASSERT_IS_BUFFER(val) do { \ if (!Buffer::HasInstance(val)) { \ - return ThrowException(Exception::TypeError(String::New( \ - "Not a buffer"))); \ + return ThrowTypeError("Not a buffer"); \ } \ } while (0) @@ -69,7 +67,20 @@ static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL namespace node { namespace crypto { -using namespace v8; +using v8::Array; +using v8::Exception; +using v8::False; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::HandleScope; +using v8::Integer; +using v8::Local; +using v8::Null; +using v8::Object; +using v8::Persistent; +using v8::String; +using v8::ThrowException; + // Forcibly clear OpenSSL's error stack on return. This stops stale errors // from popping up later in the lifecycle of crypto operations where they @@ -79,24 +90,24 @@ struct ClearErrorOnReturn { ~ClearErrorOnReturn() { ERR_clear_error(); } }; -static Persistent errno_symbol; -static Persistent syscall_symbol; -static Persistent subject_symbol; -static Persistent subjectaltname_symbol; -static Persistent modulus_symbol; -static Persistent exponent_symbol; -static Persistent issuer_symbol; -static Persistent valid_from_symbol; -static Persistent valid_to_symbol; -static Persistent fingerprint_symbol; -static Persistent name_symbol; -static Persistent version_symbol; -static Persistent ext_key_usage_symbol; -static Persistent onhandshakestart_sym; -static Persistent onhandshakedone_sym; -static Persistent onclienthello_sym; -static Persistent onnewsession_sym; -static Persistent sessionid_sym; +static Cached errno_symbol; +static Cached syscall_symbol; +static Cached subject_symbol; +static Cached subjectaltname_symbol; +static Cached modulus_symbol; +static Cached exponent_symbol; +static Cached issuer_symbol; +static Cached valid_from_symbol; +static Cached valid_to_symbol; +static Cached fingerprint_symbol; +static Cached name_symbol; +static Cached version_symbol; +static Cached ext_key_usage_symbol; +static Cached onhandshakestart_sym; +static Cached onhandshakedone_sym; +static Cached onclienthello_sym; +static Cached onnewsession_sym; +static Cached sessionid_sym; static Persistent secure_context_constructor; @@ -138,21 +149,24 @@ static void crypto_lock_cb(int mode, int n, const char* file, int line) { } -Handle ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) { +void ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) { HandleScope scope(node_isolate); char errmsg[128]; ERR_error_string_n(err, errmsg, sizeof(errmsg)); - return is_type_error ? ThrowTypeError(errmsg) : ThrowError(errmsg); + if (is_type_error) + ThrowTypeError(errmsg); + else + ThrowError(errmsg); } -Handle ThrowCryptoError(unsigned long err) { - return ThrowCryptoErrorHelper(err, false); +void ThrowCryptoError(unsigned long err) { + ThrowCryptoErrorHelper(err, false); } -Handle ThrowCryptoTypeError(unsigned long err) { - return ThrowCryptoErrorHelper(err, true); +void ThrowCryptoTypeError(unsigned long err) { + ThrowCryptoErrorHelper(err, true); } @@ -160,8 +174,7 @@ void SecureContext::Initialize(Handle target) { HandleScope scope(node_isolate); Local t = FunctionTemplate::New(SecureContext::New); - secure_context_constructor = Persistent::New(node_isolate, - t); + secure_context_constructor.Reset(node_isolate, t); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(String::NewSymbol("SecureContext")); @@ -185,15 +198,14 @@ void SecureContext::Initialize(Handle target) { } -Handle SecureContext::New(const Arguments& args) { +void SecureContext::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *p = new SecureContext(); p->Wrap(args.This()); - return args.This(); } -Handle SecureContext::Init(const Arguments& args) { +void SecureContext::Init(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); @@ -207,19 +219,19 @@ Handle SecureContext::Init(const Arguments& args) { #ifndef OPENSSL_NO_SSL2 method = SSLv2_method(); #else - return ThrowException(Exception::Error(String::New("SSLv2 methods disabled"))); + return ThrowError("SSLv2 methods disabled"); #endif } else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) { #ifndef OPENSSL_NO_SSL2 method = SSLv2_server_method(); #else - return ThrowException(Exception::Error(String::New("SSLv2 methods disabled"))); + return ThrowError("SSLv2 methods disabled"); #endif } else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) { #ifndef OPENSSL_NO_SSL2 method = SSLv2_client_method(); #else - return ThrowException(Exception::Error(String::New("SSLv2 methods disabled"))); + return ThrowError("SSLv2 methods disabled"); #endif } else if (strcmp(*sslmethod, "SSLv3_method") == 0) { method = SSLv3_method(); @@ -240,7 +252,7 @@ Handle SecureContext::Init(const Arguments& args) { } else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) { method = TLSv1_client_method(); } else { - return ThrowException(Exception::Error(String::New("Unknown method"))); + return ThrowError("Unknown method"); } } @@ -255,7 +267,6 @@ Handle SecureContext::Init(const Arguments& args) { SSL_CTX_sess_set_new_cb(sc->ctx_, NewSessionCallback); sc->ca_store_ = NULL; - return True(node_isolate); } @@ -297,9 +308,13 @@ int SecureContext::NewSessionCallback(SSL* s, SSL_SESSION* sess) { }; if (onnewsession_sym.IsEmpty()) { - onnewsession_sym = NODE_PSYMBOL("onnewsession"); + onnewsession_sym = String::New("onnewsession"); } - MakeCallback(p->handle_, onnewsession_sym, ARRAY_SIZE(argv), argv); + + MakeCallback(p->handle(node_isolate), + onnewsession_sym, + ARRAY_SIZE(argv), + argv); return 0; } @@ -352,21 +367,21 @@ static X509* LoadX509 (Handle v) { } -Handle SecureContext::SetKey(const Arguments& args) { +void SecureContext::SetKey(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); unsigned int len = args.Length(); if (len != 1 && len != 2) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } if (len == 2 && !args[1]->IsString()) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } BIO *bio = LoadBIO(args[0]); - if (!bio) return False(node_isolate); + if (!bio) return; String::Utf8Value passphrase(args[1]); @@ -377,8 +392,7 @@ Handle SecureContext::SetKey(const Arguments& args) { BIO_free_all(bio); unsigned long err = ERR_get_error(); if (!err) { - return ThrowException(Exception::Error( - String::New("PEM_read_bio_PrivateKey"))); + return ThrowError("PEM_read_bio_PrivateKey"); } return ThrowCryptoError(err); } @@ -386,8 +400,6 @@ Handle SecureContext::SetKey(const Arguments& args) { SSL_CTX_use_PrivateKey(sc->ctx_, key); EVP_PKEY_free(key); BIO_free_all(bio); - - return True(node_isolate); } @@ -457,18 +469,17 @@ end: } -Handle SecureContext::SetCert(const Arguments& args) { +void SecureContext::SetCert(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1) { - return ThrowException(Exception::TypeError( - String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } BIO* bio = LoadBIO(args[0]); - if (!bio) return False(node_isolate); + if (!bio) return; int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio); @@ -477,24 +488,21 @@ Handle SecureContext::SetCert(const Arguments& args) { if (!rv) { unsigned long err = ERR_get_error(); if (!err) { - return ThrowException(Exception::Error( - String::New("SSL_CTX_use_certificate_chain"))); + return ThrowError("SSL_CTX_use_certificate_chain"); } return ThrowCryptoError(err); } - - return True(node_isolate); } -Handle SecureContext::AddCACert(const Arguments& args) { +void SecureContext::AddCACert(const FunctionCallbackInfo& args) { bool newCAStore = false; HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } if (!sc->ca_store_) { @@ -503,7 +511,7 @@ Handle SecureContext::AddCACert(const Arguments& args) { } X509* x509 = LoadX509(args[0]); - if (!x509) return False(node_isolate); + if (!x509) return; X509_STORE_add_cert(sc->ca_store_, x509); SSL_CTX_add_client_CA(sc->ctx_, x509); @@ -513,47 +521,41 @@ Handle SecureContext::AddCACert(const Arguments& args) { if (newCAStore) { SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_); } - - return True(node_isolate); } -Handle SecureContext::AddCRL(const Arguments& args) { +void SecureContext::AddCRL(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } ClearErrorOnReturn clear_error_on_return; (void) &clear_error_on_return; // Silence compiler warning. BIO *bio = LoadBIO(args[0]); - if (!bio) return False(node_isolate); + if (!bio) return; X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL); if (x509 == NULL) { BIO_free_all(bio); - return False(node_isolate); + return; } X509_STORE_add_crl(sc->ca_store_, x509); - X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); - BIO_free_all(bio); X509_CRL_free(x509); - - return True(node_isolate); } -Handle SecureContext::AddRootCerts(const Arguments& args) { +void SecureContext::AddRootCerts(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); @@ -568,14 +570,14 @@ Handle SecureContext::AddRootCerts(const Arguments& args) { if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) { BIO_free_all(bp); - return False(node_isolate); + return; } X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL); if (x509 == NULL) { BIO_free_all(bp); - return False(node_isolate); + return; } X509_STORE_add_cert(root_cert_store, x509); @@ -587,47 +589,44 @@ Handle SecureContext::AddRootCerts(const Arguments& args) { sc->ca_store_ = root_cert_store; SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_); - - return True(node_isolate); } -Handle SecureContext::SetCiphers(const Arguments& args) { +void SecureContext::SetCiphers(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1 || !args[0]->IsString()) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } String::Utf8Value ciphers(args[0]); SSL_CTX_set_cipher_list(sc->ctx_, *ciphers); - - return True(node_isolate); } -Handle SecureContext::SetOptions(const Arguments& args) { + +void SecureContext::SetOptions(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1 || !args[0]->IntegerValue()) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue()); - - return True(node_isolate); } -Handle SecureContext::SetSessionIdContext(const Arguments& args) { + +void SecureContext::SetSessionIdContext( + const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() != 1 || !args[0]->IsString()) { - return ThrowException(Exception::TypeError(String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } String::Utf8Value sessionIdContext(args[0]); @@ -635,25 +634,28 @@ Handle SecureContext::SetSessionIdContext(const Arguments& args) { unsigned int sid_ctx_len = sessionIdContext.length(); int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len); - if (r != 1) { - Local message; - BIO* bio; - BUF_MEM* mem; - if ((bio = BIO_new(BIO_s_mem()))) { - ERR_print_errors(bio); - BIO_get_mem_ptr(bio, &mem); - message = String::New(mem->data, mem->length); - BIO_free_all(bio); - } else { - message = String::New("SSL_CTX_set_session_id_context error"); - } - return ThrowException(Exception::TypeError(message)); + if (r == 1) return; + + BIO* bio; + BUF_MEM* mem; + Local message; + + bio = BIO_new(BIO_s_mem()); + if (bio == NULL) { + message = String::New("SSL_CTX_set_session_id_context error"); + } + else { + ERR_print_errors(bio); + BIO_get_mem_ptr(bio, &mem); + message = String::New(mem->data, mem->length); + BIO_free_all(bio); } - return True(node_isolate); + ThrowException(Exception::TypeError(message)); } -Handle SecureContext::SetSessionTimeout(const Arguments& args) { + +void SecureContext::SetSessionTimeout(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); @@ -664,19 +666,18 @@ Handle SecureContext::SetSessionTimeout(const Arguments& args) { int32_t sessionTimeout = args[0]->Int32Value(); SSL_CTX_set_timeout(sc->ctx_, sessionTimeout); - - return True(node_isolate); } -Handle SecureContext::Close(const Arguments& args) { + +void SecureContext::Close(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SecureContext *sc = ObjectWrap::Unwrap(args.This()); sc->FreeCTXMem(); - return False(node_isolate); } + //Takes .pfx or .p12 and password in string or buffer format -Handle SecureContext::LoadPKCS12(const Arguments& args) { +void SecureContext::LoadPKCS12(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); BIO* in = NULL; @@ -690,14 +691,12 @@ Handle SecureContext::LoadPKCS12(const Arguments& args) { SecureContext *sc = ObjectWrap::Unwrap(args.This()); if (args.Length() < 1) { - return ThrowException(Exception::TypeError( - String::New("Bad parameter"))); + return ThrowTypeError("Bad parameter"); } in = LoadBIO(args[0]); if (in == NULL) { - return ThrowException(Exception::Error( - String::New("Unable to load BIO"))); + return ThrowError("Unable to load BIO"); } if (args.Length() >= 2) { @@ -706,8 +705,7 @@ Handle SecureContext::LoadPKCS12(const Arguments& args) { int passlen = Buffer::Length(args[1]); if (passlen < 0) { BIO_free_all(in); - return ThrowException(Exception::TypeError( - String::New("Bad password"))); + return ThrowTypeError("Bad password"); } pass = new char[passlen + 1]; int pass_written = DecodeWrite(pass, passlen, args[1], BINARY); @@ -747,10 +745,8 @@ Handle SecureContext::LoadPKCS12(const Arguments& args) { if (!ret) { unsigned long err = ERR_get_error(); const char* str = ERR_reason_error_string(err); - return ThrowException(Exception::Error(String::New(str))); + return ThrowError(str); } - - return True(node_isolate); } @@ -863,10 +859,10 @@ size_t ClientHelloParser::Write(const uint8_t* data, size_t len) { // Parse frame, call javascript handler and // move parser into the paused state if (onclienthello_sym.IsEmpty()) { - onclienthello_sym = NODE_PSYMBOL("onclienthello"); + onclienthello_sym = String::New("onclienthello"); } if (sessionid_sym.IsEmpty()) { - sessionid_sym = NODE_PSYMBOL("sessionId"); + sessionid_sym = String::New("sessionId"); } state_ = kPaused; @@ -876,7 +872,10 @@ size_t ClientHelloParser::Write(const uint8_t* data, size_t len) { session_size)); argv[0] = hello; - MakeCallback(conn_->handle_, onclienthello_sym, 1, argv); + MakeCallback(conn_->handle(node_isolate), + onclienthello_sym, + ARRAY_SIZE(argv), + argv); break; case kEnded: default: @@ -920,12 +919,12 @@ int Connection::HandleBIOError(BIO *bio, const char* func, int rv) { return 0; } else { - static char ssl_error_buf[512]; + static char ssl_error_buf[512]; ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf)); HandleScope scope(node_isolate); Local e = Exception::Error(String::New(ssl_error_buf)); - handle_->Set(String::New("error"), e); + handle(node_isolate)->Set(String::New("error"), e); DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n", ssl_, func, rv, ssl_error_buf); @@ -960,8 +959,8 @@ int Connection::HandleSSLError(const char* func, return 0; } else if (err == SSL_ERROR_ZERO_RETURN) { - handle_->Set(String::New("error"), - Exception::Error(String::New("ZERO_RETURN"))); + handle(node_isolate)->Set(String::New("error"), + Exception::Error(String::New("ZERO_RETURN"))); return rv; } else if ((err == SSL_ERROR_SYSCALL) && (ss == kIgnoreSyscall)) { @@ -983,7 +982,7 @@ int Connection::HandleSSLError(const char* func, ERR_print_errors(bio); BIO_get_mem_ptr(bio, &mem); Local e = Exception::Error(String::New(mem->data, mem->length)); - handle_->Set(String::New("error"), e); + handle(node_isolate)->Set(String::New("error"), e); BIO_free_all(bio); } @@ -999,7 +998,8 @@ void Connection::ClearError() { HandleScope scope(node_isolate); // We should clear the error in JS-land - assert(handle_->Get(String::New("error"))->BooleanValue() == false); + assert( + handle(node_isolate)->Get(String::New("error"))->BooleanValue() == false); #endif // NDEBUG } @@ -1010,11 +1010,12 @@ void Connection::SetShutdownFlags() { int flags = SSL_get_shutdown(ssl_); if (flags & SSL_SENT_SHUTDOWN) { - handle_->Set(String::New("sentShutdown"), True(node_isolate)); + handle(node_isolate)->Set(String::New("sentShutdown"), True(node_isolate)); } if (flags & SSL_RECEIVED_SHUTDOWN) { - handle_->Set(String::New("receivedShutdown"), True(node_isolate)); + handle(node_isolate)->Set(String::New("receivedShutdown"), + True(node_isolate)); } } @@ -1133,9 +1134,7 @@ int Connection::SelectNextProtoCallback_(SSL *s, Connection *p = static_cast SSL_get_app_data(s); // Release old protocol handler if present - if (!p->selectedNPNProto_.IsEmpty()) { - p->selectedNPNProto_.Dispose(node_isolate); - } + p->selectedNPNProto_.Dispose(); if (p->npnProtos_.IsEmpty()) { // We should at least select one protocol @@ -1144,8 +1143,7 @@ int Connection::SelectNextProtoCallback_(SSL *s, *outlen = 8; // set status unsupported - p->selectedNPNProto_ = Persistent::New(node_isolate, - False(node_isolate)); + p->selectedNPNProto_.Reset(node_isolate, False(node_isolate)); return SSL_TLSEXT_ERR_OK; } @@ -1158,17 +1156,15 @@ int Connection::SelectNextProtoCallback_(SSL *s, switch (status) { case OPENSSL_NPN_UNSUPPORTED: - p->selectedNPNProto_ = Persistent::New(node_isolate, - Null(node_isolate)); + p->selectedNPNProto_.Reset(node_isolate, Null(node_isolate)); break; case OPENSSL_NPN_NEGOTIATED: - p->selectedNPNProto_ = Persistent::New(node_isolate, String::New( - reinterpret_cast(*out), *outlen - )); + p->selectedNPNProto_.Reset( + node_isolate, + String::New(reinterpret_cast(*out), *outlen)); break; case OPENSSL_NPN_NO_OVERLAP: - p->selectedNPNProto_ = Persistent::New(node_isolate, - False(node_isolate)); + p->selectedNPNProto_.Reset(node_isolate, False(node_isolate)); break; default: break; @@ -1187,33 +1183,20 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername) { - if (!p->servername_.IsEmpty()) { - p->servername_.Dispose(node_isolate); - } - p->servername_ = Persistent::New(node_isolate, - String::New(servername)); + p->servername_.Reset(node_isolate, String::New(servername)); // Call the SNI callback and use its return value as context if (!p->sniObject_.IsEmpty()) { - if (!p->sniContext_.IsEmpty()) { - p->sniContext_.Dispose(node_isolate); - } - - // Get callback init args - Local argv[1] = {*p->servername_}; + p->sniContext_.Dispose(); - // Call it - Local ret = Local::New(node_isolate, - MakeCallback(p->sniObject_, - "onselect", - ARRAY_SIZE(argv), - argv)); + Local arg = Local::New(node_isolate, p->servername_); + Local ret = Local::New( + node_isolate, MakeCallback(p->sniObject_, "onselect", 1, &arg)); // If ret is SecureContext - if (secure_context_constructor->HasInstance(ret)) { - p->sniContext_ = Persistent::New(node_isolate, ret); - SecureContext *sc = ObjectWrap::Unwrap( - Local::Cast(ret)); + if (HasInstance(secure_context_constructor, ret)) { + p->sniContext_.Reset(node_isolate, ret); + SecureContext* sc = ObjectWrap::Unwrap(ret.As()); SSL_set_SSL_CTX(s, sc->ctx_); } else { return SSL_TLSEXT_ERR_NOACK; @@ -1225,15 +1208,14 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { } #endif -Handle Connection::New(const Arguments& args) { +void Connection::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *p = new Connection(); p->Wrap(args.This()); if (args.Length() < 1 || !args[0]->IsObject()) { - return ThrowException(Exception::Error(String::New( - "First argument must be a crypto module Credentials"))); + return ThrowError("First argument must be a crypto module Credentials"); } SecureContext *sc = ObjectWrap::Unwrap(args[0]->ToObject()); @@ -1305,8 +1287,6 @@ Handle Connection::New(const Arguments& args) { } else { SSL_set_connect_state(p->ssl_); } - - return args.This(); } @@ -1318,34 +1298,32 @@ void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) { HandleScope scope(node_isolate); Connection* c = static_cast(SSL_get_app_data(ssl)); if (onhandshakestart_sym.IsEmpty()) { - onhandshakestart_sym = NODE_PSYMBOL("onhandshakestart"); + onhandshakestart_sym = String::New("onhandshakestart"); } - MakeCallback(c->handle_, onhandshakestart_sym, 0, NULL); + MakeCallback(c->handle(node_isolate), onhandshakestart_sym, 0, NULL); } if (where & SSL_CB_HANDSHAKE_DONE) { HandleScope scope(node_isolate); Connection* c = static_cast(SSL_get_app_data(ssl)); if (onhandshakedone_sym.IsEmpty()) { - onhandshakedone_sym = NODE_PSYMBOL("onhandshakedone"); + onhandshakedone_sym = String::New("onhandshakedone"); } - MakeCallback(c->handle_, onhandshakedone_sym, 0, NULL); + MakeCallback(c->handle(node_isolate), onhandshakedone_sym, 0, NULL); } } -Handle Connection::EncIn(const Arguments& args) { +void Connection::EncIn(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 3) { - return ThrowException(Exception::TypeError( - String::New("Takes 3 parameters"))); + return ThrowTypeError("Takes 3 parameters"); } if (!Buffer::HasInstance(args[0])) { - return ThrowException(Exception::TypeError( - String::New("Second argument should be a buffer"))); + return ThrowTypeError("Second argument should be a buffer"); } char* buffer_data = Buffer::Data(args[0]); @@ -1354,8 +1332,7 @@ Handle Connection::EncIn(const Arguments& args) { size_t off = args[1]->Int32Value(); size_t len = args[2]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("off + len > buffer.length"))); + return ThrowError("off + len > buffer.length"); } int bytes_written; @@ -1370,23 +1347,21 @@ Handle Connection::EncIn(const Arguments& args) { ss->SetShutdownFlags(); } - return scope.Close(Integer::New(bytes_written, node_isolate)); + args.GetReturnValue().Set(bytes_written); } -Handle Connection::ClearOut(const Arguments& args) { +void Connection::ClearOut(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 3) { - return ThrowException(Exception::TypeError( - String::New("Takes 3 parameters"))); + return ThrowTypeError("Takes 3 parameters"); } if (!Buffer::HasInstance(args[0])) { - return ThrowException(Exception::TypeError( - String::New("Second argument should be a buffer"))); + return ThrowTypeError("Second argument should be a buffer"); } char* buffer_data = Buffer::Data(args[0]); @@ -1395,8 +1370,7 @@ Handle Connection::ClearOut(const Arguments& args) { size_t off = args[1]->Int32Value(); size_t len = args[2]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("off + len > buffer.length"))); + return ThrowError("off + len > buffer.length"); } if (!SSL_is_init_finished(ss->ssl_)) { @@ -1416,7 +1390,9 @@ Handle Connection::ClearOut(const Arguments& args) { kSyscallError); } - if (rv < 0) return scope.Close(Integer::New(rv, node_isolate)); + if (rv < 0) { + return args.GetReturnValue().Set(rv); + } } int bytes_read = SSL_read(ss->ssl_, buffer_data + off, len); @@ -1426,43 +1402,37 @@ Handle Connection::ClearOut(const Arguments& args) { kSyscallError); ss->SetShutdownFlags(); - return scope.Close(Integer::New(bytes_read, node_isolate)); + args.GetReturnValue().Set(bytes_read); } -Handle Connection::ClearPending(const Arguments& args) { +void Connection::ClearPending(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Connection *ss = Connection::Unwrap(args); - int bytes_pending = BIO_pending(ss->bio_read_); - return scope.Close(Integer::New(bytes_pending, node_isolate)); + args.GetReturnValue().Set(bytes_pending); } -Handle Connection::EncPending(const Arguments& args) { +void Connection::EncPending(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Connection *ss = Connection::Unwrap(args); - int bytes_pending = BIO_pending(ss->bio_write_); - return scope.Close(Integer::New(bytes_pending, node_isolate)); + args.GetReturnValue().Set(bytes_pending); } -Handle Connection::EncOut(const Arguments& args) { +void Connection::EncOut(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 3) { - return ThrowException(Exception::TypeError( - String::New("Takes 3 parameters"))); + return ThrowTypeError("Takes 3 parameters"); } if (!Buffer::HasInstance(args[0])) { - return ThrowException(Exception::TypeError( - String::New("Second argument should be a buffer"))); + return ThrowTypeError("Second argument should be a buffer"); } char* buffer_data = Buffer::Data(args[0]); @@ -1471,8 +1441,7 @@ Handle Connection::EncOut(const Arguments& args) { size_t off = args[1]->Int32Value(); size_t len = args[2]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("off + len > buffer.length"))); + return ThrowError("off + len > buffer.length"); } int bytes_read = BIO_read(ss->bio_write_, buffer_data + off, len); @@ -1480,23 +1449,21 @@ Handle Connection::EncOut(const Arguments& args) { ss->HandleBIOError(ss->bio_write_, "BIO_read:EncOut", bytes_read); ss->SetShutdownFlags(); - return scope.Close(Integer::New(bytes_read, node_isolate)); + args.GetReturnValue().Set(bytes_read); } -Handle Connection::ClearIn(const Arguments& args) { +void Connection::ClearIn(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 3) { - return ThrowException(Exception::TypeError( - String::New("Takes 3 parameters"))); + return ThrowTypeError("Takes 3 parameters"); } if (!Buffer::HasInstance(args[0])) { - return ThrowException(Exception::TypeError( - String::New("Second argument should be a buffer"))); + return ThrowTypeError("Second argument should be a buffer"); } char* buffer_data = Buffer::Data(args[0]); @@ -1505,8 +1472,7 @@ Handle Connection::ClearIn(const Arguments& args) { size_t off = args[1]->Int32Value(); size_t len = args[2]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("off + len > buffer.length"))); + return ThrowError("off + len > buffer.length"); } if (!SSL_is_init_finished(ss->ssl_)) { @@ -1525,7 +1491,9 @@ Handle Connection::ClearIn(const Arguments& args) { kSyscallError); } - if (rv < 0) return scope.Close(Integer::New(rv, node_isolate)); + if (rv < 0) { + return args.GetReturnValue().Set(rv); + } } int bytes_written = SSL_write(ss->ssl_, buffer_data + off, len); @@ -1536,16 +1504,16 @@ Handle Connection::ClearIn(const Arguments& args) { kSyscallError); ss->SetShutdownFlags(); - return scope.Close(Integer::New(bytes_written, node_isolate)); + args.GetReturnValue().Set(bytes_written); } -Handle Connection::GetPeerCertificate(const Arguments& args) { +void Connection::GetPeerCertificate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); - if (ss->ssl_ == NULL) return Undefined(node_isolate); + if (ss->ssl_ == NULL) return; Local info = Object::New(); X509* peer_cert = SSL_get_peer_certificate(ss->ssl_); if (peer_cert != NULL) { @@ -1656,51 +1624,47 @@ Handle Connection::GetPeerCertificate(const Arguments& args) { X509_free(peer_cert); } - return scope.Close(info); + + args.GetReturnValue().Set(info); } -Handle Connection::GetSession(const Arguments& args) { + +void Connection::GetSession(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); - if (ss->ssl_ == NULL) return Undefined(node_isolate); + if (ss->ssl_ == NULL) return; SSL_SESSION* sess = SSL_get_session(ss->ssl_); - if (!sess) return Undefined(node_isolate); + if (!sess) return; int slen = i2d_SSL_SESSION(sess, NULL); assert(slen > 0); - if (slen > 0) { - unsigned char* sbuf = new unsigned char[slen]; - unsigned char* p = sbuf; - i2d_SSL_SESSION(sess, &p); - Local s = Encode(sbuf, slen, BINARY); - delete[] sbuf; - return scope.Close(s); - } - - return Null(node_isolate); + unsigned char* sbuf = new unsigned char[slen]; + unsigned char* p = sbuf; + i2d_SSL_SESSION(sess, &p); + args.GetReturnValue().Set(Encode(sbuf, slen, BINARY)); + delete[] sbuf; } -Handle Connection::SetSession(const Arguments& args) { + +void Connection::SetSession(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 1 || (!args[0]->IsString() && !Buffer::HasInstance(args[0]))) { - Local exception = Exception::TypeError(String::New("Bad argument")); - return ThrowException(exception); + return ThrowTypeError("Bad argument"); } ASSERT_IS_BUFFER(args[0]); ssize_t slen = Buffer::Length(args[0]); if (slen < 0) { - Local exception = Exception::TypeError(String::New("Bad argument")); - return ThrowException(exception); + return ThrowTypeError("Bad argument"); } char* sbuf = new char[slen]; @@ -1713,21 +1677,18 @@ Handle Connection::SetSession(const Arguments& args) { delete [] sbuf; - if (!sess) - return Undefined(node_isolate); + if (!sess) return; int r = SSL_set_session(ss->ssl_, sess); SSL_SESSION_free(sess); if (!r) { - Local eStr = String::New("SSL_set_session error"); - return ThrowException(Exception::Error(eStr)); + return ThrowError("SSL_set_session error"); } - - return True(node_isolate); } -Handle Connection::LoadSession(const Arguments& args) { + +void Connection::LoadSession(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); @@ -1747,30 +1708,24 @@ Handle Connection::LoadSession(const Arguments& args) { } ss->hello_parser_.Finish(); - - return True(node_isolate); } -Handle Connection::IsSessionReused(const Arguments& args) { - HandleScope scope(node_isolate); +void Connection::IsSessionReused(const FunctionCallbackInfo& args) { + HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); - - if (ss->ssl_ == NULL || SSL_session_reused(ss->ssl_) == false) { - return False(node_isolate); - } - - return True(node_isolate); + bool yes = ss->ssl_ && SSL_session_reused(ss->ssl_); + args.GetReturnValue().Set(yes); } -Handle Connection::Start(const Arguments& args) { +void Connection::Start(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); + int rv = 0; if (!SSL_is_init_finished(ss->ssl_)) { - int rv; if (ss->is_server_) { rv = SSL_accept(ss->ssl_); ss->HandleSSLError("SSL_accept:Start", rv, kZeroIsAnError, kSyscallError); @@ -1781,62 +1736,51 @@ Handle Connection::Start(const Arguments& args) { kZeroIsAnError, kSyscallError); } - - return scope.Close(Integer::New(rv, node_isolate)); } - - return scope.Close(Integer::New(0, node_isolate)); + args.GetReturnValue().Set(rv); } -Handle Connection::Shutdown(const Arguments& args) { +void Connection::Shutdown(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); - if (ss->ssl_ == NULL) return False(node_isolate); + if (ss->ssl_ == NULL) { + return args.GetReturnValue().Set(false); + } + int rv = SSL_shutdown(ss->ssl_); ss->HandleSSLError("SSL_shutdown", rv, kZeroIsNotAnError, kIgnoreSyscall); ss->SetShutdownFlags(); - - return scope.Close(Integer::New(rv, node_isolate)); + args.GetReturnValue().Set(rv); } -Handle Connection::ReceivedShutdown(const Arguments& args) { +void Connection::ReceivedShutdown(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Connection *ss = Connection::Unwrap(args); - - if (ss->ssl_ == NULL) return False(node_isolate); - int r = SSL_get_shutdown(ss->ssl_); - - if (r & SSL_RECEIVED_SHUTDOWN) return True(node_isolate); - - return False(node_isolate); + bool yes = ss->ssl_ && SSL_get_shutdown(ss->ssl_) == SSL_RECEIVED_SHUTDOWN; + args.GetReturnValue().Set(yes); } -Handle Connection::IsInitFinished(const Arguments& args) { +void Connection::IsInitFinished(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Connection *ss = Connection::Unwrap(args); - - if (ss->ssl_ == NULL || SSL_is_init_finished(ss->ssl_) == false) { - return False(node_isolate); - } - - return True(node_isolate); + bool yes = ss->ssl_ && SSL_is_init_finished(ss->ssl_); + args.GetReturnValue().Set(yes); } -Handle Connection::VerifyError(const Arguments& args) { +void Connection::VerifyError(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); - if (ss->ssl_ == NULL) return Null(node_isolate); - + if (ss->ssl_ == NULL) { + return args.GetReturnValue().SetNull(); + } // XXX Do this check in JS land? X509* peer_cert = SSL_get_peer_certificate(ss->ssl_); @@ -1844,8 +1788,8 @@ Handle Connection::VerifyError(const Arguments& args) { // We requested a certificate and they did not send us one. // Definitely an error. // XXX is this the right error message? - return scope.Close(Exception::Error( - String::New("UNABLE_TO_GET_ISSUER_CERT"))); + return args.GetReturnValue().Set( + Exception::Error(String::New("UNABLE_TO_GET_ISSUER_CERT"))); } X509_free(peer_cert); @@ -1856,7 +1800,7 @@ Handle Connection::VerifyError(const Arguments& args) { switch (x509_verify_error) { case X509_V_OK: - return Null(node_isolate); + break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: s = String::New("UNABLE_TO_GET_ISSUER_CERT"); @@ -1971,29 +1915,33 @@ Handle Connection::VerifyError(const Arguments& args) { break; } - return scope.Close(Exception::Error(s)); + if (s.IsEmpty()) + args.GetReturnValue().SetNull(); + else + args.GetReturnValue().Set(Exception::Error(s)); } -Handle Connection::GetCurrentCipher(const Arguments& args) { +void Connection::GetCurrentCipher(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); OPENSSL_CONST SSL_CIPHER *c; - if ( ss->ssl_ == NULL ) return Undefined(node_isolate); + if (ss->ssl_ == NULL) return; c = SSL_get_current_cipher(ss->ssl_); - if ( c == NULL ) return Undefined(node_isolate); + if (c == NULL) return; Local info = Object::New(); const char* cipher_name = SSL_CIPHER_get_name(c); info->Set(name_symbol, String::New(cipher_name)); const char* cipher_version = SSL_CIPHER_get_version(c); info->Set(version_symbol, String::New(cipher_version)); - return scope.Close(info); + args.GetReturnValue().Set(info); } -Handle Connection::Close(const Arguments& args) { + +void Connection::Close(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); @@ -2002,11 +1950,11 @@ Handle Connection::Close(const Arguments& args) { SSL_free(ss->ssl_); ss->ssl_ = NULL; } - return True(node_isolate); } + #ifdef OPENSSL_NPN_NEGOTIATED -Handle Connection::GetNegotiatedProto(const Arguments& args) { +void Connection::GetNegotiatedProto(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); @@ -2018,67 +1966,57 @@ Handle Connection::GetNegotiatedProto(const Arguments& args) { SSL_get0_next_proto_negotiated(ss->ssl_, &npn_proto, &npn_proto_len); if (!npn_proto) { - return False(node_isolate); + return args.GetReturnValue().Set(false); } - return scope.Close(String::New(reinterpret_cast(npn_proto), - npn_proto_len)); + args.GetReturnValue().Set( + String::New(reinterpret_cast(npn_proto), npn_proto_len)); } else { - return ss->selectedNPNProto_; + args.GetReturnValue().Set(ss->selectedNPNProto_); } } -Handle Connection::SetNPNProtocols(const Arguments& args) { + +void Connection::SetNPNProtocols(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 1 || !Buffer::HasInstance(args[0])) { - return ThrowException(Exception::Error(String::New( - "Must give a Buffer as first argument"))); + return ThrowError("Must give a Buffer as first argument"); } - // Release old handle - if (!ss->npnProtos_.IsEmpty()) { - ss->npnProtos_.Dispose(node_isolate); - } - ss->npnProtos_ = Persistent::New(node_isolate, args[0]->ToObject()); - - return True(node_isolate); -}; + ss->npnProtos_.Reset(node_isolate, args[0].As()); +} #endif + #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB -Handle Connection::GetServername(const Arguments& args) { +void Connection::GetServername(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (ss->is_server_ && !ss->servername_.IsEmpty()) { - return ss->servername_; + args.GetReturnValue().Set(ss->servername_); } else { - return False(node_isolate); + args.GetReturnValue().Set(false); } } -Handle Connection::SetSNICallback(const Arguments& args) { + +void Connection::SetSNICallback(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Connection *ss = Connection::Unwrap(args); if (args.Length() < 1 || !args[0]->IsFunction()) { - return ThrowException(Exception::Error(String::New( - "Must give a Function as first argument"))); + return ThrowError("Must give a Function as first argument"); } - // Release old handle - if (!ss->sniObject_.IsEmpty()) { - ss->sniObject_.Dispose(node_isolate); - } - ss->sniObject_ = Persistent::New(node_isolate, Object::New()); - ss->sniObject_->Set(String::New("onselect"), args[0]); - - return True(node_isolate); + Local obj = Object::New(); + obj->Set(String::New("onselect"), args[0]); + ss->sniObject_.Reset(node_isolate, obj); } #endif @@ -2100,17 +2038,15 @@ void CipherBase::Initialize(Handle target) { } -Handle CipherBase::New(const Arguments& args) { +void CipherBase::New(const FunctionCallbackInfo& args) { + assert(args.IsConstructCall() == true); HandleScope scope(node_isolate); - CipherBase* cipher = new CipherBase(args[0]->IsTrue() ? kCipher : kDecipher); cipher->Wrap(args.This()); - return args.This(); } -Handle CipherBase::Init(char* cipher_type, - char* key_buf, - int key_buf_len) { + +void CipherBase::Init(char* cipher_type, char* key_buf, int key_buf_len) { HandleScope scope(node_isolate); assert(cipher_ == NULL); @@ -2145,11 +2081,10 @@ Handle CipherBase::Init(char* cipher_type, reinterpret_cast(iv), kind_ == kCipher); initialised_ = true; - return Null(node_isolate); } -Handle CipherBase::Init(const Arguments& args) { +void CipherBase::Init(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); CipherBase* cipher = ObjectWrap::Unwrap(args.This()); @@ -2162,23 +2097,15 @@ Handle CipherBase::Init(const Arguments& args) { String::Utf8Value cipher_type(args[0]); char* key_buf = Buffer::Data(args[1]); ssize_t key_buf_len = Buffer::Length(args[1]); - - Handle ret = cipher->Init(*cipher_type, key_buf, key_buf_len); - - if (ret->IsNull()) { - return args.This(); - } else { - // Exception - return scope.Close(ret); - } + cipher->Init(*cipher_type, key_buf, key_buf_len); } -Handle CipherBase::InitIv(char* cipher_type, - char* key, - int key_len, - char* iv, - int iv_len) { +void CipherBase::InitIv(char* cipher_type, + char* key, + int key_len, + char* iv, + int iv_len) { HandleScope scope(node_isolate); cipher_ = EVP_get_cipherbyname(cipher_type); @@ -2206,11 +2133,10 @@ Handle CipherBase::InitIv(char* cipher_type, reinterpret_cast(iv), kind_ == kCipher); initialised_ = true; - return Null(node_isolate); } -Handle CipherBase::InitIv(const Arguments& args) { +void CipherBase::InitIv(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); CipherBase* cipher = ObjectWrap::Unwrap(args.This()); @@ -2227,19 +2153,7 @@ Handle CipherBase::InitIv(const Arguments& args) { char* key_buf = Buffer::Data(args[1]); ssize_t iv_len = Buffer::Length(args[2]); char* iv_buf = Buffer::Data(args[2]); - - Handle ret = cipher->InitIv(*cipher_type, - key_buf, - key_len, - iv_buf, - iv_len); - - if (ret->IsNull()) { - return args.This(); - } else { - // Exception - return scope.Close(ret); - } + cipher->InitIv(*cipher_type, key_buf, key_len, iv_buf, iv_len); } @@ -2258,7 +2172,7 @@ bool CipherBase::Update(char* data, } -Handle CipherBase::Update(const Arguments& args) { +void CipherBase::Update(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); CipherBase* cipher = ObjectWrap::Unwrap(args.This()); @@ -2289,10 +2203,9 @@ Handle CipherBase::Update(const Arguments& args) { } Local buf = Buffer::New(reinterpret_cast(out), out_len); - if (out) delete[] out; - return scope.Close(buf); + args.GetReturnValue().Set(buf); } @@ -2302,14 +2215,10 @@ bool CipherBase::SetAutoPadding(bool auto_padding) { } -Handle CipherBase::SetAutoPadding(const Arguments& args) { +void CipherBase::SetAutoPadding(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - CipherBase* cipher = ObjectWrap::Unwrap(args.This()); - cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue()); - - return Undefined(node_isolate); } @@ -2325,7 +2234,7 @@ bool CipherBase::Final(unsigned char** out, int *out_len) { } -Handle CipherBase::Final(const Arguments& args) { +void CipherBase::Final(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); CipherBase* cipher = ObjectWrap::Unwrap(args.This()); @@ -2343,7 +2252,8 @@ Handle CipherBase::Final(const Arguments& args) { if (!r) return ThrowCryptoTypeError(ERR_get_error()); } - return scope.Close(Buffer::New(reinterpret_cast(out_value), out_len)); + args.GetReturnValue().Set( + Buffer::New(reinterpret_cast(out_value), out_len)); } @@ -2362,16 +2272,14 @@ void Hmac::Initialize(v8::Handle target) { } -Handle Hmac::New(const Arguments& args) { +void Hmac::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Hmac* hmac = new Hmac(); hmac->Wrap(args.This()); - return args.This(); } -Handle Hmac::HmacInit(char* hashType, char* key, int key_len) { +void Hmac::HmacInit(char* hashType, char* key, int key_len) { HandleScope scope(node_isolate); assert(md_ == NULL); @@ -2386,12 +2294,10 @@ Handle Hmac::HmacInit(char* hashType, char* key, int key_len) { HMAC_Init(&ctx_, key, key_len, md_); } initialised_ = true; - - return Null(node_isolate); } -Handle Hmac::HmacInit(const Arguments& args) { +void Hmac::HmacInit(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Hmac* hmac = ObjectWrap::Unwrap(args.This()); @@ -2400,22 +2306,13 @@ Handle Hmac::HmacInit(const Arguments& args) { return ThrowError("Must give hashtype string, key as arguments"); } - ASSERT_IS_BUFFER(args[1]); String::Utf8Value hashType(args[0]); char* buffer_data = Buffer::Data(args[1]); size_t buffer_length = Buffer::Length(args[1]); - - Handle ret = hmac->HmacInit(*hashType, buffer_data, buffer_length); - - if (ret->IsNull()) { - return args.This(); - } else { - // Exception - return ret; - } + hmac->HmacInit(*hashType, buffer_data, buffer_length); } @@ -2426,7 +2323,7 @@ bool Hmac::HmacUpdate(char* data, int len) { } -Handle Hmac::HmacUpdate(const Arguments& args) { +void Hmac::HmacUpdate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Hmac* hmac = ObjectWrap::Unwrap(args.This()); @@ -2451,8 +2348,6 @@ Handle Hmac::HmacUpdate(const Arguments& args) { if (!r) { return ThrowTypeError("HmacUpdate fail"); } - - return args.This(); } @@ -2466,7 +2361,7 @@ bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) { } -Handle Hmac::HmacDigest(const Arguments& args) { +void Hmac::HmacDigest(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Hmac* hmac = ObjectWrap::Unwrap(args.This()); @@ -2478,7 +2373,6 @@ Handle Hmac::HmacDigest(const Arguments& args) { unsigned char* md_value = NULL; unsigned int md_len = 0; - Local outString; bool r = hmac->HmacDigest(&md_value, &md_len); if (!r) { @@ -2486,11 +2380,10 @@ Handle Hmac::HmacDigest(const Arguments& args) { md_len = 0; } - outString = StringBytes::Encode( + Local rc = StringBytes::Encode( reinterpret_cast(md_value), md_len, encoding); - delete[] md_value; - return scope.Close(outString); + args.GetReturnValue().Set(rc); } @@ -2508,7 +2401,7 @@ void Hash::Initialize(v8::Handle target) { } -Handle Hash::New(const Arguments& args) { +void Hash::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() == 0 || !args[0]->IsString()) { @@ -2524,7 +2417,6 @@ Handle Hash::New(const Arguments& args) { } hash->Wrap(args.This()); - return args.This(); } @@ -2546,7 +2438,7 @@ bool Hash::HashUpdate(char* data, int len) { } -Handle Hash::HashUpdate(const Arguments& args) { +void Hash::HashUpdate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Hash* hash = ObjectWrap::Unwrap(args.This()); @@ -2571,12 +2463,10 @@ Handle Hash::HashUpdate(const Arguments& args) { if (!r) { return ThrowTypeError("HashUpdate fail"); } - - return args.This(); } -Handle Hash::HashDigest(const Arguments& args) { +void Hash::HashDigest(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Hash* hash = ObjectWrap::Unwrap(args.This()); @@ -2597,8 +2487,9 @@ Handle Hash::HashDigest(const Arguments& args) { EVP_MD_CTX_cleanup(&hash->mdctx_); hash->initialised_ = false; - return scope.Close(StringBytes::Encode( - reinterpret_cast(md_value), md_len, encoding)); + Local rc = StringBytes::Encode( + reinterpret_cast(md_value), md_len, encoding); + args.GetReturnValue().Set(rc); } @@ -2617,16 +2508,14 @@ void Sign::Initialize(v8::Handle target) { } -Handle Sign::New(const Arguments& args) { +void Sign::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Sign* sign = new Sign(); sign->Wrap(args.This()); - - return args.This(); } -Handle Sign::SignInit(const char* sign_type) { + +void Sign::SignInit(const char* sign_type) { HandleScope scope(node_isolate); assert(md_ == NULL); @@ -2637,11 +2526,10 @@ Handle Sign::SignInit(const char* sign_type) { EVP_MD_CTX_init(&mdctx_); EVP_SignInit_ex(&mdctx_, md_, NULL); initialised_ = true; - return Null(node_isolate); } -Handle Sign::SignInit(const Arguments& args) { +void Sign::SignInit(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Sign* sign = ObjectWrap::Unwrap(args.This()); @@ -2651,15 +2539,7 @@ Handle Sign::SignInit(const Arguments& args) { } String::Utf8Value sign_type(args[0]); - - Handle ret = sign->SignInit(*sign_type); - - if (ret->IsNull()) { - return args.This(); - } else { - // Exception - return scope.Close(ret); - } + sign->SignInit(*sign_type); } @@ -2670,7 +2550,7 @@ bool Sign::SignUpdate(char* data, int len) { } -Handle Sign::SignUpdate(const Arguments& args) { +void Sign::SignUpdate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Sign* sign = ObjectWrap::Unwrap(args.This()); @@ -2695,8 +2575,6 @@ Handle Sign::SignUpdate(const Arguments& args) { if (!r) { return ThrowTypeError("SignUpdate fail"); } - - return args.This(); } @@ -2723,14 +2601,13 @@ bool Sign::SignFinal(unsigned char** md_value, } -Handle Sign::SignFinal(const Arguments& args) { +void Sign::SignFinal(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Sign* sign = ObjectWrap::Unwrap(args.This()); unsigned char* md_value; unsigned int md_len; - Local outString; enum encoding encoding = BUFFER; if (args.Length() >= 2) { @@ -2751,11 +2628,10 @@ Handle Sign::SignFinal(const Arguments& args) { md_len = 0; } - outString = StringBytes::Encode( + Local rc = StringBytes::Encode( reinterpret_cast(md_value), md_len, encoding); - delete[] md_value; - return scope.Close(outString); + args.GetReturnValue().Set(rc); } @@ -2774,17 +2650,14 @@ void Verify::Initialize(v8::Handle target) { } -Handle Verify::New(const Arguments& args) { +void Verify::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - Verify* verify = new Verify(); verify->Wrap(args.This()); - - return args.This(); } -Handle Verify::VerifyInit(const char* verify_type) { +void Verify::VerifyInit(const char* verify_type) { HandleScope scope(node_isolate); assert(md_ == NULL); @@ -2796,12 +2669,10 @@ Handle Verify::VerifyInit(const char* verify_type) { EVP_MD_CTX_init(&mdctx_); EVP_VerifyInit_ex(&mdctx_, md_, NULL); initialised_ = true; - - return Null(node_isolate); } -Handle Verify::VerifyInit(const Arguments& args) { +void Verify::VerifyInit(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Verify* verify = ObjectWrap::Unwrap(args.This()); @@ -2811,15 +2682,7 @@ Handle Verify::VerifyInit(const Arguments& args) { } String::Utf8Value verify_type(args[0]); - - Handle ret = verify->VerifyInit(*verify_type); - - if (ret->IsNull()) { - return args.This(); - } else { - // Exception - return scope.Close(ret); - } + verify->VerifyInit(*verify_type); } @@ -2830,7 +2693,7 @@ bool Verify::VerifyUpdate(char* data, int len) { } -Handle Verify::VerifyUpdate(const Arguments& args) { +void Verify::VerifyUpdate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Verify* verify = ObjectWrap::Unwrap(args.This()); @@ -2855,26 +2718,25 @@ Handle Verify::VerifyUpdate(const Arguments& args) { if (!r) { return ThrowTypeError("VerifyUpdate fail"); } - - return args.This(); } -Handle Verify::VerifyFinal(char* key_pem, - int key_pem_len, - unsigned char* sig, - int siglen) { +bool Verify::VerifyFinal(char* key_pem, + int key_pem_len, + unsigned char* sig, + int siglen) { HandleScope scope(node_isolate); if (!initialised_) { - return ThrowError("Verify not initalised"); + ThrowError("Verify not initalised"); + return false; } EVP_PKEY* pkey = NULL; BIO* bp = NULL; X509* x509 = NULL; bool fatal = true; - int r; + int r = 0; bp = BIO_new(BIO_s_mem()); if (bp == NULL) @@ -2926,14 +2788,15 @@ exit: if (fatal) { unsigned long err = ERR_get_error(); - return ThrowCryptoError(err); + ThrowCryptoError(err); + return false; } - return scope.Close(r ? True(node_isolate) : False(node_isolate)); + return r == 1; } -Handle Verify::VerifyFinal(const Arguments& args) { +void Verify::VerifyFinal(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Verify* verify = ObjectWrap::Unwrap(args.This()); @@ -2951,7 +2814,6 @@ Handle Verify::VerifyFinal(const Arguments& args) { ssize_t hlen = StringBytes::Size(args[1], encoding); - // only copy if we need to, because it's a string. unsigned char* hbuf; if (args[1]->IsString()) { @@ -2963,11 +2825,11 @@ Handle Verify::VerifyFinal(const Arguments& args) { hbuf = reinterpret_cast(Buffer::Data(args[1])); } - Local retval = Local::New(verify->VerifyFinal(kbuf, klen, hbuf, hlen)); + bool rc = verify->VerifyFinal(kbuf, klen, hbuf, hlen); if (args[1]->IsString()) { delete[] hbuf; } - return scope.Close(retval); + args.GetReturnValue().Set(rc); } @@ -3037,7 +2899,8 @@ bool DiffieHellman::Init(unsigned char* p, } -Handle DiffieHellman::DiffieHellmanGroup(const Arguments& args) { +void DiffieHellman::DiffieHellmanGroup( + const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = new DiffieHellman(); @@ -3066,12 +2929,10 @@ Handle DiffieHellman::DiffieHellmanGroup(const Arguments& args) { } diffieHellman->Wrap(args.This()); - - return args.This(); } -Handle DiffieHellman::New(const Arguments& args) { +void DiffieHellman::New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = new DiffieHellman(); @@ -3092,12 +2953,10 @@ Handle DiffieHellman::New(const Arguments& args) { } diffieHellman->Wrap(args.This()); - - return args.This(); } -Handle DiffieHellman::GenerateKeys(const Arguments& args) { +void DiffieHellman::GenerateKeys(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3111,21 +2970,17 @@ Handle DiffieHellman::GenerateKeys(const Arguments& args) { return ThrowError("Key generation failed"); } - Local outString; - int dataSize = BN_num_bytes(diffieHellman->dh->pub_key); char* data = new char[dataSize]; BN_bn2bin(diffieHellman->dh->pub_key, reinterpret_cast(data)); - outString = Encode(data, dataSize, BUFFER); + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - - return scope.Close(outString); } -Handle DiffieHellman::GetPrime(const Arguments& args) { +void DiffieHellman::GetPrime(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3139,17 +2994,12 @@ Handle DiffieHellman::GetPrime(const Arguments& args) { char* data = new char[dataSize]; BN_bn2bin(diffieHellman->dh->p, reinterpret_cast(data)); - Local outString; - - outString = Encode(data, dataSize, BUFFER); - + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - - return scope.Close(outString); } -Handle DiffieHellman::GetGenerator(const Arguments& args) { +void DiffieHellman::GetGenerator(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3163,17 +3013,12 @@ Handle DiffieHellman::GetGenerator(const Arguments& args) { char* data = new char[dataSize]; BN_bn2bin(diffieHellman->dh->g, reinterpret_cast(data)); - Local outString; - - outString = Encode(data, dataSize, BUFFER); - + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - - return scope.Close(outString); } -Handle DiffieHellman::GetPublicKey(const Arguments& args) { +void DiffieHellman::GetPublicKey(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3192,17 +3037,12 @@ Handle DiffieHellman::GetPublicKey(const Arguments& args) { BN_bn2bin(diffieHellman->dh->pub_key, reinterpret_cast(data)); - Local outString; - - outString = Encode(data, dataSize, BUFFER); - + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - - return scope.Close(outString); } -Handle DiffieHellman::GetPrivateKey(const Arguments& args) { +void DiffieHellman::GetPrivateKey(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3221,17 +3061,12 @@ Handle DiffieHellman::GetPrivateKey(const Arguments& args) { BN_bn2bin(diffieHellman->dh->priv_key, reinterpret_cast(data)); - Local outString; - - outString = Encode(data, dataSize, BUFFER); - + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - - return scope.Close(outString); } -Handle DiffieHellman::ComputeSecret(const Arguments& args) { +void DiffieHellman::ComputeSecret(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3298,16 +3133,12 @@ Handle DiffieHellman::ComputeSecret(const Arguments& args) { memset(data, 0, dataSize - size); } - Local outString; - - outString = Encode(data, dataSize, BUFFER); - + args.GetReturnValue().Set(Encode(data, dataSize, BUFFER)); delete[] data; - return scope.Close(outString); } -Handle DiffieHellman::SetPublicKey(const Arguments& args) { +void DiffieHellman::SetPublicKey(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3325,12 +3156,10 @@ Handle DiffieHellman::SetPublicKey(const Arguments& args) { reinterpret_cast(Buffer::Data(args[0])), Buffer::Length(args[0]), 0); } - - return args.This(); } -Handle DiffieHellman::SetPrivateKey(const Arguments& args) { +void DiffieHellman::SetPrivateKey(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); DiffieHellman* diffieHellman = @@ -3349,8 +3178,6 @@ Handle DiffieHellman::SetPrivateKey(const Arguments& args) { Buffer::Length(args[0]), 0); } - - return args.This(); } @@ -3420,15 +3247,15 @@ void EIO_PBKDF2After(uv_work_t* work_req, int status) { assert(status == 0); pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req); HandleScope scope(node_isolate); + Local obj = Local::New(node_isolate, req->obj); + req->obj.Dispose(); Local argv[2]; - Persistent obj = req->obj; EIO_PBKDF2After(req, argv); MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv); - obj.Dispose(node_isolate); } -Handle PBKDF2(const Arguments& args) { +void PBKDF2(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); const char* type_error = NULL; @@ -3502,25 +3329,28 @@ Handle PBKDF2(const Arguments& args) { req->keylen = keylen; if (args[4]->IsFunction()) { - req->obj = Persistent::New(node_isolate, Object::New()); - req->obj->Set(String::New("ondone"), args[4]); + Local obj = Object::New(); + obj->Set(String::New("ondone"), args[4]); + req->obj.Reset(node_isolate, obj); uv_queue_work(uv_default_loop(), &req->work_req, EIO_PBKDF2, EIO_PBKDF2After); - return Undefined(node_isolate); } else { Local argv[2]; EIO_PBKDF2(req); EIO_PBKDF2After(req, argv); - if (argv[0]->IsObject()) return ThrowException(argv[0]); - return scope.Close(argv[1]); + if (argv[0]->IsObject()) + ThrowException(argv[0]); + else + args.GetReturnValue().Set(argv[1]); } + return; err: delete[] salt; delete[] pass; - return ThrowException(Exception::TypeError(String::New(type_error))); + return ThrowTypeError(type_error); } @@ -3535,9 +3365,7 @@ struct RandomBytesRequest { RandomBytesRequest::~RandomBytesRequest() { - if (obj_.IsEmpty()) return; - obj_.Dispose(node_isolate); - obj_.Clear(); + obj_.Dispose(); } @@ -3597,7 +3425,7 @@ void RandomBytesAfter(uv_work_t* work_req, int status) { template -Handle RandomBytes(const Arguments& args) { +void RandomBytes(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); // maybe allow a buffer to write to? cuts down on object creation @@ -3617,15 +3445,15 @@ Handle RandomBytes(const Arguments& args) { req->size_ = size; if (args[1]->IsFunction()) { - req->obj_ = Persistent::New(node_isolate, Object::New()); - req->obj_->Set(String::New("ondone"), args[1]); + Local obj = Object::New(); + obj->Set(String::New("ondone"), args[1]); + req->obj_.Reset(node_isolate, obj); uv_queue_work(uv_default_loop(), &req->work_req_, RandomBytesWork, RandomBytesAfter); - - return req->obj_; + args.GetReturnValue().Set(obj); } else { Local argv[2]; @@ -3634,14 +3462,14 @@ Handle RandomBytes(const Arguments& args) { delete req; if (!argv[0]->IsNull()) - return ThrowException(argv[0]); + ThrowException(argv[0]); else - return argv[1]; + args.GetReturnValue().Set(argv[1]); } } -Handle GetSSLCiphers(const Arguments& args) { +void GetSSLCiphers(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method()); @@ -3666,7 +3494,7 @@ Handle GetSSLCiphers(const Arguments& args) { SSL_free(ssl); SSL_CTX_free(ctx); - return scope.Close(arr); + args.GetReturnValue().Set(arr); } @@ -3680,19 +3508,19 @@ static void array_push_back(const TypeName* md, } -Handle GetCiphers(const Arguments& args) { +void GetCiphers(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local arr = Array::New(); EVP_CIPHER_do_all_sorted(array_push_back, &arr); - return scope.Close(arr); + args.GetReturnValue().Set(arr); } -Handle GetHashes(const Arguments& args) { +void GetHashes(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Local arr = Array::New(); EVP_MD_do_all_sorted(array_push_back, &arr); - return scope.Close(arr); + args.GetReturnValue().Set(arr); } @@ -3738,17 +3566,17 @@ void InitCrypto(Handle target) { NODE_SET_METHOD(target, "getCiphers", GetCiphers); NODE_SET_METHOD(target, "getHashes", GetHashes); - subject_symbol = NODE_PSYMBOL("subject"); - issuer_symbol = NODE_PSYMBOL("issuer"); - valid_from_symbol = NODE_PSYMBOL("valid_from"); - valid_to_symbol = NODE_PSYMBOL("valid_to"); - subjectaltname_symbol = NODE_PSYMBOL("subjectaltname"); - modulus_symbol = NODE_PSYMBOL("modulus"); - exponent_symbol = NODE_PSYMBOL("exponent"); - fingerprint_symbol = NODE_PSYMBOL("fingerprint"); - name_symbol = NODE_PSYMBOL("name"); - version_symbol = NODE_PSYMBOL("version"); - ext_key_usage_symbol = NODE_PSYMBOL("ext_key_usage"); + subject_symbol = String::New("subject"); + issuer_symbol = String::New("issuer"); + valid_from_symbol = String::New("valid_from"); + valid_to_symbol = String::New("valid_to"); + subjectaltname_symbol = String::New("subjectaltname"); + modulus_symbol = String::New("modulus"); + exponent_symbol = String::New("exponent"); + fingerprint_symbol = String::New("fingerprint"); + name_symbol = String::New("name"); + version_symbol = String::New("version"); + ext_key_usage_symbol = String::New("ext_key_usage"); } } // namespace crypto diff --git a/src/node_crypto.h b/src/node_crypto.h index c3c4a89a859..727b7868cbf 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -64,19 +64,21 @@ class SecureContext : ObjectWrap { protected: - static v8::Handle New(const v8::Arguments& args); - static v8::Handle Init(const v8::Arguments& args); - static v8::Handle SetKey(const v8::Arguments& args); - static v8::Handle SetCert(const v8::Arguments& args); - static v8::Handle AddCACert(const v8::Arguments& args); - static v8::Handle AddCRL(const v8::Arguments& args); - static v8::Handle AddRootCerts(const v8::Arguments& args); - static v8::Handle SetCiphers(const v8::Arguments& args); - static v8::Handle SetOptions(const v8::Arguments& args); - static v8::Handle SetSessionIdContext(const v8::Arguments& args); - static v8::Handle SetSessionTimeout(const v8::Arguments& args); - static v8::Handle Close(const v8::Arguments& args); - static v8::Handle LoadPKCS12(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void Init(const v8::FunctionCallbackInfo& args); + static void SetKey(const v8::FunctionCallbackInfo& args); + static void SetCert(const v8::FunctionCallbackInfo& args); + static void AddCACert(const v8::FunctionCallbackInfo& args); + static void AddCRL(const v8::FunctionCallbackInfo& args); + static void AddRootCerts(const v8::FunctionCallbackInfo& args); + static void SetCiphers(const v8::FunctionCallbackInfo& args); + static void SetOptions(const v8::FunctionCallbackInfo& args); + static void SetSessionIdContext( + const v8::FunctionCallbackInfo& args); + static void SetSessionTimeout( + const v8::FunctionCallbackInfo& args); + static void Close(const v8::FunctionCallbackInfo& args); + static void LoadPKCS12(const v8::FunctionCallbackInfo& args); static SSL_SESSION* GetSessionCallback(SSL* s, unsigned char* key, @@ -172,48 +174,52 @@ class Connection : ObjectWrap { #endif protected: - static v8::Handle New(const v8::Arguments& args); - static v8::Handle EncIn(const v8::Arguments& args); - static v8::Handle ClearOut(const v8::Arguments& args); - static v8::Handle ClearPending(const v8::Arguments& args); - static v8::Handle EncPending(const v8::Arguments& args); - static v8::Handle EncOut(const v8::Arguments& args); - static v8::Handle ClearIn(const v8::Arguments& args); - static v8::Handle GetPeerCertificate(const v8::Arguments& args); - static v8::Handle GetSession(const v8::Arguments& args); - static v8::Handle SetSession(const v8::Arguments& args); - static v8::Handle LoadSession(const v8::Arguments& args); - static v8::Handle IsSessionReused(const v8::Arguments& args); - static v8::Handle IsInitFinished(const v8::Arguments& args); - static v8::Handle VerifyError(const v8::Arguments& args); - static v8::Handle GetCurrentCipher(const v8::Arguments& args); - static v8::Handle Shutdown(const v8::Arguments& args); - static v8::Handle ReceivedShutdown(const v8::Arguments& args); - static v8::Handle Start(const v8::Arguments& args); - static v8::Handle Close(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void EncIn(const v8::FunctionCallbackInfo& args); + static void ClearOut(const v8::FunctionCallbackInfo& args); + static void ClearPending(const v8::FunctionCallbackInfo& args); + static void EncPending(const v8::FunctionCallbackInfo& args); + static void EncOut(const v8::FunctionCallbackInfo& args); + static void ClearIn(const v8::FunctionCallbackInfo& args); + static void GetPeerCertificate( + const v8::FunctionCallbackInfo& args); + static void GetSession(const v8::FunctionCallbackInfo& args); + static void SetSession(const v8::FunctionCallbackInfo& args); + static void LoadSession(const v8::FunctionCallbackInfo& args); + static void IsSessionReused(const v8::FunctionCallbackInfo& args); + static void IsInitFinished(const v8::FunctionCallbackInfo& args); + static void VerifyError(const v8::FunctionCallbackInfo& args); + static void GetCurrentCipher(const v8::FunctionCallbackInfo& args); + static void Shutdown(const v8::FunctionCallbackInfo& args); + static void ReceivedShutdown(const v8::FunctionCallbackInfo& args); + static void Start(const v8::FunctionCallbackInfo& args); + static void Close(const v8::FunctionCallbackInfo& args); #ifdef OPENSSL_NPN_NEGOTIATED // NPN - static v8::Handle GetNegotiatedProto(const v8::Arguments& args); - static v8::Handle SetNPNProtocols(const v8::Arguments& args); - static int AdvertiseNextProtoCallback_(SSL *s, - const unsigned char **data, - unsigned int *len, - void *arg); - static int SelectNextProtoCallback_(SSL *s, - unsigned char **out, unsigned char *outlen, + static void GetNegotiatedProto( + const v8::FunctionCallbackInfo& args); + static void SetNPNProtocols(const v8::FunctionCallbackInfo& args); + static int AdvertiseNextProtoCallback_(SSL* s, + const unsigned char** data, + unsigned int* len, + void* arg); + static int SelectNextProtoCallback_(SSL* s, + unsigned char** out, + unsigned char* outlen, const unsigned char* in, - unsigned int inlen, void *arg); + unsigned int inlen, + void* arg); #endif #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB // SNI - static v8::Handle GetServername(const v8::Arguments& args); - static v8::Handle SetSNICallback(const v8::Arguments& args); - static int SelectSNIContextCallback_(SSL *s, int *ad, void* arg); + static void GetServername(const v8::FunctionCallbackInfo& args); + static void SetSNICallback(const v8::FunctionCallbackInfo& args); + static int SelectSNIContextCallback_(SSL* s, int* ad, void* arg); #endif - int HandleBIOError(BIO *bio, const char* func, int rv); + int HandleBIOError(BIO* bio, const char* func, int rv); enum ZeroStatus { kZeroIsNotAnError, @@ -230,7 +236,7 @@ class Connection : ObjectWrap { void ClearError(); void SetShutdownFlags(); - static Connection* Unwrap(const v8::Arguments& args) { + static Connection* Unwrap(const v8::FunctionCallbackInfo& args) { Connection* ss = ObjectWrap::Unwrap(args.This()); ss->ClearError(); return ss; @@ -254,14 +260,14 @@ class Connection : ObjectWrap { } #ifdef OPENSSL_NPN_NEGOTIATED - if (!npnProtos_.IsEmpty()) npnProtos_.Dispose(node_isolate); - if (!selectedNPNProto_.IsEmpty()) selectedNPNProto_.Dispose(node_isolate); + npnProtos_.Dispose(); + selectedNPNProto_.Dispose(); #endif #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB - if (!sniObject_.IsEmpty()) sniObject_.Dispose(node_isolate); - if (!sniContext_.IsEmpty()) sniContext_.Dispose(node_isolate); - if (!servername_.IsEmpty()) servername_.Dispose(node_isolate); + sniObject_.Dispose(); + sniContext_.Dispose(); + servername_.Dispose(); #endif } @@ -291,22 +297,18 @@ class CipherBase : public ObjectWrap { kDecipher }; - v8::Handle Init(char* cipher_type, char* key_buf, int key_buf_len); - v8::Handle InitIv(char* cipher_type, - char* key, - int key_len, - char* iv, - int iv_len); + void Init(char* cipher_type, char* key_buf, int key_buf_len); + void InitIv(char* cipher_type, char* key, int key_len, char* iv, int iv_len); bool Update(char* data, int len, unsigned char** out, int* out_len); bool Final(unsigned char** out, int *out_len); bool SetAutoPadding(bool auto_padding); - static v8::Handle New(const v8::Arguments& args); - static v8::Handle Init(const v8::Arguments& args); - static v8::Handle InitIv(const v8::Arguments& args); - static v8::Handle Update(const v8::Arguments& args); - static v8::Handle Final(const v8::Arguments& args); - static v8::Handle SetAutoPadding(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void Init(const v8::FunctionCallbackInfo& args); + static void InitIv(const v8::FunctionCallbackInfo& args); + static void Update(const v8::FunctionCallbackInfo& args); + static void Final(const v8::FunctionCallbackInfo& args); + static void SetAutoPadding(const v8::FunctionCallbackInfo& args); CipherBase(CipherKind kind) : cipher_(NULL), initialised_(false), @@ -330,14 +332,14 @@ class Hmac : public ObjectWrap { static void Initialize (v8::Handle target); protected: - v8::Handle HmacInit(char* hashType, char* key, int key_len); + void HmacInit(char* hashType, char* key, int key_len); bool HmacUpdate(char* data, int len); bool HmacDigest(unsigned char** md_value, unsigned int* md_len); - static v8::Handle New(const v8::Arguments& args); - static v8::Handle HmacInit(const v8::Arguments& args); - static v8::Handle HmacUpdate(const v8::Arguments& args); - static v8::Handle HmacDigest(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void HmacInit(const v8::FunctionCallbackInfo& args); + static void HmacUpdate(const v8::FunctionCallbackInfo& args); + static void HmacDigest(const v8::FunctionCallbackInfo& args); Hmac() : md_(NULL), initialised_(false) { } @@ -361,9 +363,9 @@ class Hash : public ObjectWrap { bool HashUpdate(char* data, int len); protected: - static v8::Handle New(const v8::Arguments& args); - static v8::Handle HashUpdate(const v8::Arguments& args); - static v8::Handle HashDigest(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void HashUpdate(const v8::FunctionCallbackInfo& args); + static void HashDigest(const v8::FunctionCallbackInfo& args); Hash() : md_(NULL), initialised_(false) { } @@ -383,7 +385,7 @@ class Sign : public ObjectWrap { public: static void Initialize(v8::Handle target); - v8::Handle SignInit(const char* sign_type); + void SignInit(const char* sign_type); bool SignUpdate(char* data, int len); bool SignFinal(unsigned char** md_value, unsigned int *md_len, @@ -391,10 +393,10 @@ class Sign : public ObjectWrap { int key_pem_len); protected: - static v8::Handle New(const v8::Arguments& args); - static v8::Handle SignInit(const v8::Arguments& args); - static v8::Handle SignUpdate(const v8::Arguments& args); - static v8::Handle SignFinal(const v8::Arguments& args); + static void New(const v8::FunctionCallbackInfo& args); + static void SignInit(const v8::FunctionCallbackInfo& args); + static void SignUpdate(const v8::FunctionCallbackInfo& args); + static void SignFinal(const v8::FunctionCallbackInfo& args); Sign() : md_(NULL), initialised_(false) { } @@ -414,18 +416,18 @@ class Verify : public ObjectWrap { public: static void Initialize (v8::Handle target); - v8::Handle VerifyInit(const char* verify_type); + void VerifyInit(const char* verify_type); bool VerifyUpdate(char* data, int len); - v8::Handle VerifyFinal(char* key_pem, - int key_pem_len, - unsigned char* sig, - int siglen); + bool VerifyFinal(char* key_pem, + int key_pem_len, + unsigned char* sig, + int siglen); protected: - static v8::Handle New (const v8::Arguments& args); - static v8::Handle VerifyInit(const v8::Arguments& args); - static v8::Handle VerifyUpdate(const v8::Arguments& args); - static v8::Handle VerifyFinal(const v8::Arguments& args); + static void New (const v8::FunctionCallbackInfo& args); + static void VerifyInit(const v8::FunctionCallbackInfo& args); + static void VerifyUpdate(const v8::FunctionCallbackInfo& args); + static void VerifyFinal(const v8::FunctionCallbackInfo& args); Verify() : md_(NULL), initialised_(false) { } @@ -451,16 +453,17 @@ class DiffieHellman : public ObjectWrap { bool Init(unsigned char* p, int p_len, unsigned char* g, int g_len); protected: - static v8::Handle DiffieHellmanGroup(const v8::Arguments& args); - static v8::Handle New(const v8::Arguments& args); - static v8::Handle GenerateKeys(const v8::Arguments& args); - static v8::Handle GetPrime(const v8::Arguments& args); - static v8::Handle GetGenerator(const v8::Arguments& args); - static v8::Handle GetPublicKey(const v8::Arguments& args); - static v8::Handle GetPrivateKey(const v8::Arguments& args); - static v8::Handle ComputeSecret(const v8::Arguments& args); - static v8::Handle SetPublicKey(const v8::Arguments& args); - static v8::Handle SetPrivateKey(const v8::Arguments& args); + static void DiffieHellmanGroup( + const v8::FunctionCallbackInfo& args); + static void New(const v8::FunctionCallbackInfo& args); + static void GenerateKeys(const v8::FunctionCallbackInfo& args); + static void GetPrime(const v8::FunctionCallbackInfo& args); + static void GetGenerator(const v8::FunctionCallbackInfo& args); + static void GetPublicKey(const v8::FunctionCallbackInfo& args); + static void GetPrivateKey(const v8::FunctionCallbackInfo& args); + static void ComputeSecret(const v8::FunctionCallbackInfo& args); + static void SetPublicKey(const v8::FunctionCallbackInfo& args); + static void SetPrivateKey(const v8::FunctionCallbackInfo& args); DiffieHellman() : ObjectWrap(), initialised_(false), dh(NULL) { } diff --git a/src/node_dtrace.cc b/src/node_dtrace.cc index 4fb4fcd44fc..b7b0822c37e 100644 --- a/src/node_dtrace.cc +++ b/src/node_dtrace.cc @@ -59,12 +59,23 @@ namespace node { -using namespace v8; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::GCCallbackFlags; +using v8::GCEpilogueCallback; +using v8::GCPrologueCallback; +using v8::GCType; +using v8::Handle; +using v8::HandleScope; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; #define SLURP_STRING(obj, member, valp) \ if (!(obj)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "object for " #obj " to contain string member " #member)))); \ + return ThrowError( \ + "expected object for " #obj " to contain string member " #member); \ } \ String::Utf8Value _##member(obj->Get(String::New(#member))); \ if ((*(const char **)valp = *_##member) == NULL) \ @@ -72,22 +83,22 @@ using namespace v8; #define SLURP_INT(obj, member, valp) \ if (!(obj)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "object for " #obj " to contain integer member " #member)))); \ + return ThrowError( \ + "expected object for " #obj " to contain integer member " #member); \ } \ *valp = obj->Get(String::New(#member))->ToInteger()->Value(); #define SLURP_OBJECT(obj, member, valp) \ if (!(obj)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "object for " #obj " to contain object member " #member)))); \ + return ThrowError( \ + "expected object for " #obj " to contain object member " #member); \ } \ *valp = Local::Cast(obj->Get(String::New(#member))); #define SLURP_CONNECTION(arg, conn) \ if (!(arg)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "argument " #arg " to be a connection object")))); \ + return ThrowError( \ + "expected argument " #arg " to be a connection object"); \ } \ node_dtrace_connection_t conn; \ Local _##conn = Local::Cast(arg); \ @@ -103,8 +114,8 @@ using namespace v8; #define SLURP_CONNECTION_HTTP_CLIENT(arg, conn) \ if (!(arg)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "argument " #arg " to be a connection object")))); \ + return ThrowError( \ + "expected argument " #arg " to be a connection object"); \ } \ node_dtrace_connection_t conn; \ Local _##conn = Local::Cast(arg); \ @@ -115,12 +126,12 @@ using namespace v8; #define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn) \ if (!(arg0)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "argument " #arg0 " to be a connection object")))); \ + return ThrowError( \ + "expected argument " #arg0 " to be a connection object"); \ } \ if (!(arg1)->IsObject()) { \ - return (ThrowException(Exception::Error(String::New("expected " \ - "argument " #arg1 " to be a connection object")))); \ + return ThrowError( \ + "expected argument " #arg1 " to be a connection object"); \ } \ node_dtrace_connection_t conn; \ Local _##conn = Local::Cast(arg0); \ @@ -131,86 +142,71 @@ using namespace v8; SLURP_INT(_##conn, port, &conn.port); -Handle DTRACE_NET_SERVER_CONNECTION(const Arguments& args) { +void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_NET_SERVER_CONNECTION_ENABLED()) - return Undefined(node_isolate); + return; #endif - HandleScope scope(node_isolate); - SLURP_CONNECTION(args[0], conn); - NODE_NET_SERVER_CONNECTION(&conn, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_NET_STREAM_END(const Arguments& args) { + +void DTRACE_NET_STREAM_END(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_NET_STREAM_END_ENABLED()) - return Undefined(node_isolate); + return; #endif - HandleScope scope(node_isolate); - SLURP_CONNECTION(args[0], conn); - NODE_NET_STREAM_END(&conn, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_NET_SOCKET_READ(const Arguments& args) { + +void DTRACE_NET_SOCKET_READ(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_NET_SOCKET_READ_ENABLED()) - return Undefined(node_isolate); + return; #endif - HandleScope scope(node_isolate); - SLURP_CONNECTION(args[0], conn); if (!args[1]->IsNumber()) { - return (ThrowException(Exception::Error(String::New("expected " - "argument 1 to be number of bytes")))); + return ThrowError("expected argument 1 to be number of bytes"); } + int nbytes = args[1]->Int32Value(); NODE_NET_SOCKET_READ(&conn, nbytes, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_NET_SOCKET_WRITE(const Arguments& args) { + +void DTRACE_NET_SOCKET_WRITE(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_NET_SOCKET_WRITE_ENABLED()) - return Undefined(node_isolate); + return; #endif - HandleScope scope(node_isolate); - SLURP_CONNECTION(args[0], conn); if (!args[1]->IsNumber()) { - return (ThrowException(Exception::Error(String::New("expected " - "argument 1 to be number of bytes")))); + return ThrowError("expected argument 1 to be number of bytes"); } + int nbytes = args[1]->Int32Value(); NODE_NET_SOCKET_WRITE(&conn, nbytes, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_HTTP_SERVER_REQUEST(const Arguments& args) { + +void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo& args) { node_dtrace_http_server_request_t req; #ifndef HAVE_SYSTEMTAP if (!NODE_HTTP_SERVER_REQUEST_ENABLED()) - return Undefined(node_isolate); + return; #endif HandleScope scope(node_isolate); - Local arg0 = Local::Cast(args[0]); Local headers; @@ -218,12 +214,12 @@ Handle DTRACE_HTTP_SERVER_REQUEST(const Arguments& args) { req._un.version = 1; SLURP_STRING(arg0, url, &req.url); SLURP_STRING(arg0, method, &req.method); - SLURP_OBJECT(arg0, headers, &headers); - if (!(headers)->IsObject()) - return (ThrowException(Exception::Error(String::New("expected " - "object for request to contain string member headers")))); + if (!(headers)->IsObject()) { + return ThrowError( + "expected object for request to contain string member headers"); + } Local strfwdfor = headers->Get(String::New("x-forwarded-for")); String::Utf8Value fwdfor(strfwdfor); @@ -232,35 +228,29 @@ Handle DTRACE_HTTP_SERVER_REQUEST(const Arguments& args) { req.forwardedFor = const_cast(""); SLURP_CONNECTION(args[1], conn); - NODE_HTTP_SERVER_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \ req.url, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_HTTP_SERVER_RESPONSE(const Arguments& args) { + +void DTRACE_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_HTTP_SERVER_RESPONSE_ENABLED()) - return Undefined(node_isolate); + return; #endif - HandleScope scope(node_isolate); - SLURP_CONNECTION(args[0], conn); - NODE_HTTP_SERVER_RESPONSE(&conn, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_HTTP_CLIENT_REQUEST(const Arguments& args) { + +void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo& args) { node_dtrace_http_client_request_t req; char *header; #ifndef HAVE_SYSTEMTAP if (!NODE_HTTP_CLIENT_REQUEST_ENABLED()) - return Undefined(node_isolate); + return; #endif HandleScope scope(node_isolate); @@ -290,28 +280,21 @@ Handle DTRACE_HTTP_CLIENT_REQUEST(const Arguments& args) { *header = '\0'; SLURP_CONNECTION_HTTP_CLIENT(args[1], conn); - NODE_HTTP_CLIENT_REQUEST(&req, &conn, conn.remote, conn.port, req.method, \ req.url, conn.fd); - - return Undefined(node_isolate); } -Handle DTRACE_HTTP_CLIENT_RESPONSE(const Arguments& args) { + +void DTRACE_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo& args) { #ifndef HAVE_SYSTEMTAP if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED()) - return Undefined(node_isolate); + return; #endif HandleScope scope(node_isolate); - SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(args[0], args[1], conn); - NODE_HTTP_CLIENT_RESPONSE(&conn, conn.remote, conn.port, conn.fd); - - return Undefined(node_isolate); } -#define NODE_PROBE(name) #name, name, Persistent() static int dtrace_gc_start(GCType type, GCCallbackFlags flags) { NODE_GC_START(type, flags); @@ -322,17 +305,21 @@ static int dtrace_gc_start(GCType type, GCCallbackFlags flags) { return 0; } + static int dtrace_gc_done(GCType type, GCCallbackFlags flags) { NODE_GC_DONE(type, flags); return 0; } + void InitDTrace(Handle target) { + HandleScope scope(node_isolate); + static struct { const char *name; - Handle (*func)(const Arguments&); - Persistent templ; + void (*func)(const FunctionCallbackInfo&); } tab[] = { +#define NODE_PROBE(name) #name, name { NODE_PROBE(DTRACE_NET_SERVER_CONNECTION) }, { NODE_PROBE(DTRACE_NET_STREAM_END) }, { NODE_PROBE(DTRACE_NET_SOCKET_READ) }, @@ -341,12 +328,13 @@ void InitDTrace(Handle target) { { NODE_PROBE(DTRACE_HTTP_SERVER_RESPONSE) }, { NODE_PROBE(DTRACE_HTTP_CLIENT_REQUEST) }, { NODE_PROBE(DTRACE_HTTP_CLIENT_RESPONSE) } +#undef NODE_PROBE }; for (unsigned int i = 0; i < ARRAY_SIZE(tab); i++) { - tab[i].templ = Persistent::New(node_isolate, - FunctionTemplate::New(tab[i].func)); - target->Set(String::NewSymbol(tab[i].name), tab[i].templ->GetFunction()); + Local key = String::New(tab[i].name); + Local val = FunctionTemplate::New(tab[i].func)->GetFunction(); + target->Set(key, val); } #ifdef HAVE_ETW diff --git a/src/node_file.cc b/src/node_file.cc index 69b76736c34..68eb668d811 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -39,12 +39,23 @@ namespace node { -using namespace v8; +using v8::Array; +using v8::Function; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::Handle; +using v8::HandleScope; +using v8::Integer; +using v8::Local; +using v8::Number; +using v8::Object; +using v8::Persistent; +using v8::String; +using v8::Value; #define MIN(a,b) ((a) < (b) ? (a) : (b)) -#define TYPE_ERROR(msg) \ - ThrowException(Exception::TypeError(String::New(msg))); +#define TYPE_ERROR(msg) ThrowTypeError(msg) #define THROW_BAD_ARGS TYPE_ERROR("Bad argument") @@ -61,16 +72,16 @@ class FSReqWrap: public ReqWrap { }; -static Persistent oncomplete_sym; +static Cached oncomplete_sym; #define ASSERT_OFFSET(a) \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ - return ThrowException(Exception::TypeError(String::New("Not an integer"))); \ + return ThrowTypeError("Not an integer"); \ } #define ASSERT_TRUNCATE_LENGTH(a) \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ - return ThrowException(Exception::TypeError(String::New("Not an integer"))); \ + return ThrowTypeError("Not an integer"); \ } #define GET_OFFSET(a) ((a)->IsNumber() ? (a)->IntegerValue() : -1) #define GET_TRUNCATE_LENGTH(a) ((a)->IntegerValue()) @@ -192,9 +203,9 @@ static void After(uv_fs_t *req) { } if (oncomplete_sym.IsEmpty()) { - oncomplete_sym = NODE_PSYMBOL("oncomplete"); + oncomplete_sym = String::New("oncomplete"); } - MakeCallback(req_wrap->object_, oncomplete_sym, argc, argv); + MakeCallback(req_wrap->object(), oncomplete_sym, argc, argv); uv_fs_req_cleanup(&req_wrap->req_); delete req_wrap; @@ -216,7 +227,7 @@ struct fs_req_wrap { FSReqWrap* req_wrap = new FSReqWrap(#func); \ int r = uv_fs_##func(uv_default_loop(), &req_wrap->req_, \ __VA_ARGS__, After); \ - req_wrap->object_->Set(oncomplete_sym, callback); \ + req_wrap->object()->Set(oncomplete_sym, callback); \ req_wrap->Dispatched(); \ if (r < 0) { \ uv_fs_t* req = &req_wrap->req_; \ @@ -225,14 +236,14 @@ struct fs_req_wrap { req->errorno = uv_last_error(uv_default_loop()).code; \ After(req); \ } \ - return scope.Close(req_wrap->object_); + args.GetReturnValue().Set(req_wrap->persistent()); #define SYNC_CALL(func, path, ...) \ fs_req_wrap req_wrap; \ int result = uv_fs_##func(uv_default_loop(), &req_wrap.req, __VA_ARGS__, NULL); \ if (result < 0) { \ int code = uv_last_error(uv_default_loop()).code; \ - return ThrowException(UVException(code, #func, "", path)); \ + return ThrowUVException(code, #func, "", path); \ } #define SYNC_REQ req_wrap.req @@ -240,7 +251,7 @@ struct fs_req_wrap { #define SYNC_RESULT result -static Handle Close(const Arguments& args) { +static void Close(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1 || !args[0]->IsInt32()) { @@ -253,49 +264,49 @@ static Handle Close(const Arguments& args) { ASYNC_CALL(close, args[1], fd) } else { SYNC_CALL(close, 0, fd) - return Undefined(node_isolate); } } -static Persistent stats_constructor_template; +static Persistent stats_constructor; -static Persistent dev_symbol; -static Persistent ino_symbol; -static Persistent mode_symbol; -static Persistent nlink_symbol; -static Persistent uid_symbol; -static Persistent gid_symbol; -static Persistent rdev_symbol; -static Persistent size_symbol; -static Persistent blksize_symbol; -static Persistent blocks_symbol; -static Persistent atime_symbol; -static Persistent mtime_symbol; -static Persistent ctime_symbol; +static Cached dev_symbol; +static Cached ino_symbol; +static Cached mode_symbol; +static Cached nlink_symbol; +static Cached uid_symbol; +static Cached gid_symbol; +static Cached rdev_symbol; +static Cached size_symbol; +static Cached blksize_symbol; +static Cached blocks_symbol; +static Cached atime_symbol; +static Cached mtime_symbol; +static Cached ctime_symbol; Local BuildStatsObject(const uv_stat_t* s) { HandleScope scope(node_isolate); if (dev_symbol.IsEmpty()) { - dev_symbol = NODE_PSYMBOL("dev"); - ino_symbol = NODE_PSYMBOL("ino"); - mode_symbol = NODE_PSYMBOL("mode"); - nlink_symbol = NODE_PSYMBOL("nlink"); - uid_symbol = NODE_PSYMBOL("uid"); - gid_symbol = NODE_PSYMBOL("gid"); - rdev_symbol = NODE_PSYMBOL("rdev"); - size_symbol = NODE_PSYMBOL("size"); - blksize_symbol = NODE_PSYMBOL("blksize"); - blocks_symbol = NODE_PSYMBOL("blocks"); - atime_symbol = NODE_PSYMBOL("atime"); - mtime_symbol = NODE_PSYMBOL("mtime"); - ctime_symbol = NODE_PSYMBOL("ctime"); - } - - Local stats = - stats_constructor_template->GetFunction()->NewInstance(); - + dev_symbol = String::New("dev"); + ino_symbol = String::New("ino"); + mode_symbol = String::New("mode"); + nlink_symbol = String::New("nlink"); + uid_symbol = String::New("uid"); + gid_symbol = String::New("gid"); + rdev_symbol = String::New("rdev"); + size_symbol = String::New("size"); + blksize_symbol = String::New("blksize"); + blocks_symbol = String::New("blocks"); + atime_symbol = String::New("atime"); + mtime_symbol = String::New("mtime"); + ctime_symbol = String::New("ctime"); + } + + Local constructor = + Local::New(node_isolate, stats_constructor); + + Local stats = constructor->NewInstance(); if (stats.IsEmpty()) return Local(); // The code below is very nasty-looking but it prevents a segmentation fault @@ -355,7 +366,7 @@ Local BuildStatsObject(const uv_stat_t* s) { return scope.Close(stats); } -static Handle Stat(const Arguments& args) { +static void Stat(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -367,12 +378,12 @@ static Handle Stat(const Arguments& args) { ASYNC_CALL(stat, args[1], *path) } else { SYNC_CALL(stat, *path, *path) - return scope.Close( + args.GetReturnValue().Set( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } -static Handle LStat(const Arguments& args) { +static void LStat(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -384,12 +395,12 @@ static Handle LStat(const Arguments& args) { ASYNC_CALL(lstat, args[1], *path) } else { SYNC_CALL(lstat, *path, *path) - return scope.Close( + args.GetReturnValue().Set( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } -static Handle FStat(const Arguments& args) { +static void FStat(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1 || !args[0]->IsInt32()) { @@ -402,12 +413,12 @@ static Handle FStat(const Arguments& args) { ASYNC_CALL(fstat, args[1], fd) } else { SYNC_CALL(fstat, 0, fd) - return scope.Close( + args.GetReturnValue().Set( BuildStatsObject(static_cast(SYNC_REQ.ptr))); } } -static Handle Symlink(const Arguments& args) { +static void Symlink(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -427,8 +438,7 @@ static Handle Symlink(const Arguments& args) { } else if (strcmp(*mode, "junction") == 0) { flags |= UV_FS_SYMLINK_JUNCTION; } else if (strcmp(*mode, "file") != 0) { - return ThrowException(Exception::Error( - String::New("Unknown symlink type"))); + return ThrowError("Unknown symlink type"); } } @@ -436,11 +446,10 @@ static Handle Symlink(const Arguments& args) { ASYNC_CALL(symlink, args[3], *dest, *path, flags) } else { SYNC_CALL(symlink, *path, *dest, *path, flags) - return Undefined(node_isolate); } } -static Handle Link(const Arguments& args) { +static void Link(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -456,11 +465,10 @@ static Handle Link(const Arguments& args) { ASYNC_CALL(link, args[2], *orig_path, *new_path) } else { SYNC_CALL(link, *orig_path, *orig_path, *new_path) - return Undefined(node_isolate); } } -static Handle ReadLink(const Arguments& args) { +static void ReadLink(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -472,11 +480,12 @@ static Handle ReadLink(const Arguments& args) { ASYNC_CALL(readlink, args[1], *path) } else { SYNC_CALL(readlink, *path, *path) - return scope.Close(String::New((char*)SYNC_REQ.ptr)); + args.GetReturnValue().Set( + String::New(static_cast(SYNC_REQ.ptr))); } } -static Handle Rename(const Arguments& args) { +static void Rename(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -492,11 +501,10 @@ static Handle Rename(const Arguments& args) { ASYNC_CALL(rename, args[2], *old_path, *new_path) } else { SYNC_CALL(rename, *old_path, *old_path, *new_path) - return Undefined(node_isolate); } } -static Handle FTruncate(const Arguments& args) { +static void FTruncate(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 2 || !args[0]->IsInt32()) { @@ -512,11 +520,10 @@ static Handle FTruncate(const Arguments& args) { ASYNC_CALL(ftruncate, args[2], fd, len) } else { SYNC_CALL(ftruncate, 0, fd, len) - return Undefined(node_isolate); } } -static Handle Fdatasync(const Arguments& args) { +static void Fdatasync(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1 || !args[0]->IsInt32()) { @@ -529,11 +536,10 @@ static Handle Fdatasync(const Arguments& args) { ASYNC_CALL(fdatasync, args[1], fd) } else { SYNC_CALL(fdatasync, 0, fd) - return Undefined(node_isolate); } } -static Handle Fsync(const Arguments& args) { +static void Fsync(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1 || !args[0]->IsInt32()) { @@ -546,11 +552,10 @@ static Handle Fsync(const Arguments& args) { ASYNC_CALL(fsync, args[1], fd) } else { SYNC_CALL(fsync, 0, fd) - return Undefined(node_isolate); } } -static Handle Unlink(const Arguments& args) { +static void Unlink(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -562,11 +567,10 @@ static Handle Unlink(const Arguments& args) { ASYNC_CALL(unlink, args[1], *path) } else { SYNC_CALL(unlink, *path, *path) - return Undefined(node_isolate); } } -static Handle RMDir(const Arguments& args) { +static void RMDir(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -578,11 +582,10 @@ static Handle RMDir(const Arguments& args) { ASYNC_CALL(rmdir, args[1], *path) } else { SYNC_CALL(rmdir, *path, *path) - return Undefined(node_isolate); } } -static Handle MKDir(const Arguments& args) { +static void MKDir(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { @@ -596,11 +599,10 @@ static Handle MKDir(const Arguments& args) { ASYNC_CALL(mkdir, args[2], *path, mode) } else { SYNC_CALL(mkdir, *path, *path, mode) - return Undefined(node_isolate); } } -static Handle ReadDir(const Arguments& args) { +static void ReadDir(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 1) return TYPE_ERROR("path required"); @@ -629,11 +631,11 @@ static Handle ReadDir(const Arguments& args) { #endif } - return scope.Close(names); + args.GetReturnValue().Set(names); } } -static Handle Open(const Arguments& args) { +static void Open(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -652,8 +654,7 @@ static Handle Open(const Arguments& args) { ASYNC_CALL(open, args[3], *path, flags, mode) } else { SYNC_CALL(open, *path, *path, flags, mode) - int fd = SYNC_RESULT; - return scope.Close(Integer::New(fd, node_isolate)); + args.GetReturnValue().Set(SYNC_RESULT); } } @@ -666,7 +667,7 @@ static Handle Open(const Arguments& args) { // 3 length how much to write // 4 position if integer, position to write at in the file. // if null, write from the current position -static Handle Write(const Arguments& args) { +static void Write(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (!args[0]->IsInt32()) { @@ -676,8 +677,7 @@ static Handle Write(const Arguments& args) { int fd = args[0]->Int32Value(); if (!Buffer::HasInstance(args[1])) { - return ThrowException(Exception::Error( - String::New("Second argument needs to be a buffer"))); + return ThrowError("Second argument needs to be a buffer"); } Local buffer_obj = args[1]->ToObject(); @@ -686,14 +686,12 @@ static Handle Write(const Arguments& args) { size_t off = args[2]->Int32Value(); if (off >= buffer_length) { - return ThrowException(Exception::Error( - String::New("Offset is out of bounds"))); + return ThrowError("Offset is out of bounds"); } ssize_t len = args[3]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("off + len > buffer.length"))); + return ThrowError("off + len > buffer.length"); } ASSERT_OFFSET(args[4]); @@ -706,7 +704,7 @@ static Handle Write(const Arguments& args) { ASYNC_CALL(write, cb, fd, buf, len, pos) } else { SYNC_CALL(write, 0, fd, buf, len, pos) - return scope.Close(Integer::New(SYNC_RESULT, node_isolate)); + args.GetReturnValue().Set(SYNC_RESULT); } } @@ -722,7 +720,7 @@ static Handle Write(const Arguments& args) { * 4 position file position - null for current position * */ -static Handle Read(const Arguments& args) { +static void Read(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if (args.Length() < 2 || !args[0]->IsInt32()) { @@ -739,8 +737,7 @@ static Handle Read(const Arguments& args) { char * buf = NULL; if (!Buffer::HasInstance(args[1])) { - return ThrowException(Exception::Error( - String::New("Second argument needs to be a buffer"))); + return ThrowError("Second argument needs to be a buffer"); } Local buffer_obj = args[1]->ToObject(); @@ -749,14 +746,12 @@ static Handle Read(const Arguments& args) { size_t off = args[2]->Int32Value(); if (off >= buffer_length) { - return ThrowException(Exception::Error( - String::New("Offset is out of bounds"))); + return ThrowError("Offset is out of bounds"); } len = args[3]->Int32Value(); if (off + len > buffer_length) { - return ThrowException(Exception::Error( - String::New("Length extends beyond buffer"))); + return ThrowError("Length extends beyond buffer"); } pos = GET_OFFSET(args[4]); @@ -769,8 +764,7 @@ static Handle Read(const Arguments& args) { ASYNC_CALL(read, cb, fd, buf, len, pos); } else { SYNC_CALL(read, 0, fd, buf, len, pos) - Local bytesRead = Integer::New(SYNC_RESULT, node_isolate); - return scope.Close(bytesRead); + args.GetReturnValue().Set(SYNC_RESULT); } } @@ -778,7 +772,7 @@ static Handle Read(const Arguments& args) { /* fs.chmod(path, mode); * Wrapper for chmod(1) / EIO_CHMOD */ -static Handle Chmod(const Arguments& args) { +static void Chmod(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if(args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { @@ -791,7 +785,6 @@ static Handle Chmod(const Arguments& args) { ASYNC_CALL(chmod, args[2], *path, mode); } else { SYNC_CALL(chmod, *path, *path, mode); - return Undefined(node_isolate); } } @@ -799,7 +792,7 @@ static Handle Chmod(const Arguments& args) { /* fs.fchmod(fd, mode); * Wrapper for fchmod(1) / EIO_FCHMOD */ -static Handle FChmod(const Arguments& args) { +static void FChmod(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); if(args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) { @@ -812,7 +805,6 @@ static Handle FChmod(const Arguments& args) { ASYNC_CALL(fchmod, args[2], fd, mode); } else { SYNC_CALL(fchmod, 0, fd, mode); - return Undefined(node_isolate); } } @@ -820,7 +812,7 @@ static Handle FChmod(const Arguments& args) { /* fs.chown(path, uid, gid); * Wrapper for chown(1) / EIO_CHOWN */ -static Handle Chown(const Arguments& args) { +static void Chown(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -839,7 +831,6 @@ static Handle Chown(const Arguments& args) { ASYNC_CALL(chown, args[3], *path, uid, gid); } else { SYNC_CALL(chown, *path, *path, uid, gid); - return Undefined(node_isolate); } } @@ -847,7 +838,7 @@ static Handle Chown(const Arguments& args) { /* fs.fchown(fd, uid, gid); * Wrapper for fchown(1) / EIO_FCHOWN */ -static Handle FChown(const Arguments& args) { +static void FChown(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -866,12 +857,11 @@ static Handle FChown(const Arguments& args) { ASYNC_CALL(fchown, args[3], fd, uid, gid); } else { SYNC_CALL(fchown, 0, fd, uid, gid); - return Undefined(node_isolate); } } -static Handle UTimes(const Arguments& args) { +static void UTimes(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -890,11 +880,10 @@ static Handle UTimes(const Arguments& args) { ASYNC_CALL(utime, args[3], *path, atime, mtime); } else { SYNC_CALL(utime, *path, *path, atime, mtime); - return Undefined(node_isolate); } } -static Handle FUTimes(const Arguments& args) { +static void FUTimes(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); int len = args.Length(); @@ -913,7 +902,6 @@ static Handle FUTimes(const Arguments& args) { ASYNC_CALL(futime, args[3], fd, atime, mtime); } else { SYNC_CALL(futime, 0, fd, atime, mtime); - return Undefined(node_isolate); } } @@ -954,15 +942,15 @@ void File::Initialize(Handle target) { void InitFs(Handle target) { HandleScope scope(node_isolate); + // Initialize the stats object - Local stat_templ = FunctionTemplate::New(); - stats_constructor_template = Persistent::New(node_isolate, - stat_templ); - target->Set(String::NewSymbol("Stats"), - stats_constructor_template->GetFunction()); + Local constructor = FunctionTemplate::New()->GetFunction(); + target->Set(String::NewSymbol("Stats"), constructor); + stats_constructor.Reset(node_isolate, constructor); + File::Initialize(target); - oncomplete_sym = NODE_PSYMBOL("oncomplete"); + oncomplete_sym = String::New("oncomplete"); StatWatcher::Initialize(target); } diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index c9391b57c77..de89b4e74e0 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -47,26 +47,37 @@ namespace node { -using namespace v8; - -static Persistent on_headers_sym; -static Persistent on_headers_complete_sym; -static Persistent on_body_sym; -static Persistent on_message_complete_sym; - -static Persistent method_sym; -static Persistent status_code_sym; -static Persistent http_version_sym; -static Persistent version_major_sym; -static Persistent version_minor_sym; -static Persistent should_keep_alive_sym; -static Persistent upgrade_sym; -static Persistent headers_sym; -static Persistent url_sym; - -static Persistent unknown_method_sym; - -#define X(num, name, string) static Persistent name##_sym; +using v8::Array; +using v8::Exception; +using v8::Function; +using v8::FunctionCallbackInfo; +using v8::FunctionTemplate; +using v8::Handle; +using v8::HandleScope; +using v8::Integer; +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + +static Cached on_headers_sym; +static Cached on_headers_complete_sym; +static Cached on_body_sym; +static Cached on_message_complete_sym; + +static Cached method_sym; +static Cached status_code_sym; +static Cached http_version_sym; +static Cached version_major_sym; +static Cached version_minor_sym; +static Cached should_keep_alive_sym; +static Cached upgrade_sym; +static Cached headers_sym; +static Cached url_sym; + +static Cached unknown_method_sym; + +#define X(num, name, string) static Cached name##_sym; HTTP_METHOD_MAP(X) #undef X @@ -97,7 +108,7 @@ static size_t current_buffer_len; int name##_(const char* at, size_t length) -static inline Persistent +static inline Handle method_to_str(unsigned short m) { switch (m) { #define X(num, name, string) case HTTP_##name: return name##_sym; @@ -243,7 +254,8 @@ public: HTTP_CB(on_headers_complete) { - Local cb = handle_->Get(on_headers_complete_sym); + Local obj = handle(node_isolate); + Local cb = obj->Get(on_headers_complete_sym); if (!cb->IsFunction()) return 0; @@ -288,9 +300,8 @@ public: : False(node_isolate)); Local argv[1] = { message_info }; - Local head_response = - Local::Cast(cb)->Call(handle_, 1, argv); + cb.As()->Call(obj, ARRAY_SIZE(argv), argv); if (head_response.IsEmpty()) { got_exception_ = true; @@ -304,7 +315,9 @@ public: HTTP_DATA_CB(on_body) { HandleScope scope(node_isolate); - Local cb = handle_->Get(on_body_sym); + Local obj = handle(node_isolate); + Local cb = obj->Get(on_body_sym); + if (!cb->IsFunction()) return 0; @@ -314,7 +327,7 @@ public: Integer::New(length, node_isolate) }; - Local r = Local::Cast(cb)->Call(handle_, 3, argv); + Local r = cb.As()->Call(obj, ARRAY_SIZE(argv), argv); if (r.IsEmpty()) { got_exception_ = true; @@ -331,12 +344,13 @@ public: if (num_fields_) Flush(); // Flush trailing HTTP headers. - Local cb = handle_->Get(on_message_complete_sym); + Local obj = handle(node_isolate); + Local cb = obj->Get(on_message_complete_sym); if (!cb->IsFunction()) return 0; - Local r = Local::Cast(cb)->Call(handle_, 0, NULL); + Local r = cb.As()->Call(obj, 0, NULL); if (r.IsEmpty()) { got_exception_ = true; @@ -347,21 +361,15 @@ public: } - static Handle New(const Arguments& args) { + static void New(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); http_parser_type type = static_cast(args[0]->Int32Value()); - if (type != HTTP_REQUEST && type != HTTP_RESPONSE) { - return ThrowException(Exception::Error(String::New( - "Argument must be HTTPParser.REQUEST or HTTPParser.RESPONSE"))); - } - + assert(type == HTTP_REQUEST || type == HTTP_RESPONSE); Parser* parser = new Parser(type); parser->Wrap(args.This()); - - return args.This(); } @@ -379,7 +387,7 @@ public: // var bytesParsed = parser->execute(buffer); - static Handle Execute(const Arguments& args) { + static void Execute(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Parser* parser = ObjectWrap::Unwrap(args.This()); @@ -388,15 +396,13 @@ public: assert(!current_buffer_data); if (current_buffer) { - return ThrowException(Exception::TypeError( - String::New("Already parsing a buffer"))); + return ThrowTypeError("Already parsing a buffer"); } Local buffer_v = args[0]; if (!Buffer::HasInstance(buffer_v)) { - return ThrowException(Exception::TypeError( - String::New("Argument should be a buffer"))); + return ThrowTypeError("Argument should be a buffer"); } Local buffer_obj = buffer_v->ToObject(); @@ -420,7 +426,7 @@ public: current_buffer_data = NULL; // If there was an exception in one of the callbacks - if (parser->got_exception_) return Local(); + if (parser->got_exception_) return; Local nparsed_obj = Integer::New(nparsed, node_isolate); // If there was a parse error in one of the callbacks @@ -432,14 +438,14 @@ public: Local obj = e->ToObject(); obj->Set(String::NewSymbol("bytesParsed"), nparsed_obj); obj->Set(String::NewSymbol("code"), String::New(http_errno_name(err))); - return scope.Close(e); + args.GetReturnValue().Set(e); } else { - return scope.Close(nparsed_obj); + args.GetReturnValue().Set(nparsed_obj); } } - static Handle Finish(const Arguments& args) { + static void Finish(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); Parser* parser = ObjectWrap::Unwrap(args.This()); @@ -449,7 +455,7 @@ public: int rv = http_parser_execute(&(parser->parser_), &settings, NULL, 0); - if (parser->got_exception_) return Local(); + if (parser->got_exception_) return; if (rv != 0) { enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_); @@ -458,28 +464,20 @@ public: Local obj = e->ToObject(); obj->Set(String::NewSymbol("bytesParsed"), Integer::New(0, node_isolate)); obj->Set(String::NewSymbol("code"), String::New(http_errno_name(err))); - return scope.Close(e); + args.GetReturnValue().Set(e); } - - return Undefined(node_isolate); } - static Handle Reinitialize(const Arguments& args) { + static void Reinitialize(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); http_parser_type type = static_cast(args[0]->Int32Value()); - if (type != HTTP_REQUEST && type != HTTP_RESPONSE) { - return ThrowException(Exception::Error(String::New( - "Argument must be HTTPParser.REQUEST or HTTPParser.RESPONSE"))); - } - + assert(type == HTTP_REQUEST || type == HTTP_RESPONSE); Parser* parser = ObjectWrap::Unwrap(args.This()); parser->Init(type); - - return Undefined(node_isolate); } @@ -503,7 +501,8 @@ private: void Flush() { HandleScope scope(node_isolate); - Local cb = handle_->Get(on_headers_sym); + Local obj = handle(node_isolate); + Local cb = obj->Get(on_headers_sym); if (!cb->IsFunction()) return; @@ -513,7 +512,7 @@ private: url_.ToString() }; - Local r = Local::Cast(cb)->Call(handle_, 2, argv); + Local r = cb.As()->Call(obj, ARRAY_SIZE(argv), argv); if (r.IsEmpty()) got_exception_ = true; @@ -551,13 +550,10 @@ void InitHttpParser(Handle target) { t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(String::NewSymbol("HTTPParser")); - PropertyAttribute attrib = (PropertyAttribute) (ReadOnly | DontDelete); t->Set(String::NewSymbol("REQUEST"), - Integer::New(HTTP_REQUEST, node_isolate), - attrib); + Integer::New(HTTP_REQUEST, node_isolate)); t->Set(String::NewSymbol("RESPONSE"), - Integer::New(HTTP_RESPONSE, node_isolate), - attrib); + Integer::New(HTTP_RESPONSE, node_isolate)); NODE_SET_PROTOTYPE_METHOD(t, "execute", Parser::Execute); NODE_SET_PROTOTYPE_METHOD(t, "finish", Parser::Finish); @@ -565,25 +561,25 @@ void InitHttpParser(Handle target) { target->Set(String::NewSymbol("HTTPParser"), t->GetFunction()); - on_headers_sym = NODE_PSYMBOL("onHeaders"); - on_headers_complete_sym = NODE_PSYMBOL("onHeadersComplete"); - on_body_sym = NODE_PSYMBOL("onBody"); - on_message_complete_sym = NODE_PSYMBOL("onMessageComplete"); + on_headers_sym = String::New("onHeaders"); + on_headers_complete_sym = String::New("onHeadersComplete"); + on_body_sym = String::New("onBody"); + on_message_complete_sym = String::New("onMessageComplete"); -#define X(num, name, string) name##_sym = NODE_PSYMBOL(#string); +#define X(num, name, string) name##_sym = String::New(#string); HTTP_METHOD_MAP(X) #undef X - unknown_method_sym = NODE_PSYMBOL("UNKNOWN_METHOD"); - - method_sym = NODE_PSYMBOL("method"); - status_code_sym = NODE_PSYMBOL("statusCode"); - http_version_sym = NODE_PSYMBOL("httpVersion"); - version_major_sym = NODE_PSYMBOL("versionMajor"); - version_minor_sym = NODE_PSYMBOL("versionMinor"); - should_keep_alive_sym = NODE_PSYMBOL("shouldKeepAlive"); - upgrade_sym = NODE_PSYMBOL("upgrade"); - headers_sym = NODE_PSYMBOL("headers"); - url_sym = NODE_PSYMBOL("url"); + unknown_method_sym = String::New("UNKNOWN_METHOD"); + + method_sym = String::New("method"); + status_code_sym = String::New("statusCode"); + http_version_sym = String::New("httpVersion"); + version_major_sym = String::New("versionMajor"); + version_minor_sym = String::New("versionMinor"); + should_keep_alive_sym = String::New("shouldKeepAlive"); + upgrade_sym = String::New("upgrade"); + headers_sym = String::New("headers"); + url_sym = String::New("url"); settings.on_message_begin = Parser::on_message_begin; settings.on_url = Parser::on_url; diff --git a/src/node_internals.h b/src/node_internals.h index 9e5e0bf92df..29c38adb0ab 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -22,6 +22,7 @@ #ifndef SRC_NODE_INTERNALS_H_ #define SRC_NODE_INTERNALS_H_ +#include #include #include "v8.h" @@ -32,7 +33,67 @@ namespace node { extern v8::Isolate* node_isolate; // Defined in node.cc at startup. -extern v8::Persistent process; +extern v8::Persistent process_p; + +template +class CachedBase { +public: + CachedBase(); + operator v8::Handle() const; + void operator=(v8::Handle that); // Can only assign once. + bool IsEmpty() const; +private: + CachedBase(const CachedBase&); + void operator=(const CachedBase&); + v8::Persistent handle_; +}; + +template +class Cached : public CachedBase { +public: + operator v8::Handle() const; + void operator=(v8::Handle that); +}; + +template <> +class Cached : public CachedBase { +public: + operator v8::Handle() const; + void operator=(v8::Handle that); +}; + +template +v8::Handle MakeCallback( + const v8::Persistent& recv, + const TypeName method, + int argc, + v8::Handle* argv); + +template +v8::Handle MakeCallback( + const v8::Persistent& recv, + const Cached& method, + int argc, + v8::Handle* argv); + +inline bool HasInstance(v8::Persistent& function_template, + v8::Handle value); + +inline v8::Local NewInstance(v8::Persistent& ctor, + int argc = 0, + v8::Handle* argv = NULL); + +// TODO(bnoordhuis) Move to src/node_buffer.h once it's been established +// that the current approach to dealing with Persistent is working out. +namespace Buffer { + +template +inline char* Data(v8::Persistent& val); + +template +inline size_t Length(v8::Persistent& val); + +} // namespace Buffer #ifdef _WIN32 // emulate snprintf() on windows, _snprintf() doesn't zero-terminate the buffer @@ -87,22 +148,44 @@ inline static int snprintf(char* buf, unsigned int len, const char* fmt, ...) { #define THROW_ERROR(fun) \ do { \ v8::HandleScope scope(node_isolate); \ - return v8::ThrowException(fun(v8::String::New(errmsg))); \ + v8::ThrowException(fun(v8::String::New(errmsg))); \ } \ while (0) -inline static v8::Handle ThrowError(const char* errmsg) { +inline static void ThrowError(const char* errmsg) { THROW_ERROR(v8::Exception::Error); } -inline static v8::Handle ThrowTypeError(const char* errmsg) { +inline static void ThrowTypeError(const char* errmsg) { THROW_ERROR(v8::Exception::TypeError); } -inline static v8::Handle ThrowRangeError(const char* errmsg) { +inline static void ThrowRangeError(const char* errmsg) { THROW_ERROR(v8::Exception::RangeError); } +inline static void ThrowErrnoException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL) { + NODE_EXTERN v8::Local ErrnoException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL); + v8::ThrowException(ErrnoException(errorno, syscall, message, path)); +} + +inline static void ThrowUVException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL) { + NODE_EXTERN v8::Local UVException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL); + v8::ThrowException(UVException(errorno, syscall, message, path)); +} + NO_RETURN void FatalError(const char* location, const char* message); #define UNWRAP(type) \ @@ -116,10 +199,6 @@ NO_RETURN void FatalError(const char* location, const char* message); abort(); \ } -v8::Handle FromConstructorTemplate( - v8::Persistent t, - const v8::Arguments& args); - // allow for quick domain check extern bool using_domains; @@ -165,6 +244,115 @@ inline MUST_USE_RESULT bool ParseArrayIndex(v8::Handle arg, return true; } +template +CachedBase::CachedBase() { +} + +template +CachedBase::operator v8::Handle() const { + return v8::Local::New(node_isolate, handle_); +} + +template +void CachedBase::operator=(v8::Handle that) { + assert(handle_.IsEmpty() == true); // Can only assign once. + handle_.Reset(node_isolate, that); +} + +template +bool CachedBase::IsEmpty() const { + return handle_.IsEmpty(); +} + +template +Cached::operator v8::Handle() const { + return CachedBase::operator v8::Handle(); +} + +template +void Cached::operator=(v8::Handle that) { + CachedBase::operator=(that); +} + +inline Cached::operator v8::Handle() const { + return CachedBase::operator v8::Handle(); +} + +inline void Cached::operator=(v8::Handle that) { + CachedBase::operator=(that); +} + +// Forward declarations, see node.h +NODE_EXTERN v8::Handle MakeCallback( + const v8::Handle recv, + const char* method, + int argc, + v8::Handle* argv); +NODE_EXTERN v8::Handle MakeCallback( + const v8::Handle object, + const v8::Handle symbol, + int argc, + v8::Handle* argv); +NODE_EXTERN v8::Handle MakeCallback( + const v8::Handle object, + const v8::Handle callback, + int argc, + v8::Handle* argv); + +template +v8::Handle MakeCallback( + const v8::Persistent& recv, + const TypeName method, + int argc, + v8::Handle* argv) { + v8::Local recv_obj = + v8::Local::New(node_isolate, recv); + return MakeCallback(recv_obj, method, argc, argv); +} + +template +v8::Handle MakeCallback( + const v8::Persistent& recv, + const Cached& method, + int argc, + v8::Handle* argv) { + const v8::Handle handle = method; + return MakeCallback(recv, handle, argc, argv); +} + +inline bool HasInstance(v8::Persistent& function_template, + v8::Handle value) { + v8::Local function_template_handle = + v8::Local::New(node_isolate, function_template); + return function_template_handle->HasInstance(value); +} + +inline v8::Local NewInstance(v8::Persistent& ctor, + int argc, + v8::Handle* argv) { + v8::Local constructor_handle = + v8::Local::New(node_isolate, ctor); + return constructor_handle->NewInstance(argc, argv); +} + +namespace Buffer { + +template +inline char* Data(v8::Persistent& val) { + NODE_EXTERN char* Data(v8::Handle); + NODE_EXTERN char* Data(v8::Handle); + return Data(v8::Local::New(node_isolate, val)); +} + +template +inline size_t Length(v8::Persistent& val) { + NODE_EXTERN size_t Length(v8::Handle); + NODE_EXTERN size_t Length(v8::Handle); + return Length(v8::Local::New(node_isolate, val)); +} + +} // namespace Buffer + } // namespace node #endif // SRC_NODE_INTERNALS_H_ diff --git a/src/node_object_wrap.h b/src/node_object_wrap.h index 19f536dfe9a..990c82b1dbd 100644 --- a/src/node_object_wrap.h +++ b/src/node_object_wrap.h @@ -38,49 +38,56 @@ namespace node { class NODE_EXTERN ObjectWrap { - public: - ObjectWrap ( ) { +public: + ObjectWrap() { refs_ = 0; } - virtual ~ObjectWrap ( ) { - if (!handle_.IsEmpty()) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - assert(handle_.IsNearDeath(isolate)); - handle_.ClearWeak(isolate); - handle_->SetAlignedPointerInInternalField(0, 0); - handle_.Dispose(isolate); - handle_.Clear(); - } + virtual ~ObjectWrap() { + if (persistent().IsEmpty()) return; + assert(persistent().IsNearDeath()); + persistent().ClearWeak(); + persistent().Dispose(); } template - static inline T* Unwrap (v8::Handle handle) { + static inline T* Unwrap(v8::Handle handle) { assert(!handle.IsEmpty()); assert(handle->InternalFieldCount() > 0); return static_cast(handle->GetAlignedPointerFromInternalField(0)); } - v8::Persistent handle_; // ro + inline v8::Local handle() { + return handle(v8::Isolate::GetCurrent()); + } + + + inline v8::Local handle(v8::Isolate* isolate) { + return v8::Local::New(isolate, persistent()); + } + - protected: - inline void Wrap (v8::Handle handle) { - assert(handle_.IsEmpty()); + inline v8::Persistent& persistent() { + return handle_; + } + + +protected: + inline void Wrap(v8::Handle handle) { + assert(persistent().IsEmpty()); assert(handle->InternalFieldCount() > 0); - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - handle_ = v8::Persistent::New(isolate, handle); - handle_->SetAlignedPointerInInternalField(0, this); + handle->SetAlignedPointerInInternalField(0, this); + persistent().Reset(v8::Isolate::GetCurrent(), handle); MakeWeak(); } - inline void MakeWeak (void) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - handle_.MakeWeak(isolate, this, WeakCallback); - handle_.MarkIndependent(isolate); + inline void MakeWeak(void) { + persistent().MakeWeak(this, WeakCallback); + persistent().MarkIndependent(); } /* Ref() marks the object as being attached to an event loop. @@ -88,9 +95,9 @@ class NODE_EXTERN ObjectWrap { * all references are lost. */ virtual void Ref() { - assert(!handle_.IsEmpty()); + assert(!persistent().IsEmpty()); + persistent().ClearWeak(); refs_++; - handle_.ClearWeak(v8::Isolate::GetCurrent()); } /* Unref() marks an object as detached from the event loop. This is its @@ -103,26 +110,26 @@ class NODE_EXTERN ObjectWrap { * DO NOT CALL THIS FROM DESTRUCTOR */ virtual void Unref() { - assert(!handle_.IsEmpty()); - assert(!handle_.IsWeak(v8::Isolate::GetCurrent())); + assert(!persistent().IsEmpty()); + assert(!persistent().IsWeak()); assert(refs_ > 0); - if (--refs_ == 0) { MakeWeak(); } + if (--refs_ == 0) MakeWeak(); } + int refs_; // ro - int refs_; // ro - - - private: +private: static void WeakCallback(v8::Isolate* isolate, v8::Persistent* pobj, ObjectWrap* wrap) { v8::HandleScope scope(isolate); assert(wrap->refs_ == 0); - assert(*pobj == wrap->handle_); - assert((*pobj).IsNearDeath(isolate)); + assert(*pobj == wrap->persistent()); + assert((*pobj).IsNearDeath()); delete wrap; } + + v8::Persistent handle_; }; } // namespace node diff --git a/src/node_os.cc b/src/node_os.cc index 9bff7e6b0bc..6e11002be96 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -46,81 +46,95 @@ namespace node { -using namespace v8; - -static Handle GetEndianness(const Arguments& args) { +using v8::Array; +using v8::FunctionCallbackInfo; +using v8::HandleScope; +using v8::Integer; +using v8::Local; +using v8::Number; +using v8::Object; +using v8::String; +using v8::Value; + + +static void GetEndianness(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); - return scope.Close(String::New(IsBigEndian() ? "BE" : "LE")); + const char* rval = IsBigEndian() ? "BE" : "LE"; + args.GetReturnValue().Set(String::New(rval)); } -static Handle GetHostname(const Arguments& args) { + +static void GetHostname(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); char buf[MAXHOSTNAMELEN + 1]; if (gethostname(buf, sizeof(buf))) { #ifdef __POSIX__ - return ThrowException(ErrnoException(errno, "gethostname")); + int errorno = errno; #else // __MINGW32__ - return ThrowException(ErrnoException(WSAGetLastError(), "gethostname")); + int errorno = WSAGetLastError(); #endif // __MINGW32__ + return ThrowErrnoException(errorno, "gethostname"); } buf[sizeof(buf) - 1] = '\0'; - return scope.Close(String::New(buf)); + args.GetReturnValue().Set(String::New(buf)); } -static Handle GetOSType(const Arguments& args) { + +static void GetOSType(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); + const char* rval; #ifdef __POSIX__ struct utsname info; if (uname(&info) < 0) { - return ThrowException(ErrnoException(errno, "uname")); + return ThrowErrnoException(errno, "uname"); } - return scope.Close(String::New(info.sysname)); + rval = info.sysname; #else // __MINGW32__ - return scope.Close(String::New("Windows_NT")); + rval ="Windows_NT"; #endif + + args.GetReturnValue().Set(String::New(rval)); } -static Handle GetOSRelease(const Arguments& args) { + +static void GetOSRelease(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); + const char* rval; #ifdef __POSIX__ struct utsname info; if (uname(&info) < 0) { - return ThrowException(ErrnoException(errno, "uname")); + return ThrowErrnoException(errno, "uname"); } - return scope.Close(String::New(info.release)); + rval = info.release; #else // __MINGW32__ char release[256]; OSVERSIONINFO info; - info.dwOSVersionInfoSize = sizeof(info); - if (GetVersionEx(&info) == 0) { - return Undefined(node_isolate); - } + info.dwOSVersionInfoSize = sizeof(info); + if (GetVersionEx(&info) == 0) return; sprintf(release, "%d.%d.%d", static_cast(info.dwMajorVersion), static_cast(info.dwMinorVersion), static_cast(info.dwBuildNumber)); - return scope.Close(String::New(release)); + rval = release; #endif + args.GetReturnValue().Set(String::New(rval)); } -static Handle GetCPUInfo(const Arguments& args) { + +static void GetCPUInfo(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); uv_cpu_info_t* cpu_infos; int count, i; uv_err_t err = uv_cpu_info(&cpu_infos, &count); - - if (err.code != UV_OK) { - return Undefined(node_isolate); - } + if (err.code != UV_OK) return; Local cpus = Array::New(); - for (i = 0; i < count; i++) { Local times_info = Object::New(); times_info->Set(String::New("user"), @@ -143,60 +157,48 @@ static Handle GetCPUInfo(const Arguments& args) { } uv_free_cpu_info(cpu_infos, count); - - return scope.Close(cpus); + args.GetReturnValue().Set(cpus); } -static Handle GetFreeMemory(const Arguments& args) { + +static void GetFreeMemory(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); double amount = uv_get_free_memory(); - - if (amount < 0) { - return Undefined(node_isolate); - } - - return scope.Close(Number::New(amount)); + if (amount < 0) return; + args.GetReturnValue().Set(amount); } -static Handle GetTotalMemory(const Arguments& args) { + +static void GetTotalMemory(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); double amount = uv_get_total_memory(); - - if (amount < 0) { - return Undefined(node_isolate); - } - - return scope.Close(Number::New(amount)); + if (amount < 0) return; + args.GetReturnValue().Set(amount); } -static Handle GetUptime(const Arguments& args) { + +static void GetUptime(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); double uptime; - uv_err_t err = uv_uptime(&uptime); - - if (err.code != UV_OK) { - return Undefined(node_isolate); - } - - return scope.Close(Number::New(uptime)); + if (err.code != UV_OK) return; + args.GetReturnValue().Set(uptime); } -static Handle GetLoadAvg(const Arguments& args) { + +static void GetLoadAvg(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); double loadavg[3]; uv_loadavg(loadavg); - Local loads = Array::New(3); loads->Set(0, Number::New(loadavg[0])); loads->Set(1, Number::New(loadavg[1])); loads->Set(2, Number::New(loadavg[2])); - - return scope.Close(loads); + args.GetReturnValue().Set(loads); } -static Handle GetInterfaceAddresses(const Arguments& args) { +static void GetInterfaceAddresses(const FunctionCallbackInfo& args) { HandleScope scope(node_isolate); uv_interface_address_t* interfaces; int count, i; @@ -207,9 +209,9 @@ static Handle GetInterfaceAddresses(const Arguments& args) { Local ifarr; uv_err_t err = uv_interface_addresses(&interfaces, &count); - - if (err.code != UV_OK) - return ThrowException(UVException(err.code, "uv_interface_addresses")); + if (err.code != UV_OK) { + return ThrowUVException(err.code, "uv_interface_addresses"); + } ret = Object::New(); @@ -248,8 +250,7 @@ static Handle GetInterfaceAddresses(const Arguments& args) { } uv_free_interface_addresses(interfaces, count); - - return scope.Close(ret); + args.GetReturnValue().Set(ret); } diff --git a/src/node_script.cc b/src/node_script.cc index 4766cd05a69..0e98f067661 100644 --- a/src/node_script.cc +++ b/src/node_script.cc @@ -26,11 +26,11 @@ namespace node { -using v8::Arguments; using v8::Array; using v8::Context; using v8::Exception; using v8::Function; +using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Handle; using v8::HandleScope; @@ -39,7 +39,6 @@ using v8::Object; using v8::Persistent; using v8::Script; using v8::String; -using v8::ThrowException; using v8::TryCatch; using v8::V8; using v8::Value; @@ -48,9 +47,9 @@ using v8::Value; class WrappedContext : ObjectWrap { public: static void Initialize(Handle target); - static Handle New(const Arguments& args); + static void New(const FunctionCallbackInfo& args); - Persistent GetV8Context(); + Local GetV8Context(); static Local NewInstance(); static bool InstanceOf(Handle value); @@ -81,57 +80,55 @@ class WrappedScript : ObjectWrap { EvalContextFlags context_flag, EvalOutputFlags output_flag, EvalTimeoutFlags timeout_flag> - static Handle EvalMachine(const Arguments& args); + static void EvalMachine(const FunctionCallbackInfo& args); protected: - static Persistent constructor_template; - WrappedScript() : ObjectWrap() {} ~WrappedScript(); - static Handle New(const Arguments& args); - static Handle CreateContext(const Arguments& arg); - static Handle RunInContext(const Arguments& args); - static Handle RunInThisContext(const Arguments& args); - static Handle RunInNewContext(const Arguments& args); - static Handle CompileRunInContext(const Arguments& args); - static Handle CompileRunInThisContext(const Arguments& args); - static Handle CompileRunInNewContext(const Arguments& args); + static void New(const FunctionCallbackInfo& args); + static void CreateContext(const FunctionCallbackInfo& args); + static void RunInContext(const FunctionCallbackInfo& args); + static void RunInThisContext(const FunctionCallbackInfo& args); + static void RunInNewContext(const FunctionCallbackInfo& args); + static void CompileRunInContext(const FunctionCallbackInfo& args); + static void CompileRunInThisContext(const FunctionCallbackInfo& args); + static void CompileRunInNewContext(const FunctionCallbackInfo& args); Persistent