Browse Source

src: remove `node_isolate` from source

fix #6899
v0.11.12-release
Fedor Indutny 11 years ago
parent
commit
75adde07f9
  1. 148
      src/cares_wrap.cc
  2. 52
      src/env-inl.h
  3. 77
      src/env.h
  4. 22
      src/fs_event_wrap.cc
  5. 15
      src/handle_wrap.cc
  6. 517
      src/node.cc
  7. 100
      src/node.h
  8. 121
      src/node_buffer.cc
  9. 40
      src/node_buffer.h
  10. 118
      src/node_contextify.cc
  11. 8
      src/node_counters.cc
  12. 3
      src/node_counters.h
  13. 624
      src/node_crypto.cc
  14. 6
      src/node_crypto.h
  15. 66
      src/node_dtrace.cc
  16. 3
      src/node_dtrace.h
  17. 130
      src/node_file.cc
  18. 102
      src/node_http_parser.cc
  19. 71
      src/node_internals.h
  20. 14
      src/node_javascript.cc
  21. 5
      src/node_javascript.h
  22. 104
      src/node_os.cc
  23. 13
      src/node_stat_watcher.cc
  24. 2
      src/node_stat_watcher.h
  25. 2
      src/node_wrap.h
  26. 60
      src/node_zlib.cc
  27. 22
      src/pipe_wrap.cc
  28. 69
      src/process_wrap.cc
  29. 11
      src/signal_wrap.cc
  30. 95
      src/smalloc.cc
  31. 17
      src/smalloc.h
  32. 11
      src/spawn_sync.cc
  33. 4
      src/spawn_sync.h
  34. 56
      src/stream_wrap.cc
  35. 98
      src/string_bytes.cc
  36. 67
      src/string_bytes.h
  37. 47
      src/tcp_wrap.cc
  38. 26
      src/timer_wrap.cc
  39. 60
      src/tls_wrap.cc
  40. 24
      src/tty_wrap.cc
  41. 27
      src/udp_wrap.cc
  42. 16
      src/uv.cc

148
src/cares_wrap.cc

@ -193,14 +193,14 @@ static void ares_sockstate_cb(void* data,
} }
static Local<Array> HostentToAddresses(struct hostent* host) { static Local<Array> HostentToAddresses(Environment* env, struct hostent* host) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<Array> addresses = Array::New(); Local<Array> addresses = Array::New();
char ip[INET6_ADDRSTRLEN]; char ip[INET6_ADDRSTRLEN];
for (uint32_t i = 0; host->h_addr_list[i] != NULL; ++i) { for (uint32_t i = 0; host->h_addr_list[i] != NULL; ++i) {
uv_inet_ntop(host->h_addrtype, host->h_addr_list[i], ip, sizeof(ip)); uv_inet_ntop(host->h_addrtype, host->h_addr_list[i], ip, sizeof(ip));
Local<String> address = OneByteString(node_isolate, ip); Local<String> address = OneByteString(env->isolate(), ip);
addresses->Set(i, address); addresses->Set(i, address);
} }
@ -208,12 +208,12 @@ static Local<Array> HostentToAddresses(struct hostent* host) {
} }
static Local<Array> HostentToNames(struct hostent* host) { static Local<Array> HostentToNames(Environment* env, struct hostent* host) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<Array> names = Array::New(); Local<Array> names = Array::New();
for (uint32_t i = 0; host->h_aliases[i] != NULL; ++i) { for (uint32_t i = 0; host->h_aliases[i] != NULL; ++i) {
Local<String> address = OneByteString(node_isolate, host->h_aliases[i]); Local<String> address = OneByteString(env->isolate(), host->h_aliases[i]);
names->Set(i, address); names->Set(i, address);
} }
@ -377,7 +377,7 @@ class QueryAWrap: public QueryWrap {
return; return;
} }
Local<Array> addresses = HostentToAddresses(host); Local<Array> addresses = HostentToAddresses(env(), host);
ares_free_hostent(host); ares_free_hostent(host);
this->CallOnComplete(addresses); this->CallOnComplete(addresses);
@ -414,7 +414,7 @@ class QueryAaaaWrap: public QueryWrap {
return; return;
} }
Local<Array> addresses = HostentToAddresses(host); Local<Array> addresses = HostentToAddresses(env(), host);
ares_free_hostent(host); ares_free_hostent(host);
this->CallOnComplete(addresses); this->CallOnComplete(addresses);
@ -453,7 +453,7 @@ class QueryCnameWrap: public QueryWrap {
// A cname lookup always returns a single record but we follow the // A cname lookup always returns a single record but we follow the
// common API here. // common API here.
Local<Array> result = Array::New(1); Local<Array> result = Array::New(1);
result->Set(0, OneByteString(node_isolate, host->h_name)); result->Set(0, OneByteString(env()->isolate(), host->h_name));
ares_free_hostent(host); ares_free_hostent(host);
this->CallOnComplete(result); this->CallOnComplete(result);
@ -490,18 +490,16 @@ class QueryMxWrap: public QueryWrap {
} }
Local<Array> mx_records = Array::New(); Local<Array> mx_records = Array::New();
Local<String> exchange_symbol = Local<String> exchange_symbol = env()->exchange_string();
FIXED_ONE_BYTE_STRING(node_isolate, "exchange"); Local<String> priority_symbol = env()->priority_string();
Local<String> priority_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "priority");
ares_mx_reply* current = mx_start; ares_mx_reply* current = mx_start;
for (uint32_t i = 0; current != NULL; ++i, current = current->next) { for (uint32_t i = 0; current != NULL; ++i, current = current->next) {
Local<Object> mx_record = Object::New(); Local<Object> mx_record = Object::New();
mx_record->Set(exchange_symbol, mx_record->Set(exchange_symbol,
OneByteString(node_isolate, current->host)); OneByteString(env()->isolate(), current->host));
mx_record->Set(priority_symbol, mx_record->Set(priority_symbol,
Integer::New(current->priority, node_isolate)); Integer::New(current->priority, env()->isolate()));
mx_records->Set(i, mx_record); mx_records->Set(i, mx_record);
} }
@ -540,7 +538,7 @@ class QueryNsWrap: public QueryWrap {
return; return;
} }
Local<Array> names = HostentToNames(host); Local<Array> names = HostentToNames(env(), host);
ares_free_hostent(host); ares_free_hostent(host);
this->CallOnComplete(names); this->CallOnComplete(names);
@ -580,7 +578,7 @@ class QueryTxtWrap: public QueryWrap {
ares_txt_reply* current = txt_out; ares_txt_reply* current = txt_out;
for (uint32_t i = 0; current != NULL; ++i, current = current->next) { for (uint32_t i = 0; current != NULL; ++i, current = current->next) {
Local<String> txt = OneByteString(node_isolate, current->txt); Local<String> txt = OneByteString(env()->isolate(), current->txt);
txt_records->Set(i, txt); txt_records->Set(i, txt);
} }
@ -620,26 +618,22 @@ class QuerySrvWrap: public QueryWrap {
} }
Local<Array> srv_records = Array::New(); Local<Array> srv_records = Array::New();
Local<String> name_symbol = Local<String> name_symbol = env()->name_string();
FIXED_ONE_BYTE_STRING(node_isolate, "name"); Local<String> port_symbol = env()->port_string();
Local<String> port_symbol = Local<String> priority_symbol = env()->priority_string();
FIXED_ONE_BYTE_STRING(node_isolate, "port"); Local<String> weight_symbol = env()->weight_string();
Local<String> priority_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "priority");
Local<String> weight_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "weight");
ares_srv_reply* current = srv_start; ares_srv_reply* current = srv_start;
for (uint32_t i = 0; current != NULL; ++i, current = current->next) { for (uint32_t i = 0; current != NULL; ++i, current = current->next) {
Local<Object> srv_record = Object::New(); Local<Object> srv_record = Object::New();
srv_record->Set(name_symbol, srv_record->Set(name_symbol,
OneByteString(node_isolate, current->host)); OneByteString(env()->isolate(), current->host));
srv_record->Set(port_symbol, srv_record->Set(port_symbol,
Integer::New(current->port, node_isolate)); Integer::New(current->port, env()->isolate()));
srv_record->Set(priority_symbol, srv_record->Set(priority_symbol,
Integer::New(current->priority, node_isolate)); Integer::New(current->priority, env()->isolate()));
srv_record->Set(weight_symbol, srv_record->Set(weight_symbol,
Integer::New(current->weight, node_isolate)); Integer::New(current->weight, env()->isolate()));
srv_records->Set(i, srv_record); srv_records->Set(i, srv_record);
} }
@ -679,34 +673,28 @@ class QueryNaptrWrap: public QueryWrap {
} }
Local<Array> naptr_records = Array::New(); Local<Array> naptr_records = Array::New();
Local<String> flags_symbol = Local<String> flags_symbol = env()->flags_string();
FIXED_ONE_BYTE_STRING(node_isolate, "flags"); Local<String> service_symbol = env()->service_string();
Local<String> service_symbol = Local<String> regexp_symbol = env()->regexp_string();
FIXED_ONE_BYTE_STRING(node_isolate, "service"); Local<String> replacement_symbol = env()->replacement_string();
Local<String> regexp_symbol = Local<String> order_symbol = env()->order_string();
FIXED_ONE_BYTE_STRING(node_isolate, "regexp"); Local<String> preference_symbol = env()->preference_string();
Local<String> replacement_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "replacement");
Local<String> order_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "order");
Local<String> preference_symbol =
FIXED_ONE_BYTE_STRING(node_isolate, "preference");
ares_naptr_reply* current = naptr_start; ares_naptr_reply* current = naptr_start;
for (uint32_t i = 0; current != NULL; ++i, current = current->next) { for (uint32_t i = 0; current != NULL; ++i, current = current->next) {
Local<Object> naptr_record = Object::New(); Local<Object> naptr_record = Object::New();
naptr_record->Set(flags_symbol, naptr_record->Set(flags_symbol,
OneByteString(node_isolate, current->flags)); OneByteString(env()->isolate(), current->flags));
naptr_record->Set(service_symbol, naptr_record->Set(service_symbol,
OneByteString(node_isolate, current->service)); OneByteString(env()->isolate(), current->service));
naptr_record->Set(regexp_symbol, naptr_record->Set(regexp_symbol,
OneByteString(node_isolate, current->regexp)); OneByteString(env()->isolate(), current->regexp));
naptr_record->Set(replacement_symbol, naptr_record->Set(replacement_symbol,
OneByteString(node_isolate, current->replacement)); OneByteString(env()->isolate(), current->replacement));
naptr_record->Set(order_symbol, naptr_record->Set(order_symbol,
Integer::New(current->order, node_isolate)); Integer::New(current->order, env()->isolate()));
naptr_record->Set(preference_symbol, naptr_record->Set(preference_symbol,
Integer::New(current->preference, node_isolate)); Integer::New(current->preference, env()->isolate()));
naptr_records->Set(i, naptr_record); naptr_records->Set(i, naptr_record);
} }
@ -748,20 +736,20 @@ class QuerySoaWrap: public QueryWrap {
Local<Object> soa_record = Object::New(); Local<Object> soa_record = Object::New();
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "nsname"), soa_record->Set(env()->nsname_string(),
OneByteString(node_isolate, soa_out->nsname)); OneByteString(env()->isolate(), soa_out->nsname));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "hostmaster"), soa_record->Set(env()->hostmaster_string(),
OneByteString(node_isolate, soa_out->hostmaster)); OneByteString(env()->isolate(), soa_out->hostmaster));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "serial"), soa_record->Set(env()->serial_string(),
Integer::New(soa_out->serial, node_isolate)); Integer::New(soa_out->serial, env()->isolate()));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "refresh"), soa_record->Set(env()->refresh_string(),
Integer::New(soa_out->refresh, node_isolate)); Integer::New(soa_out->refresh, env()->isolate()));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "retry"), soa_record->Set(env()->retry_string(),
Integer::New(soa_out->retry, node_isolate)); Integer::New(soa_out->retry, env()->isolate()));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "expire"), soa_record->Set(env()->expire_string(),
Integer::New(soa_out->expire, node_isolate)); Integer::New(soa_out->expire, env()->isolate()));
soa_record->Set(FIXED_ONE_BYTE_STRING(node_isolate, "minttl"), soa_record->Set(env()->minttl_string(),
Integer::New(soa_out->minttl, node_isolate)); Integer::New(soa_out->minttl, env()->isolate()));
ares_free_data(soa_out); ares_free_data(soa_out);
@ -803,7 +791,7 @@ class GetHostByAddrWrap: public QueryWrap {
void Parse(struct hostent* host) { void Parse(struct hostent* host) {
HandleScope handle_scope(env()->isolate()); HandleScope handle_scope(env()->isolate());
Context::Scope context_scope(env()->context()); Context::Scope context_scope(env()->context());
this->CallOnComplete(HostentToNames(host)); this->CallOnComplete(HostentToNames(env(), host));
} }
}; };
@ -825,10 +813,10 @@ class GetHostByNameWrap: public QueryWrap {
protected: protected:
void Parse(struct hostent* host) { void Parse(struct hostent* host) {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
Local<Array> addresses = HostentToAddresses(host); Local<Array> addresses = HostentToAddresses(env(), host);
Local<Integer> family = Integer::New(host->h_addrtype, node_isolate); Local<Integer> family = Integer::New(host->h_addrtype, env()->isolate());
this->CallOnComplete(addresses, family); this->CallOnComplete(addresses, family);
} }
@ -865,8 +853,8 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) {
Context::Scope context_scope(env->context()); Context::Scope context_scope(env->context());
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
Null(node_isolate) Null(env->isolate())
}; };
if (status == 0) { if (status == 0) {
@ -906,7 +894,7 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) {
continue; continue;
// Create JavaScript string // Create JavaScript string
Local<String> s = OneByteString(node_isolate, ip); Local<String> s = OneByteString(env->isolate(), ip);
results->Set(n, s); results->Set(n, s);
n++; n++;
} }
@ -933,7 +921,7 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) {
continue; continue;
// Create JavaScript string // Create JavaScript string
Local<String> s = OneByteString(node_isolate, ip); Local<String> s = OneByteString(env->isolate(), ip);
results->Set(n, s); results->Set(n, s);
n++; n++;
} }
@ -956,7 +944,8 @@ void AfterGetAddrInfo(uv_getaddrinfo_t* req, int status, struct addrinfo* res) {
static void IsIP(const FunctionCallbackInfo<Value>& args) { static void IsIP(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
String::AsciiValue ip(args[0]); String::AsciiValue ip(args[0]);
char address_buffer[sizeof(struct in6_addr)]; char address_buffer[sizeof(struct in6_addr)];
@ -1041,7 +1030,7 @@ static void GetServers(const FunctionCallbackInfo<Value>& args) {
int err = uv_inet_ntop(cur->family, caddr, ip, sizeof(ip)); int err = uv_inet_ntop(cur->family, caddr, ip, sizeof(ip));
assert(err == 0); assert(err == 0);
Local<String> addr = OneByteString(node_isolate, ip); Local<String> addr = OneByteString(env->isolate(), ip);
server_array->Set(i, addr); server_array->Set(i, addr);
} }
@ -1121,9 +1110,10 @@ static void SetServers(const FunctionCallbackInfo<Value>& args) {
static void StrError(const FunctionCallbackInfo<Value>& args) { static void StrError(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
const char* errmsg = ares_strerror(args[0]->Int32Value()); const char* errmsg = ares_strerror(args[0]->Int32Value());
args.GetReturnValue().Set(OneByteString(node_isolate, errmsg)); args.GetReturnValue().Set(OneByteString(env->isolate(), errmsg));
} }
@ -1169,12 +1159,12 @@ static void Initialize(Handle<Object> target,
NODE_SET_METHOD(target, "getServers", GetServers); NODE_SET_METHOD(target, "getServers", GetServers);
NODE_SET_METHOD(target, "setServers", SetServers); NODE_SET_METHOD(target, "setServers", SetServers);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "AF_INET"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "AF_INET"),
Integer::New(AF_INET, node_isolate)); Integer::New(AF_INET, env->isolate()));
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "AF_INET6"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "AF_INET6"),
Integer::New(AF_INET6, node_isolate)); Integer::New(AF_INET6, env->isolate()));
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "AF_UNSPEC"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "AF_UNSPEC"),
Integer::New(AF_UNSPEC, node_isolate)); Integer::New(AF_UNSPEC, env->isolate()));
} }
} // namespace cares_wrap } // namespace cares_wrap

52
src/env-inl.h

@ -23,6 +23,7 @@
#define SRC_ENV_INL_H_ #define SRC_ENV_INL_H_
#include "env.h" #include "env.h"
#include "node.h"
#include "util.h" #include "util.h"
#include "util-inl.h" #include "util-inl.h"
#include "uv.h" #include "uv.h"
@ -364,6 +365,57 @@ inline Environment::IsolateData* Environment::isolate_data() const {
return isolate_data_; return isolate_data_;
} }
// this would have been a template function were it not for the fact that g++
// sometimes fails to resolve it...
#define THROW_ERROR(fun) \
do { \
v8::HandleScope scope(isolate); \
v8::ThrowException(fun(OneByteString(isolate, errmsg))); \
} \
while (0)
inline void Environment::ThrowError(v8::Isolate* isolate, const char* errmsg) {
THROW_ERROR(v8::Exception::Error);
}
inline void Environment::ThrowTypeError(v8::Isolate* isolate,
const char* errmsg) {
THROW_ERROR(v8::Exception::TypeError);
}
inline void Environment::ThrowRangeError(v8::Isolate* isolate,
const char* errmsg) {
THROW_ERROR(v8::Exception::RangeError);
}
inline void Environment::ThrowError(const char* errmsg) {
ThrowError(isolate(), errmsg);
}
inline void Environment::ThrowTypeError(const char* errmsg) {
ThrowTypeError(isolate(), errmsg);
}
inline void Environment::ThrowRangeError(const char* errmsg) {
ThrowRangeError(isolate(), errmsg);
}
inline void Environment::ThrowErrnoException(int errorno,
const char* syscall,
const char* message,
const char* path) {
v8::ThrowException(
ErrnoException(isolate(), errorno, syscall, message, path));
}
inline void Environment::ThrowUVException(int errorno,
const char* syscall,
const char* message,
const char* path) {
v8::ThrowException(
UVException(isolate(), errorno, syscall, message, path));
}
#define V(PropertyName, StringValue) \ #define V(PropertyName, StringValue) \
inline \ inline \
v8::Local<v8::String> Environment::IsolateData::PropertyName() const { \ v8::Local<v8::String> Environment::IsolateData::PropertyName() const { \

77
src/env.h

@ -54,6 +54,7 @@ namespace node {
#define PER_ISOLATE_STRING_PROPERTIES(V) \ #define PER_ISOLATE_STRING_PROPERTIES(V) \
V(address_string, "address") \ V(address_string, "address") \
V(args_string, "args") \ V(args_string, "args") \
V(argv_string, "argv") \
V(async_queue_string, "_asyncQueue") \ V(async_queue_string, "_asyncQueue") \
V(async, "async") \ V(async, "async") \
V(atime_string, "atime") \ V(atime_string, "atime") \
@ -62,21 +63,35 @@ namespace node {
V(blocks_string, "blocks") \ V(blocks_string, "blocks") \
V(buffer_string, "buffer") \ V(buffer_string, "buffer") \
V(bytes_string, "bytes") \ V(bytes_string, "bytes") \
V(bytes_parsed_string, "bytesParsed") \
V(byte_length_string, "byteLength") \
V(callback_string, "callback") \ V(callback_string, "callback") \
V(change_string, "change") \ V(change_string, "change") \
V(close_string, "close") \ V(close_string, "close") \
V(code_string, "code") \ V(code_string, "code") \
V(ctime_string, "ctime") \ V(ctime_string, "ctime") \
V(cwd_string, "cwd") \ V(cwd_string, "cwd") \
V(debug_port_string, "debugPort") \
V(debug_string, "debug") \
V(detached_string, "detached") \ V(detached_string, "detached") \
V(dev_string, "dev") \ V(dev_string, "dev") \
V(disposed_string, "_disposed") \ V(disposed_string, "_disposed") \
V(domain_string, "domain") \ V(domain_string, "domain") \
V(exchange_string, "exchange") \
V(idle_string, "idle") \
V(irq_string, "irq") \
V(enter_string, "enter") \ V(enter_string, "enter") \
V(env_pairs_string, "envPairs") \ V(env_pairs_string, "envPairs") \
V(env_string, "env") \
V(errno_string, "errno") \ V(errno_string, "errno") \
V(error_string, "error") \ V(error_string, "error") \
V(events_string, "_events") \
V(exec_argv_string, "execArgv") \
V(exec_path_string, "execPath") \
V(exiting_string, "_exiting") \
V(exit_code_string, "exitCode") \
V(exit_string, "exit") \ V(exit_string, "exit") \
V(expire_string, "expire") \
V(exponent_string, "exponent") \ V(exponent_string, "exponent") \
V(exports_string, "exports") \ V(exports_string, "exports") \
V(ext_key_usage_string, "ext_key_usage") \ V(ext_key_usage_string, "ext_key_usage") \
@ -86,30 +101,42 @@ namespace node {
V(file_string, "file") \ V(file_string, "file") \
V(fingerprint_string, "fingerprint") \ V(fingerprint_string, "fingerprint") \
V(flags_string, "flags") \ V(flags_string, "flags") \
V(fsevent_string, "FSEvent") \
V(gid_string, "gid") \ V(gid_string, "gid") \
V(handle_string, "handle") \ V(handle_string, "handle") \
V(headers_string, "headers") \ V(headers_string, "headers") \
V(heap_size_limit_string, "heap_size_limit") \ V(heap_size_limit_string, "heap_size_limit") \
V(heap_total_string, "heapTotal") \ V(heap_total_string, "heapTotal") \
V(heap_used_string, "heapUsed") \ V(heap_used_string, "heapUsed") \
V(hostmaster_string, "hostmaster") \
V(ignore_string, "ignore") \ V(ignore_string, "ignore") \
V(immediate_callback_string, "_immediateCallback") \ V(immediate_callback_string, "_immediateCallback") \
V(inherit_string, "inherit") \ V(inherit_string, "inherit") \
V(ino_string, "ino") \ V(ino_string, "ino") \
V(input_string, "input") \ V(input_string, "input") \
V(internal_string, "internal") \
V(ipv4_string, "IPv4") \ V(ipv4_string, "IPv4") \
V(ipv6_lc_string, "ipv6") \
V(ipv6_string, "IPv6") \ V(ipv6_string, "IPv6") \
V(issuer_string, "issuer") \ V(issuer_string, "issuer") \
V(kill_signal_string, "killSignal") \ V(kill_signal_string, "killSignal") \
V(mac_string, "mac") \
V(mark_sweep_compact_string, "mark-sweep-compact") \ V(mark_sweep_compact_string, "mark-sweep-compact") \
V(max_buffer_string, "maxBuffer") \ V(max_buffer_string, "maxBuffer") \
V(message_string, "message") \ V(message_string, "message") \
V(method_string, "method") \ V(method_string, "method") \
V(minttl_string, "minttl") \
V(mode_string, "mode") \ V(mode_string, "mode") \
V(model_string, "model") \
V(modulus_string, "modulus") \ V(modulus_string, "modulus") \
V(mtime_string, "mtime") \ V(mtime_string, "mtime") \
V(name_string, "name") \ V(name_string, "name") \
V(need_imm_cb_string, "_needImmediateCallback") \
V(netmask_string, "netmask") \
V(nice_string, "nice") \
V(nlink_string, "nlink") \ V(nlink_string, "nlink") \
V(nsname_string, "nsname") \
V(offset_string, "offset") \
V(onchange_string, "onchange") \ V(onchange_string, "onchange") \
V(onclienthello_string, "onclienthello") \ V(onclienthello_string, "onclienthello") \
V(oncomplete_string, "oncomplete") \ V(oncomplete_string, "oncomplete") \
@ -127,17 +154,33 @@ namespace node {
V(onsignal_string, "onsignal") \ V(onsignal_string, "onsignal") \
V(onstop_string, "onstop") \ V(onstop_string, "onstop") \
V(output_string, "output") \ V(output_string, "output") \
V(order_string, "order") \
V(owner_string, "owner") \
V(parse_error_string, "Parse Error") \
V(path_string, "path") \ V(path_string, "path") \
V(pbkdf2_error_string, "PBKDF2 Error") \
V(pid_string, "pid") \ V(pid_string, "pid") \
V(pipe_string, "pipe") \ V(pipe_string, "pipe") \
V(port_string, "port") \ V(port_string, "port") \
V(preference_string, "preference") \
V(priority_string, "priority") \
V(processed_string, "processed") \ V(processed_string, "processed") \
V(prototype_string, "prototype") \
V(rdev_string, "rdev") \ V(rdev_string, "rdev") \
V(readable_string, "readable") \ V(readable_string, "readable") \
V(received_shutdown_string, "receivedShutdown") \
V(refresh_string, "refresh") \
V(regexp_string, "regexp") \
V(rename_string, "rename") \ V(rename_string, "rename") \
V(replacement_string, "replacement") \
V(retry_string, "retry") \
V(rss_string, "rss") \ V(rss_string, "rss") \
V(serial_string, "serial") \
V(scavenge_string, "scavenge") \ V(scavenge_string, "scavenge") \
V(scopeid_string, "scopeid") \
V(sent_shutdown_string, "sentShutdown") \
V(serial_number_string, "serialNumber") \ V(serial_number_string, "serialNumber") \
V(service_string, "service") \
V(servername_string, "servername") \ V(servername_string, "servername") \
V(session_id_string, "sessionId") \ V(session_id_string, "sessionId") \
V(should_keep_alive_string, "shouldKeepAlive") \ V(should_keep_alive_string, "shouldKeepAlive") \
@ -146,6 +189,7 @@ namespace node {
V(smalloc_p_string, "_smalloc_p") \ V(smalloc_p_string, "_smalloc_p") \
V(sni_context_err_string, "Invalid SNI context") \ V(sni_context_err_string, "Invalid SNI context") \
V(sni_context_string, "sni_context") \ V(sni_context_string, "sni_context") \
V(speed_string, "speed") \
V(stack_string, "stack") \ V(stack_string, "stack") \
V(status_code_string, "statusCode") \ V(status_code_string, "statusCode") \
V(status_message_string, "statusMessage") \ V(status_message_string, "statusMessage") \
@ -153,27 +197,43 @@ namespace node {
V(stdio_string, "stdio") \ V(stdio_string, "stdio") \
V(subject_string, "subject") \ V(subject_string, "subject") \
V(subjectaltname_string, "subjectaltname") \ V(subjectaltname_string, "subjectaltname") \
V(sys_string, "sys") \
V(syscall_string, "syscall") \ V(syscall_string, "syscall") \
V(tick_callback_string, "_tickCallback") \
V(tick_domain_cb_string, "_tickDomainCallback") \
V(tick_info_string, "_tickInfo") \
V(timeout_string, "timeout") \ V(timeout_string, "timeout") \
V(times_string, "times") \
V(timestamp_string, "timestamp") \ V(timestamp_string, "timestamp") \
V(title_string, "title") \
V(tls_npn_string, "tls_npn") \
V(tls_sni_string, "tls_sni") \
V(tls_string, "tls") \
V(tls_ticket_string, "tlsTicket") \ V(tls_ticket_string, "tlsTicket") \
V(total_heap_size_executable_string, "total_heap_size_executable") \ V(total_heap_size_executable_string, "total_heap_size_executable") \
V(total_heap_size_string, "total_heap_size") \ V(total_heap_size_string, "total_heap_size") \
V(total_physical_size_string, "total_physical_size") \ V(total_physical_size_string, "total_physical_size") \
V(type_string, "type") \ V(type_string, "type") \
V(uid_string, "uid") \ V(uid_string, "uid") \
V(unknown_string, "<unknown>") \
V(upgrade_string, "upgrade") \ V(upgrade_string, "upgrade") \
V(url_string, "url") \ V(url_string, "url") \
V(used_heap_size_string, "used_heap_size") \ V(used_heap_size_string, "used_heap_size") \
V(user_string, "user") \
V(uv_string, "uv") \
V(valid_from_string, "valid_from") \ V(valid_from_string, "valid_from") \
V(valid_to_string, "valid_to") \ V(valid_to_string, "valid_to") \
V(verify_error_string, "verifyError") \ V(verify_error_string, "verifyError") \
V(version_major_string, "versionMajor") \ V(version_major_string, "versionMajor") \
V(version_minor_string, "versionMinor") \ V(version_minor_string, "versionMinor") \
V(version_string, "version") \ V(version_string, "version") \
V(weight_string, "weight") \
V(windows_verbatim_arguments_string, "windowsVerbatimArguments") \ V(windows_verbatim_arguments_string, "windowsVerbatimArguments") \
V(wrap_string, "wrap") \
V(writable_string, "writable") \ V(writable_string, "writable") \
V(write_queue_size_string, "writeQueueSize") \ V(write_queue_size_string, "writeQueueSize") \
V(x_forwarded_string, "x-forwarded-for") \
V(zero_return_string, "ZERO_RETURN") \
#define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) \ #define ENVIRONMENT_STRONG_PERSISTENT_PROPERTIES(V) \
V(async_listener_run_function, v8::Function) \ V(async_listener_run_function, v8::Function) \
@ -331,6 +391,23 @@ class Environment {
inline bool printed_error() const; inline bool printed_error() const;
inline void set_printed_error(bool value); inline void set_printed_error(bool value);
inline void ThrowError(const char* errmsg);
inline void ThrowTypeError(const char* errmsg);
inline void ThrowRangeError(const char* errmsg);
inline void ThrowErrnoException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL);
inline void ThrowUVException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL);
// Convenience methods for contextify
inline static void ThrowError(v8::Isolate* isolate, const char* errmsg);
inline static void ThrowTypeError(v8::Isolate* isolate, const char* errmsg);
inline static void ThrowRangeError(v8::Isolate* isolate, const char* errmsg);
// Strings are shared across shared contexts. The getters simply proxy to // Strings are shared across shared contexts. The getters simply proxy to
// the per-isolate primitive. // the per-isolate primitive.
#define V(PropertyName, StringValue) \ #define V(PropertyName, StringValue) \

22
src/fs_event_wrap.cc

@ -81,14 +81,16 @@ FSEventWrap::~FSEventWrap() {
void FSEventWrap::Initialize(Handle<Object> target, void FSEventWrap::Initialize(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context) { Handle<Context> context) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(New); Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "FSEvent")); t->SetClassName(env->fsevent_string());
NODE_SET_PROTOTYPE_METHOD(t, "start", Start); NODE_SET_PROTOTYPE_METHOD(t, "start", Start);
NODE_SET_PROTOTYPE_METHOD(t, "close", Close); NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "FSEvent"), t->GetFunction()); target->Set(env->fsevent_string(), t->GetFunction());
} }
@ -101,12 +103,13 @@ void FSEventWrap::New(const FunctionCallbackInfo<Value>& args) {
void FSEventWrap::Start(const FunctionCallbackInfo<Value>& args) { void FSEventWrap::Start(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This()); FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This());
if (args.Length() < 1 || !args[0]->IsString()) { if (args.Length() < 1 || !args[0]->IsString()) {
return ThrowTypeError("Bad arguments"); return env->ThrowTypeError("Bad arguments");
} }
String::Utf8Value path(args[0]); String::Utf8Value path(args[0]);
@ -158,7 +161,7 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename,
// unreasonable, right? Still, we should revisit this before v1.0. // unreasonable, right? Still, we should revisit this before v1.0.
Local<String> event_string; Local<String> event_string;
if (status) { if (status) {
event_string = String::Empty(node_isolate); event_string = String::Empty(env->isolate());
} else if (events & UV_RENAME) { } else if (events & UV_RENAME) {
event_string = env->rename_string(); event_string = env->rename_string();
} else if (events & UV_CHANGE) { } else if (events & UV_CHANGE) {
@ -169,13 +172,13 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename,
} }
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
event_string, event_string,
Null(node_isolate) Null(env->isolate())
}; };
if (filename != NULL) { if (filename != NULL) {
argv[2] = OneByteString(node_isolate, filename); argv[2] = OneByteString(env->isolate(), filename);
} }
wrap->MakeCallback(env->onchange_string(), ARRAY_SIZE(argv), argv); wrap->MakeCallback(env->onchange_string(), ARRAY_SIZE(argv), argv);
@ -183,7 +186,8 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename,
void FSEventWrap::Close(const FunctionCallbackInfo<Value>& args) { void FSEventWrap::Close(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This()); FSEventWrap* wrap = Unwrap<FSEventWrap>(args.This());

15
src/handle_wrap.cc

@ -44,7 +44,8 @@ extern QUEUE handle_wrap_queue;
void HandleWrap::Ref(const FunctionCallbackInfo<Value>& args) { void HandleWrap::Ref(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
HandleWrap* wrap = Unwrap<HandleWrap>(args.This()); HandleWrap* wrap = Unwrap<HandleWrap>(args.This());
@ -56,7 +57,8 @@ void HandleWrap::Ref(const FunctionCallbackInfo<Value>& args) {
void HandleWrap::Unref(const FunctionCallbackInfo<Value>& args) { void HandleWrap::Unref(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
HandleWrap* wrap = Unwrap<HandleWrap>(args.This()); HandleWrap* wrap = Unwrap<HandleWrap>(args.This());
@ -68,7 +70,8 @@ void HandleWrap::Unref(const FunctionCallbackInfo<Value>& args) {
void HandleWrap::Close(const FunctionCallbackInfo<Value>& args) { void HandleWrap::Close(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
HandleWrap* wrap = Unwrap<HandleWrap>(args.This()); HandleWrap* wrap = Unwrap<HandleWrap>(args.This());
@ -76,7 +79,6 @@ void HandleWrap::Close(const FunctionCallbackInfo<Value>& args) {
if (wrap == NULL || wrap->handle__ == NULL) if (wrap == NULL || wrap->handle__ == NULL)
return; return;
Environment* env = wrap->env();
assert(!wrap->persistent().IsEmpty()); assert(!wrap->persistent().IsEmpty());
uv_close(wrap->handle__, OnClose); uv_close(wrap->handle__, OnClose);
wrap->handle__ = NULL; wrap->handle__ = NULL;
@ -96,7 +98,7 @@ HandleWrap::HandleWrap(Environment* env,
flags_(0), flags_(0),
handle__(handle) { handle__(handle) {
handle__->data = this; handle__->data = this;
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Wrap<HandleWrap>(object, this); Wrap<HandleWrap>(object, this);
QUEUE_INSERT_TAIL(&handle_wrap_queue, &handle_wrap_queue_); QUEUE_INSERT_TAIL(&handle_wrap_queue, &handle_wrap_queue_);
} }
@ -109,10 +111,9 @@ HandleWrap::~HandleWrap() {
void HandleWrap::OnClose(uv_handle_t* handle) { void HandleWrap::OnClose(uv_handle_t* handle) {
HandleScope scope(node_isolate);
HandleWrap* wrap = static_cast<HandleWrap*>(handle->data); HandleWrap* wrap = static_cast<HandleWrap*>(handle->data);
Environment* env = wrap->env(); Environment* env = wrap->env();
HandleScope scope(env->isolate());
// The wrap object should still be there. // The wrap object should still be there.
assert(wrap->persistent().IsEmpty() == false); assert(wrap->persistent().IsEmpty() == false);

517
src/node.cc

File diff suppressed because it is too large

100
src/node.h

@ -61,19 +61,47 @@
#include "v8.h" // NOLINT(build/include_order) #include "v8.h" // NOLINT(build/include_order)
#include "node_version.h" // NODE_MODULE_VERSION #include "node_version.h" // NODE_MODULE_VERSION
#define NODE_DEPRECATED(msg, fn) V8_DEPRECATED(msg, fn)
// Forward-declare these functions now to stop MSVS from becoming // Forward-declare these functions now to stop MSVS from becoming
// terminally confused when it's done in node_internals.h // terminally confused when it's done in node_internals.h
namespace node { namespace node {
NODE_EXTERN v8::Local<v8::Value> ErrnoException(int errorno, NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
int errorno,
const char* syscall = NULL, const char* syscall = NULL,
const char* message = NULL, const char* message = NULL,
const char* path = NULL); const char* path = NULL);
NODE_EXTERN v8::Local<v8::Value> UVException(int errorno, NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
int errorno,
const char* syscall = NULL, const char* syscall = NULL,
const char* message = NULL, const char* message = NULL,
const char* path = NULL); const char* path = NULL);
NODE_DEPRECATED("Use UVException(isolate, ...)",
inline v8::Local<v8::Value> ErrnoException(
int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL) {
return ErrnoException(v8::Isolate::GetCurrent(),
errorno,
syscall,
message,
path);
})
inline v8::Local<v8::Value> UVException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL) {
return UVException(v8::Isolate::GetCurrent(),
errorno,
syscall,
message,
path);
}
/* /*
* MakeCallback doesn't have a HandleScope. That means the callers scope * MakeCallback doesn't have a HandleScope. That means the callers scope
* will retain ownership of created handles from MakeCallback and related. * will retain ownership of created handles from MakeCallback and related.
@ -187,27 +215,79 @@ inline void NODE_SET_PROTOTYPE_METHOD(v8::Handle<v8::FunctionTemplate> recv,
#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
enum encoding ParseEncoding(v8::Handle<v8::Value> encoding_v, enum encoding ParseEncoding(v8::Isolate* isolate,
v8::Handle<v8::Value> encoding_v,
enum encoding _default = BINARY); enum encoding _default = BINARY);
NODE_EXTERN void FatalException(const v8::TryCatch& try_catch); NODE_DEPRECATED("Use ParseEncoding(isolate, ...)",
inline enum encoding ParseEncoding(
NODE_EXTERN v8::Local<v8::Value> Encode(const void *buf, size_t len, v8::Handle<v8::Value> encoding_v,
enum encoding _default = BINARY) {
return ParseEncoding(v8::Isolate::GetCurrent(), encoding_v, _default);
})
NODE_EXTERN void FatalException(v8::Isolate* isolate,
const v8::TryCatch& try_catch);
NODE_DEPRECATED("Use FatalException(isolate, ...)",
inline void FatalException(const v8::TryCatch& try_catch) {
return FatalException(v8::Isolate::GetCurrent(), try_catch);
})
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
const void* buf,
size_t len,
enum encoding encoding = BINARY); enum encoding encoding = BINARY);
NODE_DEPRECATED("Use Encode(isolate, ...)",
inline v8::Local<v8::Value> Encode(
const void* buf,
size_t len,
enum encoding encoding = BINARY) {
return Encode(v8::Isolate::GetCurrent(), buf, len, encoding);
})
// Returns -1 if the handle was not valid for decoding // Returns -1 if the handle was not valid for decoding
NODE_EXTERN ssize_t DecodeBytes(v8::Handle<v8::Value>, NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
v8::Handle<v8::Value>,
enum encoding encoding = BINARY); enum encoding encoding = BINARY);
NODE_DEPRECATED("Use DecodeBytes(isolate, ...)",
inline ssize_t DecodeBytes(
v8::Handle<v8::Value> val,
enum encoding encoding = BINARY) {
return DecodeBytes(v8::Isolate::GetCurrent(), val, encoding);
})
// returns bytes written. // returns bytes written.
NODE_EXTERN ssize_t DecodeWrite(char *buf, NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
char* buf,
size_t buflen, size_t buflen,
v8::Handle<v8::Value>, v8::Handle<v8::Value>,
enum encoding encoding = BINARY); enum encoding encoding = BINARY);
NODE_DEPRECATED("Use DecodeWrite(isolate, ...)",
inline ssize_t DecodeWrite(char* buf,
size_t buflen,
v8::Handle<v8::Value> val,
enum encoding encoding = BINARY) {
return DecodeWrite(v8::Isolate::GetCurrent(), buf, buflen, val, encoding);
})
#ifdef _WIN32 #ifdef _WIN32
NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(int errorno, NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
const char *syscall = NULL, const char *msg = "", v8::Isolate* isolate,
int errorno,
const char *syscall = NULL,
const char *msg = "",
const char *path = NULL); const char *path = NULL);
NODE_DEPRECATED("Use WinapiErrnoException(isolate, ...)",
inline v8::Local<v8::Value> WinapiErrnoException(int errorno,
const char *syscall = NULL, const char *msg = "",
const char *path = NULL) {
return WinapiErrnoException(v8::Isolate::GetCurrent(),
errorno,
syscall,
msg,
path);
})
#endif #endif
const char *signo_string(int errorno); const char *signo_string(int errorno);

121
src/node_buffer.cc

@ -37,7 +37,9 @@
#define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b))
#define CHECK_NOT_OOB(r) \ #define CHECK_NOT_OOB(r) \
do { if (!(r)) return ThrowRangeError("out of range index"); } while (0) do { \
if (!(r)) return env->ThrowRangeError("out of range index"); \
} while (0)
#define ARGS_THIS(argT) \ #define ARGS_THIS(argT) \
Local<Object> obj = argT; \ Local<Object> obj = argT; \
@ -66,6 +68,7 @@ using v8::FunctionCallbackInfo;
using v8::FunctionTemplate; using v8::FunctionTemplate;
using v8::Handle; using v8::Handle;
using v8::HandleScope; using v8::HandleScope;
using v8::Isolate;
using v8::Local; using v8::Local;
using v8::Number; using v8::Number;
using v8::Object; using v8::Object;
@ -113,23 +116,22 @@ size_t Length(Handle<Object> obj) {
} }
Local<Object> New(Handle<String> string, enum encoding enc) { Local<Object> New(Isolate* isolate, Handle<String> string, enum encoding enc) {
HandleScope scope(node_isolate); HandleScope scope(isolate);
size_t length = StringBytes::Size(string, enc); size_t length = StringBytes::Size(isolate, string, enc);
Local<Object> buf = New(length); Local<Object> buf = New(length);
char* data = Buffer::Data(buf); char* data = Buffer::Data(buf);
StringBytes::Write(data, length, string, enc); StringBytes::Write(isolate, data, length, string, enc);
return scope.Close(buf); return scope.Close(buf);
} }
Local<Object> New(size_t length) { Local<Object> New(Isolate* isolate, size_t length) {
HandleScope handle_scope(node_isolate); HandleScope handle_scope(isolate);
Environment* env = Environment::GetCurrent(node_isolate); Local<Object> obj = Buffer::New(Environment::GetCurrent(isolate), length);
Local<Object> obj = Buffer::New(env, length);
return handle_scope.Close(obj); return handle_scope.Close(obj);
} }
@ -137,11 +139,11 @@ Local<Object> New(size_t length) {
// TODO(trevnorris): these have a flaw by needing to call the Buffer inst then // TODO(trevnorris): these have a flaw by needing to call the Buffer inst then
// Alloc. continue to look for a better architecture. // Alloc. continue to look for a better architecture.
Local<Object> New(Environment* env, size_t length) { Local<Object> New(Environment* env, size_t length) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
assert(length <= kMaxLength); assert(length <= kMaxLength);
Local<Value> arg = Uint32::NewFromUnsigned(length, node_isolate); Local<Value> arg = Uint32::NewFromUnsigned(length, env->isolate());
Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg); Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
// TODO(trevnorris): done like this to handle HasInstance since only checks // TODO(trevnorris): done like this to handle HasInstance since only checks
@ -155,15 +157,15 @@ Local<Object> New(Environment* env, size_t length) {
} else { } else {
data = NULL; data = NULL;
} }
smalloc::Alloc(obj, data, length); smalloc::Alloc(env, obj, data, length);
return scope.Close(obj); return scope.Close(obj);
} }
Local<Object> New(const char* data, size_t length) { Local<Object> New(Isolate* isolate, const char* data, size_t length) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(isolate);
Environment* env = Environment::GetCurrent(node_isolate); HandleScope handle_scope(env->isolate());
Local<Object> obj = Buffer::New(env, data, length); Local<Object> obj = Buffer::New(env, data, length);
return handle_scope.Close(obj); return handle_scope.Close(obj);
} }
@ -173,11 +175,11 @@ Local<Object> New(const char* data, size_t length) {
// but for consistency w/ the other should use data. And a copy version renamed // but for consistency w/ the other should use data. And a copy version renamed
// to something else. // to something else.
Local<Object> New(Environment* env, const char* data, size_t length) { Local<Object> New(Environment* env, const char* data, size_t length) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
assert(length <= kMaxLength); assert(length <= kMaxLength);
Local<Value> arg = Uint32::NewFromUnsigned(length, node_isolate); Local<Value> arg = Uint32::NewFromUnsigned(length, env->isolate());
Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg); Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
// TODO(trevnorris): done like this to handle HasInstance since only checks // TODO(trevnorris): done like this to handle HasInstance since only checks
@ -193,18 +195,19 @@ Local<Object> New(Environment* env, const char* data, size_t length) {
new_data = NULL; new_data = NULL;
} }
smalloc::Alloc(obj, new_data, length); smalloc::Alloc(env, obj, new_data, length);
return scope.Close(obj); return scope.Close(obj);
} }
Local<Object> New(char* data, Local<Object> New(Isolate* isolate,
char* data,
size_t length, size_t length,
smalloc::FreeCallback callback, smalloc::FreeCallback callback,
void* hint) { void* hint) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(isolate);
Environment* env = Environment::GetCurrent(node_isolate); HandleScope handle_scope(env->isolate());
Local<Object> obj = Buffer::New(env, data, length, callback, hint); Local<Object> obj = Buffer::New(env, data, length, callback, hint);
return handle_scope.Close(obj); return handle_scope.Close(obj);
} }
@ -215,36 +218,36 @@ Local<Object> New(Environment* env,
size_t length, size_t length,
smalloc::FreeCallback callback, smalloc::FreeCallback callback,
void* hint) { void* hint) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
assert(length <= kMaxLength); assert(length <= kMaxLength);
Local<Value> arg = Uint32::NewFromUnsigned(length, node_isolate); Local<Value> arg = Uint32::NewFromUnsigned(length, env->isolate());
Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg); Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
smalloc::Alloc(obj, data, length, callback, hint); smalloc::Alloc(env, obj, data, length, callback, hint);
return scope.Close(obj); return scope.Close(obj);
} }
Local<Object> Use(char* data, uint32_t length) { Local<Object> Use(Isolate* isolate, char* data, uint32_t length) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(isolate);
Environment* env = Environment::GetCurrent(node_isolate); HandleScope handle_scope(env->isolate());
Local<Object> obj = Buffer::Use(env, data, length); Local<Object> obj = Buffer::Use(env, data, length);
return handle_scope.Close(obj); return handle_scope.Close(obj);
} }
Local<Object> Use(Environment* env, char* data, uint32_t length) { Local<Object> Use(Environment* env, char* data, uint32_t length) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
assert(length <= kMaxLength); assert(length <= kMaxLength);
Local<Value> arg = Uint32::NewFromUnsigned(length, node_isolate); Local<Value> arg = Uint32::NewFromUnsigned(length, env->isolate());
Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg); Local<Object> obj = env->buffer_constructor_function()->NewInstance(1, &arg);
smalloc::Alloc(obj, data, length); smalloc::Alloc(env, obj, data, length);
return scope.Close(obj); return scope.Close(obj);
} }
@ -252,13 +255,14 @@ Local<Object> Use(Environment* env, char* data, uint32_t length) {
template <encoding encoding> template <encoding encoding>
void StringSlice(const FunctionCallbackInfo<Value>& args) { void StringSlice(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ARGS_THIS(args.This()) ARGS_THIS(args.This())
SLICE_START_END(args[0], args[1], obj_length) SLICE_START_END(args[0], args[1], obj_length)
args.GetReturnValue().Set( args.GetReturnValue().Set(
StringBytes::Encode(obj_data + start, length, encoding)); StringBytes::Encode(env->isolate(), obj_data + start, length, encoding));
} }
@ -294,12 +298,13 @@ void Base64Slice(const FunctionCallbackInfo<Value>& args) {
// bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]); // bytesCopied = buffer.copy(target[, targetStart][, sourceStart][, sourceEnd]);
void Copy(const FunctionCallbackInfo<Value> &args) { void Copy(const FunctionCallbackInfo<Value> &args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Local<Object> target = args[0]->ToObject(); Local<Object> target = args[0]->ToObject();
if (!HasInstance(target)) if (!HasInstance(target))
return ThrowTypeError("first arg should be a Buffer"); return env->ThrowTypeError("first arg should be a Buffer");
ARGS_THIS(args.This()) ARGS_THIS(args.This())
size_t target_length = target->GetIndexedPropertiesExternalArrayDataLength(); size_t target_length = target->GetIndexedPropertiesExternalArrayDataLength();
@ -318,7 +323,7 @@ void Copy(const FunctionCallbackInfo<Value> &args) {
return args.GetReturnValue().Set(0); return args.GetReturnValue().Set(0);
if (source_start > obj_length) if (source_start > obj_length)
return ThrowRangeError("out of range index"); return env->ThrowRangeError("out of range index");
if (source_end - source_start > target_length - target_start) if (source_end - source_start > target_length - target_start)
source_end = source_start + target_length - target_start; source_end = source_start + target_length - target_start;
@ -334,7 +339,8 @@ void Copy(const FunctionCallbackInfo<Value> &args) {
// buffer.fill(value[, start][, end]); // buffer.fill(value[, start][, end]);
void Fill(const FunctionCallbackInfo<Value>& args) { void Fill(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ARGS_THIS(args.This()) ARGS_THIS(args.This())
SLICE_START_END(args[1], args[2], obj_length) SLICE_START_END(args[1], args[2], obj_length)
@ -379,17 +385,18 @@ void Fill(const FunctionCallbackInfo<Value>& args) {
template <encoding encoding> template <encoding encoding>
void StringWrite(const FunctionCallbackInfo<Value>& args) { void StringWrite(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ARGS_THIS(args.This()) ARGS_THIS(args.This())
if (!args[0]->IsString()) if (!args[0]->IsString())
return ThrowTypeError("Argument must be a string"); return env->ThrowTypeError("Argument must be a string");
Local<String> str = args[0]->ToString(); Local<String> str = args[0]->ToString();
if (encoding == HEX && str->Length() % 2 != 0) if (encoding == HEX && str->Length() % 2 != 0)
return ThrowTypeError("Invalid hex string"); return env->ThrowTypeError("Invalid hex string");
size_t offset; size_t offset;
size_t max_length; size_t max_length;
@ -406,9 +413,10 @@ void StringWrite(const FunctionCallbackInfo<Value>& args) {
max_length = max_length / 2; max_length = max_length / 2;
if (offset >= obj_length) if (offset >= obj_length)
return ThrowRangeError("Offset is out of bounds"); return env->ThrowRangeError("Offset is out of bounds");
uint32_t written = StringBytes::Write(obj_data + offset, uint32_t written = StringBytes::Write(env->isolate(),
obj_data + offset,
max_length, max_length,
str, str,
encoding, encoding,
@ -459,6 +467,7 @@ static inline void Swizzle(char* start, unsigned int len) {
template <typename T, enum Endianness endianness> template <typename T, enum Endianness endianness>
void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) { void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args.GetIsolate());
bool doAssert = !args[1]->BooleanValue(); bool doAssert = !args[1]->BooleanValue();
size_t offset; size_t offset;
@ -467,7 +476,7 @@ void ReadFloatGeneric(const FunctionCallbackInfo<Value>& args) {
if (doAssert) { if (doAssert) {
size_t len = Length(args.This()); size_t len = Length(args.This());
if (offset + sizeof(T) > len || offset + sizeof(T) < offset) if (offset + sizeof(T) > len || offset + sizeof(T) < offset)
return ThrowRangeError("Trying to read beyond buffer length"); return env->ThrowRangeError("Trying to read beyond buffer length");
} }
union NoAlias { union NoAlias {
@ -508,20 +517,21 @@ void ReadDoubleBE(const FunctionCallbackInfo<Value>& args) {
template <typename T, enum Endianness endianness> template <typename T, enum Endianness endianness>
uint32_t WriteFloatGeneric(const FunctionCallbackInfo<Value>& args) { uint32_t WriteFloatGeneric(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args.GetIsolate());
bool doAssert = !args[2]->BooleanValue(); bool doAssert = !args[2]->BooleanValue();
T val = static_cast<T>(args[0]->NumberValue()); T val = static_cast<T>(args[0]->NumberValue());
size_t offset; size_t offset;
if (!ParseArrayIndex(args[1], 0, &offset)) { if (!ParseArrayIndex(args[1], 0, &offset)) {
ThrowRangeError("out of range index"); env->ThrowRangeError("out of range index");
return 0; return 0;
} }
if (doAssert) { if (doAssert) {
size_t len = Length(args.This()); size_t len = Length(args.This());
if (offset + sizeof(T) > len || offset + sizeof(T) < offset) { if (offset + sizeof(T) > len || offset + sizeof(T) < offset) {
ThrowRangeError("Trying to write beyond buffer length"); env->ThrowRangeError("Trying to write beyond buffer length");
return 0; return 0;
} }
} }
@ -562,7 +572,8 @@ void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) {
void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) { void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ARGS_THIS(args.This()); ARGS_THIS(args.This());
void* adata = malloc(obj_length); void* adata = malloc(obj_length);
@ -581,30 +592,30 @@ void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
void ByteLength(const FunctionCallbackInfo<Value> &args) { void ByteLength(const FunctionCallbackInfo<Value> &args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (!args[0]->IsString()) if (!args[0]->IsString())
return ThrowTypeError("Argument must be a string"); return env->ThrowTypeError("Argument must be a string");
Local<String> s = args[0]->ToString(); Local<String> s = args[0]->ToString();
enum encoding e = ParseEncoding(args[1], UTF8); enum encoding e = ParseEncoding(env->isolate(), args[1], UTF8);
uint32_t size = StringBytes::Size(s, e); uint32_t size = StringBytes::Size(env->isolate(), s, e);
args.GetReturnValue().Set(size); args.GetReturnValue().Set(size);
} }
// pass Buffer object to load prototype methods // pass Buffer object to load prototype methods
void SetupBufferJS(const FunctionCallbackInfo<Value>& args) { void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(args.GetIsolate());
Environment* env = Environment::GetCurrent(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
assert(args[0]->IsFunction()); assert(args[0]->IsFunction());
Local<Function> bv = args[0].As<Function>(); Local<Function> bv = args[0].As<Function>();
env->set_buffer_constructor_function(bv); env->set_buffer_constructor_function(bv);
Local<Value> proto_v = Local<Value> proto_v = bv->Get(env->prototype_string());
bv->Get(FIXED_ONE_BYTE_STRING(node_isolate, "prototype"));
assert(proto_v->IsObject()); assert(proto_v->IsObject());
@ -640,15 +651,15 @@ void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
NODE_SET_METHOD(proto, "fill", Fill); NODE_SET_METHOD(proto, "fill", Fill);
// for backwards compatibility // for backwards compatibility
proto->Set(FIXED_ONE_BYTE_STRING(node_isolate, "offset"), proto->Set(env->offset_string(),
Uint32::New(0, node_isolate), Uint32::New(0, env->isolate()),
v8::ReadOnly); v8::ReadOnly);
assert(args[1]->IsObject()); assert(args[1]->IsObject());
Local<Object> internal = args[1].As<Object>(); Local<Object> internal = args[1].As<Object>();
internal->Set(FIXED_ONE_BYTE_STRING(node_isolate, "byteLength"), internal->Set(env->byte_length_string(),
FunctionTemplate::New(ByteLength)->GetFunction()); FunctionTemplate::New(ByteLength)->GetFunction());
} }

40
src/node_buffer.h

@ -43,22 +43,52 @@ NODE_EXTERN size_t Length(v8::Handle<v8::Value> val);
NODE_EXTERN size_t Length(v8::Handle<v8::Object> val); NODE_EXTERN size_t Length(v8::Handle<v8::Object> val);
// public constructor // public constructor
NODE_EXTERN v8::Local<v8::Object> New(size_t length); NODE_EXTERN v8::Local<v8::Object> New(v8::Isolate* isolate, size_t length);
NODE_DEPRECATED("Use New(isolate, ...)",
inline v8::Local<v8::Object> New(size_t length) {
return New(v8::Isolate::GetCurrent(), length);
})
// public constructor from string // public constructor from string
NODE_EXTERN v8::Local<v8::Object> New(v8::Handle<v8::String> string, NODE_EXTERN v8::Local<v8::Object> New(v8::Isolate* isolate,
v8::Handle<v8::String> string,
enum encoding enc = UTF8); enum encoding enc = UTF8);
NODE_DEPRECATED("Use New(isolate, ...)",
inline v8::Local<v8::Object> New(v8::Handle<v8::String> string,
enum encoding enc = UTF8) {
return New(v8::Isolate::GetCurrent(), string, enc);
})
// public constructor - data is copied // public constructor - data is copied
// TODO(trevnorris): should be something like Copy() // TODO(trevnorris): should be something like Copy()
NODE_EXTERN v8::Local<v8::Object> New(const char* data, size_t len); NODE_EXTERN v8::Local<v8::Object> New(v8::Isolate* isolate,
const char* data,
size_t len);
NODE_DEPRECATED("Use New(isolate, ...)",
inline v8::Local<v8::Object> New(const char* data, size_t len) {
return New(v8::Isolate::GetCurrent(), data, len);
})
// public constructor - data is used, callback is passed data on object gc // public constructor - data is used, callback is passed data on object gc
NODE_EXTERN v8::Local<v8::Object> New(char* data, NODE_EXTERN v8::Local<v8::Object> New(v8::Isolate* isolate,
char* data,
size_t length, size_t length,
smalloc::FreeCallback callback, smalloc::FreeCallback callback,
void* hint); void* hint);
NODE_DEPRECATED("Use New(isolate, ...)",
inline v8::Local<v8::Object> New(char* data,
size_t length,
smalloc::FreeCallback callback,
void* hint) {
return New(v8::Isolate::GetCurrent(), data, length, callback, hint);
})
// public constructor - data is used. // public constructor - data is used.
// TODO(trevnorris): should be New() for consistency // TODO(trevnorris): should be New() for consistency
NODE_EXTERN v8::Local<v8::Object> Use(char* data, uint32_t len); NODE_EXTERN v8::Local<v8::Object> Use(v8::Isolate* isolate,
char* data,
uint32_t len);
NODE_DEPRECATED("Use Use(isolate, ...)",
inline v8::Local<v8::Object> Use(char* data, uint32_t len) {
return Use(v8::Isolate::GetCurrent(), data, len);
})
// This is verbose to be explicit with inline commenting // This is verbose to be explicit with inline commenting
static inline bool IsWithinBounds(size_t off, size_t len, size_t max) { static inline bool IsWithinBounds(size_t off, size_t len, size_t max) {

118
src/node_contextify.cc

@ -128,7 +128,7 @@ class ContextifyContext {
// should be fixed properly in V8, and this copy function should be // should be fixed properly in V8, and this copy function should be
// removed once there is a better way. // removed once there is a better way.
void CopyProperties() { void CopyProperties() {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
Local<Context> context = PersistentToLocal(env()->isolate(), context_); Local<Context> context = PersistentToLocal(env()->isolate(), context_);
Local<Object> global = context->Global()->GetPrototype()->ToObject(); Local<Object> global = context->Global()->GetPrototype()->ToObject();
@ -155,7 +155,7 @@ class ContextifyContext {
// which doesn't faithfully capture the full range of configurations // which doesn't faithfully capture the full range of configurations
// that can be done using Object.defineProperty. // that can be done using Object.defineProperty.
if (clone_property_method.IsEmpty()) { if (clone_property_method.IsEmpty()) {
Local<String> code = FIXED_ONE_BYTE_STRING(node_isolate, Local<String> code = FIXED_ONE_BYTE_STRING(env()->isolate(),
"(function cloneProperty(source, key, target) {\n" "(function cloneProperty(source, key, target) {\n"
" if (key === 'Proxy') return;\n" " if (key === 'Proxy') return;\n"
" try {\n" " try {\n"
@ -167,7 +167,7 @@ class ContextifyContext {
" }\n" " }\n"
"})"); "})");
Local<String> fname = FIXED_ONE_BYTE_STRING(node_isolate, Local<String> fname = FIXED_ONE_BYTE_STRING(env()->isolate(),
"binding:script"); "binding:script");
Local<Script> script = Script::Compile(code, fname); Local<Script> script = Script::Compile(code, fname);
clone_property_method = Local<Function>::Cast(script->Run()); clone_property_method = Local<Function>::Cast(script->Run());
@ -186,7 +186,7 @@ class ContextifyContext {
// NamedPropertyHandler will store a reference to it forever and keep it // NamedPropertyHandler will store a reference to it forever and keep it
// from getting gc'd. // from getting gc'd.
Local<Value> CreateDataWrapper(Environment* env) { Local<Value> CreateDataWrapper(Environment* env) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<Object> wrapper = Local<Object> wrapper =
env->script_data_constructor_function()->NewInstance(); env->script_data_constructor_function()->NewInstance();
if (wrapper.IsEmpty()) if (wrapper.IsEmpty())
@ -198,11 +198,11 @@ class ContextifyContext {
Local<Context> CreateV8Context(Environment* env) { Local<Context> CreateV8Context(Environment* env) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<FunctionTemplate> function_template = FunctionTemplate::New(); Local<FunctionTemplate> function_template = FunctionTemplate::New();
function_template->SetHiddenPrototype(true); function_template->SetHiddenPrototype(true);
Local<Object> sandbox = PersistentToLocal(node_isolate, sandbox_); Local<Object> sandbox = PersistentToLocal(env->isolate(), sandbox_);
function_template->SetClassName(sandbox->GetConstructorName()); function_template->SetClassName(sandbox->GetConstructorName());
Local<ObjectTemplate> object_template = Local<ObjectTemplate> object_template =
@ -215,7 +215,7 @@ class ContextifyContext {
CreateDataWrapper(env)); CreateDataWrapper(env));
object_template->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck, object_template->SetAccessCheckCallbacks(GlobalPropertyNamedAccessCheck,
GlobalPropertyIndexedAccessCheck); GlobalPropertyIndexedAccessCheck);
return scope.Close(Context::New(node_isolate, NULL, object_template)); return scope.Close(Context::New(env->isolate(), NULL, object_template));
} }
@ -230,16 +230,16 @@ class ContextifyContext {
static void MakeContext(const FunctionCallbackInfo<Value>& args) { static void MakeContext(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(args.GetIsolate());
Environment* env = Environment::GetCurrent(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (!args[0]->IsObject()) { if (!args[0]->IsObject()) {
return ThrowTypeError("sandbox argument must be an object."); return env->ThrowTypeError("sandbox argument must be an object.");
} }
Local<Object> sandbox = args[0].As<Object>(); Local<Object> sandbox = args[0].As<Object>();
Local<String> hidden_name = Local<String> hidden_name =
FIXED_ONE_BYTE_STRING(node_isolate, "_contextifyHidden"); FIXED_ONE_BYTE_STRING(env->isolate(), "_contextifyHidden");
// Don't allow contextifying a sandbox multiple times. // Don't allow contextifying a sandbox multiple times.
assert(sandbox->GetHiddenValue(hidden_name).IsEmpty()); assert(sandbox->GetHiddenValue(hidden_name).IsEmpty());
@ -261,16 +261,17 @@ class ContextifyContext {
static void IsContext(const FunctionCallbackInfo<Value>& args) { static void IsContext(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (!args[0]->IsObject()) { if (!args[0]->IsObject()) {
ThrowTypeError("sandbox must be an object"); env->ThrowTypeError("sandbox must be an object");
return; return;
} }
Local<Object> sandbox = args[0].As<Object>(); Local<Object> sandbox = args[0].As<Object>();
Local<String> hidden_name = Local<String> hidden_name =
FIXED_ONE_BYTE_STRING(node_isolate, "_contextifyHidden"); FIXED_ONE_BYTE_STRING(env->isolate(), "_contextifyHidden");
args.GetReturnValue().Set(!sandbox->GetHiddenValue(hidden_name).IsEmpty()); args.GetReturnValue().Set(!sandbox->GetHiddenValue(hidden_name).IsEmpty());
} }
@ -287,9 +288,10 @@ class ContextifyContext {
static ContextifyContext* ContextFromContextifiedSandbox( static ContextifyContext* ContextFromContextifiedSandbox(
Isolate* isolate,
const Local<Object>& sandbox) { const Local<Object>& sandbox) {
Local<String> hidden_name = Local<String> hidden_name =
FIXED_ONE_BYTE_STRING(node_isolate, "_contextifyHidden"); FIXED_ONE_BYTE_STRING(isolate, "_contextifyHidden");
Local<Value> context_external_v = sandbox->GetHiddenValue(hidden_name); Local<Value> context_external_v = sandbox->GetHiddenValue(hidden_name);
if (context_external_v.IsEmpty() || !context_external_v->IsExternal()) { if (context_external_v.IsEmpty() || !context_external_v->IsExternal()) {
return NULL; return NULL;
@ -319,20 +321,21 @@ class ContextifyContext {
static void GlobalPropertyGetterCallback( static void GlobalPropertyGetterCallback(
Local<String> property, Local<String> property,
const PropertyCallbackInfo<Value>& args) { const PropertyCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
ContextifyContext* ctx = ContextifyContext* ctx =
Unwrap<ContextifyContext>(args.Data().As<Object>()); Unwrap<ContextifyContext>(args.Data().As<Object>());
Local<Object> sandbox = PersistentToLocal(node_isolate, ctx->sandbox_); Local<Object> sandbox = PersistentToLocal(isolate, ctx->sandbox_);
Local<Value> rv = sandbox->GetRealNamedProperty(property); Local<Value> rv = sandbox->GetRealNamedProperty(property);
if (rv.IsEmpty()) { if (rv.IsEmpty()) {
Local<Object> proxy_global = PersistentToLocal(node_isolate, Local<Object> proxy_global = PersistentToLocal(isolate,
ctx->proxy_global_); ctx->proxy_global_);
rv = proxy_global->GetRealNamedProperty(property); rv = proxy_global->GetRealNamedProperty(property);
} }
if (!rv.IsEmpty() && rv == ctx->sandbox_) { if (!rv.IsEmpty() && rv == ctx->sandbox_) {
rv = PersistentToLocal(node_isolate, ctx->proxy_global_); rv = PersistentToLocal(isolate, ctx->proxy_global_);
} }
args.GetReturnValue().Set(rv); args.GetReturnValue().Set(rv);
@ -343,25 +346,27 @@ class ContextifyContext {
Local<String> property, Local<String> property,
Local<Value> value, Local<Value> value,
const PropertyCallbackInfo<Value>& args) { const PropertyCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
ContextifyContext* ctx = ContextifyContext* ctx =
Unwrap<ContextifyContext>(args.Data().As<Object>()); Unwrap<ContextifyContext>(args.Data().As<Object>());
PersistentToLocal(node_isolate, ctx->sandbox_)->Set(property, value); PersistentToLocal(isolate, ctx->sandbox_)->Set(property, value);
} }
static void GlobalPropertyQueryCallback( static void GlobalPropertyQueryCallback(
Local<String> property, Local<String> property,
const PropertyCallbackInfo<Integer>& args) { const PropertyCallbackInfo<Integer>& args) {
HandleScope scope(node_isolate); Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
ContextifyContext* ctx = ContextifyContext* ctx =
Unwrap<ContextifyContext>(args.Data().As<Object>()); Unwrap<ContextifyContext>(args.Data().As<Object>());
Local<Object> sandbox = PersistentToLocal(node_isolate, ctx->sandbox_); Local<Object> sandbox = PersistentToLocal(isolate, ctx->sandbox_);
Local<Object> proxy_global = PersistentToLocal(node_isolate, Local<Object> proxy_global = PersistentToLocal(isolate,
ctx->proxy_global_); ctx->proxy_global_);
bool in_sandbox = sandbox->GetRealNamedProperty(property).IsEmpty(); bool in_sandbox = sandbox->GetRealNamedProperty(property).IsEmpty();
@ -376,15 +381,16 @@ class ContextifyContext {
static void GlobalPropertyDeleterCallback( static void GlobalPropertyDeleterCallback(
Local<String> property, Local<String> property,
const PropertyCallbackInfo<Boolean>& args) { const PropertyCallbackInfo<Boolean>& args) {
HandleScope scope(node_isolate); Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
ContextifyContext* ctx = ContextifyContext* ctx =
Unwrap<ContextifyContext>(args.Data().As<Object>()); Unwrap<ContextifyContext>(args.Data().As<Object>());
bool success = PersistentToLocal(node_isolate, bool success = PersistentToLocal(isolate,
ctx->sandbox_)->Delete(property); ctx->sandbox_)->Delete(property);
if (!success) { if (!success) {
success = PersistentToLocal(node_isolate, success = PersistentToLocal(isolate,
ctx->proxy_global_)->Delete(property); ctx->proxy_global_)->Delete(property);
} }
args.GetReturnValue().Set(success); args.GetReturnValue().Set(success);
@ -393,12 +399,12 @@ class ContextifyContext {
static void GlobalPropertyEnumeratorCallback( static void GlobalPropertyEnumeratorCallback(
const PropertyCallbackInfo<Array>& args) { const PropertyCallbackInfo<Array>& args) {
HandleScope scope(node_isolate); HandleScope scope(args.GetIsolate());
ContextifyContext* ctx = ContextifyContext* ctx =
Unwrap<ContextifyContext>(args.Data().As<Object>()); Unwrap<ContextifyContext>(args.Data().As<Object>());
Local<Object> sandbox = PersistentToLocal(node_isolate, ctx->sandbox_); Local<Object> sandbox = PersistentToLocal(args.GetIsolate(), ctx->sandbox_);
args.GetReturnValue().Set(sandbox->GetPropertyNames()); args.GetReturnValue().Set(sandbox->GetPropertyNames());
} }
}; };
@ -409,9 +415,9 @@ class ContextifyScript : public BaseObject {
public: public:
static void Init(Environment* env, Local<Object> target) { static void Init(Environment* env, Local<Object> target) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<String> class_name = Local<String> class_name =
FIXED_ONE_BYTE_STRING(node_isolate, "ContextifyScript"); FIXED_ONE_BYTE_STRING(env->isolate(), "ContextifyScript");
Local<FunctionTemplate> script_tmpl = FunctionTemplate::New(New); Local<FunctionTemplate> script_tmpl = FunctionTemplate::New(New);
script_tmpl->InstanceTemplate()->SetInternalFieldCount(1); script_tmpl->InstanceTemplate()->SetInternalFieldCount(1);
@ -428,13 +434,13 @@ class ContextifyScript : public BaseObject {
// args: code, [options] // args: code, [options]
static void New(const FunctionCallbackInfo<Value>& args) { static void New(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (!args.IsConstructCall()) { if (!args.IsConstructCall()) {
return ThrowError("Must call vm.Script as a constructor."); return env->ThrowError("Must call vm.Script as a constructor.");
} }
Environment* env = Environment::GetCurrent(args.GetIsolate());
ContextifyScript* contextify_script = ContextifyScript* contextify_script =
new ContextifyScript(env, args.This()); new ContextifyScript(env, args.This());
@ -459,7 +465,7 @@ class ContextifyScript : public BaseObject {
try_catch.ReThrow(); try_catch.ReThrow();
return; return;
} }
contextify_script->script_.Reset(node_isolate, v8_script); contextify_script->script_.Reset(env->isolate(), v8_script);
} }
@ -471,8 +477,8 @@ class ContextifyScript : public BaseObject {
// args: [options] // args: [options]
static void RunInThisContext(const FunctionCallbackInfo<Value>& args) { static void RunInThisContext(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(args.GetIsolate()); Isolate* isolate = args.GetIsolate();
Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope handle_scope(isolate);
// Assemble arguments // Assemble arguments
TryCatch try_catch; TryCatch try_catch;
@ -484,17 +490,20 @@ class ContextifyScript : public BaseObject {
} }
// Do the eval within this context // Do the eval within this context
Environment* env = Environment::GetCurrent(isolate);
EvalMachine(env, timeout, display_errors, args, try_catch); EvalMachine(env, timeout, display_errors, args, try_catch);
} }
// args: sandbox, [options] // args: sandbox, [options]
static void RunInContext(const FunctionCallbackInfo<Value>& args) { static void RunInContext(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
// Assemble arguments // Assemble arguments
TryCatch try_catch; TryCatch try_catch;
if (!args[0]->IsObject()) { if (!args[0]->IsObject()) {
return ThrowTypeError("contextifiedSandbox argument must be an object."); return env->ThrowTypeError(
"contextifiedSandbox argument must be an object.");
} }
Local<Object> sandbox = args[0].As<Object>(); Local<Object> sandbox = args[0].As<Object>();
int64_t timeout = GetTimeoutArg(args, 1); int64_t timeout = GetTimeoutArg(args, 1);
@ -506,9 +515,10 @@ class ContextifyScript : public BaseObject {
// Get the context from the sandbox // Get the context from the sandbox
ContextifyContext* contextify_context = ContextifyContext* contextify_context =
ContextifyContext::ContextFromContextifiedSandbox(sandbox); ContextifyContext::ContextFromContextifiedSandbox(env->isolate(),
sandbox);
if (contextify_context == NULL) { if (contextify_context == NULL) {
return ThrowTypeError( return env->ThrowTypeError(
"sandbox argument must have been converted to a context."); "sandbox argument must have been converted to a context.");
} }
@ -532,11 +542,12 @@ class ContextifyScript : public BaseObject {
return -1; return -1;
} }
if (!args[i]->IsObject()) { if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object"); Environment::ThrowTypeError(args.GetIsolate(),
"options must be an object");
return -1; return -1;
} }
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "timeout"); Local<String> key = FIXED_ONE_BYTE_STRING(args.GetIsolate(), "timeout");
Local<Value> value = args[i].As<Object>()->Get(key); Local<Value> value = args[i].As<Object>()->Get(key);
if (value->IsUndefined()) { if (value->IsUndefined()) {
return -1; return -1;
@ -544,7 +555,8 @@ class ContextifyScript : public BaseObject {
int64_t timeout = value->IntegerValue(); int64_t timeout = value->IntegerValue();
if (timeout <= 0) { if (timeout <= 0) {
ThrowRangeError("timeout must be a positive number"); Environment::ThrowRangeError(args.GetIsolate(),
"timeout must be a positive number");
return -1; return -1;
} }
return timeout; return timeout;
@ -557,11 +569,13 @@ class ContextifyScript : public BaseObject {
return true; return true;
} }
if (!args[i]->IsObject()) { if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object"); Environment::ThrowTypeError(args.GetIsolate(),
"options must be an object");
return false; return false;
} }
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "displayErrors"); Local<String> key = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
"displayErrors");
Local<Value> value = args[i].As<Object>()->Get(key); Local<Value> value = args[i].As<Object>()->Get(key);
return value->IsUndefined() ? true : value->BooleanValue(); return value->IsUndefined() ? true : value->BooleanValue();
@ -571,7 +585,7 @@ class ContextifyScript : public BaseObject {
static Local<String> GetFilenameArg(const FunctionCallbackInfo<Value>& args, static Local<String> GetFilenameArg(const FunctionCallbackInfo<Value>& args,
const int i) { const int i) {
Local<String> defaultFilename = Local<String> defaultFilename =
FIXED_ONE_BYTE_STRING(node_isolate, "evalmachine.<anonymous>"); FIXED_ONE_BYTE_STRING(args.GetIsolate(), "evalmachine.<anonymous>");
if (args[i]->IsUndefined()) { if (args[i]->IsUndefined()) {
return defaultFilename; return defaultFilename;
@ -580,11 +594,12 @@ class ContextifyScript : public BaseObject {
return args[i].As<String>(); return args[i].As<String>();
} }
if (!args[i]->IsObject()) { if (!args[i]->IsObject()) {
ThrowTypeError("options must be an object"); Environment::ThrowTypeError(args.GetIsolate(),
"options must be an object");
return Local<String>(); return Local<String>();
} }
Local<String> key = FIXED_ONE_BYTE_STRING(node_isolate, "filename"); Local<String> key = FIXED_ONE_BYTE_STRING(args.GetIsolate(), "filename");
Local<Value> value = args[i].As<Object>()->Get(key); Local<Value> value = args[i].As<Object>()->Get(key);
return value->IsUndefined() ? defaultFilename : value->ToString(); return value->IsUndefined() ? defaultFilename : value->ToString();
@ -597,13 +612,14 @@ class ContextifyScript : public BaseObject {
const FunctionCallbackInfo<Value>& args, const FunctionCallbackInfo<Value>& args,
TryCatch& try_catch) { TryCatch& try_catch) {
if (!ContextifyScript::InstanceOf(env, args.This())) { if (!ContextifyScript::InstanceOf(env, args.This())) {
ThrowTypeError("Script methods can only be called on script instances."); env->ThrowTypeError(
"Script methods can only be called on script instances.");
return false; return false;
} }
ContextifyScript* wrapped_script = ContextifyScript* wrapped_script =
Unwrap<ContextifyScript>(args.This()); Unwrap<ContextifyScript>(args.This());
Local<Script> script = PersistentToLocal(node_isolate, Local<Script> script = PersistentToLocal(env->isolate(),
wrapped_script->script_); wrapped_script->script_);
Local<Value> result; Local<Value> result;
@ -616,7 +632,7 @@ class ContextifyScript : public BaseObject {
if (try_catch.HasCaught() && try_catch.HasTerminated()) { if (try_catch.HasCaught() && try_catch.HasTerminated()) {
V8::CancelTerminateExecution(args.GetIsolate()); V8::CancelTerminateExecution(args.GetIsolate());
ThrowError("Script execution timed out."); env->ThrowError("Script execution timed out.");
return false; return false;
} }

8
src/node_counters.cc

@ -21,6 +21,8 @@
#include "node_counters.h" #include "node_counters.h"
#include "uv.h" #include "uv.h"
#include "env.h"
#include "env-inl.h"
#include <string.h> #include <string.h>
@ -96,8 +98,8 @@ static void counter_gc_done(GCType type, GCCallbackFlags flags) {
} }
void InitPerfCounters(Handle<Object> target) { void InitPerfCounters(Environment* env, Handle<Object> target) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
static struct { static struct {
const char* name; const char* name;
@ -114,7 +116,7 @@ void InitPerfCounters(Handle<Object> target) {
}; };
for (int i = 0; i < ARRAY_SIZE(tab); i++) { for (int i = 0; i < ARRAY_SIZE(tab); i++) {
Local<String> key = OneByteString(node_isolate, tab[i].name); Local<String> key = OneByteString(env->isolate(), tab[i].name);
Local<Value> val = FunctionTemplate::New(tab[i].func)->GetFunction(); Local<Value> val = FunctionTemplate::New(tab[i].func)->GetFunction();
target->Set(key, val); target->Set(key, val);
} }

3
src/node_counters.h

@ -43,10 +43,11 @@
#endif #endif
#include "v8.h" #include "v8.h"
#include "env.h"
namespace node { namespace node {
void InitPerfCounters(v8::Handle<v8::Object> target); void InitPerfCounters(Environment* env, v8::Handle<v8::Object> target);
void TermPerfCounters(v8::Handle<v8::Object> target); void TermPerfCounters(v8::Handle<v8::Object> target);
} // namespace node } // namespace node

624
src/node_crypto.cc

File diff suppressed because it is too large

6
src/node_crypto.h

@ -167,7 +167,7 @@ class SSLWrap {
protected: protected:
static void InitNPN(SecureContext* sc, Base* base); static void InitNPN(SecureContext* sc, Base* base);
static void AddMethods(v8::Handle<v8::FunctionTemplate> t); static void AddMethods(Environment* env, v8::Handle<v8::FunctionTemplate> t);
static SSL_SESSION* GetSessionCallback(SSL* s, static SSL_SESSION* GetSessionCallback(SSL* s,
unsigned char* key, unsigned char* key,
@ -477,7 +477,7 @@ class SignBase : public BaseObject {
} }
protected: protected:
static void CheckThrow(Error error); void CheckThrow(Error error);
EVP_MD_CTX mdctx_; /* coverity[member_decl] */ EVP_MD_CTX mdctx_; /* coverity[member_decl] */
const EVP_MD* md_; /* coverity[member_decl] */ const EVP_MD* md_; /* coverity[member_decl] */
@ -579,7 +579,7 @@ class DiffieHellman : public BaseObject {
class Certificate : public AsyncWrap { class Certificate : public AsyncWrap {
public: public:
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(Environment* env, v8::Handle<v8::Object> target);
v8::Handle<v8::Value> CertificateInit(const char* sign_type); v8::Handle<v8::Value> CertificateInit(const char* sign_type);
bool VerifySpkac(const char* data, unsigned int len); bool VerifySpkac(const char* data, unsigned int len);

66
src/node_dtrace.cc

@ -50,6 +50,9 @@
#define NODE_GC_DONE(arg0, arg1) #define NODE_GC_DONE(arg0, arg1)
#endif #endif
#include "env.h"
#include "env-inl.h"
namespace node { namespace node {
using v8::FunctionCallbackInfo; using v8::FunctionCallbackInfo;
@ -67,35 +70,38 @@ using v8::Value;
#define SLURP_STRING(obj, member, valp) \ #define SLURP_STRING(obj, member, valp) \
if (!(obj)->IsObject()) { \ if (!(obj)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected object for " #obj " to contain string member " #member); \ "expected object for " #obj " to contain string member " #member); \
} \ } \
String::Utf8Value _##member(obj->Get(OneByteString(node_isolate, #member))); \ String::Utf8Value _##member(obj->Get(OneByteString(env->isolate(), \
#member))); \
if ((*(const char **)valp = *_##member) == NULL) \ if ((*(const char **)valp = *_##member) == NULL) \
*(const char **)valp = "<unknown>"; *(const char **)valp = "<unknown>";
#define SLURP_INT(obj, member, valp) \ #define SLURP_INT(obj, member, valp) \
if (!(obj)->IsObject()) { \ if (!(obj)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected object for " #obj " to contain integer member " #member); \ "expected object for " #obj " to contain integer member " #member); \
} \ } \
*valp = obj->Get(OneByteString(node_isolate, #member))->ToInteger()->Value(); *valp = obj->Get(OneByteString(env->isolate(), #member)) \
->ToInteger()->Value();
#define SLURP_OBJECT(obj, member, valp) \ #define SLURP_OBJECT(obj, member, valp) \
if (!(obj)->IsObject()) { \ if (!(obj)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected object for " #obj " to contain object member " #member); \ "expected object for " #obj " to contain object member " #member); \
} \ } \
*valp = Local<Object>::Cast(obj->Get(OneByteString(node_isolate, #member))); *valp = Local<Object>::Cast(obj->Get(OneByteString(env->isolate(), #member)));
#define SLURP_CONNECTION(arg, conn) \ #define SLURP_CONNECTION(arg, conn) \
if (!(arg)->IsObject()) { \ if (!(arg)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected argument " #arg " to be a connection object"); \ "expected argument " #arg " to be a connection object"); \
} \ } \
node_dtrace_connection_t conn; \ node_dtrace_connection_t conn; \
Local<Object> _##conn = Local<Object>::Cast(arg); \ Local<Object> _##conn = Local<Object>::Cast(arg); \
Local<Value> _handle = (_##conn)->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_handle")); \ Local<Value> _handle = \
(_##conn)->Get(FIXED_ONE_BYTE_STRING(env->isolate(), "_handle")); \
if (_handle->IsObject()) { \ if (_handle->IsObject()) { \
SLURP_INT(_handle.As<Object>(), fd, &conn.fd); \ SLURP_INT(_handle.As<Object>(), fd, &conn.fd); \
} else { \ } else { \
@ -107,7 +113,7 @@ using v8::Value;
#define SLURP_CONNECTION_HTTP_CLIENT(arg, conn) \ #define SLURP_CONNECTION_HTTP_CLIENT(arg, conn) \
if (!(arg)->IsObject()) { \ if (!(arg)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected argument " #arg " to be a connection object"); \ "expected argument " #arg " to be a connection object"); \
} \ } \
node_dtrace_connection_t conn; \ node_dtrace_connection_t conn; \
@ -119,11 +125,11 @@ using v8::Value;
#define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn) \ #define SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(arg0, arg1, conn) \
if (!(arg0)->IsObject()) { \ if (!(arg0)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected argument " #arg0 " to be a connection object"); \ "expected argument " #arg0 " to be a connection object"); \
} \ } \
if (!(arg1)->IsObject()) { \ if (!(arg1)->IsObject()) { \
return ThrowError( \ return env->ThrowError( \
"expected argument " #arg1 " to be a connection object"); \ "expected argument " #arg1 " to be a connection object"); \
} \ } \
node_dtrace_connection_t conn; \ node_dtrace_connection_t conn; \
@ -138,7 +144,8 @@ using v8::Value;
void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo<Value>& args) { void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo<Value>& args) {
if (!NODE_NET_SERVER_CONNECTION_ENABLED()) if (!NODE_NET_SERVER_CONNECTION_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION(args[0], conn); SLURP_CONNECTION(args[0], conn);
NODE_NET_SERVER_CONNECTION(&conn, conn.remote, conn.port, conn.fd); NODE_NET_SERVER_CONNECTION(&conn, conn.remote, conn.port, conn.fd);
} }
@ -147,7 +154,8 @@ void DTRACE_NET_SERVER_CONNECTION(const FunctionCallbackInfo<Value>& args) {
void DTRACE_NET_STREAM_END(const FunctionCallbackInfo<Value>& args) { void DTRACE_NET_STREAM_END(const FunctionCallbackInfo<Value>& args) {
if (!NODE_NET_STREAM_END_ENABLED()) if (!NODE_NET_STREAM_END_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION(args[0], conn); SLURP_CONNECTION(args[0], conn);
NODE_NET_STREAM_END(&conn, conn.remote, conn.port, conn.fd); NODE_NET_STREAM_END(&conn, conn.remote, conn.port, conn.fd);
} }
@ -156,11 +164,12 @@ void DTRACE_NET_STREAM_END(const FunctionCallbackInfo<Value>& args) {
void DTRACE_NET_SOCKET_READ(const FunctionCallbackInfo<Value>& args) { void DTRACE_NET_SOCKET_READ(const FunctionCallbackInfo<Value>& args) {
if (!NODE_NET_SOCKET_READ_ENABLED()) if (!NODE_NET_SOCKET_READ_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION(args[0], conn); SLURP_CONNECTION(args[0], conn);
if (!args[1]->IsNumber()) { if (!args[1]->IsNumber()) {
return ThrowError("expected argument 1 to be number of bytes"); return env->ThrowError("expected argument 1 to be number of bytes");
} }
int nbytes = args[1]->Int32Value(); int nbytes = args[1]->Int32Value();
@ -171,11 +180,12 @@ void DTRACE_NET_SOCKET_READ(const FunctionCallbackInfo<Value>& args) {
void DTRACE_NET_SOCKET_WRITE(const FunctionCallbackInfo<Value>& args) { void DTRACE_NET_SOCKET_WRITE(const FunctionCallbackInfo<Value>& args) {
if (!NODE_NET_SOCKET_WRITE_ENABLED()) if (!NODE_NET_SOCKET_WRITE_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION(args[0], conn); SLURP_CONNECTION(args[0], conn);
if (!args[1]->IsNumber()) { if (!args[1]->IsNumber()) {
return ThrowError("expected argument 1 to be number of bytes"); return env->ThrowError("expected argument 1 to be number of bytes");
} }
int nbytes = args[1]->Int32Value(); int nbytes = args[1]->Int32Value();
@ -189,7 +199,8 @@ void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo<Value>& args) {
if (!NODE_HTTP_SERVER_REQUEST_ENABLED()) if (!NODE_HTTP_SERVER_REQUEST_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Local<Object> arg0 = Local<Object>::Cast(args[0]); Local<Object> arg0 = Local<Object>::Cast(args[0]);
Local<Object> headers; Local<Object> headers;
@ -200,11 +211,11 @@ void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo<Value>& args) {
SLURP_OBJECT(arg0, headers, &headers); SLURP_OBJECT(arg0, headers, &headers);
if (!(headers)->IsObject()) { if (!(headers)->IsObject()) {
return ThrowError( return env->ThrowError(
"expected object for request to contain string member headers"); "expected object for request to contain string member headers");
} }
Local<Value> strfwdfor = headers->Get(FIXED_ONE_BYTE_STRING(node_isolate, "x-forwarded-for")); Local<Value> strfwdfor = headers->Get(env->x_forwarded_string());
String::Utf8Value fwdfor(strfwdfor); String::Utf8Value fwdfor(strfwdfor);
if (!strfwdfor->IsString() || (req.forwardedFor = *fwdfor) == NULL) if (!strfwdfor->IsString() || (req.forwardedFor = *fwdfor) == NULL)
@ -219,7 +230,8 @@ void DTRACE_HTTP_SERVER_REQUEST(const FunctionCallbackInfo<Value>& args) {
void DTRACE_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo<Value>& args) { void DTRACE_HTTP_SERVER_RESPONSE(const FunctionCallbackInfo<Value>& args) {
if (!NODE_HTTP_SERVER_RESPONSE_ENABLED()) if (!NODE_HTTP_SERVER_RESPONSE_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION(args[0], conn); SLURP_CONNECTION(args[0], conn);
NODE_HTTP_SERVER_RESPONSE(&conn, conn.remote, conn.port, conn.fd); NODE_HTTP_SERVER_RESPONSE(&conn, conn.remote, conn.port, conn.fd);
} }
@ -232,7 +244,8 @@ void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo<Value>& args) {
if (!NODE_HTTP_CLIENT_REQUEST_ENABLED()) if (!NODE_HTTP_CLIENT_REQUEST_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
/* /*
* For the method and URL, we're going to dig them out of the header. This * For the method and URL, we're going to dig them out of the header. This
@ -267,7 +280,8 @@ void DTRACE_HTTP_CLIENT_REQUEST(const FunctionCallbackInfo<Value>& args) {
void DTRACE_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo<Value>& args) { void DTRACE_HTTP_CLIENT_RESPONSE(const FunctionCallbackInfo<Value>& args) {
if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED()) if (!NODE_HTTP_CLIENT_RESPONSE_ENABLED())
return; return;
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(args[0], args[1], conn); SLURP_CONNECTION_HTTP_CLIENT_RESPONSE(args[0], args[1], conn);
NODE_HTTP_CLIENT_RESPONSE(&conn, conn.remote, conn.port, conn.fd); NODE_HTTP_CLIENT_RESPONSE(&conn, conn.remote, conn.port, conn.fd);
} }
@ -289,8 +303,8 @@ static int dtrace_gc_done(GCType type, GCCallbackFlags flags) {
} }
void InitDTrace(Handle<Object> target) { void InitDTrace(Environment* env, Handle<Object> target) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
static struct { static struct {
const char *name; const char *name;
@ -309,7 +323,7 @@ void InitDTrace(Handle<Object> target) {
}; };
for (unsigned int i = 0; i < ARRAY_SIZE(tab); i++) { for (unsigned int i = 0; i < ARRAY_SIZE(tab); i++) {
Local<String> key = OneByteString(node_isolate, tab[i].name); Local<String> key = OneByteString(env->isolate(), tab[i].name);
Local<Value> val = FunctionTemplate::New(tab[i].func)->GetFunction(); Local<Value> val = FunctionTemplate::New(tab[i].func)->GetFunction();
target->Set(key, val); target->Set(key, val);
} }

3
src/node_dtrace.h

@ -24,6 +24,7 @@
#include "node.h" #include "node.h"
#include "v8.h" #include "v8.h"
#include "env.h"
extern "C" { extern "C" {
/* /*
@ -74,7 +75,7 @@ typedef struct {
namespace node { namespace node {
void InitDTrace(v8::Handle<v8::Object> target); void InitDTrace(Environment* env, v8::Handle<v8::Object> target);
} // namespace node } // namespace node

130
src/node_file.cc

@ -60,7 +60,7 @@ using v8::Value;
#define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b))
#define TYPE_ERROR(msg) ThrowTypeError(msg) #define TYPE_ERROR(msg) env->ThrowTypeError(msg)
#define THROW_BAD_ARGS TYPE_ERROR("Bad argument") #define THROW_BAD_ARGS TYPE_ERROR("Bad argument")
@ -98,11 +98,11 @@ class FSReqWrap: public ReqWrap<uv_fs_t> {
#define ASSERT_OFFSET(a) \ #define ASSERT_OFFSET(a) \
if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \
return ThrowTypeError("Not an integer"); \ return env->ThrowTypeError("Not an integer"); \
} }
#define ASSERT_TRUNCATE_LENGTH(a) \ #define ASSERT_TRUNCATE_LENGTH(a) \
if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \ if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \
return ThrowTypeError("Not an integer"); \ return env->ThrowTypeError("Not an integer"); \
} }
#define GET_OFFSET(a) ((a)->IsNumber() ? (a)->IntegerValue() : -1) #define GET_OFFSET(a) ((a)->IsNumber() ? (a)->IntegerValue() : -1)
#define GET_TRUNCATE_LENGTH(a) ((a)->IntegerValue()) #define GET_TRUNCATE_LENGTH(a) ((a)->IntegerValue())
@ -148,7 +148,7 @@ static void After(uv_fs_t *req) {
} }
} else { } else {
// error value is empty or null for non-error. // error value is empty or null for non-error.
argv[0] = Null(node_isolate); argv[0] = Null(env->isolate());
// All have at least two args now. // All have at least two args now.
argc = 2; argc = 2;
@ -179,11 +179,11 @@ static void After(uv_fs_t *req) {
break; break;
case UV_FS_OPEN: case UV_FS_OPEN:
argv[1] = Integer::New(req->result, node_isolate); argv[1] = Integer::New(req->result, env->isolate());
break; break;
case UV_FS_WRITE: case UV_FS_WRITE:
argv[1] = Integer::New(req->result, node_isolate); argv[1] = Integer::New(req->result, env->isolate());
break; break;
case UV_FS_STAT: case UV_FS_STAT:
@ -194,13 +194,13 @@ static void After(uv_fs_t *req) {
break; break;
case UV_FS_READLINK: case UV_FS_READLINK:
argv[1] = String::NewFromUtf8(node_isolate, argv[1] = String::NewFromUtf8(env->isolate(),
static_cast<const char*>(req->ptr)); static_cast<const char*>(req->ptr));
break; break;
case UV_FS_READ: case UV_FS_READ:
// Buffer interface // Buffer interface
argv[1] = Integer::New(req->result, node_isolate); argv[1] = Integer::New(req->result, env->isolate());
break; break;
case UV_FS_READDIR: case UV_FS_READDIR:
@ -211,7 +211,7 @@ static void After(uv_fs_t *req) {
Local<Array> names = Array::New(nnames); Local<Array> names = Array::New(nnames);
for (int i = 0; i < nnames; i++) { for (int i = 0; i < nnames; i++) {
Local<String> name = String::NewFromUtf8(node_isolate, namebuf); Local<String> name = String::NewFromUtf8(env->isolate(), namebuf);
names->Set(i, name); names->Set(i, name);
#ifndef NDEBUG #ifndef NDEBUG
namebuf += strlen(namebuf); namebuf += strlen(namebuf);
@ -281,7 +281,6 @@ struct fs_req_wrap {
#define SYNC_DEST_CALL(func, path, dest, ...) \ #define SYNC_DEST_CALL(func, path, dest, ...) \
fs_req_wrap req_wrap; \ fs_req_wrap req_wrap; \
Environment* env = Environment::GetCurrent(args.GetIsolate()); \
int err = uv_fs_ ## func(env->event_loop(), \ int err = uv_fs_ ## func(env->event_loop(), \
&req_wrap.req, \ &req_wrap.req, \
__VA_ARGS__, \ __VA_ARGS__, \
@ -291,9 +290,9 @@ struct fs_req_wrap {
(err == UV_EEXIST || \ (err == UV_EEXIST || \
err == UV_ENOTEMPTY || \ err == UV_ENOTEMPTY || \
err == UV_EPERM)) { \ err == UV_EPERM)) { \
return ThrowUVException(err, #func, "", dest); \ return env->ThrowUVException(err, #func, "", dest); \
} else { \ } else { \
return ThrowUVException(err, #func, "", path); \ return env->ThrowUVException(err, #func, "", path); \
} \ } \
} \ } \
@ -306,7 +305,8 @@ struct fs_req_wrap {
static void Close(const FunctionCallbackInfo<Value>& args) { static void Close(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1 || !args[0]->IsInt32()) { if (args.Length() < 1 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -346,7 +346,7 @@ Local<Object> BuildStatsObject(Environment* env, const uv_stat_t* s) {
// and make sure that we bail out when V8 returns an empty handle. // and make sure that we bail out when V8 returns an empty handle.
#define X(name) \ #define X(name) \
{ \ { \
Local<Value> val = Integer::New(s->st_##name, node_isolate); \ Local<Value> val = Integer::New(s->st_##name, env->isolate()); \
if (val.IsEmpty()) \ if (val.IsEmpty()) \
return Local<Object>(); \ return Local<Object>(); \
stats->Set(env->name ## _string(), val); \ stats->Set(env->name ## _string(), val); \
@ -395,7 +395,8 @@ Local<Object> BuildStatsObject(Environment* env, const uv_stat_t* s) {
} }
static void Stat(const FunctionCallbackInfo<Value>& args) { static void Stat(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -414,7 +415,8 @@ static void Stat(const FunctionCallbackInfo<Value>& args) {
} }
static void LStat(const FunctionCallbackInfo<Value>& args) { static void LStat(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -433,7 +435,8 @@ static void LStat(const FunctionCallbackInfo<Value>& args) {
} }
static void FStat(const FunctionCallbackInfo<Value>& args) { static void FStat(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1 || !args[0]->IsInt32()) { if (args.Length() < 1 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -451,7 +454,8 @@ static void FStat(const FunctionCallbackInfo<Value>& args) {
} }
static void Symlink(const FunctionCallbackInfo<Value>& args) { static void Symlink(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -474,7 +478,7 @@ static void Symlink(const FunctionCallbackInfo<Value>& args) {
} else if (strcmp(*mode, "junction") == 0) { } else if (strcmp(*mode, "junction") == 0) {
flags |= UV_FS_SYMLINK_JUNCTION; flags |= UV_FS_SYMLINK_JUNCTION;
} else if (strcmp(*mode, "file") != 0) { } else if (strcmp(*mode, "file") != 0) {
return ThrowError("Unknown symlink type"); return env->ThrowError("Unknown symlink type");
} }
} }
@ -486,7 +490,8 @@ static void Symlink(const FunctionCallbackInfo<Value>& args) {
} }
static void Link(const FunctionCallbackInfo<Value>& args) { static void Link(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -509,7 +514,8 @@ static void Link(const FunctionCallbackInfo<Value>& args) {
} }
static void ReadLink(const FunctionCallbackInfo<Value>& args) { static void ReadLink(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -523,13 +529,14 @@ static void ReadLink(const FunctionCallbackInfo<Value>& args) {
} else { } else {
SYNC_CALL(readlink, *path, *path) SYNC_CALL(readlink, *path, *path)
const char* link_path = static_cast<const char*>(SYNC_REQ.ptr); const char* link_path = static_cast<const char*>(SYNC_REQ.ptr);
Local<String> rc = String::NewFromUtf8(node_isolate, link_path); Local<String> rc = String::NewFromUtf8(env->isolate(), link_path);
args.GetReturnValue().Set(rc); args.GetReturnValue().Set(rc);
} }
} }
static void Rename(const FunctionCallbackInfo<Value>& args) { static void Rename(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -552,7 +559,8 @@ static void Rename(const FunctionCallbackInfo<Value>& args) {
} }
static void FTruncate(const FunctionCallbackInfo<Value>& args) { static void FTruncate(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 2 || !args[0]->IsInt32()) { if (args.Length() < 2 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -571,7 +579,8 @@ static void FTruncate(const FunctionCallbackInfo<Value>& args) {
} }
static void Fdatasync(const FunctionCallbackInfo<Value>& args) { static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1 || !args[0]->IsInt32()) { if (args.Length() < 1 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -587,7 +596,8 @@ static void Fdatasync(const FunctionCallbackInfo<Value>& args) {
} }
static void Fsync(const FunctionCallbackInfo<Value>& args) { static void Fsync(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1 || !args[0]->IsInt32()) { if (args.Length() < 1 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -603,7 +613,8 @@ static void Fsync(const FunctionCallbackInfo<Value>& args) {
} }
static void Unlink(const FunctionCallbackInfo<Value>& args) { static void Unlink(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -620,7 +631,8 @@ static void Unlink(const FunctionCallbackInfo<Value>& args) {
} }
static void RMDir(const FunctionCallbackInfo<Value>& args) { static void RMDir(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -637,7 +649,8 @@ static void RMDir(const FunctionCallbackInfo<Value>& args) {
} }
static void MKDir(const FunctionCallbackInfo<Value>& args) { static void MKDir(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -654,7 +667,8 @@ static void MKDir(const FunctionCallbackInfo<Value>& args) {
} }
static void ReadDir(const FunctionCallbackInfo<Value>& args) { static void ReadDir(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 1) if (args.Length() < 1)
return TYPE_ERROR("path required"); return TYPE_ERROR("path required");
@ -674,7 +688,7 @@ static void ReadDir(const FunctionCallbackInfo<Value>& args) {
Local<Array> names = Array::New(nnames); Local<Array> names = Array::New(nnames);
for (uint32_t i = 0; i < nnames; ++i) { for (uint32_t i = 0; i < nnames; ++i) {
names->Set(i, String::NewFromUtf8(node_isolate, namebuf)); names->Set(i, String::NewFromUtf8(env->isolate(), namebuf));
#ifndef NDEBUG #ifndef NDEBUG
namebuf += strlen(namebuf); namebuf += strlen(namebuf);
assert(*namebuf == '\0'); assert(*namebuf == '\0');
@ -689,7 +703,8 @@ static void ReadDir(const FunctionCallbackInfo<Value>& args) {
} }
static void Open(const FunctionCallbackInfo<Value>& args) { static void Open(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -728,7 +743,8 @@ static void Open(const FunctionCallbackInfo<Value>& args) {
// 4 position if integer, position to write at in the file. // 4 position if integer, position to write at in the file.
// if null, write from the current position // if null, write from the current position
static void WriteBuffer(const FunctionCallbackInfo<Value>& args) { static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
assert(args[0]->IsInt32()); assert(args[0]->IsInt32());
assert(Buffer::HasInstance(args[1])); assert(Buffer::HasInstance(args[1]));
@ -743,13 +759,13 @@ static void WriteBuffer(const FunctionCallbackInfo<Value>& args) {
Local<Value> cb = args[5]; Local<Value> cb = args[5];
if (off > buffer_length) if (off > buffer_length)
return ThrowRangeError("offset out of bounds"); return env->ThrowRangeError("offset out of bounds");
if (len > buffer_length) if (len > buffer_length)
return ThrowRangeError("length out of bounds"); return env->ThrowRangeError("length out of bounds");
if (off + len < off) if (off + len < off)
return ThrowRangeError("off + len overflow"); return env->ThrowRangeError("off + len overflow");
if (!Buffer::IsWithinBounds(off, len, buffer_length)) if (!Buffer::IsWithinBounds(off, len, buffer_length))
return ThrowRangeError("off + len > buffer.length"); return env->ThrowRangeError("off + len > buffer.length");
buf += off; buf += off;
@ -776,7 +792,7 @@ static void WriteString(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate());
if (!args[0]->IsInt32()) if (!args[0]->IsInt32())
return ThrowTypeError("First argument must be file descriptor"); return env->ThrowTypeError("First argument must be file descriptor");
Local<Value> cb; Local<Value> cb;
Local<Value> string = args[1]; Local<Value> string = args[1];
@ -787,15 +803,16 @@ static void WriteString(const FunctionCallbackInfo<Value>& args) {
bool must_free = false; bool must_free = false;
// will assign buf and len if string was external // will assign buf and len if string was external
if (!StringBytes::GetExternalParts(string, if (!StringBytes::GetExternalParts(env->isolate(),
string,
const_cast<const char**>(&buf), const_cast<const char**>(&buf),
&len)) { &len)) {
enum encoding enc = ParseEncoding(args[3], UTF8); enum encoding enc = ParseEncoding(args[3], UTF8);
len = StringBytes::StorageSize(string, enc); len = StringBytes::StorageSize(env->isolate(), string, enc);
buf = new char[len]; buf = new char[len];
// StorageSize may return too large a char, so correct the actual length // StorageSize may return too large a char, so correct the actual length
// by the write size // by the write size
len = StringBytes::Write(buf, len, args[1], enc); len = StringBytes::Write(env->isolate(), buf, len, args[1], enc);
must_free = true; must_free = true;
} }
pos = GET_OFFSET(args[2]); pos = GET_OFFSET(args[2]);
@ -842,7 +859,8 @@ static void WriteString(const FunctionCallbackInfo<Value>& args) {
* *
*/ */
static void Read(const FunctionCallbackInfo<Value>& args) { static void Read(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 2 || !args[0]->IsInt32()) { if (args.Length() < 2 || !args[0]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -858,7 +876,7 @@ static void Read(const FunctionCallbackInfo<Value>& args) {
char * buf = NULL; char * buf = NULL;
if (!Buffer::HasInstance(args[1])) { if (!Buffer::HasInstance(args[1])) {
return ThrowError("Second argument needs to be a buffer"); return env->ThrowError("Second argument needs to be a buffer");
} }
Local<Object> buffer_obj = args[1]->ToObject(); Local<Object> buffer_obj = args[1]->ToObject();
@ -867,12 +885,12 @@ static void Read(const FunctionCallbackInfo<Value>& args) {
size_t off = args[2]->Int32Value(); size_t off = args[2]->Int32Value();
if (off >= buffer_length) { if (off >= buffer_length) {
return ThrowError("Offset is out of bounds"); return env->ThrowError("Offset is out of bounds");
} }
len = args[3]->Int32Value(); len = args[3]->Int32Value();
if (!Buffer::IsWithinBounds(off, len, buffer_length)) if (!Buffer::IsWithinBounds(off, len, buffer_length))
return ThrowRangeError("Length extends beyond buffer"); return env->ThrowRangeError("Length extends beyond buffer");
pos = GET_OFFSET(args[4]); pos = GET_OFFSET(args[4]);
@ -893,7 +911,8 @@ static void Read(const FunctionCallbackInfo<Value>& args) {
* Wrapper for chmod(1) / EIO_CHMOD * Wrapper for chmod(1) / EIO_CHMOD
*/ */
static void Chmod(const FunctionCallbackInfo<Value>& args) { static void Chmod(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) { if (args.Length() < 2 || !args[0]->IsString() || !args[1]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -913,7 +932,8 @@ static void Chmod(const FunctionCallbackInfo<Value>& args) {
* Wrapper for fchmod(1) / EIO_FCHMOD * Wrapper for fchmod(1) / EIO_FCHMOD
*/ */
static void FChmod(const FunctionCallbackInfo<Value>& args) { static void FChmod(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) { if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsInt32()) {
return THROW_BAD_ARGS; return THROW_BAD_ARGS;
@ -933,7 +953,8 @@ static void FChmod(const FunctionCallbackInfo<Value>& args) {
* Wrapper for chown(1) / EIO_CHOWN * Wrapper for chown(1) / EIO_CHOWN
*/ */
static void Chown(const FunctionCallbackInfo<Value>& args) { static void Chown(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -965,7 +986,8 @@ static void Chown(const FunctionCallbackInfo<Value>& args) {
* Wrapper for fchown(1) / EIO_FCHOWN * Wrapper for fchown(1) / EIO_FCHOWN
*/ */
static void FChown(const FunctionCallbackInfo<Value>& args) { static void FChown(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -994,7 +1016,8 @@ static void FChown(const FunctionCallbackInfo<Value>& args) {
static void UTimes(const FunctionCallbackInfo<Value>& args) { static void UTimes(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -1022,7 +1045,8 @@ static void UTimes(const FunctionCallbackInfo<Value>& args) {
} }
static void FUTimes(const FunctionCallbackInfo<Value>& args) { static void FUTimes(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int len = args.Length(); int len = args.Length();
if (len < 1) if (len < 1)
@ -1058,7 +1082,7 @@ void InitFs(Handle<Object> target,
// Initialize the stats object // Initialize the stats object
Local<Function> constructor = FunctionTemplate::New()->GetFunction(); Local<Function> constructor = FunctionTemplate::New()->GetFunction();
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Stats"), constructor); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Stats"), constructor);
env->set_stats_constructor_function(constructor); env->set_stats_constructor_function(constructor);
NODE_SET_METHOD(target, "close", Close); NODE_SET_METHOD(target, "close", Close);
@ -1092,7 +1116,7 @@ void InitFs(Handle<Object> target,
NODE_SET_METHOD(target, "utimes", UTimes); NODE_SET_METHOD(target, "utimes", UTimes);
NODE_SET_METHOD(target, "futimes", FUTimes); NODE_SET_METHOD(target, "futimes", FUTimes);
StatWatcher::Initialize(target); StatWatcher::Initialize(env, target);
} }
} // end namespace node } // end namespace node

102
src/node_http_parser.cc

@ -149,11 +149,11 @@ struct StringPtr {
} }
Local<String> ToString() const { Local<String> ToString(Environment* env) const {
if (str_) if (str_)
return OneByteString(node_isolate, str_, size_); return OneByteString(env->isolate(), str_, size_);
else else
return String::Empty(node_isolate); return String::Empty(env->isolate());
} }
@ -252,7 +252,7 @@ class Parser : public BaseObject {
// Fast case, pass headers and URL to JS land. // Fast case, pass headers and URL to JS land.
message_info->Set(env()->headers_string(), CreateHeaders()); message_info->Set(env()->headers_string(), CreateHeaders());
if (parser_.type == HTTP_REQUEST) if (parser_.type == HTTP_REQUEST)
message_info->Set(env()->url_string(), url_.ToString()); message_info->Set(env()->url_string(), url_.ToString(env()));
} }
num_fields_ = num_values_ = 0; num_fields_ = num_values_ = 0;
@ -265,24 +265,24 @@ class Parser : public BaseObject {
// STATUS // STATUS
if (parser_.type == HTTP_RESPONSE) { if (parser_.type == HTTP_RESPONSE) {
message_info->Set(env()->status_code_string(), message_info->Set(env()->status_code_string(),
Integer::New(parser_.status_code, node_isolate)); Integer::New(parser_.status_code, env()->isolate()));
message_info->Set(env()->status_message_string(), message_info->Set(env()->status_message_string(),
status_message_.ToString()); status_message_.ToString(env()));
} }
// VERSION // VERSION
message_info->Set(env()->version_major_string(), message_info->Set(env()->version_major_string(),
Integer::New(parser_.http_major, node_isolate)); Integer::New(parser_.http_major, env()->isolate()));
message_info->Set(env()->version_minor_string(), message_info->Set(env()->version_minor_string(),
Integer::New(parser_.http_minor, node_isolate)); Integer::New(parser_.http_minor, env()->isolate()));
message_info->Set(env()->should_keep_alive_string(), message_info->Set(env()->should_keep_alive_string(),
http_should_keep_alive(&parser_) ? True(node_isolate) http_should_keep_alive(&parser_) ?
: False(node_isolate)); True(env()->isolate()) : False(env()->isolate()));
message_info->Set(env()->upgrade_string(), message_info->Set(env()->upgrade_string(),
parser_.upgrade ? True(node_isolate) parser_.upgrade ? True(env()->isolate())
: False(node_isolate)); : False(env()->isolate()));
Local<Value> argv[1] = { message_info }; Local<Value> argv[1] = { message_info };
Local<Value> head_response = Local<Value> head_response =
@ -298,7 +298,7 @@ class Parser : public BaseObject {
HTTP_DATA_CB(on_body) { HTTP_DATA_CB(on_body) {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
Local<Object> obj = object(); Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnBody); Local<Value> cb = obj->Get(kOnBody);
@ -308,8 +308,8 @@ class Parser : public BaseObject {
Local<Value> argv[3] = { Local<Value> argv[3] = {
current_buffer_, current_buffer_,
Integer::NewFromUnsigned(at - current_buffer_data_, node_isolate), Integer::NewFromUnsigned(at - current_buffer_data_, env()->isolate()),
Integer::NewFromUnsigned(length, node_isolate) Integer::NewFromUnsigned(length, env()->isolate())
}; };
Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv); Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv);
@ -324,7 +324,7 @@ class Parser : public BaseObject {
HTTP_CB(on_message_complete) { HTTP_CB(on_message_complete) {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
if (num_fields_) if (num_fields_)
Flush(); // Flush trailing HTTP headers. Flush(); // Flush trailing HTTP headers.
@ -372,7 +372,8 @@ class Parser : public BaseObject {
// var bytesParsed = parser->execute(buffer); // var bytesParsed = parser->execute(buffer);
static void Execute(const FunctionCallbackInfo<Value>& args) { static void Execute(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Parser* parser = Unwrap<Parser>(args.This()); Parser* parser = Unwrap<Parser>(args.This());
assert(parser->current_buffer_.IsEmpty()); assert(parser->current_buffer_.IsEmpty());
@ -406,18 +407,17 @@ class Parser : public BaseObject {
if (parser->got_exception_) if (parser->got_exception_)
return; return;
Local<Integer> nparsed_obj = Integer::New(nparsed, node_isolate); Local<Integer> nparsed_obj = Integer::New(nparsed, env->isolate());
// If there was a parse error in one of the callbacks // If there was a parse error in one of the callbacks
// TODO(bnoordhuis) What if there is an error on EOF? // TODO(bnoordhuis) What if there is an error on EOF?
if (!parser->parser_.upgrade && nparsed != buffer_len) { if (!parser->parser_.upgrade && nparsed != buffer_len) {
enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_); enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_);
Local<Value> e = Exception::Error( Local<Value> e = Exception::Error(env->parse_error_string());
FIXED_ONE_BYTE_STRING(node_isolate, "Parse Error"));
Local<Object> obj = e->ToObject(); Local<Object> obj = e->ToObject();
obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "bytesParsed"), nparsed_obj); obj->Set(env->bytes_parsed_string(), nparsed_obj);
obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "code"), obj->Set(env->code_string(),
OneByteString(node_isolate, http_errno_name(err))); OneByteString(env->isolate(), http_errno_name(err)));
args.GetReturnValue().Set(e); args.GetReturnValue().Set(e);
} else { } else {
@ -427,7 +427,8 @@ class Parser : public BaseObject {
static void Finish(const FunctionCallbackInfo<Value>& args) { static void Finish(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Parser* parser = Unwrap<Parser>(args.This()); Parser* parser = Unwrap<Parser>(args.This());
@ -442,13 +443,11 @@ class Parser : public BaseObject {
if (rv != 0) { if (rv != 0) {
enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_); enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_);
Local<Value> e = Exception::Error( Local<Value> e = env->parse_error_string();
FIXED_ONE_BYTE_STRING(node_isolate, "Parse Error"));
Local<Object> obj = e->ToObject(); Local<Object> obj = e->ToObject();
obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "bytesParsed"), obj->Set(env->bytes_parsed_string(), Integer::New(0, env->isolate()));
Integer::New(0, node_isolate)); obj->Set(env->code_string(),
obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "code"), OneByteString(env->isolate(), http_errno_name(err)));
OneByteString(node_isolate, http_errno_name(err)));
args.GetReturnValue().Set(e); args.GetReturnValue().Set(e);
} }
@ -489,8 +488,8 @@ class Parser : public BaseObject {
Local<Array> headers = Array::New(2 * num_values_); Local<Array> headers = Array::New(2 * num_values_);
for (int i = 0; i < num_values_; ++i) { for (int i = 0; i < num_values_; ++i) {
headers->Set(2 * i, fields_[i].ToString()); headers->Set(2 * i, fields_[i].ToString(env()));
headers->Set(2 * i + 1, values_[i].ToString()); headers->Set(2 * i + 1, values_[i].ToString(env()));
} }
return headers; return headers;
@ -499,7 +498,7 @@ class Parser : public BaseObject {
// spill headers and request path to JS land // spill headers and request path to JS land
void Flush() { void Flush() {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
Local<Object> obj = object(); Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnHeaders); Local<Value> cb = obj->Get(kOnHeaders);
@ -509,7 +508,7 @@ class Parser : public BaseObject {
Local<Value> argv[2] = { Local<Value> argv[2] = {
CreateHeaders(), CreateHeaders(),
url_.ToString() url_.ToString(env())
}; };
Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv); Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv);
@ -565,29 +564,30 @@ void InitHttpParser(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context, Handle<Context> context,
void* priv) { void* priv) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(Parser::New); Local<FunctionTemplate> t = FunctionTemplate::New(Parser::New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "HTTPParser")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "REQUEST"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
Integer::New(HTTP_REQUEST, node_isolate)); Integer::New(HTTP_REQUEST, env->isolate()));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "RESPONSE"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
Integer::New(HTTP_RESPONSE, node_isolate)); Integer::New(HTTP_RESPONSE, env->isolate()));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kOnHeaders"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
Integer::NewFromUnsigned(kOnHeaders, node_isolate)); Integer::NewFromUnsigned(kOnHeaders, env->isolate()));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kOnHeadersComplete"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
Integer::NewFromUnsigned(kOnHeadersComplete, node_isolate)); Integer::NewFromUnsigned(kOnHeadersComplete, env->isolate()));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kOnBody"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
Integer::NewFromUnsigned(kOnBody, node_isolate)); Integer::NewFromUnsigned(kOnBody, env->isolate()));
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kOnMessageComplete"), t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
Integer::NewFromUnsigned(kOnMessageComplete, node_isolate)); Integer::NewFromUnsigned(kOnMessageComplete, env->isolate()));
Local<Array> methods = Array::New(); Local<Array> methods = Array::New();
#define V(num, name, string) \ #define V(num, name, string) \
methods->Set(num, FIXED_ONE_BYTE_STRING(node_isolate, #string)); methods->Set(num, FIXED_ONE_BYTE_STRING(env->isolate(), #string));
HTTP_METHOD_MAP(V) HTTP_METHOD_MAP(V)
#undef V #undef V
t->Set(FIXED_ONE_BYTE_STRING(node_isolate, "methods"), methods); t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "methods"), methods);
NODE_SET_PROTOTYPE_METHOD(t, "execute", Parser::Execute); NODE_SET_PROTOTYPE_METHOD(t, "execute", Parser::Execute);
NODE_SET_PROTOTYPE_METHOD(t, "finish", Parser::Finish); NODE_SET_PROTOTYPE_METHOD(t, "finish", Parser::Finish);
@ -595,7 +595,7 @@ void InitHttpParser(Handle<Object> target,
NODE_SET_PROTOTYPE_METHOD(t, "pause", Parser::Pause<true>); NODE_SET_PROTOTYPE_METHOD(t, "pause", Parser::Pause<true>);
NODE_SET_PROTOTYPE_METHOD(t, "resume", Parser::Pause<false>); NODE_SET_PROTOTYPE_METHOD(t, "resume", Parser::Pause<false>);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "HTTPParser"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
t->GetFunction()); t->GetFunction());
} }

71
src/node_internals.h

@ -22,6 +22,7 @@
#ifndef SRC_NODE_INTERNALS_H_ #ifndef SRC_NODE_INTERNALS_H_
#define SRC_NODE_INTERNALS_H_ #define SRC_NODE_INTERNALS_H_
#include "node.h"
#include "env.h" #include "env.h"
#include "util.h" #include "util.h"
#include "util-inl.h" #include "util-inl.h"
@ -36,9 +37,6 @@ struct sockaddr;
namespace node { namespace node {
// Defined in node.cc
extern v8::Isolate* node_isolate;
// If persistent.IsWeak() == false, then do not call persistent.Dispose() // If persistent.IsWeak() == false, then do not call persistent.Dispose()
// while the returned Local<T> is still in scope, it will destroy the // while the returned Local<T> is still in scope, it will destroy the
// reference to the object. // reference to the object.
@ -120,41 +118,6 @@ inline static int snprintf(char* buf, unsigned int len, const char* fmt, ...) {
# define NO_RETURN # define NO_RETURN
#endif #endif
// this would have been a template function were it not for the fact that g++
// sometimes fails to resolve it...
#define THROW_ERROR(fun) \
do { \
v8::HandleScope scope(node_isolate); \
v8::ThrowException(fun(OneByteString(node_isolate, errmsg))); \
} \
while (0)
inline static void ThrowError(const char* errmsg) {
THROW_ERROR(v8::Exception::Error);
}
inline static void ThrowTypeError(const char* errmsg) {
THROW_ERROR(v8::Exception::TypeError);
}
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) {
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) {
v8::ThrowException(UVException(errorno, syscall, message, path));
}
void AppendExceptionLine(Environment* env, void AppendExceptionLine(Environment* env,
v8::Handle<v8::Value> er, v8::Handle<v8::Value> er,
v8::Handle<v8::Message> message); v8::Handle<v8::Message> message);
@ -205,6 +168,38 @@ inline MUST_USE_RESULT bool ParseArrayIndex(v8::Handle<v8::Value> arg,
return true; return true;
} }
NODE_DEPRECATED("Use env->ThrowError()",
inline void ThrowError(const char* errmsg) {
Environment* env = Environment::GetCurrent(v8::Isolate::GetCurrent());
return env->ThrowError(errmsg);
})
NODE_DEPRECATED("Use env->ThrowTypeError()",
inline void ThrowTypeError(const char* errmsg) {
Environment* env = Environment::GetCurrent(v8::Isolate::GetCurrent());
return env->ThrowTypeError(errmsg);
})
NODE_DEPRECATED("Use env->ThrowRangeError()",
inline void ThrowRangeError(const char* errmsg) {
Environment* env = Environment::GetCurrent(v8::Isolate::GetCurrent());
return env->ThrowRangeError(errmsg);
})
NODE_DEPRECATED("Use env->ThrowErrnoException()",
inline void ThrowErrnoException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL) {
Environment* env = Environment::GetCurrent(v8::Isolate::GetCurrent());
return env->ThrowErrnoException(errorno, syscall, message, path);
})
NODE_DEPRECATED("Use env->ThrowUVException()",
inline void ThrowUVException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL) {
Environment* env = Environment::GetCurrent(v8::Isolate::GetCurrent());
return env->ThrowUVException(errorno, syscall, message, path);
})
} // namespace node } // namespace node
#endif // SRC_NODE_INTERNALS_H_ #endif // SRC_NODE_INTERNALS_H_

14
src/node_javascript.cc

@ -22,6 +22,8 @@
#include "node.h" #include "node.h"
#include "node_natives.h" #include "node_natives.h"
#include "v8.h" #include "v8.h"
#include "env.h"
#include "env-inl.h"
#include <string.h> #include <string.h>
#if !defined(_MSC_VER) #if !defined(_MSC_VER)
@ -36,17 +38,17 @@ using v8::Local;
using v8::Object; using v8::Object;
using v8::String; using v8::String;
Handle<String> MainSource() { Handle<String> MainSource(Environment* env) {
return OneByteString(node_isolate, node_native, sizeof(node_native) - 1); return OneByteString(env->isolate(), node_native, sizeof(node_native) - 1);
} }
void DefineJavaScript(Handle<Object> target) { void DefineJavaScript(Environment* env, Handle<Object> target) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
for (int i = 0; natives[i].name; i++) { for (int i = 0; natives[i].name; i++) {
if (natives[i].source != node_native) { if (natives[i].source != node_native) {
Local<String> name = String::NewFromUtf8(node_isolate, natives[i].name); Local<String> name = String::NewFromUtf8(env->isolate(), natives[i].name);
Handle<String> source = String::NewFromUtf8(node_isolate, Handle<String> source = String::NewFromUtf8(env->isolate(),
natives[i].source, natives[i].source,
String::kNormalString, String::kNormalString,
natives[i].source_len); natives[i].source_len);

5
src/node_javascript.h

@ -23,11 +23,12 @@
#define SRC_NODE_JAVASCRIPT_H_ #define SRC_NODE_JAVASCRIPT_H_
#include "v8.h" #include "v8.h"
#include "env.h"
namespace node { namespace node {
void DefineJavaScript(v8::Handle<v8::Object> target); void DefineJavaScript(Environment* env, v8::Handle<v8::Object> target);
v8::Handle<v8::String> MainSource(); v8::Handle<v8::String> MainSource(Environment* env);
} // namespace node } // namespace node

104
src/node_os.cc

@ -22,6 +22,8 @@
#include "node.h" #include "node.h"
#include "v8.h" #include "v8.h"
#include "env.h"
#include "env-inl.h"
#include <errno.h> #include <errno.h>
#include <string.h> #include <string.h>
@ -59,14 +61,16 @@ using v8::Value;
static void GetEndianness(const FunctionCallbackInfo<Value>& args) { static void GetEndianness(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
const char* rval = IsBigEndian() ? "BE" : "LE"; const char* rval = IsBigEndian() ? "BE" : "LE";
args.GetReturnValue().Set(OneByteString(node_isolate, rval)); args.GetReturnValue().Set(OneByteString(env->isolate(), rval));
} }
static void GetHostname(const FunctionCallbackInfo<Value>& args) { static void GetHostname(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
char buf[MAXHOSTNAMELEN + 1]; char buf[MAXHOSTNAMELEN + 1];
if (gethostname(buf, sizeof(buf))) { if (gethostname(buf, sizeof(buf))) {
@ -75,40 +79,42 @@ static void GetHostname(const FunctionCallbackInfo<Value>& args) {
#else // __MINGW32__ #else // __MINGW32__
int errorno = WSAGetLastError(); int errorno = WSAGetLastError();
#endif // __POSIX__ #endif // __POSIX__
return ThrowErrnoException(errorno, "gethostname"); return env->ThrowErrnoException(errorno, "gethostname");
} }
buf[sizeof(buf) - 1] = '\0'; buf[sizeof(buf) - 1] = '\0';
args.GetReturnValue().Set(OneByteString(node_isolate, buf)); args.GetReturnValue().Set(OneByteString(env->isolate(), buf));
} }
static void GetOSType(const FunctionCallbackInfo<Value>& args) { static void GetOSType(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
const char* rval; const char* rval;
#ifdef __POSIX__ #ifdef __POSIX__
struct utsname info; struct utsname info;
if (uname(&info) < 0) { if (uname(&info) < 0) {
return ThrowErrnoException(errno, "uname"); return env->ThrowErrnoException(errno, "uname");
} }
rval = info.sysname; rval = info.sysname;
#else // __MINGW32__ #else // __MINGW32__
rval ="Windows_NT"; rval ="Windows_NT";
#endif // __POSIX__ #endif // __POSIX__
args.GetReturnValue().Set(OneByteString(node_isolate, rval)); args.GetReturnValue().Set(OneByteString(env->isolate(), rval));
} }
static void GetOSRelease(const FunctionCallbackInfo<Value>& args) { static void GetOSRelease(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
const char* rval; const char* rval;
#ifdef __POSIX__ #ifdef __POSIX__
struct utsname info; struct utsname info;
if (uname(&info) < 0) { if (uname(&info) < 0) {
return ThrowErrnoException(errno, "uname"); return env->ThrowErrnoException(errno, "uname");
} }
rval = info.release; rval = info.release;
#else // __MINGW32__ #else // __MINGW32__
@ -128,12 +134,13 @@ static void GetOSRelease(const FunctionCallbackInfo<Value>& args) {
rval = release; rval = release;
#endif // __POSIX__ #endif // __POSIX__
args.GetReturnValue().Set(OneByteString(node_isolate, rval)); args.GetReturnValue().Set(OneByteString(env->isolate(), rval));
} }
static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) { static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
uv_cpu_info_t* cpu_infos; uv_cpu_info_t* cpu_infos;
int count, i; int count, i;
@ -146,23 +153,23 @@ static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
uv_cpu_info_t* ci = cpu_infos + i; uv_cpu_info_t* ci = cpu_infos + i;
Local<Object> times_info = Object::New(); Local<Object> times_info = Object::New();
times_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "user"), times_info->Set(env->user_string(),
Number::New(node_isolate, ci->cpu_times.user)); Number::New(env->isolate(), ci->cpu_times.user));
times_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "nice"), times_info->Set(env->nice_string(),
Number::New(node_isolate, ci->cpu_times.nice)); Number::New(env->isolate(), ci->cpu_times.nice));
times_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "sys"), times_info->Set(env->sys_string(),
Number::New(node_isolate, ci->cpu_times.sys)); Number::New(env->isolate(), ci->cpu_times.sys));
times_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "idle"), times_info->Set(env->idle_string(),
Number::New(node_isolate, ci->cpu_times.idle)); Number::New(env->isolate(), ci->cpu_times.idle));
times_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "irq"), times_info->Set(env->irq_string(),
Number::New(node_isolate, ci->cpu_times.irq)); Number::New(env->isolate(), ci->cpu_times.irq));
Local<Object> cpu_info = Object::New(); Local<Object> cpu_info = Object::New();
cpu_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "model"), cpu_info->Set(env->model_string(),
OneByteString(node_isolate, ci->model)); OneByteString(env->isolate(), ci->model));
cpu_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "speed"), cpu_info->Set(env->speed_string(),
Number::New(node_isolate, ci->speed)); Number::New(env->isolate(), ci->speed));
cpu_info->Set(FIXED_ONE_BYTE_STRING(node_isolate, "times"), times_info); cpu_info->Set(env->times_string(), times_info);
(*cpus)->Set(i, cpu_info); (*cpus)->Set(i, cpu_info);
} }
@ -173,7 +180,8 @@ static void GetCPUInfo(const FunctionCallbackInfo<Value>& args) {
static void GetFreeMemory(const FunctionCallbackInfo<Value>& args) { static void GetFreeMemory(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
double amount = uv_get_free_memory(); double amount = uv_get_free_memory();
if (amount < 0) if (amount < 0)
return; return;
@ -182,7 +190,8 @@ static void GetFreeMemory(const FunctionCallbackInfo<Value>& args) {
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) { static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
double amount = uv_get_total_memory(); double amount = uv_get_total_memory();
if (amount < 0) if (amount < 0)
return; return;
@ -191,7 +200,8 @@ static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
static void GetUptime(const FunctionCallbackInfo<Value>& args) { static void GetUptime(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
double uptime; double uptime;
int err = uv_uptime(&uptime); int err = uv_uptime(&uptime);
if (err == 0) if (err == 0)
@ -200,7 +210,8 @@ static void GetUptime(const FunctionCallbackInfo<Value>& args) {
static void GetLoadAvg(const FunctionCallbackInfo<Value>& args) { static void GetLoadAvg(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
double loadavg[3]; double loadavg[3];
uv_loadavg(loadavg); uv_loadavg(loadavg);
Local<Array> loads = Array::New(3); Local<Array> loads = Array::New(3);
@ -212,7 +223,8 @@ static void GetLoadAvg(const FunctionCallbackInfo<Value>& args) {
static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) { static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
uv_interface_address_t* interfaces; uv_interface_address_t* interfaces;
int count, i; int count, i;
char ip[INET6_ADDRSTRLEN]; char ip[INET6_ADDRSTRLEN];
@ -229,11 +241,11 @@ static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
if (err == UV_ENOSYS) { if (err == UV_ENOSYS) {
args.GetReturnValue().Set(ret); args.GetReturnValue().Set(ret);
} else if (err) { } else if (err) {
return ThrowUVException(err, "uv_interface_addresses"); return env->ThrowUVException(err, "uv_interface_addresses");
} }
for (i = 0; i < count; i++) { for (i = 0; i < count; i++) {
name = OneByteString(node_isolate, interfaces[i].name); name = OneByteString(env->isolate(), interfaces[i].name);
if (ret->Has(name)) { if (ret->Has(name)) {
ifarr = Local<Array>::Cast(ret->Get(name)); ifarr = Local<Array>::Cast(ret->Get(name));
} else { } else {
@ -254,34 +266,30 @@ static void GetInterfaceAddresses(const FunctionCallbackInfo<Value>& args) {
if (interfaces[i].address.address4.sin_family == AF_INET) { if (interfaces[i].address.address4.sin_family == AF_INET) {
uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip)); uv_ip4_name(&interfaces[i].address.address4, ip, sizeof(ip));
uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask)); uv_ip4_name(&interfaces[i].netmask.netmask4, netmask, sizeof(netmask));
family = FIXED_ONE_BYTE_STRING(node_isolate, "IPv4"); family = env->ipv4_string();
} else if (interfaces[i].address.address4.sin_family == AF_INET6) { } else if (interfaces[i].address.address4.sin_family == AF_INET6) {
uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip)); uv_ip6_name(&interfaces[i].address.address6, ip, sizeof(ip));
uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask)); uv_ip6_name(&interfaces[i].netmask.netmask6, netmask, sizeof(netmask));
family = FIXED_ONE_BYTE_STRING(node_isolate, "IPv6"); family = env->ipv6_string();
} else { } else {
strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN); strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN);
family = FIXED_ONE_BYTE_STRING(node_isolate, "<unknown>"); family = env->unknown_string();
} }
o = Object::New(); o = Object::New();
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "address"), o->Set(env->address_string(), OneByteString(env->isolate(), ip));
OneByteString(node_isolate, ip)); o->Set(env->netmask_string(), OneByteString(env->isolate(), netmask));
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "netmask"), o->Set(env->family_string(), family);
OneByteString(node_isolate, netmask)); o->Set(env->mac_string(), FIXED_ONE_BYTE_STRING(env->isolate(), mac));
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "family"), family);
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "mac"),
FIXED_ONE_BYTE_STRING(node_isolate, mac));
if (interfaces[i].address.address4.sin_family == AF_INET6) { if (interfaces[i].address.address4.sin_family == AF_INET6) {
uint32_t scopeid = interfaces[i].address.address6.sin6_scope_id; uint32_t scopeid = interfaces[i].address.address6.sin6_scope_id;
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "scopeid"), o->Set(env->scopeid_string(), Integer::NewFromUnsigned(scopeid));
Integer::NewFromUnsigned(scopeid));
} }
const bool internal = interfaces[i].is_internal; const bool internal = interfaces[i].is_internal;
o->Set(FIXED_ONE_BYTE_STRING(node_isolate, "internal"), o->Set(env->internal_string(),
internal ? True(node_isolate) : False(node_isolate)); internal ? True(env->isolate()) : False(env->isolate()));
ifarr->Set(ifarr->Length(), o); ifarr->Set(ifarr->Length(), o);
} }

13
src/node_stat_watcher.cc

@ -45,17 +45,17 @@ using v8::String;
using v8::Value; using v8::Value;
void StatWatcher::Initialize(Handle<Object> target) { void StatWatcher::Initialize(Environment* env, Handle<Object> target) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<FunctionTemplate> t = FunctionTemplate::New(StatWatcher::New); Local<FunctionTemplate> t = FunctionTemplate::New(StatWatcher::New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "StatWatcher")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "StatWatcher"));
NODE_SET_PROTOTYPE_METHOD(t, "start", StatWatcher::Start); NODE_SET_PROTOTYPE_METHOD(t, "start", StatWatcher::Start);
NODE_SET_PROTOTYPE_METHOD(t, "stop", StatWatcher::Stop); NODE_SET_PROTOTYPE_METHOD(t, "stop", StatWatcher::Stop);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "StatWatcher"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "StatWatcher"),
t->GetFunction()); t->GetFunction());
} }
@ -92,7 +92,7 @@ void StatWatcher::Callback(uv_fs_poll_t* handle,
Local<Value> argv[] = { Local<Value> argv[] = {
BuildStatsObject(env, curr), BuildStatsObject(env, curr),
BuildStatsObject(env, prev), BuildStatsObject(env, prev),
Integer::New(status, node_isolate) Integer::New(status, env->isolate())
}; };
wrap->MakeCallback(env->onchange_string(), ARRAY_SIZE(argv), argv); wrap->MakeCallback(env->onchange_string(), ARRAY_SIZE(argv), argv);
} }
@ -108,7 +108,8 @@ void StatWatcher::New(const FunctionCallbackInfo<Value>& args) {
void StatWatcher::Start(const FunctionCallbackInfo<Value>& args) { void StatWatcher::Start(const FunctionCallbackInfo<Value>& args) {
assert(args.Length() == 3); assert(args.Length() == 3);
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
StatWatcher* wrap = Unwrap<StatWatcher>(args.This()); StatWatcher* wrap = Unwrap<StatWatcher>(args.This());
String::Utf8Value path(args[0]); String::Utf8Value path(args[0]);

2
src/node_stat_watcher.h

@ -34,7 +34,7 @@ class StatWatcher : public AsyncWrap {
public: public:
virtual ~StatWatcher(); virtual ~StatWatcher();
static void Initialize(v8::Handle<v8::Object> target); static void Initialize(Environment* env, v8::Handle<v8::Object> target);
protected: protected:
StatWatcher(Environment* env, v8::Local<v8::Object> wrap); StatWatcher(Environment* env, v8::Local<v8::Object> wrap);

2
src/node_wrap.h

@ -54,7 +54,7 @@ namespace node {
inline uv_stream_t* HandleToStream(Environment* env, inline uv_stream_t* HandleToStream(Environment* env,
v8::Local<v8::Object> obj) { v8::Local<v8::Object> obj) {
v8::HandleScope scope(node_isolate); v8::HandleScope scope(env->isolate());
WITH_GENERIC_STREAM(env, obj, { WITH_GENERIC_STREAM(env, obj, {
return reinterpret_cast<uv_stream_t*>(wrap->UVHandle()); return reinterpret_cast<uv_stream_t*>(wrap->UVHandle());

60
src/node_zlib.cc

@ -110,11 +110,13 @@ class ZCtx : public AsyncWrap {
if (mode_ == DEFLATE || mode_ == GZIP || mode_ == DEFLATERAW) { if (mode_ == DEFLATE || mode_ == GZIP || mode_ == DEFLATERAW) {
(void)deflateEnd(&strm_); (void)deflateEnd(&strm_);
node_isolate->AdjustAmountOfExternalAllocatedMemory(-kDeflateContextSize); env()->isolate()
->AdjustAmountOfExternalAllocatedMemory(-kDeflateContextSize);
} else if (mode_ == INFLATE || mode_ == GUNZIP || mode_ == INFLATERAW || } else if (mode_ == INFLATE || mode_ == GUNZIP || mode_ == INFLATERAW ||
mode_ == UNZIP) { mode_ == UNZIP) {
(void)inflateEnd(&strm_); (void)inflateEnd(&strm_);
node_isolate->AdjustAmountOfExternalAllocatedMemory(-kInflateContextSize); env()->isolate()
->AdjustAmountOfExternalAllocatedMemory(-kInflateContextSize);
} }
mode_ = NONE; mode_ = NONE;
@ -126,7 +128,8 @@ class ZCtx : public AsyncWrap {
static void Close(const FunctionCallbackInfo<Value>& args) { static void Close(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ZCtx* ctx = Unwrap<ZCtx>(args.This()); ZCtx* ctx = Unwrap<ZCtx>(args.This());
ctx->Close(); ctx->Close();
} }
@ -135,7 +138,8 @@ class ZCtx : public AsyncWrap {
// write(flush, in, in_off, in_len, out, out_off, out_len) // write(flush, in, in_off, in_len, out, out_off, out_len)
template <bool async> template <bool async>
static void Write(const FunctionCallbackInfo<Value>& args) { static void Write(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
assert(args.Length() == 7); assert(args.Length() == 7);
ZCtx* ctx = Unwrap<ZCtx>(args.This()); ZCtx* ctx = Unwrap<ZCtx>(args.This());
@ -219,8 +223,12 @@ class ZCtx : public AsyncWrap {
static void AfterSync(ZCtx* ctx, const FunctionCallbackInfo<Value>& args) { static void AfterSync(ZCtx* ctx, const FunctionCallbackInfo<Value>& args) {
Local<Integer> avail_out = Integer::New(ctx->strm_.avail_out, node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
Local<Integer> avail_in = Integer::New(ctx->strm_.avail_in, node_isolate); HandleScope scope(env->isolate());
Local<Integer> avail_out = Integer::New(ctx->strm_.avail_out,
env->isolate());
Local<Integer> avail_in = Integer::New(ctx->strm_.avail_in,
env->isolate());
ctx->write_in_progress_ = false; ctx->write_in_progress_ = false;
@ -321,8 +329,10 @@ class ZCtx : public AsyncWrap {
if (!CheckError(ctx)) if (!CheckError(ctx))
return; return;
Local<Integer> avail_out = Integer::New(ctx->strm_.avail_out, node_isolate); Local<Integer> avail_out = Integer::New(ctx->strm_.avail_out,
Local<Integer> avail_in = Integer::New(ctx->strm_.avail_in, node_isolate); env->isolate());
Local<Integer> avail_in = Integer::New(ctx->strm_.avail_in,
env->isolate());
ctx->write_in_progress_ = false; ctx->write_in_progress_ = false;
@ -345,9 +355,9 @@ class ZCtx : public AsyncWrap {
message = ctx->strm_.msg; message = ctx->strm_.msg;
} }
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<Value> args[2] = { Local<Value> args[2] = {
OneByteString(node_isolate, message), OneByteString(env->isolate(), message),
Number::New(ctx->err_) Number::New(ctx->err_)
}; };
ctx->MakeCallback(env->onerror_string(), ARRAY_SIZE(args), args); ctx->MakeCallback(env->onerror_string(), ARRAY_SIZE(args), args);
@ -364,12 +374,12 @@ class ZCtx : public AsyncWrap {
Environment* env = Environment::GetCurrent(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsInt32()) { if (args.Length() < 1 || !args[0]->IsInt32()) {
return ThrowTypeError("Bad argument"); return env->ThrowTypeError("Bad argument");
} }
node_zlib_mode mode = static_cast<node_zlib_mode>(args[0]->Int32Value()); node_zlib_mode mode = static_cast<node_zlib_mode>(args[0]->Int32Value());
if (mode < DEFLATE || mode > UNZIP) { if (mode < DEFLATE || mode > UNZIP) {
return ThrowTypeError("Bad argument"); return env->ThrowTypeError("Bad argument");
} }
new ZCtx(env, args.This(), mode); new ZCtx(env, args.This(), mode);
@ -377,7 +387,8 @@ class ZCtx : public AsyncWrap {
// just pull the ints out of the args and call the other Init // just pull the ints out of the args and call the other Init
static void Init(const FunctionCallbackInfo<Value>& args) { static void Init(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
assert((args.Length() == 4 || args.Length() == 5) && assert((args.Length() == 4 || args.Length() == 5) &&
"init(windowBits, level, memLevel, strategy, [dictionary])"); "init(windowBits, level, memLevel, strategy, [dictionary])");
@ -417,7 +428,8 @@ class ZCtx : public AsyncWrap {
} }
static void Params(const FunctionCallbackInfo<Value>& args) { static void Params(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
assert(args.Length() == 2 && "params(level, strategy)"); assert(args.Length() == 2 && "params(level, strategy)");
@ -427,7 +439,8 @@ class ZCtx : public AsyncWrap {
} }
static void Reset(const FunctionCallbackInfo<Value> &args) { static void Reset(const FunctionCallbackInfo<Value> &args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ZCtx* ctx = Unwrap<ZCtx>(args.This()); ZCtx* ctx = Unwrap<ZCtx>(args.This());
@ -472,16 +485,16 @@ class ZCtx : public AsyncWrap {
ctx->windowBits_, ctx->windowBits_,
ctx->memLevel_, ctx->memLevel_,
ctx->strategy_); ctx->strategy_);
node_isolate-> ctx->env()->isolate()
AdjustAmountOfExternalAllocatedMemory(kDeflateContextSize); ->AdjustAmountOfExternalAllocatedMemory(kDeflateContextSize);
break; break;
case INFLATE: case INFLATE:
case GUNZIP: case GUNZIP:
case INFLATERAW: case INFLATERAW:
case UNZIP: case UNZIP:
ctx->err_ = inflateInit2(&ctx->strm_, ctx->windowBits_); ctx->err_ = inflateInit2(&ctx->strm_, ctx->windowBits_);
node_isolate-> ctx->env()->isolate()
AdjustAmountOfExternalAllocatedMemory(kInflateContextSize); ->AdjustAmountOfExternalAllocatedMemory(kInflateContextSize);
break; break;
default: default:
assert(0 && "wtf?"); assert(0 && "wtf?");
@ -599,6 +612,7 @@ void InitZlib(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context, Handle<Context> context,
void* priv) { void* priv) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> z = FunctionTemplate::New(ZCtx::New); Local<FunctionTemplate> z = FunctionTemplate::New(ZCtx::New);
z->InstanceTemplate()->SetInternalFieldCount(1); z->InstanceTemplate()->SetInternalFieldCount(1);
@ -610,8 +624,8 @@ void InitZlib(Handle<Object> target,
NODE_SET_PROTOTYPE_METHOD(z, "params", ZCtx::Params); NODE_SET_PROTOTYPE_METHOD(z, "params", ZCtx::Params);
NODE_SET_PROTOTYPE_METHOD(z, "reset", ZCtx::Reset); NODE_SET_PROTOTYPE_METHOD(z, "reset", ZCtx::Reset);
z->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "Zlib")); z->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Zlib"));
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Zlib"), z->GetFunction()); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Zlib"), z->GetFunction());
// valid flush values. // valid flush values.
NODE_DEFINE_CONSTANT(target, Z_NO_FLUSH); NODE_DEFINE_CONSTANT(target, Z_NO_FLUSH);
@ -651,8 +665,8 @@ void InitZlib(Handle<Object> target,
NODE_DEFINE_CONSTANT(target, INFLATERAW); NODE_DEFINE_CONSTANT(target, INFLATERAW);
NODE_DEFINE_CONSTANT(target, UNZIP); NODE_DEFINE_CONSTANT(target, UNZIP);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ZLIB_VERSION"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "ZLIB_VERSION"),
FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION)); FIXED_ONE_BYTE_STRING(env->isolate(), ZLIB_VERSION));
} }
} // namespace node } // namespace node

22
src/pipe_wrap.cc

@ -75,12 +75,12 @@ void PipeWrap::Initialize(Handle<Object> target,
Environment* env = Environment::GetCurrent(context); Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(New); Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "Pipe")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Pipe"));
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
enum PropertyAttribute attributes = enum PropertyAttribute attributes =
static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete); static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"), t->InstanceTemplate()->SetAccessor(env->fd_string(),
StreamWrap::GetFD, StreamWrap::GetFD,
NULL, NULL,
Handle<Value>(), Handle<Value>(),
@ -111,7 +111,7 @@ void PipeWrap::Initialize(Handle<Object> target,
NODE_SET_PROTOTYPE_METHOD(t, "setPendingInstances", SetPendingInstances); NODE_SET_PROTOTYPE_METHOD(t, "setPendingInstances", SetPendingInstances);
#endif #endif
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Pipe"), t->GetFunction()); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Pipe"), t->GetFunction());
env->set_pipe_constructor_template(t); env->set_pipe_constructor_template(t);
} }
@ -140,7 +140,8 @@ PipeWrap::PipeWrap(Environment* env, Handle<Object> object, bool ipc)
void PipeWrap::Bind(const FunctionCallbackInfo<Value>& args) { void PipeWrap::Bind(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
PipeWrap* wrap = Unwrap<PipeWrap>(args.This()); PipeWrap* wrap = Unwrap<PipeWrap>(args.This());
@ -152,7 +153,8 @@ void PipeWrap::Bind(const FunctionCallbackInfo<Value>& args) {
#ifdef _WIN32 #ifdef _WIN32
void PipeWrap::SetPendingInstances(const FunctionCallbackInfo<Value>& args) { void PipeWrap::SetPendingInstances(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
PipeWrap* wrap = Unwrap<PipeWrap>(args.This()); PipeWrap* wrap = Unwrap<PipeWrap>(args.This());
@ -164,7 +166,8 @@ void PipeWrap::SetPendingInstances(const FunctionCallbackInfo<Value>& args) {
void PipeWrap::Listen(const FunctionCallbackInfo<Value>& args) { void PipeWrap::Listen(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
PipeWrap* wrap = Unwrap<PipeWrap>(args.This()); PipeWrap* wrap = Unwrap<PipeWrap>(args.This());
@ -190,7 +193,7 @@ void PipeWrap::OnConnection(uv_stream_t* handle, int status) {
assert(pipe_wrap->persistent().IsEmpty() == false); assert(pipe_wrap->persistent().IsEmpty() == false);
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
Undefined() Undefined()
}; };
@ -239,7 +242,7 @@ void PipeWrap::AfterConnect(uv_connect_t* req, int status) {
Local<Object> req_wrap_obj = req_wrap->object(); Local<Object> req_wrap_obj = req_wrap->object();
Local<Value> argv[5] = { Local<Value> argv[5] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
wrap->object(), wrap->object(),
req_wrap_obj, req_wrap_obj,
Boolean::New(readable), Boolean::New(readable),
@ -253,7 +256,8 @@ void PipeWrap::AfterConnect(uv_connect_t* req, int status) {
void PipeWrap::Open(const FunctionCallbackInfo<Value>& args) { void PipeWrap::Open(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
PipeWrap* wrap = Unwrap<PipeWrap>(args.This()); PipeWrap* wrap = Unwrap<PipeWrap>(args.This());

69
src/process_wrap.cc

@ -50,9 +50,10 @@ class ProcessWrap : public HandleWrap {
static void Initialize(Handle<Object> target, static void Initialize(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context) { Handle<Context> context) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> constructor = FunctionTemplate::New(New); Local<FunctionTemplate> constructor = FunctionTemplate::New(New);
constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "Process")); constructor->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Process"));
NODE_SET_PROTOTYPE_METHOD(constructor, "close", HandleWrap::Close); NODE_SET_PROTOTYPE_METHOD(constructor, "close", HandleWrap::Close);
@ -62,7 +63,7 @@ class ProcessWrap : public HandleWrap {
NODE_SET_PROTOTYPE_METHOD(constructor, "ref", HandleWrap::Ref); NODE_SET_PROTOTYPE_METHOD(constructor, "ref", HandleWrap::Ref);
NODE_SET_PROTOTYPE_METHOD(constructor, "unref", HandleWrap::Unref); NODE_SET_PROTOTYPE_METHOD(constructor, "unref", HandleWrap::Unref);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Process"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Process"),
constructor->GetFunction()); constructor->GetFunction());
} }
@ -90,8 +91,7 @@ class ProcessWrap : public HandleWrap {
static void ParseStdioOptions(Environment* env, static void ParseStdioOptions(Environment* env,
Local<Object> js_options, Local<Object> js_options,
uv_process_options_t* options) { uv_process_options_t* options) {
Local<String> stdio_key = Local<String> stdio_key = env->stdio_string();
FIXED_ONE_BYTE_STRING(node_isolate, "stdio");
Local<Array> stdios = js_options->Get(stdio_key).As<Array>(); Local<Array> stdios = js_options->Get(stdio_key).As<Array>();
uint32_t len = stdios->Length(); uint32_t len = stdios->Length();
@ -100,23 +100,20 @@ class ProcessWrap : public HandleWrap {
for (uint32_t i = 0; i < len; i++) { for (uint32_t i = 0; i < len; i++) {
Local<Object> stdio = stdios->Get(i).As<Object>(); Local<Object> stdio = stdios->Get(i).As<Object>();
Local<Value> type = Local<Value> type = stdio->Get(env->type_string());
stdio->Get(FIXED_ONE_BYTE_STRING(node_isolate, "type"));
if (type->Equals(FIXED_ONE_BYTE_STRING(node_isolate, "ignore"))) { if (type->Equals(env->ignore_string())) {
options->stdio[i].flags = UV_IGNORE; options->stdio[i].flags = UV_IGNORE;
} else if (type->Equals(FIXED_ONE_BYTE_STRING(node_isolate, "pipe"))) { } else if (type->Equals(env->pipe_string())) {
options->stdio[i].flags = static_cast<uv_stdio_flags>( options->stdio[i].flags = static_cast<uv_stdio_flags>(
UV_CREATE_PIPE | UV_READABLE_PIPE | UV_WRITABLE_PIPE); UV_CREATE_PIPE | UV_READABLE_PIPE | UV_WRITABLE_PIPE);
Local<String> handle_key = Local<String> handle_key = env->handle_string();
FIXED_ONE_BYTE_STRING(node_isolate, "handle");
Local<Object> handle = stdio->Get(handle_key).As<Object>(); Local<Object> handle = stdio->Get(handle_key).As<Object>();
options->stdio[i].data.stream = options->stdio[i].data.stream =
reinterpret_cast<uv_stream_t*>( reinterpret_cast<uv_stream_t*>(
Unwrap<PipeWrap>(handle)->UVHandle()); Unwrap<PipeWrap>(handle)->UVHandle());
} else if (type->Equals(FIXED_ONE_BYTE_STRING(node_isolate, "wrap"))) { } else if (type->Equals(env->wrap_string())) {
Local<String> handle_key = Local<String> handle_key = env->handle_string();
FIXED_ONE_BYTE_STRING(node_isolate, "handle");
Local<Object> handle = stdio->Get(handle_key).As<Object>(); Local<Object> handle = stdio->Get(handle_key).As<Object>();
uv_stream_t* stream = HandleToStream(env, handle); uv_stream_t* stream = HandleToStream(env, handle);
assert(stream != NULL); assert(stream != NULL);
@ -124,7 +121,7 @@ class ProcessWrap : public HandleWrap {
options->stdio[i].flags = UV_INHERIT_STREAM; options->stdio[i].flags = UV_INHERIT_STREAM;
options->stdio[i].data.stream = stream; options->stdio[i].data.stream = stream;
} else { } else {
Local<String> fd_key = FIXED_ONE_BYTE_STRING(node_isolate, "fd"); Local<String> fd_key = env->fd_string();
int fd = static_cast<int>(stdio->Get(fd_key)->IntegerValue()); int fd = static_cast<int>(stdio->Get(fd_key)->IntegerValue());
options->stdio[i].flags = UV_INHERIT_FD; options->stdio[i].flags = UV_INHERIT_FD;
options->stdio[i].data.fd = fd; options->stdio[i].data.fd = fd;
@ -146,48 +143,44 @@ class ProcessWrap : public HandleWrap {
options.exit_cb = OnExit; options.exit_cb = OnExit;
// options.uid // options.uid
Local<Value> uid_v = Local<Value> uid_v = js_options->Get(env->uid_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "uid"));
if (uid_v->IsInt32()) { if (uid_v->IsInt32()) {
int32_t uid = uid_v->Int32Value(); int32_t uid = uid_v->Int32Value();
if (uid & ~((uv_uid_t) ~0)) { if (uid & ~((uv_uid_t) ~0)) {
return ThrowRangeError("options.uid is out of range"); return env->ThrowRangeError("options.uid is out of range");
} }
options.flags |= UV_PROCESS_SETUID; options.flags |= UV_PROCESS_SETUID;
options.uid = (uv_uid_t) uid; options.uid = (uv_uid_t) uid;
} else if (!uid_v->IsUndefined() && !uid_v->IsNull()) { } else if (!uid_v->IsUndefined() && !uid_v->IsNull()) {
return ThrowTypeError("options.uid should be a number"); return env->ThrowTypeError("options.uid should be a number");
} }
// options.gid // options.gid
Local<Value> gid_v = Local<Value> gid_v = js_options->Get(env->gid_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "gid"));
if (gid_v->IsInt32()) { if (gid_v->IsInt32()) {
int32_t gid = gid_v->Int32Value(); int32_t gid = gid_v->Int32Value();
if (gid & ~((uv_gid_t) ~0)) { if (gid & ~((uv_gid_t) ~0)) {
return ThrowRangeError("options.gid is out of range"); return env->ThrowRangeError("options.gid is out of range");
} }
options.flags |= UV_PROCESS_SETGID; options.flags |= UV_PROCESS_SETGID;
options.gid = (uv_gid_t) gid; options.gid = (uv_gid_t) gid;
} else if (!gid_v->IsUndefined() && !gid_v->IsNull()) { } else if (!gid_v->IsUndefined() && !gid_v->IsNull()) {
return ThrowTypeError("options.gid should be a number"); return env->ThrowTypeError("options.gid should be a number");
} }
// TODO(bnoordhuis) is this possible to do without mallocing ? // TODO(bnoordhuis) is this possible to do without mallocing ?
// options.file // options.file
Local<Value> file_v = Local<Value> file_v = js_options->Get(env->file_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "file"));
String::Utf8Value file(file_v->IsString() ? file_v : Local<Value>()); String::Utf8Value file(file_v->IsString() ? file_v : Local<Value>());
if (file.length() > 0) { if (file.length() > 0) {
options.file = *file; options.file = *file;
} else { } else {
return ThrowTypeError("Bad argument"); return env->ThrowTypeError("Bad argument");
} }
// options.args // options.args
Local<Value> argv_v = Local<Value> argv_v = js_options->Get(env->args_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "args"));
if (!argv_v.IsEmpty() && argv_v->IsArray()) { if (!argv_v.IsEmpty() && argv_v->IsArray()) {
Local<Array> js_argv = Local<Array>::Cast(argv_v); Local<Array> js_argv = Local<Array>::Cast(argv_v);
int argc = js_argv->Length(); int argc = js_argv->Length();
@ -201,16 +194,14 @@ class ProcessWrap : public HandleWrap {
} }
// options.cwd // options.cwd
Local<Value> cwd_v = Local<Value> cwd_v = js_options->Get(env->cwd_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "cwd"));
String::Utf8Value cwd(cwd_v->IsString() ? cwd_v : Local<Value>()); String::Utf8Value cwd(cwd_v->IsString() ? cwd_v : Local<Value>());
if (cwd.length() > 0) { if (cwd.length() > 0) {
options.cwd = *cwd; options.cwd = *cwd;
} }
// options.env // options.env
Local<Value> env_v = Local<Value> env_v = js_options->Get(env->env_pairs_string());
js_options->Get(FIXED_ONE_BYTE_STRING(node_isolate, "envPairs"));
if (!env_v.IsEmpty() && env_v->IsArray()) { if (!env_v.IsEmpty() && env_v->IsArray()) {
Local<Array> env = Local<Array>::Cast(env_v); Local<Array> env = Local<Array>::Cast(env_v);
int envc = env->Length(); int envc = env->Length();
@ -227,14 +218,13 @@ class ProcessWrap : public HandleWrap {
// options.windows_verbatim_arguments // options.windows_verbatim_arguments
Local<String> windows_verbatim_arguments_key = Local<String> windows_verbatim_arguments_key =
FIXED_ONE_BYTE_STRING(node_isolate, "windowsVerbatimArguments"); env->windows_verbatim_arguments_string();
if (js_options->Get(windows_verbatim_arguments_key)->IsTrue()) { if (js_options->Get(windows_verbatim_arguments_key)->IsTrue()) {
options.flags |= UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS; options.flags |= UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS;
} }
// options.detached // options.detached
Local<String> detached_key = Local<String> detached_key = env->detached_string();
FIXED_ONE_BYTE_STRING(node_isolate, "detached");
if (js_options->Get(detached_key)->IsTrue()) { if (js_options->Get(detached_key)->IsTrue()) {
options.flags |= UV_PROCESS_DETACHED; options.flags |= UV_PROCESS_DETACHED;
} }
@ -243,8 +233,8 @@ class ProcessWrap : public HandleWrap {
if (err == 0) { if (err == 0) {
assert(wrap->process_.data == wrap); assert(wrap->process_.data == wrap);
wrap->object()->Set(FIXED_ONE_BYTE_STRING(node_isolate, "pid"), wrap->object()->Set(env->pid_string(),
Integer::New(wrap->process_.pid, node_isolate)); Integer::New(wrap->process_.pid, env->isolate()));
} }
if (options.args) { if (options.args) {
@ -263,7 +253,8 @@ class ProcessWrap : public HandleWrap {
} }
static void Kill(const FunctionCallbackInfo<Value>& args) { static void Kill(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
ProcessWrap* wrap = Unwrap<ProcessWrap>(args.This()); ProcessWrap* wrap = Unwrap<ProcessWrap>(args.This());
int signal = args[0]->Int32Value(); int signal = args[0]->Int32Value();
@ -283,8 +274,8 @@ class ProcessWrap : public HandleWrap {
Context::Scope context_scope(env->context()); Context::Scope context_scope(env->context());
Local<Value> argv[] = { Local<Value> argv[] = {
Number::New(node_isolate, static_cast<double>(exit_status)), Number::New(env->isolate(), static_cast<double>(exit_status)),
OneByteString(node_isolate, signo_string(term_signal)) OneByteString(env->isolate(), signo_string(term_signal))
}; };
wrap->MakeCallback(env->onexit_string(), ARRAY_SIZE(argv), argv); wrap->MakeCallback(env->onexit_string(), ARRAY_SIZE(argv), argv);

11
src/signal_wrap.cc

@ -46,9 +46,10 @@ class SignalWrap : public HandleWrap {
static void Initialize(Handle<Object> target, static void Initialize(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context) { Handle<Context> context) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> constructor = FunctionTemplate::New(New); Local<FunctionTemplate> constructor = FunctionTemplate::New(New);
constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "Signal")); constructor->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Signal"));
NODE_SET_PROTOTYPE_METHOD(constructor, "close", HandleWrap::Close); NODE_SET_PROTOTYPE_METHOD(constructor, "close", HandleWrap::Close);
NODE_SET_PROTOTYPE_METHOD(constructor, "ref", HandleWrap::Ref); NODE_SET_PROTOTYPE_METHOD(constructor, "ref", HandleWrap::Ref);
@ -56,7 +57,7 @@ class SignalWrap : public HandleWrap {
NODE_SET_PROTOTYPE_METHOD(constructor, "start", Start); NODE_SET_PROTOTYPE_METHOD(constructor, "start", Start);
NODE_SET_PROTOTYPE_METHOD(constructor, "stop", Stop); NODE_SET_PROTOTYPE_METHOD(constructor, "stop", Stop);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Signal"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Signal"),
constructor->GetFunction()); constructor->GetFunction());
} }
@ -84,7 +85,8 @@ class SignalWrap : public HandleWrap {
} }
static void Start(const FunctionCallbackInfo<Value>& args) { static void Start(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SignalWrap* wrap = Unwrap<SignalWrap>(args.This()); SignalWrap* wrap = Unwrap<SignalWrap>(args.This());
int signum = args[0]->Int32Value(); int signum = args[0]->Int32Value();
@ -93,7 +95,8 @@ class SignalWrap : public HandleWrap {
} }
static void Stop(const FunctionCallbackInfo<Value>& args) { static void Stop(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
SignalWrap* wrap = Unwrap<SignalWrap>(args.This()); SignalWrap* wrap = Unwrap<SignalWrap>(args.This());
int err = uv_signal_stop(&wrap->handle_); int err = uv_signal_stop(&wrap->handle_);

95
src/smalloc.cc

@ -95,20 +95,21 @@ size_t ExternalArraySize(enum ExternalArrayType type) {
// copyOnto(source, source_start, dest, dest_start, copy_length) // copyOnto(source, source_start, dest, dest_start, copy_length)
void CopyOnto(const FunctionCallbackInfo<Value>& args) { void CopyOnto(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
if (!args[0]->IsObject()) if (!args[0]->IsObject())
return ThrowTypeError("source must be an object"); return env->ThrowTypeError("source must be an object");
if (!args[2]->IsObject()) if (!args[2]->IsObject())
return ThrowTypeError("dest must be an object"); return env->ThrowTypeError("dest must be an object");
Local<Object> source = args[0].As<Object>(); Local<Object> source = args[0].As<Object>();
Local<Object> dest = args[2].As<Object>(); Local<Object> dest = args[2].As<Object>();
if (!source->HasIndexedPropertiesInExternalArrayData()) if (!source->HasIndexedPropertiesInExternalArrayData())
return ThrowError("source has no external array data"); return env->ThrowError("source has no external array data");
if (!dest->HasIndexedPropertiesInExternalArrayData()) if (!dest->HasIndexedPropertiesInExternalArrayData())
return ThrowError("dest has no external array data"); return env->ThrowError("dest has no external array data");
size_t source_start = args[1]->Uint32Value(); size_t source_start = args[1]->Uint32Value();
size_t dest_start = args[3]->Uint32Value(); size_t dest_start = args[3]->Uint32Value();
@ -131,16 +132,16 @@ void CopyOnto(const FunctionCallbackInfo<Value>& args) {
// optimization for Uint8 arrays (i.e. Buffers) // optimization for Uint8 arrays (i.e. Buffers)
if (source_size != 1 && dest_size != 1) { if (source_size != 1 && dest_size != 1) {
if (source_size == 0) if (source_size == 0)
return ThrowTypeError("unknown source external array type"); return env->ThrowTypeError("unknown source external array type");
if (dest_size == 0) if (dest_size == 0)
return ThrowTypeError("unknown dest external array type"); return env->ThrowTypeError("unknown dest external array type");
if (source_length * source_size < source_length) if (source_length * source_size < source_length)
return ThrowRangeError("source_length * source_size overflow"); return env->ThrowRangeError("source_length * source_size overflow");
if (copy_length * source_size < copy_length) if (copy_length * source_size < copy_length)
return ThrowRangeError("copy_length * source_size overflow"); return env->ThrowRangeError("copy_length * source_size overflow");
if (dest_length * dest_size < dest_length) if (dest_length * dest_size < dest_length)
return ThrowRangeError("dest_length * dest_size overflow"); return env->ThrowRangeError("dest_length * dest_size overflow");
source_length *= source_size; source_length *= source_size;
copy_length *= source_size; copy_length *= source_size;
@ -149,19 +150,19 @@ void CopyOnto(const FunctionCallbackInfo<Value>& args) {
// necessary to check in case (source|dest)_start _and_ copy_length overflow // necessary to check in case (source|dest)_start _and_ copy_length overflow
if (copy_length > source_length) if (copy_length > source_length)
return ThrowRangeError("copy_length > source_length"); return env->ThrowRangeError("copy_length > source_length");
if (copy_length > dest_length) if (copy_length > dest_length)
return ThrowRangeError("copy_length > dest_length"); return env->ThrowRangeError("copy_length > dest_length");
if (source_start > source_length) if (source_start > source_length)
return ThrowRangeError("source_start > source_length"); return env->ThrowRangeError("source_start > source_length");
if (dest_start > dest_length) if (dest_start > dest_length)
return ThrowRangeError("dest_start > dest_length"); return env->ThrowRangeError("dest_start > dest_length");
// now we can guarantee these will catch oob access and *_start overflow // now we can guarantee these will catch oob access and *_start overflow
if (source_start + copy_length > source_length) if (source_start + copy_length > source_length)
return ThrowRangeError("source_start + copy_length > source_length"); return env->ThrowRangeError("source_start + copy_length > source_length");
if (dest_start + copy_length > dest_length) if (dest_start + copy_length > dest_length)
return ThrowRangeError("dest_start + copy_length > dest_length"); return env->ThrowRangeError("dest_start + copy_length > dest_length");
memmove(dest_data + dest_start, source_data + source_start, copy_length); memmove(dest_data + dest_start, source_data + source_start, copy_length);
} }
@ -171,7 +172,8 @@ void CopyOnto(const FunctionCallbackInfo<Value>& args) {
// for internal use: // for internal use:
// dest._data = sliceOnto(source, dest, start, end); // dest._data = sliceOnto(source, dest, start, end);
void SliceOnto(const FunctionCallbackInfo<Value>& args) { void SliceOnto(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Local<Object> source = args[0].As<Object>(); Local<Object> source = args[0].As<Object>();
Local<Object> dest = args[1].As<Object>(); Local<Object> dest = args[1].As<Object>();
@ -211,13 +213,14 @@ void SliceOnto(const FunctionCallbackInfo<Value>& args) {
// for internal use: // for internal use:
// alloc(obj, n[, type]); // alloc(obj, n[, type]);
void Alloc(const FunctionCallbackInfo<Value>& args) { void Alloc(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
Local<Object> obj = args[0].As<Object>(); Local<Object> obj = args[0].As<Object>();
// can't perform this check in JS // can't perform this check in JS
if (obj->HasIndexedPropertiesInExternalArrayData()) if (obj->HasIndexedPropertiesInExternalArrayData())
return ThrowTypeError("object already has external array data"); return env->ThrowTypeError("object already has external array data");
size_t length = args[1]->Uint32Value(); size_t length = args[1]->Uint32Value();
enum ExternalArrayType array_type; enum ExternalArrayType array_type;
@ -232,19 +235,22 @@ void Alloc(const FunctionCallbackInfo<Value>& args) {
length *= type_length; length *= type_length;
} }
Alloc(obj, length, array_type); Alloc(env, obj, length, array_type);
args.GetReturnValue().Set(obj); args.GetReturnValue().Set(obj);
} }
void Alloc(Handle<Object> obj, size_t length, enum ExternalArrayType type) { void Alloc(Environment* env,
Handle<Object> obj,
size_t length,
enum ExternalArrayType type) {
size_t type_size = ExternalArraySize(type); size_t type_size = ExternalArraySize(type);
assert(length <= kMaxLength); assert(length <= kMaxLength);
assert(type_size > 0); assert(type_size > 0);
if (length == 0) if (length == 0)
return Alloc(obj, NULL, length, type); return Alloc(env, obj, NULL, length, type);
char* data = static_cast<char*>(malloc(length)); char* data = static_cast<char*>(malloc(length));
if (data == NULL) { if (data == NULL) {
@ -252,17 +258,18 @@ void Alloc(Handle<Object> obj, size_t length, enum ExternalArrayType type) {
" v8::ExternalArrayType)", "Out Of Memory"); " v8::ExternalArrayType)", "Out Of Memory");
} }
Alloc(obj, data, length, type); Alloc(env, obj, data, length, type);
} }
void Alloc(Handle<Object> obj, void Alloc(Environment* env,
Handle<Object> obj,
char* data, char* data,
size_t length, size_t length,
enum ExternalArrayType type) { enum ExternalArrayType type) {
assert(!obj->HasIndexedPropertiesInExternalArrayData()); assert(!obj->HasIndexedPropertiesInExternalArrayData());
Persistent<Object> p_obj(node_isolate, obj); Persistent<Object> p_obj(env->isolate(), obj);
node_isolate->AdjustAmountOfExternalAllocatedMemory(length); env->isolate()->AdjustAmountOfExternalAllocatedMemory(length);
p_obj.MakeWeak(data, TargetCallback); p_obj.MakeWeak(data, TargetCallback);
p_obj.MarkIndependent(); p_obj.MarkIndependent();
p_obj.SetWrapperClassId(ALLOC_ID); p_obj.SetWrapperClassId(ALLOC_ID);
@ -293,20 +300,20 @@ void TargetCallback(Isolate* isolate,
// for internal use: dispose(obj); // for internal use: dispose(obj);
void AllocDispose(const FunctionCallbackInfo<Value>& args) { void AllocDispose(const FunctionCallbackInfo<Value>& args) {
AllocDispose(args[0].As<Object>()); Environment* env = Environment::GetCurrent(args.GetIsolate());
AllocDispose(env, args[0].As<Object>());
} }
void AllocDispose(Handle<Object> obj) { void AllocDispose(Environment* env, Handle<Object> obj) {
HandleScope handle_scope(node_isolate); HandleScope handle_scope(env->isolate());
Environment* env = Environment::GetCurrent(node_isolate);
if (env->using_smalloc_alloc_cb()) { if (env->using_smalloc_alloc_cb()) {
Local<Value> ext_v = obj->GetHiddenValue(env->smalloc_p_string()); Local<Value> ext_v = obj->GetHiddenValue(env->smalloc_p_string());
if (ext_v->IsExternal()) { if (ext_v->IsExternal()) {
Local<External> ext = ext_v.As<External>(); Local<External> ext = ext_v.As<External>();
CallbackInfo* cb_info = static_cast<CallbackInfo*>(ext->Value()); CallbackInfo* cb_info = static_cast<CallbackInfo*>(ext->Value());
TargetFreeCallback(node_isolate, &cb_info->p_obj, cb_info); TargetFreeCallback(env->isolate(), &cb_info->p_obj, cb_info);
return; return;
} }
} }
@ -329,12 +336,13 @@ void AllocDispose(Handle<Object> obj) {
free(data); free(data);
} }
if (length != 0) { if (length != 0) {
node_isolate->AdjustAmountOfExternalAllocatedMemory(-length); env->isolate()->AdjustAmountOfExternalAllocatedMemory(-length);
} }
} }
void Alloc(Handle<Object> obj, void Alloc(Environment* env,
Handle<Object> obj,
size_t length, size_t length,
FreeCallback fn, FreeCallback fn,
void* hint, void* hint,
@ -349,11 +357,12 @@ void Alloc(Handle<Object> obj,
length *= type_size; length *= type_size;
char* data = new char[length]; char* data = new char[length];
Alloc(obj, data, length, fn, hint, type); Alloc(env, obj, data, length, fn, hint, type);
} }
void Alloc(Handle<Object> obj, void Alloc(Environment* env,
Handle<Object> obj,
char* data, char* data,
size_t length, size_t length,
FreeCallback fn, FreeCallback fn,
@ -361,18 +370,17 @@ void Alloc(Handle<Object> obj,
enum ExternalArrayType type) { enum ExternalArrayType type) {
assert(!obj->HasIndexedPropertiesInExternalArrayData()); assert(!obj->HasIndexedPropertiesInExternalArrayData());
HandleScope handle_scope(node_isolate); HandleScope handle_scope(env->isolate());
Environment* env = Environment::GetCurrent(node_isolate);
env->set_using_smalloc_alloc_cb(true); env->set_using_smalloc_alloc_cb(true);
CallbackInfo* cb_info = new CallbackInfo; CallbackInfo* cb_info = new CallbackInfo;
cb_info->cb = fn; cb_info->cb = fn;
cb_info->hint = hint; cb_info->hint = hint;
cb_info->p_obj.Reset(node_isolate, obj); cb_info->p_obj.Reset(env->isolate(), obj);
obj->SetHiddenValue(env->smalloc_p_string(), External::New(cb_info)); obj->SetHiddenValue(env->smalloc_p_string(), External::New(cb_info));
node_isolate->AdjustAmountOfExternalAllocatedMemory(length + env->isolate()->AdjustAmountOfExternalAllocatedMemory(length +
sizeof(*cb_info)); sizeof(*cb_info));
cb_info->p_obj.MakeWeak(cb_info, TargetFreeCallback); cb_info->p_obj.MakeWeak(cb_info, TargetFreeCallback);
cb_info->p_obj.MarkIndependent(); cb_info->p_obj.MarkIndependent();
cb_info->p_obj.SetWrapperClassId(ALLOC_ID); cb_info->p_obj.SetWrapperClassId(ALLOC_ID);
@ -404,12 +412,13 @@ void TargetFreeCallback(Isolate* isolate,
void HasExternalData(const FunctionCallbackInfo<Value>& args) { void HasExternalData(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args.GetIsolate());
args.GetReturnValue().Set(args[0]->IsObject() && args.GetReturnValue().Set(args[0]->IsObject() &&
HasExternalData(args[0].As<Object>())); HasExternalData(env, args[0].As<Object>()));
} }
bool HasExternalData(Local<Object> obj) { bool HasExternalData(Environment* env, Local<Object> obj) {
return obj->HasIndexedPropertiesInExternalArrayData(); return obj->HasIndexedPropertiesInExternalArrayData();
} }
@ -485,7 +494,7 @@ void Initialize(Handle<Object> exports,
NODE_SET_METHOD(exports, "hasExternalData", HasExternalData); NODE_SET_METHOD(exports, "hasExternalData", HasExternalData);
exports->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kMaxLength"), exports->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
Uint32::NewFromUnsigned(kMaxLength, env->isolate())); Uint32::NewFromUnsigned(kMaxLength, env->isolate()));
HeapProfiler* heap_profiler = env->isolate()->GetHeapProfiler(); HeapProfiler* heap_profiler = env->isolate()->GetHeapProfiler();

17
src/smalloc.h

@ -24,6 +24,7 @@
#include "node.h" #include "node.h"
#include "v8.h" #include "v8.h"
#include "env.h"
namespace node { namespace node {
@ -72,22 +73,26 @@ NODE_EXTERN size_t ExternalArraySize(enum v8::ExternalArrayType type);
* v8::Integer::NewFromUnsigned(array_length)); * v8::Integer::NewFromUnsigned(array_length));
* \code * \code
*/ */
NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj, NODE_EXTERN void Alloc(Environment* env,
v8::Handle<v8::Object> obj,
size_t length, size_t length,
enum v8::ExternalArrayType type = enum v8::ExternalArrayType type =
v8::kExternalUnsignedByteArray); v8::kExternalUnsignedByteArray);
NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj, NODE_EXTERN void Alloc(Environment* env,
v8::Handle<v8::Object> obj,
char* data, char* data,
size_t length, size_t length,
enum v8::ExternalArrayType type = enum v8::ExternalArrayType type =
v8::kExternalUnsignedByteArray); v8::kExternalUnsignedByteArray);
NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj, NODE_EXTERN void Alloc(Environment* env,
v8::Handle<v8::Object> obj,
size_t length, size_t length,
FreeCallback fn, FreeCallback fn,
void* hint, void* hint,
enum v8::ExternalArrayType type = enum v8::ExternalArrayType type =
v8::kExternalUnsignedByteArray); v8::kExternalUnsignedByteArray);
NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj, NODE_EXTERN void Alloc(Environment* env,
v8::Handle<v8::Object> obj,
char* data, char* data,
size_t length, size_t length,
FreeCallback fn, FreeCallback fn,
@ -99,13 +104,13 @@ NODE_EXTERN void Alloc(v8::Handle<v8::Object> obj,
* Free memory associated with an externally allocated object. If no external * Free memory associated with an externally allocated object. If no external
* memory is allocated to the object then nothing will happen. * memory is allocated to the object then nothing will happen.
*/ */
NODE_EXTERN void AllocDispose(v8::Handle<v8::Object> obj); NODE_EXTERN void AllocDispose(Environment* env, v8::Handle<v8::Object> obj);
/** /**
* Check if the Object has externally allocated memory. * Check if the Object has externally allocated memory.
*/ */
NODE_EXTERN bool HasExternalData(v8::Local<v8::Object> obj); NODE_EXTERN bool HasExternalData(Environment* env, v8::Local<v8::Object> obj);
} // namespace smalloc } // namespace smalloc
} // namespace node } // namespace node

11
src/spawn_sync.cc

@ -940,6 +940,7 @@ bool SyncProcessRunner::CheckRange(Local<Value> js_value) {
int SyncProcessRunner::CopyJsString(Local<Value> js_value, int SyncProcessRunner::CopyJsString(Local<Value> js_value,
const char** target) { const char** target) {
Isolate* isolate = env()->isolate();
Local<String> js_string; Local<String> js_string;
size_t size, written; size_t size, written;
char* buffer; char* buffer;
@ -950,11 +951,11 @@ int SyncProcessRunner::CopyJsString(Local<Value> js_value,
js_string = js_value->ToString(); js_string = js_value->ToString();
// Include space for null terminator byte. // Include space for null terminator byte.
size = StringBytes::StorageSize(js_string, UTF8) + 1; size = StringBytes::StorageSize(isolate, js_string, UTF8) + 1;
buffer = new char[size]; buffer = new char[size];
written = StringBytes::Write(buffer, -1, js_string, UTF8); written = StringBytes::Write(isolate, buffer, -1, js_string, UTF8);
buffer[written] = '\0'; buffer[written] = '\0';
*target = buffer; *target = buffer;
@ -964,6 +965,7 @@ int SyncProcessRunner::CopyJsString(Local<Value> js_value,
int SyncProcessRunner::CopyJsStringArray(Local<Value> js_value, int SyncProcessRunner::CopyJsStringArray(Local<Value> js_value,
char** target) { char** target) {
Isolate* isolate = env()->isolate();
Local<Array> js_array; Local<Array> js_array;
uint32_t length; uint32_t length;
size_t list_size, data_size, data_offset; size_t list_size, data_size, data_offset;
@ -991,7 +993,7 @@ int SyncProcessRunner::CopyJsStringArray(Local<Value> js_value,
// after every string. Align strings to cache lines. // after every string. Align strings to cache lines.
data_size = 0; data_size = 0;
for (uint32_t i = 0; i < length; i++) { for (uint32_t i = 0; i < length; i++) {
data_size += StringBytes::StorageSize(js_array->Get(i), UTF8) + 1; data_size += StringBytes::StorageSize(isolate, js_array->Get(i), UTF8) + 1;
data_size = ROUND_UP(data_size, sizeof(void*)); // NOLINT(runtime/sizeof) data_size = ROUND_UP(data_size, sizeof(void*)); // NOLINT(runtime/sizeof)
} }
@ -1002,7 +1004,8 @@ int SyncProcessRunner::CopyJsStringArray(Local<Value> js_value,
for (uint32_t i = 0; i < length; i++) { for (uint32_t i = 0; i < length; i++) {
list[i] = buffer + data_offset; list[i] = buffer + data_offset;
data_offset += StringBytes::Write(buffer + data_offset, data_offset += StringBytes::Write(isolate,
buffer + data_offset,
-1, -1,
js_array->Get(i), js_array->Get(i),
UTF8); UTF8);

4
src/spawn_sync.h

@ -196,8 +196,8 @@ class SyncProcessRunner {
static bool IsSet(Local<Value> value); static bool IsSet(Local<Value> value);
template <typename t> static bool CheckRange(Local<Value> js_value); template <typename t> static bool CheckRange(Local<Value> js_value);
static int CopyJsString(Local<Value> js_value, const char** target); int CopyJsString(Local<Value> js_value, const char** target);
static int CopyJsStringArray(Local<Value> js_value, char** target); int CopyJsStringArray(Local<Value> js_value, char** target);
static void ExitCallback(uv_process_t* handle, static void ExitCallback(uv_process_t* handle,
int64_t exit_status, int64_t exit_status,

56
src/stream_wrap.cc

@ -68,7 +68,8 @@ StreamWrap::StreamWrap(Environment* env,
void StreamWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) { void StreamWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
#if !defined(_WIN32) #if !defined(_WIN32)
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
StreamWrap* wrap = Unwrap<StreamWrap>(args.This()); StreamWrap* wrap = Unwrap<StreamWrap>(args.This());
int fd = -1; int fd = -1;
if (wrap != NULL && wrap->stream() != NULL) { if (wrap != NULL && wrap->stream() != NULL) {
@ -80,15 +81,16 @@ void StreamWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
void StreamWrap::UpdateWriteQueueSize() { void StreamWrap::UpdateWriteQueueSize() {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
Local<Integer> write_queue_size = Local<Integer> write_queue_size =
Integer::NewFromUnsigned(stream()->write_queue_size, node_isolate); Integer::NewFromUnsigned(stream()->write_queue_size, env()->isolate());
object()->Set(env()->write_queue_size_string(), write_queue_size); object()->Set(env()->write_queue_size_string(), write_queue_size);
} }
void StreamWrap::ReadStart(const FunctionCallbackInfo<Value>& args) { void StreamWrap::ReadStart(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
StreamWrap* wrap = Unwrap<StreamWrap>(args.This()); StreamWrap* wrap = Unwrap<StreamWrap>(args.This());
@ -104,7 +106,8 @@ void StreamWrap::ReadStart(const FunctionCallbackInfo<Value>& args) {
void StreamWrap::ReadStop(const FunctionCallbackInfo<Value>& args) { void StreamWrap::ReadStop(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
StreamWrap* wrap = Unwrap<StreamWrap>(args.This()); StreamWrap* wrap = Unwrap<StreamWrap>(args.This());
@ -124,7 +127,7 @@ void StreamWrap::OnAlloc(uv_handle_t* handle,
template <class WrapType, class UVType> template <class WrapType, class UVType>
static Local<Object> AcceptHandle(Environment* env, uv_stream_t* pipe) { static Local<Object> AcceptHandle(Environment* env, uv_stream_t* pipe) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
Local<Object> wrap_obj; Local<Object> wrap_obj;
UVType* handle; UVType* handle;
@ -227,7 +230,7 @@ void StreamWrap::WriteBuffer(const FunctionCallbackInfo<Value>& args) {
NULL, NULL,
StreamWrap::AfterWrite); StreamWrap::AfterWrite);
req_wrap->Dispatched(); req_wrap->Dispatched();
req_wrap_obj->Set(env->async(), True(node_isolate)); req_wrap_obj->Set(env->async(), True(env->isolate()));
if (err) { if (err) {
req_wrap->~WriteWrap(); req_wrap->~WriteWrap();
@ -239,7 +242,7 @@ void StreamWrap::WriteBuffer(const FunctionCallbackInfo<Value>& args) {
if (msg != NULL) if (msg != NULL)
req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg)); req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg));
req_wrap_obj->Set(env->bytes_string(), req_wrap_obj->Set(env->bytes_string(),
Integer::NewFromUnsigned(length, node_isolate)); Integer::NewFromUnsigned(length, env->isolate()));
args.GetReturnValue().Set(err); args.GetReturnValue().Set(err);
} }
@ -263,9 +266,9 @@ void StreamWrap::WriteStringImpl(const FunctionCallbackInfo<Value>& args) {
// computing their actual size, rather than tripling the storage. // computing their actual size, rather than tripling the storage.
size_t storage_size; size_t storage_size;
if (encoding == UTF8 && string->Length() > 65535) if (encoding == UTF8 && string->Length() > 65535)
storage_size = StringBytes::Size(string, encoding); storage_size = StringBytes::Size(env->isolate(), string, encoding);
else else
storage_size = StringBytes::StorageSize(string, encoding); storage_size = StringBytes::StorageSize(env->isolate(), string, encoding);
if (storage_size > INT_MAX) { if (storage_size > INT_MAX) {
args.GetReturnValue().Set(UV_ENOBUFS); args.GetReturnValue().Set(UV_ENOBUFS);
@ -283,7 +286,8 @@ void StreamWrap::WriteStringImpl(const FunctionCallbackInfo<Value>& args) {
bool try_write = storage_size + 15 <= sizeof(stack_storage) && bool try_write = storage_size + 15 <= sizeof(stack_storage) &&
(!wrap->is_named_pipe_ipc() || !args[2]->IsObject()); (!wrap->is_named_pipe_ipc() || !args[2]->IsObject());
if (try_write) { if (try_write) {
data_size = StringBytes::Write(stack_storage, data_size = StringBytes::Write(env->isolate(),
stack_storage,
storage_size, storage_size,
string, string,
encoding); encoding);
@ -313,7 +317,11 @@ void StreamWrap::WriteStringImpl(const FunctionCallbackInfo<Value>& args) {
data_size = buf.len; data_size = buf.len;
} else { } else {
// Write it // Write it
data_size = StringBytes::Write(data, storage_size, string, encoding); data_size = StringBytes::Write(env->isolate(),
data,
storage_size,
string,
encoding);
} }
assert(data_size <= storage_size); assert(data_size <= storage_size);
@ -348,7 +356,7 @@ void StreamWrap::WriteStringImpl(const FunctionCallbackInfo<Value>& args) {
} }
req_wrap->Dispatched(); req_wrap->Dispatched();
req_wrap->object()->Set(env->async(), True(node_isolate)); req_wrap->object()->Set(env->async(), True(env->isolate()));
if (err) { if (err) {
req_wrap->~WriteWrap(); req_wrap->~WriteWrap();
@ -360,7 +368,7 @@ void StreamWrap::WriteStringImpl(const FunctionCallbackInfo<Value>& args) {
if (msg != NULL) if (msg != NULL)
req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg)); req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg));
req_wrap_obj->Set(env->bytes_string(), req_wrap_obj->Set(env->bytes_string(),
Integer::NewFromUnsigned(data_size, node_isolate)); Integer::NewFromUnsigned(data_size, env->isolate()));
args.GetReturnValue().Set(err); args.GetReturnValue().Set(err);
} }
@ -395,9 +403,9 @@ void StreamWrap::Writev(const FunctionCallbackInfo<Value>& args) {
enum encoding encoding = ParseEncoding(chunks->Get(i * 2 + 1)); enum encoding encoding = ParseEncoding(chunks->Get(i * 2 + 1));
size_t chunk_size; size_t chunk_size;
if (encoding == UTF8 && string->Length() > 65535) if (encoding == UTF8 && string->Length() > 65535)
chunk_size = StringBytes::Size(string, encoding); chunk_size = StringBytes::Size(env->isolate(), string, encoding);
else else
chunk_size = StringBytes::StorageSize(string, encoding); chunk_size = StringBytes::StorageSize(env->isolate(), string, encoding);
storage_size += chunk_size + 15; storage_size += chunk_size + 15;
} }
@ -436,7 +444,11 @@ void StreamWrap::Writev(const FunctionCallbackInfo<Value>& args) {
Handle<String> string = chunk->ToString(); Handle<String> string = chunk->ToString();
enum encoding encoding = ParseEncoding(chunks->Get(i * 2 + 1)); enum encoding encoding = ParseEncoding(chunks->Get(i * 2 + 1));
str_size = StringBytes::Write(str_storage, str_size, string, encoding); str_size = StringBytes::Write(env->isolate(),
str_storage,
str_size,
string,
encoding);
bufs[i].base = str_storage; bufs[i].base = str_storage;
bufs[i].len = str_size; bufs[i].len = str_size;
offset += str_size; offset += str_size;
@ -454,9 +466,9 @@ void StreamWrap::Writev(const FunctionCallbackInfo<Value>& args) {
delete[] bufs; delete[] bufs;
req_wrap->Dispatched(); req_wrap->Dispatched();
req_wrap->object()->Set(env->async(), True(node_isolate)); req_wrap->object()->Set(env->async(), True(env->isolate()));
req_wrap->object()->Set(env->bytes_string(), req_wrap->object()->Set(env->bytes_string(),
Number::New(node_isolate, bytes)); Number::New(env->isolate(), bytes));
const char* msg = wrap->callbacks()->Error(); const char* msg = wrap->callbacks()->Error();
if (msg != NULL) if (msg != NULL)
req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg)); req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg));
@ -503,7 +515,7 @@ void StreamWrap::AfterWrite(uv_write_t* req, int status) {
wrap->callbacks()->AfterWrite(req_wrap); wrap->callbacks()->AfterWrite(req_wrap);
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
wrap->object(), wrap->object(),
req_wrap_obj, req_wrap_obj,
Undefined() Undefined()
@ -554,7 +566,7 @@ void StreamWrap::AfterShutdown(uv_shutdown_t* req, int status) {
Local<Object> req_wrap_obj = req_wrap->object(); Local<Object> req_wrap_obj = req_wrap->object();
Local<Value> argv[3] = { Local<Value> argv[3] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
wrap->object(), wrap->object(),
req_wrap_obj req_wrap_obj
}; };
@ -668,7 +680,7 @@ void StreamWrapCallbacks::DoRead(uv_stream_t* handle,
Context::Scope context_scope(env->context()); Context::Scope context_scope(env->context());
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(nread, node_isolate), Integer::New(nread, env->isolate()),
Undefined(), Undefined(),
Undefined() Undefined()
}; };

98
src/string_bytes.cc

@ -38,6 +38,7 @@ namespace node {
using v8::Handle; using v8::Handle;
using v8::HandleScope; using v8::HandleScope;
using v8::Isolate;
using v8::Local; using v8::Local;
using v8::String; using v8::String;
using v8::Value; using v8::Value;
@ -46,9 +47,12 @@ using v8::Value;
template <typename ResourceType, typename TypeName> template <typename ResourceType, typename TypeName>
class ExternString: public ResourceType { class ExternString: public ResourceType {
public: public:
explicit ExternString(Isolate* isolate) : isolate_(isolate) {
}
~ExternString() { ~ExternString() {
delete[] data_; delete[] data_;
node_isolate->AdjustAmountOfExternalAllocatedMemory(-length_); isolate()->AdjustAmountOfExternalAllocatedMemory(-length_);
} }
const TypeName* data() const { const TypeName* data() const {
@ -59,37 +63,46 @@ class ExternString: public ResourceType {
return length_; return length_;
} }
static Local<String> NewFromCopy(const TypeName* data, size_t length) { static Local<String> NewFromCopy(Isolate* isolate,
HandleScope scope(node_isolate); const TypeName* data,
size_t length) {
HandleScope scope(isolate);
if (length == 0) if (length == 0)
return scope.Close(String::Empty(node_isolate)); return scope.Close(String::Empty(isolate));
TypeName* new_data = new TypeName[length]; TypeName* new_data = new TypeName[length];
memcpy(new_data, data, length * sizeof(*new_data)); memcpy(new_data, data, length * sizeof(*new_data));
return scope.Close(ExternString<ResourceType, TypeName>::New(new_data, return scope.Close(ExternString<ResourceType, TypeName>::New(isolate,
new_data,
length)); length));
} }
// uses "data" for external resource, and will be free'd on gc // uses "data" for external resource, and will be free'd on gc
static Local<String> New(const TypeName* data, size_t length) { static Local<String> New(Isolate* isolate,
HandleScope scope(node_isolate); const TypeName* data,
size_t length) {
HandleScope scope(isolate);
if (length == 0) if (length == 0)
return scope.Close(String::Empty(node_isolate)); return scope.Close(String::Empty(isolate));
ExternString* h_str = new ExternString<ResourceType, TypeName>(data, ExternString* h_str = new ExternString<ResourceType, TypeName>(isolate,
data,
length); length);
Local<String> str = String::NewExternal(h_str); Local<String> str = String::NewExternal(h_str);
node_isolate->AdjustAmountOfExternalAllocatedMemory(length); isolate->AdjustAmountOfExternalAllocatedMemory(length);
return scope.Close(str); return scope.Close(str);
} }
inline Isolate* isolate() const { return isolate_; }
private: private:
ExternString(const TypeName* data, size_t length) ExternString(Isolate* isolate, const TypeName* data, size_t length)
: data_(data), length_(length) { } : isolate_(isolate), data_(data), length_(length) { }
Isolate* isolate_;
const TypeName* data_; const TypeName* data_;
size_t length_; size_t length_;
}; };
@ -244,7 +257,8 @@ size_t hex_decode(char* buf,
} }
bool StringBytes::GetExternalParts(Handle<Value> val, bool StringBytes::GetExternalParts(Isolate* isolate,
Handle<Value> val,
const char** data, const char** data,
size_t* len) { size_t* len) {
if (Buffer::HasInstance(val)) { if (Buffer::HasInstance(val)) {
@ -277,15 +291,16 @@ bool StringBytes::GetExternalParts(Handle<Value> val,
} }
size_t StringBytes::Write(char* buf, size_t StringBytes::Write(Isolate* isolate,
char* buf,
size_t buflen, size_t buflen,
Handle<Value> val, Handle<Value> val,
enum encoding encoding, enum encoding encoding,
int* chars_written) { int* chars_written) {
HandleScope scope(node_isolate); HandleScope scope(isolate);
const char* data; const char* data;
size_t len = 0; size_t len = 0;
bool is_extern = GetExternalParts(val, &data, &len); bool is_extern = GetExternalParts(isolate, val, &data, &len);
Local<String> str = val.As<String>(); Local<String> str = val.As<String>();
len = len < buflen ? len : buflen; len = len < buflen ? len : buflen;
@ -358,7 +373,9 @@ size_t StringBytes::Write(char* buf,
} }
bool StringBytes::IsValidString(Handle<String> string, enum encoding enc) { bool StringBytes::IsValidString(Isolate* isolate,
Handle<String> string,
enum encoding enc) {
if (enc == HEX && string->Length() % 2 != 0) if (enc == HEX && string->Length() % 2 != 0)
return false; return false;
// TODO(bnoordhuis) Add BASE64 check? // TODO(bnoordhuis) Add BASE64 check?
@ -369,8 +386,10 @@ bool StringBytes::IsValidString(Handle<String> string, enum encoding enc) {
// Quick and dirty size calculation // Quick and dirty size calculation
// Will always be at least big enough, but may have some extra // Will always be at least big enough, but may have some extra
// UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes // UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes
size_t StringBytes::StorageSize(Handle<Value> val, enum encoding encoding) { size_t StringBytes::StorageSize(Isolate* isolate,
HandleScope scope(node_isolate); Handle<Value> val,
enum encoding encoding) {
HandleScope scope(isolate);
size_t data_size = 0; size_t data_size = 0;
bool is_buffer = Buffer::HasInstance(val); bool is_buffer = Buffer::HasInstance(val);
@ -416,8 +435,10 @@ size_t StringBytes::StorageSize(Handle<Value> val, enum encoding encoding) {
} }
size_t StringBytes::Size(Handle<Value> val, enum encoding encoding) { size_t StringBytes::Size(Isolate* isolate,
HandleScope scope(node_isolate); Handle<Value> val,
enum encoding encoding) {
HandleScope scope(isolate);
size_t data_size = 0; size_t data_size = 0;
bool is_buffer = Buffer::HasInstance(val); bool is_buffer = Buffer::HasInstance(val);
@ -425,7 +446,7 @@ size_t StringBytes::Size(Handle<Value> val, enum encoding encoding) {
return Buffer::Length(val); return Buffer::Length(val);
const char* data; const char* data;
if (GetExternalParts(val, &data, &data_size)) if (GetExternalParts(isolate, val, &data, &data_size))
return data_size; return data_size;
Local<String> str = val->ToString(); Local<String> str = val->ToString();
@ -651,14 +672,15 @@ static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
Local<Value> StringBytes::Encode(const char* buf, Local<Value> StringBytes::Encode(Isolate* isolate,
const char* buf,
size_t buflen, size_t buflen,
enum encoding encoding) { enum encoding encoding) {
HandleScope scope(node_isolate); HandleScope scope(isolate);
assert(buflen <= Buffer::kMaxLength); assert(buflen <= Buffer::kMaxLength);
if (!buflen && encoding != BUFFER) if (!buflen && encoding != BUFFER)
return scope.Close(String::Empty(node_isolate)); return scope.Close(String::Empty(isolate));
Local<String> val; Local<String> val;
switch (encoding) { switch (encoding) {
@ -670,21 +692,21 @@ Local<Value> StringBytes::Encode(const char* buf,
char* out = new char[buflen]; char* out = new char[buflen];
force_ascii(buf, out, buflen); force_ascii(buf, out, buflen);
if (buflen < EXTERN_APEX) { if (buflen < EXTERN_APEX) {
val = OneByteString(node_isolate, out, buflen); val = OneByteString(isolate, out, buflen);
delete[] out; delete[] out;
} else { } else {
val = ExternOneByteString::New(out, buflen); val = ExternOneByteString::New(isolate, out, buflen);
} }
} else { } else {
if (buflen < EXTERN_APEX) if (buflen < EXTERN_APEX)
val = OneByteString(node_isolate, buf, buflen); val = OneByteString(isolate, buf, buflen);
else else
val = ExternOneByteString::NewFromCopy(buf, buflen); val = ExternOneByteString::NewFromCopy(isolate, buf, buflen);
} }
break; break;
case UTF8: case UTF8:
val = String::NewFromUtf8(node_isolate, val = String::NewFromUtf8(isolate,
buf, buf,
String::kNormalString, String::kNormalString,
buflen); buflen);
@ -692,9 +714,9 @@ Local<Value> StringBytes::Encode(const char* buf,
case BINARY: case BINARY:
if (buflen < EXTERN_APEX) if (buflen < EXTERN_APEX)
val = OneByteString(node_isolate, buf, buflen); val = OneByteString(isolate, buf, buflen);
else else
val = ExternOneByteString::NewFromCopy(buf, buflen); val = ExternOneByteString::NewFromCopy(isolate, buf, buflen);
break; break;
case BASE64: { case BASE64: {
@ -705,10 +727,10 @@ Local<Value> StringBytes::Encode(const char* buf,
assert(written == dlen); assert(written == dlen);
if (dlen < EXTERN_APEX) { if (dlen < EXTERN_APEX) {
val = OneByteString(node_isolate, dst, dlen); val = OneByteString(isolate, dst, dlen);
delete[] dst; delete[] dst;
} else { } else {
val = ExternOneByteString::New(dst, dlen); val = ExternOneByteString::New(isolate, dst, dlen);
} }
break; break;
} }
@ -716,12 +738,12 @@ Local<Value> StringBytes::Encode(const char* buf,
case UCS2: { case UCS2: {
const uint16_t* out = reinterpret_cast<const uint16_t*>(buf); const uint16_t* out = reinterpret_cast<const uint16_t*>(buf);
if (buflen < EXTERN_APEX) if (buflen < EXTERN_APEX)
val = String::NewFromTwoByte(node_isolate, val = String::NewFromTwoByte(isolate,
out, out,
String::kNormalString, String::kNormalString,
buflen / 2); buflen / 2);
else else
val = ExternTwoByteString::NewFromCopy(out, buflen / 2); val = ExternTwoByteString::NewFromCopy(isolate, out, buflen / 2);
break; break;
} }
@ -732,10 +754,10 @@ Local<Value> StringBytes::Encode(const char* buf,
assert(written == dlen); assert(written == dlen);
if (dlen < EXTERN_APEX) { if (dlen < EXTERN_APEX) {
val = OneByteString(node_isolate, dst, dlen); val = OneByteString(isolate, dst, dlen);
delete[] dst; delete[] dst;
} else { } else {
val = ExternOneByteString::New(dst, dlen); val = ExternOneByteString::New(isolate, dst, dlen);
} }
break; break;
} }

67
src/string_bytes.h

@ -34,19 +34,26 @@ class StringBytes {
// Does the string match the encoding? Quick but non-exhaustive. // Does the string match the encoding? Quick but non-exhaustive.
// Example: a HEX string must have a length that's a multiple of two. // Example: a HEX string must have a length that's a multiple of two.
// FIXME(bnoordhuis) IsMaybeValidString()? Naming things is hard... // FIXME(bnoordhuis) IsMaybeValidString()? Naming things is hard...
static bool IsValidString(v8::Handle<v8::String> string, enum encoding enc); static bool IsValidString(v8::Isolate* isolate,
v8::Handle<v8::String> string,
enum encoding enc);
// Fast, but can be 2 bytes oversized for Base64, and // Fast, but can be 2 bytes oversized for Base64, and
// as much as triple UTF-8 strings <= 65536 chars in length // as much as triple UTF-8 strings <= 65536 chars in length
static size_t StorageSize(v8::Handle<v8::Value> val, enum encoding enc); static size_t StorageSize(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
enum encoding enc);
// Precise byte count, but slightly slower for Base64 and // Precise byte count, but slightly slower for Base64 and
// very much slower for UTF-8 // very much slower for UTF-8
static size_t Size(v8::Handle<v8::Value> val, enum encoding enc); static size_t Size(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
enum encoding enc);
// If the string is external then assign external properties to data and len, // If the string is external then assign external properties to data and len,
// then return true. If not return false. // then return true. If not return false.
static bool GetExternalParts(v8::Handle<v8::Value> val, static bool GetExternalParts(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
const char** data, const char** data,
size_t* len); size_t* len);
@ -54,16 +61,64 @@ class StringBytes {
// returns the number of bytes written, which will always be // returns the number of bytes written, which will always be
// <= buflen. Use StorageSize/Size first to know how much // <= buflen. Use StorageSize/Size first to know how much
// memory to allocate. // memory to allocate.
static size_t Write(char* buf, static size_t Write(v8::Isolate* isolate,
char* buf,
size_t buflen, size_t buflen,
v8::Handle<v8::Value> val, v8::Handle<v8::Value> val,
enum encoding enc, enum encoding enc,
int* chars_written = NULL); int* chars_written = NULL);
// Take the bytes in the src, and turn it into a Buffer or String. // Take the bytes in the src, and turn it into a Buffer or String.
static v8::Local<v8::Value> Encode(const char* buf, static v8::Local<v8::Value> Encode(v8::Isolate* isolate,
const char* buf,
size_t buflen, size_t buflen,
enum encoding encoding); enum encoding encoding);
// Deprecated legacy interface
NODE_DEPRECATED("Use IsValidString(isolate, ...)",
static inline bool IsValidString(
v8::Handle<v8::String> string,
enum encoding enc) {
return IsValidString(v8::Isolate::GetCurrent(), string, enc);
})
NODE_DEPRECATED("Use StorageSize(isolate, ...)",
static inline size_t StorageSize(v8::Handle<v8::Value> val,
enum encoding enc) {
return StorageSize(v8::Isolate::GetCurrent(), val, enc);
})
NODE_DEPRECATED("Use Size(isolate, ...)",
static inline size_t Size(v8::Handle<v8::Value> val,
enum encoding enc) {
return Size(v8::Isolate::GetCurrent(), val, enc);
})
NODE_DEPRECATED("Use GetExternalParts(isolate, ...)",
static inline bool GetExternalParts(v8::Handle<v8::Value> val,
const char** data,
size_t* len) {
return GetExternalParts(v8::Isolate::GetCurrent(), val, data, len);
})
NODE_DEPRECATED("Use Write(isolate, ...)",
static inline size_t Write(char* buf,
size_t buflen,
v8::Handle<v8::Value> val,
enum encoding enc,
int* chars_written = NULL) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
return Write(isolate, buf, buflen, val, enc, chars_written);
})
NODE_DEPRECATED("Use Encode(isolate, ...)",
static inline v8::Local<v8::Value> Encode(
const char* buf,
size_t buflen,
enum encoding encoding) {
return Encode(v8::Isolate::GetCurrent(), buf, buflen, encoding);
})
}; };
} // namespace node } // namespace node

47
src/tcp_wrap.cc

@ -70,12 +70,12 @@ void TCPWrap::Initialize(Handle<Object> target,
Environment* env = Environment::GetCurrent(context); Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(New); Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "TCP")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TCP"));
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
enum PropertyAttribute attributes = enum PropertyAttribute attributes =
static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete); static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"), t->InstanceTemplate()->SetAccessor(env->fd_string(),
StreamWrap::GetFD, StreamWrap::GetFD,
NULL, NULL,
Handle<Value>(), Handle<Value>(),
@ -116,7 +116,7 @@ void TCPWrap::Initialize(Handle<Object> target,
SetSimultaneousAccepts); SetSimultaneousAccepts);
#endif #endif
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "TCP"), t->GetFunction()); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "TCP"), t->GetFunction());
env->set_tcp_constructor_template(t); env->set_tcp_constructor_template(t);
} }
@ -202,7 +202,8 @@ void TCPWrap::GetPeerName(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) { void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -213,7 +214,8 @@ void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) { void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -227,7 +229,8 @@ void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
#ifdef _WIN32 #ifdef _WIN32
void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo<Value>& args) { void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -239,7 +242,8 @@ void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) { void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
int fd = args[0]->IntegerValue(); int fd = args[0]->IntegerValue();
uv_tcp_open(&wrap->handle_, fd); uv_tcp_open(&wrap->handle_, fd);
@ -247,7 +251,8 @@ void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) { void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -267,7 +272,8 @@ void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) { void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -287,7 +293,8 @@ void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) { void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TCPWrap* wrap = Unwrap<TCPWrap>(args.This()); TCPWrap* wrap = Unwrap<TCPWrap>(args.This());
@ -312,7 +319,7 @@ void TCPWrap::OnConnection(uv_stream_t* handle, int status) {
assert(tcp_wrap->persistent().IsEmpty() == false); assert(tcp_wrap->persistent().IsEmpty() == false);
Local<Value> argv[2] = { Local<Value> argv[2] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
Undefined() Undefined()
}; };
@ -349,11 +356,11 @@ void TCPWrap::AfterConnect(uv_connect_t* req, int status) {
Local<Object> req_wrap_obj = req_wrap->object(); Local<Object> req_wrap_obj = req_wrap->object();
Local<Value> argv[5] = { Local<Value> argv[5] = {
Integer::New(status, node_isolate), Integer::New(status, env->isolate()),
wrap->object(), wrap->object(),
req_wrap_obj, req_wrap_obj,
v8::True(node_isolate), v8::True(env->isolate()),
v8::True(node_isolate) v8::True(env->isolate())
}; };
req_wrap->MakeCallback(env->oncomplete_string(), ARRAY_SIZE(argv), argv); req_wrap->MakeCallback(env->oncomplete_string(), ARRAY_SIZE(argv), argv);
@ -434,7 +441,7 @@ void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
Local<Object> AddressToJS(Environment* env, Local<Object> AddressToJS(Environment* env,
const sockaddr* addr, const sockaddr* addr,
Local<Object> info) { Local<Object> info) {
HandleScope scope(node_isolate); HandleScope scope(env->isolate());
char ip[INET6_ADDRSTRLEN]; char ip[INET6_ADDRSTRLEN];
const sockaddr_in *a4; const sockaddr_in *a4;
const sockaddr_in6 *a6; const sockaddr_in6 *a6;
@ -448,22 +455,22 @@ Local<Object> AddressToJS(Environment* env,
a6 = reinterpret_cast<const sockaddr_in6*>(addr); a6 = reinterpret_cast<const sockaddr_in6*>(addr);
uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip); uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
port = ntohs(a6->sin6_port); port = ntohs(a6->sin6_port);
info->Set(env->address_string(), OneByteString(node_isolate, ip)); info->Set(env->address_string(), OneByteString(env->isolate(), ip));
info->Set(env->family_string(), env->ipv6_string()); info->Set(env->family_string(), env->ipv6_string());
info->Set(env->port_string(), Integer::New(port, node_isolate)); info->Set(env->port_string(), Integer::New(port, env->isolate()));
break; break;
case AF_INET: case AF_INET:
a4 = reinterpret_cast<const sockaddr_in*>(addr); a4 = reinterpret_cast<const sockaddr_in*>(addr);
uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip); uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
port = ntohs(a4->sin_port); port = ntohs(a4->sin_port);
info->Set(env->address_string(), OneByteString(node_isolate, ip)); info->Set(env->address_string(), OneByteString(env->isolate(), ip));
info->Set(env->family_string(), env->ipv4_string()); info->Set(env->family_string(), env->ipv4_string());
info->Set(env->port_string(), Integer::New(port, node_isolate)); info->Set(env->port_string(), Integer::New(port, env->isolate()));
break; break;
default: default:
info->Set(env->address_string(), String::Empty(node_isolate)); info->Set(env->address_string(), String::Empty(env->isolate()));
} }
return scope.Close(info); return scope.Close(info);

26
src/timer_wrap.cc

@ -49,11 +49,12 @@ class TimerWrap : public HandleWrap {
static void Initialize(Handle<Object> target, static void Initialize(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context) { Handle<Context> context) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> constructor = FunctionTemplate::New(New); Local<FunctionTemplate> constructor = FunctionTemplate::New(New);
constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "Timer")); constructor->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "Timer"));
constructor->Set(FIXED_ONE_BYTE_STRING(node_isolate, "kOnTimeout"), constructor->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnTimeout"),
Integer::New(kOnTimeout, node_isolate)); Integer::New(kOnTimeout, env->isolate()));
NODE_SET_METHOD(constructor, "now", Now); NODE_SET_METHOD(constructor, "now", Now);
@ -67,7 +68,7 @@ class TimerWrap : public HandleWrap {
NODE_SET_PROTOTYPE_METHOD(constructor, "getRepeat", GetRepeat); NODE_SET_PROTOTYPE_METHOD(constructor, "getRepeat", GetRepeat);
NODE_SET_PROTOTYPE_METHOD(constructor, "again", Again); NODE_SET_PROTOTYPE_METHOD(constructor, "again", Again);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "Timer"), target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "Timer"),
constructor->GetFunction()); constructor->GetFunction());
} }
@ -95,7 +96,8 @@ class TimerWrap : public HandleWrap {
} }
static void Start(const FunctionCallbackInfo<Value>& args) { static void Start(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TimerWrap* wrap = Unwrap<TimerWrap>(args.This()); TimerWrap* wrap = Unwrap<TimerWrap>(args.This());
int64_t timeout = args[0]->IntegerValue(); int64_t timeout = args[0]->IntegerValue();
@ -105,7 +107,8 @@ class TimerWrap : public HandleWrap {
} }
static void Stop(const FunctionCallbackInfo<Value>& args) { static void Stop(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TimerWrap* wrap = Unwrap<TimerWrap>(args.This()); TimerWrap* wrap = Unwrap<TimerWrap>(args.This());
int err = uv_timer_stop(&wrap->handle_); int err = uv_timer_stop(&wrap->handle_);
@ -113,7 +116,8 @@ class TimerWrap : public HandleWrap {
} }
static void Again(const FunctionCallbackInfo<Value>& args) { static void Again(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TimerWrap* wrap = Unwrap<TimerWrap>(args.This()); TimerWrap* wrap = Unwrap<TimerWrap>(args.This());
int err = uv_timer_again(&wrap->handle_); int err = uv_timer_again(&wrap->handle_);
@ -121,7 +125,8 @@ class TimerWrap : public HandleWrap {
} }
static void SetRepeat(const FunctionCallbackInfo<Value>& args) { static void SetRepeat(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TimerWrap* wrap = Unwrap<TimerWrap>(args.This()); TimerWrap* wrap = Unwrap<TimerWrap>(args.This());
int64_t repeat = args[0]->IntegerValue(); int64_t repeat = args[0]->IntegerValue();
@ -130,7 +135,8 @@ class TimerWrap : public HandleWrap {
} }
static void GetRepeat(const FunctionCallbackInfo<Value>& args) { static void GetRepeat(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TimerWrap* wrap = Unwrap<TimerWrap>(args.This()); TimerWrap* wrap = Unwrap<TimerWrap>(args.This());
int64_t repeat = uv_timer_get_repeat(&wrap->handle_); int64_t repeat = uv_timer_get_repeat(&wrap->handle_);
@ -142,7 +148,7 @@ class TimerWrap : public HandleWrap {
Environment* env = wrap->env(); Environment* env = wrap->env();
HandleScope handle_scope(env->isolate()); HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context()); Context::Scope context_scope(env->context());
Local<Value> argv[1] = { Integer::New(status, node_isolate) }; Local<Value> argv[1] = { Integer::New(status, env->isolate()) };
wrap->MakeCallback(kOnTimeout, ARRAY_SIZE(argv), argv); wrap->MakeCallback(kOnTimeout, ARRAY_SIZE(argv), argv);
} }

60
src/tls_wrap.cc

@ -209,12 +209,16 @@ void TLSCallbacks::Wrap(const FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope(args.GetIsolate()); HandleScope handle_scope(args.GetIsolate());
Environment* env = Environment::GetCurrent(args.GetIsolate()); Environment* env = Environment::GetCurrent(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsObject()) if (args.Length() < 1 || !args[0]->IsObject()) {
return ThrowTypeError("First argument should be a StreamWrap instance"); return env->ThrowTypeError(
if (args.Length() < 2 || !args[1]->IsObject()) "First argument should be a StreamWrap instance");
return ThrowTypeError("Second argument should be a SecureContext instance"); }
if (args.Length() < 2 || !args[1]->IsObject()) {
return env->ThrowTypeError(
"Second argument should be a SecureContext instance");
}
if (args.Length() < 3 || !args[2]->IsBoolean()) if (args.Length() < 3 || !args[2]->IsBoolean())
return ThrowTypeError("Third argument should be boolean"); return env->ThrowTypeError("Third argument should be boolean");
Local<Object> stream = args[0].As<Object>(); Local<Object> stream = args[0].As<Object>();
Local<Object> sc = args[1].As<Object>(); Local<Object> sc = args[1].As<Object>();
@ -261,12 +265,13 @@ void TLSCallbacks::Receive(const FunctionCallbackInfo<Value>& args) {
void TLSCallbacks::Start(const FunctionCallbackInfo<Value>& args) { void TLSCallbacks::Start(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
if (wrap->started_) if (wrap->started_)
return ThrowError("Already started."); return env->ThrowError("Already started.");
wrap->started_ = true; wrap->started_ = true;
// Send ClientHello handshake // Send ClientHello handshake
@ -403,7 +408,7 @@ const char* TLSCallbacks::PrintErrors() {
Local<Value> TLSCallbacks::GetSSLError(int status, int* err, const char** msg) { Local<Value> TLSCallbacks::GetSSLError(int status, int* err, const char** msg) {
HandleScope scope(node_isolate); HandleScope scope(env()->isolate());
*err = SSL_get_error(ssl_, status); *err = SSL_get_error(ssl_, status);
switch (*err) { switch (*err) {
@ -412,7 +417,7 @@ Local<Value> TLSCallbacks::GetSSLError(int status, int* err, const char** msg) {
case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_WRITE:
break; break;
case SSL_ERROR_ZERO_RETURN: case SSL_ERROR_ZERO_RETURN:
return scope.Close(FIXED_ONE_BYTE_STRING(node_isolate, "ZERO_RETURN")); return scope.Close(env()->zero_return_string());
break; break;
default: default:
{ {
@ -421,7 +426,7 @@ Local<Value> TLSCallbacks::GetSSLError(int status, int* err, const char** msg) {
const char* buf = PrintErrors(); const char* buf = PrintErrors();
Local<String> message = Local<String> message =
OneByteString(node_isolate, buf, strlen(buf)); OneByteString(env()->isolate(), buf, strlen(buf));
Local<Value> exception = Exception::Error(message); Local<Value> exception = Exception::Error(message);
if (msg != NULL) { if (msg != NULL) {
@ -452,7 +457,7 @@ void TLSCallbacks::ClearOut() {
read = SSL_read(ssl_, out, sizeof(out)); read = SSL_read(ssl_, out, sizeof(out));
if (read > 0) { if (read > 0) {
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(read, node_isolate), Integer::New(read, env()->isolate()),
Buffer::New(env(), out, read) Buffer::New(env(), out, read)
}; };
wrap()->MakeCallback(env()->onread_string(), ARRAY_SIZE(argv), argv); wrap()->MakeCallback(env()->onread_string(), ARRAY_SIZE(argv), argv);
@ -462,7 +467,7 @@ void TLSCallbacks::ClearOut() {
int flags = SSL_get_shutdown(ssl_); int flags = SSL_get_shutdown(ssl_);
if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) { if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
eof_ = true; eof_ = true;
Local<Value> arg = Integer::New(UV_EOF, node_isolate); Local<Value> arg = Integer::New(UV_EOF, env()->isolate());
wrap()->MakeCallback(env()->onread_string(), 1, &arg); wrap()->MakeCallback(env()->onread_string(), 1, &arg);
} }
@ -629,7 +634,7 @@ void TLSCallbacks::DoRead(uv_stream_t* handle,
HandleScope handle_scope(env()->isolate()); HandleScope handle_scope(env()->isolate());
Context::Scope context_scope(env()->context()); Context::Scope context_scope(env()->context());
Local<Value> arg = Integer::New(nread, node_isolate); Local<Value> arg = Integer::New(nread, env()->isolate());
wrap()->MakeCallback(env()->onread_string(), 1, &arg); wrap()->MakeCallback(env()->onread_string(), 1, &arg);
return; return;
} }
@ -664,12 +669,13 @@ int TLSCallbacks::DoShutdown(ShutdownWrap* req_wrap, uv_shutdown_cb cb) {
void TLSCallbacks::SetVerifyMode(const FunctionCallbackInfo<Value>& args) { void TLSCallbacks::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean()) if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
return ThrowTypeError("Bad arguments, expected two booleans"); return env->ThrowTypeError("Bad arguments, expected two booleans");
int verify_mode; int verify_mode;
if (wrap->is_server()) { if (wrap->is_server()) {
@ -695,7 +701,8 @@ void TLSCallbacks::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
void TLSCallbacks::EnableSessionCallbacks( void TLSCallbacks::EnableSessionCallbacks(
const FunctionCallbackInfo<Value>& args) { const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
@ -705,7 +712,8 @@ void TLSCallbacks::EnableSessionCallbacks(
void TLSCallbacks::EnableHelloParser(const FunctionCallbackInfo<Value>& args) { void TLSCallbacks::EnableHelloParser(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
@ -723,14 +731,15 @@ void TLSCallbacks::OnClientHelloParseEnd(void* arg) {
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
void TLSCallbacks::GetServername(const FunctionCallbackInfo<Value>& args) { void TLSCallbacks::GetServername(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
const char* servername = SSL_get_servername(wrap->ssl_, const char* servername = SSL_get_servername(wrap->ssl_,
TLSEXT_NAMETYPE_host_name); TLSEXT_NAMETYPE_host_name);
if (servername != NULL) { if (servername != NULL) {
args.GetReturnValue().Set(OneByteString(node_isolate, servername)); args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
} else { } else {
args.GetReturnValue().Set(false); args.GetReturnValue().Set(false);
} }
@ -738,15 +747,16 @@ void TLSCallbacks::GetServername(const FunctionCallbackInfo<Value>& args) {
void TLSCallbacks::SetServername(const FunctionCallbackInfo<Value>& args) { void TLSCallbacks::SetServername(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This()); TLSCallbacks* wrap = Unwrap<TLSCallbacks>(args.This());
if (args.Length() < 1 || !args[0]->IsString()) if (args.Length() < 1 || !args[0]->IsString())
return ThrowTypeError("First argument should be a string"); return env->ThrowTypeError("First argument should be a string");
if (wrap->started_) if (wrap->started_)
return ThrowError("Already started."); return env->ThrowError("Already started.");
if (!wrap->is_client()) if (!wrap->is_client())
return; return;
@ -785,7 +795,7 @@ int TLSCallbacks::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
} }
p->sni_context_.Dispose(); p->sni_context_.Dispose();
p->sni_context_.Reset(node_isolate, ctx); p->sni_context_.Reset(env->isolate(), ctx);
SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>()); SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
InitNPN(sc, p); InitNPN(sc, p);
@ -804,7 +814,7 @@ void TLSCallbacks::Initialize(Handle<Object> target,
Local<FunctionTemplate> t = FunctionTemplate::New(); Local<FunctionTemplate> t = FunctionTemplate::New();
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "TLSWrap")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"));
NODE_SET_PROTOTYPE_METHOD(t, "receive", Receive); NODE_SET_PROTOTYPE_METHOD(t, "receive", Receive);
NODE_SET_PROTOTYPE_METHOD(t, "start", Start); NODE_SET_PROTOTYPE_METHOD(t, "start", Start);
@ -816,7 +826,7 @@ void TLSCallbacks::Initialize(Handle<Object> target,
"enableHelloParser", "enableHelloParser",
EnableHelloParser); EnableHelloParser);
SSLWrap<TLSCallbacks>::AddMethods(t); SSLWrap<TLSCallbacks>::AddMethods(env, t);
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
NODE_SET_PROTOTYPE_METHOD(t, "getServername", GetServername); NODE_SET_PROTOTYPE_METHOD(t, "getServername", GetServername);

24
src/tty_wrap.cc

@ -54,12 +54,12 @@ void TTYWrap::Initialize(Handle<Object> target,
Environment* env = Environment::GetCurrent(context); Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = FunctionTemplate::New(New); Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "TTY")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TTY"));
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
enum PropertyAttribute attributes = enum PropertyAttribute attributes =
static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete); static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"), t->InstanceTemplate()->SetAccessor(env->fd_string(),
StreamWrap::GetFD, StreamWrap::GetFD,
NULL, NULL,
Handle<Value>(), Handle<Value>(),
@ -85,7 +85,7 @@ void TTYWrap::Initialize(Handle<Object> target,
NODE_SET_METHOD(target, "isTTY", IsTTY); NODE_SET_METHOD(target, "isTTY", IsTTY);
NODE_SET_METHOD(target, "guessHandleType", GuessHandleType); NODE_SET_METHOD(target, "guessHandleType", GuessHandleType);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "TTY"), t->GetFunction()); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "TTY"), t->GetFunction());
env->set_tty_constructor_template(t); env->set_tty_constructor_template(t);
} }
@ -96,7 +96,8 @@ uv_tty_t* TTYWrap::UVHandle() {
void TTYWrap::GuessHandleType(const FunctionCallbackInfo<Value>& args) { void TTYWrap::GuessHandleType(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int fd = args[0]->Int32Value(); int fd = args[0]->Int32Value();
assert(fd >= 0); assert(fd >= 0);
@ -114,12 +115,13 @@ void TTYWrap::GuessHandleType(const FunctionCallbackInfo<Value>& args) {
abort(); abort();
} }
args.GetReturnValue().Set(OneByteString(node_isolate, type)); args.GetReturnValue().Set(OneByteString(env->isolate(), type));
} }
void TTYWrap::IsTTY(const FunctionCallbackInfo<Value>& args) { void TTYWrap::IsTTY(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int fd = args[0]->Int32Value(); int fd = args[0]->Int32Value();
assert(fd >= 0); assert(fd >= 0);
bool rc = uv_guess_handle(fd) == UV_TTY; bool rc = uv_guess_handle(fd) == UV_TTY;
@ -128,7 +130,8 @@ void TTYWrap::IsTTY(const FunctionCallbackInfo<Value>& args) {
void TTYWrap::GetWindowSize(const FunctionCallbackInfo<Value>& args) { void TTYWrap::GetWindowSize(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TTYWrap* wrap = Unwrap<TTYWrap>(args.This()); TTYWrap* wrap = Unwrap<TTYWrap>(args.This());
assert(args[0]->IsArray()); assert(args[0]->IsArray());
@ -138,8 +141,8 @@ void TTYWrap::GetWindowSize(const FunctionCallbackInfo<Value>& args) {
if (err == 0) { if (err == 0) {
Local<v8::Array> a = args[0].As<Array>(); Local<v8::Array> a = args[0].As<Array>();
a->Set(0, Integer::New(width, node_isolate)); a->Set(0, Integer::New(width, env->isolate()));
a->Set(1, Integer::New(height, node_isolate)); a->Set(1, Integer::New(height, env->isolate()));
} }
args.GetReturnValue().Set(err); args.GetReturnValue().Set(err);
@ -147,7 +150,8 @@ void TTYWrap::GetWindowSize(const FunctionCallbackInfo<Value>& args) {
void TTYWrap::SetRawMode(const FunctionCallbackInfo<Value>& args) { void TTYWrap::SetRawMode(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
TTYWrap* wrap = Unwrap<TTYWrap>(args.This()); TTYWrap* wrap = Unwrap<TTYWrap>(args.This());

27
src/udp_wrap.cc

@ -93,11 +93,11 @@ void UDPWrap::Initialize(Handle<Object> target,
Local<FunctionTemplate> t = FunctionTemplate::New(New); Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1); t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(node_isolate, "UDP")); t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"));
enum PropertyAttribute attributes = enum PropertyAttribute attributes =
static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete); static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
t->InstanceTemplate()->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "fd"), t->InstanceTemplate()->SetAccessor(env->fd_string(),
UDPWrap::GetFD, UDPWrap::GetFD,
NULL, NULL,
Handle<Value>(), Handle<Value>(),
@ -122,7 +122,7 @@ void UDPWrap::Initialize(Handle<Object> target,
NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref); NODE_SET_PROTOTYPE_METHOD(t, "ref", HandleWrap::Ref);
NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref); NODE_SET_PROTOTYPE_METHOD(t, "unref", HandleWrap::Unref);
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "UDP"), t->GetFunction()); target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"), t->GetFunction());
env->set_udp_constructor_function(t->GetFunction()); env->set_udp_constructor_function(t->GetFunction());
} }
@ -137,7 +137,8 @@ void UDPWrap::New(const FunctionCallbackInfo<Value>& args) {
void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) { void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
#if !defined(_WIN32) #if !defined(_WIN32)
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
int fd = (wrap == NULL) ? -1 : wrap->handle_.io_watcher.fd; int fd = (wrap == NULL) ? -1 : wrap->handle_.io_watcher.fd;
args.GetReturnValue().Set(fd); args.GetReturnValue().Set(fd);
@ -146,7 +147,8 @@ void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) { void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
@ -193,7 +195,7 @@ void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
#define X(name, fn) \ #define X(name, fn) \
void UDPWrap::name(const FunctionCallbackInfo<Value>& args) { \ void UDPWrap::name(const FunctionCallbackInfo<Value>& args) { \
HandleScope scope(node_isolate); \ HandleScope scope(args.GetIsolate()); \
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); \ UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); \
assert(args.Length() == 1); \ assert(args.Length() == 1); \
int flag = args[0]->Int32Value(); \ int flag = args[0]->Int32Value(); \
@ -211,7 +213,8 @@ X(SetMulticastLoopback, uv_udp_set_multicast_loop)
void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args, void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
uv_membership membership) { uv_membership membership) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
assert(args.Length() == 2); assert(args.Length() == 2);
@ -315,7 +318,8 @@ void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) { void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv); int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
@ -327,7 +331,8 @@ void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) { void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
HandleScope scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
UDPWrap* wrap = Unwrap<UDPWrap>(args.This()); UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
int r = uv_udp_recv_stop(&wrap->handle_); int r = uv_udp_recv_stop(&wrap->handle_);
@ -366,7 +371,7 @@ void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
Environment* env = req_wrap->env(); Environment* env = req_wrap->env();
HandleScope handle_scope(env->isolate()); HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context()); Context::Scope context_scope(env->context());
Local<Value> arg = Integer::New(status, node_isolate); Local<Value> arg = Integer::New(status, env->isolate());
req_wrap->MakeCallback(env->oncomplete_string(), 1, &arg); req_wrap->MakeCallback(env->oncomplete_string(), 1, &arg);
} }
delete req_wrap; delete req_wrap;
@ -405,7 +410,7 @@ void UDPWrap::OnRecv(uv_udp_t* handle,
Local<Object> wrap_obj = wrap->object(); Local<Object> wrap_obj = wrap->object();
Local<Value> argv[] = { Local<Value> argv[] = {
Integer::New(nread, node_isolate), Integer::New(nread, env->isolate()),
wrap_obj, wrap_obj,
Undefined(env->isolate()), Undefined(env->isolate()),
Undefined(env->isolate()) Undefined(env->isolate())

16
src/uv.cc

@ -21,6 +21,8 @@
#include "uv.h" #include "uv.h"
#include "node.h" #include "node.h"
#include "env.h"
#include "env-inl.h"
namespace node { namespace node {
namespace uv { namespace uv {
@ -37,23 +39,25 @@ using v8::Value;
void ErrName(const FunctionCallbackInfo<Value>& args) { void ErrName(const FunctionCallbackInfo<Value>& args) {
v8::HandleScope handle_scope(node_isolate); Environment* env = Environment::GetCurrent(args.GetIsolate());
HandleScope scope(env->isolate());
int err = args[0]->Int32Value(); int err = args[0]->Int32Value();
if (err >= 0) if (err >= 0)
return ThrowError("err >= 0"); return env->ThrowError("err >= 0");
const char* name = uv_err_name(err); const char* name = uv_err_name(err);
args.GetReturnValue().Set(OneByteString(node_isolate, name)); args.GetReturnValue().Set(OneByteString(env->isolate(), name));
} }
void Initialize(Handle<Object> target, void Initialize(Handle<Object> target,
Handle<Value> unused, Handle<Value> unused,
Handle<Context> context) { Handle<Context> context) {
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "errname"), Environment* env = Environment::GetCurrent(context);
target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "errname"),
FunctionTemplate::New(ErrName)->GetFunction()); FunctionTemplate::New(ErrName)->GetFunction());
#define V(name, _) \ #define V(name, _) \
target->Set(FIXED_ONE_BYTE_STRING(node_isolate, "UV_" # name), \ target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "UV_" # name), \
Integer::New(UV_ ## name, node_isolate)); Integer::New(UV_ ## name, env->isolate()));
UV_ERRNO_MAP(V) UV_ERRNO_MAP(V)
#undef V #undef V
} }

Loading…
Cancel
Save