1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
9 #include <limits.h> /* PATH_MAX */
13 #include <dlfcn.h> /* dlopen(), dlsym() */
14 #include <sys/types.h>
15 #include <unistd.h> /* setuid, getuid */
17 #include <node_buffer.h>
18 #include <node_io_watcher.h>
19 #include <node_net2.h>
20 #include <node_events.h>
21 #include <node_cares.h>
22 #include <node_file.h>
25 # include <node_idle_watcher.h>
27 #include <node_http_parser.h>
28 #include <node_signal_watcher.h>
29 #include <node_stat_watcher.h>
30 #include <node_timer.h>
31 #include <node_child_process.h>
32 #include <node_constants.h>
33 #include <node_stdio.h>
34 #include <node_natives.h>
35 #include <node_version.h>
37 #include <node_crypto.h>
39 #include <node_script.h>
45 extern char **environ;
49 static Persistent<Object> process;
51 static Persistent<String> errno_symbol;
52 static Persistent<String> syscall_symbol;
54 static Persistent<String> dev_symbol;
55 static Persistent<String> ino_symbol;
56 static Persistent<String> mode_symbol;
57 static Persistent<String> nlink_symbol;
58 static Persistent<String> uid_symbol;
59 static Persistent<String> gid_symbol;
60 static Persistent<String> rdev_symbol;
61 static Persistent<String> size_symbol;
62 static Persistent<String> blksize_symbol;
63 static Persistent<String> blocks_symbol;
64 static Persistent<String> atime_symbol;
65 static Persistent<String> mtime_symbol;
66 static Persistent<String> ctime_symbol;
68 static Persistent<String> rss_symbol;
69 static Persistent<String> vsize_symbol;
70 static Persistent<String> heap_total_symbol;
71 static Persistent<String> heap_used_symbol;
73 static Persistent<String> listeners_symbol;
74 static Persistent<String> uncaught_exception_symbol;
75 static Persistent<String> emit_symbol;
77 static int option_end_index = 0;
78 static bool use_debug_agent = false;
79 static bool debug_wait_connect = false;
80 static int debug_port=5858;
82 static ev_prepare next_tick_watcher;
83 static ev_idle tick_spinner;
84 static bool need_tick_cb;
85 static Persistent<String> tick_callback_sym;
87 static ev_async eio_want_poll_notifier;
88 static ev_async eio_done_poll_notifier;
89 static ev_idle eio_poller;
91 // We need to notify V8 when we're idle so that it can run the garbage
92 // collector. The interface to this is V8::IdleNotification(). It returns
93 // true if the heap hasn't be fully compacted, and needs to be run again.
94 // Returning false means that it doesn't have anymore work to do.
96 // We try to wait for a period of GC_INTERVAL (2 seconds) of idleness, where
97 // idleness means that no libev watchers have been executed. Since
98 // everything in node uses libev watchers, this is a pretty good measure of
99 // idleness. This is done with gc_check, which records the timestamp
100 // last_active on every tick of the event loop, and with gc_timer which
101 // executes every few seconds to measure if
102 // last_active + GC_INTERVAL < ev_now()
103 // If we do find a period of idleness, then we start the gc_idle timer which
104 // will very repaidly call IdleNotification until the heap is fully
106 static ev_tstamp last_active;
107 static ev_timer gc_timer;
108 static ev_check gc_check;
109 static ev_idle gc_idle;
110 #define GC_INTERVAL 1.0
112 static void gc_timer_start () {
113 if (!ev_is_active(&gc_timer)) {
114 ev_timer_start(EV_DEFAULT_UC_ &gc_timer);
115 ev_unref(EV_DEFAULT_UC);
119 static void gc_timer_stop () {
120 if (ev_is_active(&gc_timer)) {
121 ev_ref(EV_DEFAULT_UC);
122 ev_timer_stop(EV_DEFAULT_UC_ &gc_timer);
127 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
128 assert(watcher == &gc_timer);
129 assert(revents == EV_TIMER);
131 //fprintf(stderr, "check idle\n");
133 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
135 if (idle_time > GC_INTERVAL) {
136 if (!V8::IdleNotification()) {
137 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
144 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
145 assert(watcher == &gc_idle);
146 assert(revents == EV_IDLE);
148 //fprintf(stderr, "notify idle\n");
150 if (V8::IdleNotification()) {
151 ev_idle_stop(EV_A_ watcher);
157 static void Activity(EV_P_ ev_check *watcher, int revents) {
158 assert(watcher == &gc_check);
159 assert(revents == EV_CHECK);
161 int pending = ev_pending_count(EV_DEFAULT_UC);
163 // Don't count GC watchers as activity.
165 if (ev_is_pending(&gc_timer)) pending--;
166 if (ev_is_pending(&gc_idle)) pending--;
167 if (ev_is_pending(&gc_check)) pending--;
169 assert(pending >= 0);
171 //fprintf(stderr, "activity, pending: %d\n", pending);
174 last_active = ev_now(EV_DEFAULT_UC);
175 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
181 static Handle<Value> NeedTickCallback(const Arguments& args) {
184 ev_idle_start(EV_DEFAULT_UC_ &tick_spinner);
189 static void Spin(EV_P_ ev_idle *watcher, int revents) {
190 assert(watcher == &tick_spinner);
191 assert(revents == EV_IDLE);
195 static void Tick(EV_P_ ev_prepare *watcher, int revents) {
196 assert(watcher == &next_tick_watcher);
197 assert(revents == EV_PREPARE);
199 // Avoid entering a V8 scope.
200 if (!need_tick_cb) return;
202 need_tick_cb = false;
203 ev_idle_stop(EV_DEFAULT_UC_ &tick_spinner);
207 if (tick_callback_sym.IsEmpty()) {
208 // Lazily set the symbol
210 Persistent<String>::New(String::NewSymbol("_tickCallback"));
213 Local<Value> cb_v = process->Get(tick_callback_sym);
214 if (!cb_v->IsFunction()) return;
215 Local<Function> cb = Local<Function>::Cast(cb_v);
219 cb->Call(process, 0, NULL);
221 if (try_catch.HasCaught()) {
222 FatalException(try_catch);
227 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
228 assert(watcher == &eio_poller);
229 assert(revents == EV_IDLE);
231 //printf("eio_poller\n");
233 if (eio_poll() != -1) {
234 //printf("eio_poller stop\n");
235 ev_idle_stop(EV_DEFAULT_UC_ watcher);
240 // Called from the main thread.
241 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
242 assert(watcher == &eio_want_poll_notifier);
243 assert(revents == EV_ASYNC);
245 //printf("want poll notifier\n");
247 if (eio_poll() == -1) {
248 //printf("eio_poller start\n");
249 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
254 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
255 assert(watcher == &eio_done_poll_notifier);
256 assert(revents == EV_ASYNC);
258 //printf("done poll notifier\n");
260 if (eio_poll() != -1) {
261 //printf("eio_poller stop\n");
262 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
267 // EIOWantPoll() is called from the EIO thread pool each time an EIO
268 // request (that is, one of the node.fs.* functions) has completed.
269 static void EIOWantPoll(void) {
270 // Signal the main thread that eio_poll need to be processed.
271 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
275 static void EIODonePoll(void) {
276 // Signal the main thread that we should stop calling eio_poll().
277 // from the idle watcher.
278 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
282 static inline const char *errno_string(int errorno) {
283 #define ERRNO_CASE(e) case e: return #e;
291 ERRNO_CASE(EADDRINUSE);
295 ERRNO_CASE(EADDRNOTAVAIL);
299 ERRNO_CASE(EAFNOSUPPORT);
306 ERRNO_CASE(EWOULDBLOCK);
311 ERRNO_CASE(EALREADY);
327 ERRNO_CASE(ECANCELED);
335 ERRNO_CASE(ECONNABORTED);
339 ERRNO_CASE(ECONNREFUSED);
343 ERRNO_CASE(ECONNRESET);
351 ERRNO_CASE(EDESTADDRREQ);
375 ERRNO_CASE(EHOSTUNREACH);
387 ERRNO_CASE(EINPROGRESS);
423 ERRNO_CASE(EMSGSIZE);
427 ERRNO_CASE(EMULTIHOP);
431 ERRNO_CASE(ENAMETOOLONG);
435 ERRNO_CASE(ENETDOWN);
439 ERRNO_CASE(ENETRESET);
443 ERRNO_CASE(ENETUNREACH);
487 ERRNO_CASE(ENOPROTOOPT);
507 ERRNO_CASE(ENOTCONN);
515 ERRNO_CASE(ENOTEMPTY);
519 ERRNO_CASE(ENOTSOCK);
526 ERRNO_CASE(EOPNOTSUPP);
540 ERRNO_CASE(EOVERFLOW);
555 #ifdef EPROTONOSUPPORT
556 ERRNO_CASE(EPROTONOSUPPORT);
560 ERRNO_CASE(EPROTOTYPE);
588 ERRNO_CASE(ETIMEDOUT);
604 Local<Value> ErrnoException(int errorno,
607 Local<String> estring = String::NewSymbol(errno_string(errorno));
608 if (!msg[0]) msg = strerror(errorno);
609 Local<String> message = String::NewSymbol(msg);
611 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
612 Local<String> cons2 = String::Concat(cons1, message);
614 Local<Value> e = Exception::Error(cons2);
616 Local<Object> obj = e->ToObject();
618 if (errno_symbol.IsEmpty()) {
619 syscall_symbol = NODE_PSYMBOL("syscall");
620 errno_symbol = NODE_PSYMBOL("errno");
623 obj->Set(errno_symbol, Integer::New(errorno));
624 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
629 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
632 if (!encoding_v->IsString()) return _default;
634 String::Utf8Value encoding(encoding_v->ToString());
636 if (strcasecmp(*encoding, "utf8") == 0) {
638 } else if (strcasecmp(*encoding, "utf-8") == 0) {
640 } else if (strcasecmp(*encoding, "ascii") == 0) {
642 } else if (strcasecmp(*encoding, "binary") == 0) {
644 } else if (strcasecmp(*encoding, "raw") == 0) {
645 fprintf(stderr, "'raw' (array of integers) has been removed. "
648 } else if (strcasecmp(*encoding, "raws") == 0) {
649 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
650 "Please update your code.\n");
657 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
660 if (!len) return scope.Close(String::Empty());
662 if (encoding == BINARY) {
663 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
664 uint16_t * twobytebuf = new uint16_t[len];
665 for (size_t i = 0; i < len; i++) {
666 // XXX is the following line platform independent?
667 twobytebuf[i] = cbuf[i];
669 Local<String> chunk = String::New(twobytebuf, len);
670 delete [] twobytebuf; // TODO use ExternalTwoByteString?
671 return scope.Close(chunk);
674 // utf8 or ascii encoding
675 Local<String> chunk = String::New((const char*)buf, len);
676 return scope.Close(chunk);
679 // Returns -1 if the handle was not valid for decoding
680 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
683 if (val->IsArray()) {
684 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
690 Local<String> str = val->ToString();
692 if (encoding == UTF8) return str->Utf8Length();
694 return str->Length();
698 # define MIN(a, b) ((a) < (b) ? (a) : (b))
701 // Returns number of bytes written.
702 ssize_t DecodeWrite(char *buf,
704 v8::Handle<v8::Value> val,
705 enum encoding encoding) {
709 // A lot of improvement can be made here. See:
710 // http://code.google.com/p/v8/issues/detail?id=270
711 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
712 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
714 if (val->IsArray()) {
715 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
721 Local<String> str = val->ToString();
723 if (encoding == UTF8) {
724 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
728 if (encoding == ASCII) {
729 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
733 // THIS IS AWFUL!!! FIXME
735 assert(encoding == BINARY);
737 uint16_t * twobytebuf = new uint16_t[buflen];
739 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
741 for (size_t i = 0; i < buflen; i++) {
742 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
747 delete [] twobytebuf;
752 static Persistent<FunctionTemplate> stats_constructor_template;
754 Local<Object> BuildStatsObject(struct stat * s) {
757 if (dev_symbol.IsEmpty()) {
758 dev_symbol = NODE_PSYMBOL("dev");
759 ino_symbol = NODE_PSYMBOL("ino");
760 mode_symbol = NODE_PSYMBOL("mode");
761 nlink_symbol = NODE_PSYMBOL("nlink");
762 uid_symbol = NODE_PSYMBOL("uid");
763 gid_symbol = NODE_PSYMBOL("gid");
764 rdev_symbol = NODE_PSYMBOL("rdev");
765 size_symbol = NODE_PSYMBOL("size");
766 blksize_symbol = NODE_PSYMBOL("blksize");
767 blocks_symbol = NODE_PSYMBOL("blocks");
768 atime_symbol = NODE_PSYMBOL("atime");
769 mtime_symbol = NODE_PSYMBOL("mtime");
770 ctime_symbol = NODE_PSYMBOL("ctime");
773 Local<Object> stats =
774 stats_constructor_template->GetFunction()->NewInstance();
776 /* ID of device containing file */
777 stats->Set(dev_symbol, Integer::New(s->st_dev));
780 stats->Set(ino_symbol, Integer::New(s->st_ino));
783 stats->Set(mode_symbol, Integer::New(s->st_mode));
785 /* number of hard links */
786 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
788 /* user ID of owner */
789 stats->Set(uid_symbol, Integer::New(s->st_uid));
791 /* group ID of owner */
792 stats->Set(gid_symbol, Integer::New(s->st_gid));
794 /* device ID (if special file) */
795 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
797 /* total size, in bytes */
798 stats->Set(size_symbol, Integer::New(s->st_size));
800 /* blocksize for filesystem I/O */
801 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
803 /* number of blocks allocated */
804 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
806 /* time of last access */
807 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
809 /* time of last modification */
810 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
812 /* time of last status change */
813 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
815 return scope.Close(stats);
819 // Extracts a C str from a V8 Utf8Value.
820 const char* ToCString(const v8::String::Utf8Value& value) {
821 return *value ? *value : "<str conversion failed>";
824 static void ReportException(TryCatch &try_catch, bool show_line = false) {
825 Handle<Message> message = try_catch.Message();
827 Handle<Value> error = try_catch.Exception();
828 Handle<String> stack;
830 if (error->IsObject()) {
831 Handle<Object> obj = Handle<Object>::Cast(error);
832 Handle<Value> raw_stack = obj->Get(String::New("stack"));
833 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
836 if (show_line && !message.IsEmpty()) {
837 // Print (filename):(line number): (message).
838 String::Utf8Value filename(message->GetScriptResourceName());
839 const char* filename_string = ToCString(filename);
840 int linenum = message->GetLineNumber();
841 fprintf(stderr, "%s:%i\n", filename_string, linenum);
842 // Print line of source code.
843 String::Utf8Value sourceline(message->GetSourceLine());
844 const char* sourceline_string = ToCString(sourceline);
845 fprintf(stderr, "%s\n", sourceline_string);
846 // Print wavy underline (GetUnderline is deprecated).
847 int start = message->GetStartColumn();
848 for (int i = 0; i < start; i++) {
849 fprintf(stderr, " ");
851 int end = message->GetEndColumn();
852 for (int i = start; i < end; i++) {
853 fprintf(stderr, "^");
855 fprintf(stderr, "\n");
858 if (stack.IsEmpty()) {
859 message->PrintCurrentStackTrace(stderr);
861 String::Utf8Value trace(stack);
862 fprintf(stderr, "%s\n", *trace);
867 // Executes a str within the current v8 context.
868 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
872 Local<v8::Script> script = v8::Script::Compile(source, filename);
873 if (script.IsEmpty()) {
874 ReportException(try_catch);
878 Local<Value> result = script->Run();
879 if (result.IsEmpty()) {
880 ReportException(try_catch);
884 return scope.Close(result);
887 static Handle<Value> ByteLength(const Arguments& args) {
890 if (args.Length() < 1 || !args[0]->IsString()) {
891 return ThrowException(Exception::Error(String::New("Bad argument.")));
894 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
896 return scope.Close(length);
899 static Handle<Value> Loop(const Arguments& args) {
901 assert(args.Length() == 0);
903 // TODO Probably don't need to start this each time.
904 // Avoids failing on test/mjsunit/test-eio-race3.js though
905 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
907 ev_loop(EV_DEFAULT_UC_ 0);
911 static Handle<Value> Unloop(const Arguments& args) {
912 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
914 int how = EVUNLOOP_ONE;
915 if (args[0]->IsString()) {
916 String::Utf8Value how_s(args[0]->ToString());
917 if (0 == strcmp(*how_s, "all")) {
921 ev_unloop(EV_DEFAULT_ how);
925 static Handle<Value> Chdir(const Arguments& args) {
928 if (args.Length() != 1 || !args[0]->IsString()) {
929 return ThrowException(Exception::Error(String::New("Bad argument.")));
932 String::Utf8Value path(args[0]->ToString());
934 int r = chdir(*path);
937 return ThrowException(Exception::Error(String::New(strerror(errno))));
943 static Handle<Value> Cwd(const Arguments& args) {
945 assert(args.Length() == 0);
947 char output[PATH_MAX];
948 char *r = getcwd(output, PATH_MAX);
950 return ThrowException(Exception::Error(String::New(strerror(errno))));
952 Local<String> cwd = String::New(output);
954 return scope.Close(cwd);
957 static Handle<Value> Umask(const Arguments& args){
960 if(args.Length() < 1) {
964 else if(!args[0]->IsInt32()) {
965 return ThrowException(Exception::TypeError(
966 String::New("argument must be an integer.")));
969 old = umask((mode_t)args[0]->Uint32Value());
971 return scope.Close(Uint32::New(old));
975 static Handle<Value> GetUid(const Arguments& args) {
977 assert(args.Length() == 0);
979 return scope.Close(Integer::New(uid));
982 static Handle<Value> GetGid(const Arguments& args) {
984 assert(args.Length() == 0);
986 return scope.Close(Integer::New(gid));
990 static Handle<Value> SetGid(const Arguments& args) {
993 if (args.Length() < 1) {
994 return ThrowException(Exception::Error(
995 String::New("setgid requires 1 argument")));
998 Local<Integer> given_gid = args[0]->ToInteger();
999 int gid = given_gid->Int32Value();
1001 if ((result = setgid(gid)) != 0) {
1002 return ThrowException(Exception::Error(String::New(strerror(errno))));
1007 static Handle<Value> SetUid(const Arguments& args) {
1010 if (args.Length() < 1) {
1011 return ThrowException(Exception::Error(
1012 String::New("setuid requires 1 argument")));
1015 Local<Integer> given_uid = args[0]->ToInteger();
1016 int uid = given_uid->Int32Value();
1018 if ((result = setuid(uid)) != 0) {
1019 return ThrowException(Exception::Error(String::New(strerror(errno))));
1025 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
1029 exit(args[0]->IntegerValue());
1034 #define HAVE_GETMEM 1
1035 #include <unistd.h> /* getpagesize() */
1037 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
1038 #define PROCFS_FILE_OFFSET_BITS_HACK 1
1039 #undef _FILE_OFFSET_BITS
1041 #define PROCFS_FILE_OFFSET_BITS_HACK 0
1046 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
1047 #define _FILE_OFFSET_BITS 64
1050 int getmem(size_t *rss, size_t *vsize) {
1051 pid_t pid = getpid();
1053 size_t page_size = getpagesize();
1055 sprintf(pidpath, "/proc/%d/psinfo", pid);
1058 FILE *f = fopen(pidpath, "r");
1061 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
1068 *vsize = (size_t) psinfo.pr_size * page_size;
1069 *rss = (size_t) psinfo.pr_rssize * 1024;
1079 #define HAVE_GETMEM 1
1081 #include <sys/param.h>
1082 #include <sys/sysctl.h>
1083 #include <sys/user.h>
1088 int getmem(size_t *rss, size_t *vsize) {
1090 struct kinfo_proc *kinfo = NULL;
1093 size_t page_size = getpagesize();
1097 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
1098 if (kd == NULL) goto error;
1100 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
1101 if (kinfo == NULL) goto error;
1103 *rss = kinfo->ki_rssize * page_size;
1104 *vsize = kinfo->ki_size;
1111 if (kd) kvm_close(kd);
1114 #endif // __FreeBSD__
1118 #define HAVE_GETMEM 1
1119 /* Researched by Tim Becker and Michael Knight
1120 * http://blog.kuriositaet.de/?p=257
1123 #include <mach/task.h>
1124 #include <mach/mach_init.h>
1126 int getmem(size_t *rss, size_t *vsize) {
1127 struct task_basic_info t_info;
1128 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
1130 int r = task_info(mach_task_self(),
1132 (task_info_t)&t_info,
1135 if (r != KERN_SUCCESS) return -1;
1137 *rss = t_info.resident_size;
1138 *vsize = t_info.virtual_size;
1145 # define HAVE_GETMEM 1
1146 # include <sys/param.h> /* for MAXPATHLEN */
1148 int getmem(size_t *rss, size_t *vsize) {
1149 FILE *f = fopen("/proc/self/stat", "r");
1154 char buffer[MAXPATHLEN];
1155 size_t page_size = getpagesize();
1158 if (fscanf(f, "%d ", &itmp) == 0) goto error;
1160 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
1162 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
1163 /* Parent process */
1164 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1166 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1168 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1170 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1171 /* TTY owner process group */
1172 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1174 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1175 /* Minor faults (no memory page) */
1176 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1177 /* Minor faults, children */
1178 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1179 /* Major faults (memory page faults) */
1180 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1181 /* Major faults, children */
1182 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1184 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1186 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1187 /* utime, children */
1188 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1189 /* stime, children */
1190 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1191 /* jiffies remaining in current time slice */
1192 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1194 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1195 /* jiffies until next timeout */
1196 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1197 /* jiffies until next SIGALRM */
1198 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1199 /* start time (jiffies since system boot) */
1200 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1202 /* Virtual memory size */
1203 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1204 *vsize = (size_t) itmp;
1206 /* Resident set size */
1207 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1208 *rss = (size_t) itmp * page_size;
1211 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1213 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1215 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1216 /* Start of stack */
1217 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1229 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
1231 assert(args.Length() == 0);
1234 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
1238 int r = getmem(&rss, &vsize);
1241 return ThrowException(Exception::Error(String::New(strerror(errno))));
1244 Local<Object> info = Object::New();
1246 if (rss_symbol.IsEmpty()) {
1247 rss_symbol = NODE_PSYMBOL("rss");
1248 vsize_symbol = NODE_PSYMBOL("vsize");
1249 heap_total_symbol = NODE_PSYMBOL("heapTotal");
1250 heap_used_symbol = NODE_PSYMBOL("heapUsed");
1253 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
1254 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
1257 HeapStatistics v8_heap_stats;
1258 V8::GetHeapStatistics(&v8_heap_stats);
1259 info->Set(heap_total_symbol,
1260 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
1261 info->Set(heap_used_symbol,
1262 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
1264 return scope.Close(info);
1269 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
1272 if (args.Length() < 1 || !args[0]->IsNumber()) {
1273 return ThrowException(Exception::Error(String::New("Bad argument.")));
1276 pid_t pid = args[0]->IntegerValue();
1280 if (args.Length() >= 2) {
1281 if (args[1]->IsNumber()) {
1282 sig = args[1]->Int32Value();
1283 } else if (args[1]->IsString()) {
1284 Local<String> signame = args[1]->ToString();
1286 Local<Value> sig_v = process->Get(signame);
1287 if (!sig_v->IsNumber()) {
1288 return ThrowException(Exception::Error(String::New("Unknown signal")));
1290 sig = sig_v->Int32Value();
1294 int r = kill(pid, sig);
1297 return ThrowException(Exception::Error(String::New(strerror(errno))));
1303 typedef void (*extInit)(Handle<Object> exports);
1305 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
1307 Handle<Value> DLOpen(const v8::Arguments& args) {
1310 if (args.Length() < 2) return Undefined();
1312 String::Utf8Value filename(args[0]->ToString()); // Cast
1313 Local<Object> target = args[1]->ToObject(); // Cast
1315 // Actually call dlopen().
1316 // FIXME: This is a blocking function and should be called asynchronously!
1317 // This function should be moved to file.cc and use libeio to make this
1319 void *handle = dlopen(*filename, RTLD_LAZY);
1322 if (handle == NULL) {
1323 Local<Value> exception = Exception::Error(String::New(dlerror()));
1324 return ThrowException(exception);
1327 // Get the init() function from the dynamically shared object.
1328 void *init_handle = dlsym(handle, "init");
1329 // Error out if not found.
1330 if (init_handle == NULL) {
1331 Local<Value> exception =
1332 Exception::Error(String::New("No 'init' symbol found in module."));
1333 return ThrowException(exception);
1335 extInit init = (extInit)(init_handle); // Cast
1337 // Execute the C++ module
1344 Handle<Value> Compile(const Arguments& args) {
1347 if (args.Length() < 2) {
1348 return ThrowException(Exception::TypeError(
1349 String::New("needs two arguments.")));
1352 Local<String> source = args[0]->ToString();
1353 Local<String> filename = args[1]->ToString();
1357 Local<v8::Script> script = v8::Script::Compile(source, filename);
1358 if (try_catch.HasCaught()) {
1359 // Hack because I can't get a proper stacktrace on SyntaxError
1360 ReportException(try_catch, true);
1364 Local<Value> result = script->Run();
1365 if (try_catch.HasCaught()) return try_catch.ReThrow();
1367 return scope.Close(result);
1370 static void OnFatalError(const char* location, const char* message) {
1372 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1374 fprintf(stderr, "FATAL ERROR: %s\n", message);
1379 static int uncaught_exception_counter = 0;
1381 void FatalException(TryCatch &try_catch) {
1384 // Check if uncaught_exception_counter indicates a recursion
1385 if (uncaught_exception_counter > 0) {
1386 ReportException(try_catch);
1390 if (listeners_symbol.IsEmpty()) {
1391 listeners_symbol = NODE_PSYMBOL("listeners");
1392 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1393 emit_symbol = NODE_PSYMBOL("emit");
1396 Local<Value> listeners_v = process->Get(listeners_symbol);
1397 assert(listeners_v->IsFunction());
1399 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1401 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1402 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1403 Local<Value> ret = listeners->Call(process, 1, argv);
1405 assert(ret->IsArray());
1407 Local<Array> listener_array = Local<Array>::Cast(ret);
1409 uint32_t length = listener_array->Length();
1410 // Report and exit if process has no "uncaughtException" listener
1412 ReportException(try_catch);
1416 // Otherwise fire the process "uncaughtException" event
1417 Local<Value> emit_v = process->Get(emit_symbol);
1418 assert(emit_v->IsFunction());
1420 Local<Function> emit = Local<Function>::Cast(emit_v);
1422 Local<Value> error = try_catch.Exception();
1423 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1425 uncaught_exception_counter++;
1426 emit->Call(process, 2, event_argv);
1427 // Decrement so we know if the next exception is a recursion or not
1428 uncaught_exception_counter--;
1432 static ev_async debug_watcher;
1433 volatile static bool debugger_msg_pending = false;
1435 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1437 assert(watcher == &debug_watcher);
1438 assert(revents == EV_ASYNC);
1439 Debug::ProcessDebugMessages();
1442 static void DebugMessageDispatch(void) {
1443 // This function is called from V8's debug thread when a debug TCP client
1444 // has sent a message.
1446 // Send a signal to our main thread saying that it should enter V8 to
1447 // handle the message.
1448 debugger_msg_pending = true;
1449 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1452 static Handle<Value> CheckBreak(const Arguments& args) {
1454 assert(args.Length() == 0);
1456 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1457 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1458 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1459 // get it to halt until Eclipse connects.
1461 if (!debug_wait_connect)
1464 printf("Waiting for remote debugger connection...\n");
1466 const int halfSecond = 50;
1467 const int tenMs=10000;
1468 debugger_msg_pending = false;
1470 if (debugger_msg_pending) {
1471 Debug::DebugBreak();
1472 Debug::ProcessDebugMessages();
1473 debugger_msg_pending = false;
1475 // wait for 500 msec of silence from remote debugger
1476 int cnt = halfSecond;
1478 debugger_msg_pending = false;
1480 if (debugger_msg_pending) {
1481 debugger_msg_pending = false;
1492 Persistent<Object> binding_cache;
1494 static Handle<Value> Binding(const Arguments& args) {
1497 Local<String> module = args[0]->ToString();
1498 String::Utf8Value module_v(module);
1500 if (binding_cache.IsEmpty()) {
1501 binding_cache = Persistent<Object>::New(Object::New());
1504 Local<Object> exports;
1506 // TODO DRY THIS UP!
1508 if (!strcmp(*module_v, "stdio")) {
1509 if (binding_cache->Has(module)) {
1510 exports = binding_cache->Get(module)->ToObject();
1512 exports = Object::New();
1513 Stdio::Initialize(exports);
1514 binding_cache->Set(module, exports);
1517 } else if (!strcmp(*module_v, "cares")) {
1518 if (binding_cache->Has(module)) {
1519 exports = binding_cache->Get(module)->ToObject();
1521 exports = Object::New();
1522 Cares::Initialize(exports);
1523 binding_cache->Set(module, exports);
1526 } else if (!strcmp(*module_v, "fs")) {
1527 if (binding_cache->Has(module)) {
1528 exports = binding_cache->Get(module)->ToObject();
1530 exports = Object::New();
1532 // Initialize the stats object
1533 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1534 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1535 exports->Set(String::NewSymbol("Stats"),
1536 stats_constructor_template->GetFunction());
1537 StatWatcher::Initialize(exports);
1538 File::Initialize(exports);
1539 binding_cache->Set(module, exports);
1542 } else if (!strcmp(*module_v, "signal_watcher")) {
1543 if (binding_cache->Has(module)) {
1544 exports = binding_cache->Get(module)->ToObject();
1546 exports = Object::New();
1547 SignalWatcher::Initialize(exports);
1548 binding_cache->Set(module, exports);
1551 } else if (!strcmp(*module_v, "net")) {
1552 if (binding_cache->Has(module)) {
1553 exports = binding_cache->Get(module)->ToObject();
1555 exports = Object::New();
1557 binding_cache->Set(module, exports);
1560 } else if (!strcmp(*module_v, "http_parser")) {
1561 if (binding_cache->Has(module)) {
1562 exports = binding_cache->Get(module)->ToObject();
1564 exports = Object::New();
1565 InitHttpParser(exports);
1566 binding_cache->Set(module, exports);
1569 } else if (!strcmp(*module_v, "child_process")) {
1570 if (binding_cache->Has(module)) {
1571 exports = binding_cache->Get(module)->ToObject();
1573 exports = Object::New();
1574 ChildProcess::Initialize(exports);
1575 binding_cache->Set(module, exports);
1578 } else if (!strcmp(*module_v, "buffer")) {
1579 if (binding_cache->Has(module)) {
1580 exports = binding_cache->Get(module)->ToObject();
1582 exports = Object::New();
1583 Buffer::Initialize(exports);
1584 binding_cache->Set(module, exports);
1587 } else if (!strcmp(*module_v, "crypto")) {
1588 if (binding_cache->Has(module)) {
1589 exports = binding_cache->Get(module)->ToObject();
1591 exports = Object::New();
1592 InitCrypto(exports);
1593 binding_cache->Set(module, exports);
1596 } else if (!strcmp(*module_v, "evals")) {
1597 if (binding_cache->Has(module)) {
1598 exports = binding_cache->Get(module)->ToObject();
1600 exports = Object::New();
1601 node::Script::Initialize(exports);
1602 binding_cache->Set(module, exports);
1605 } else if (!strcmp(*module_v, "natives")) {
1606 if (binding_cache->Has(module)) {
1607 exports = binding_cache->Get(module)->ToObject();
1609 exports = Object::New();
1610 // Explicitly define native sources.
1611 // TODO DRY/automate this?
1612 exports->Set(String::New("assert"), String::New(native_assert));
1613 exports->Set(String::New("buffer"), String::New(native_buffer));
1614 exports->Set(String::New("child_process"),String::New(native_child_process));
1615 exports->Set(String::New("dns"), String::New(native_dns));
1616 exports->Set(String::New("events"), String::New(native_events));
1617 exports->Set(String::New("file"), String::New(native_file));
1618 exports->Set(String::New("freelist"), String::New(native_freelist));
1619 exports->Set(String::New("fs"), String::New(native_fs));
1620 exports->Set(String::New("http"), String::New(native_http));
1621 exports->Set(String::New("crypto"), String::New(native_crypto));
1622 exports->Set(String::New("ini"), String::New(native_ini));
1623 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1624 exports->Set(String::New("net"), String::New(native_net));
1625 exports->Set(String::New("posix"), String::New(native_posix));
1626 exports->Set(String::New("querystring"), String::New(native_querystring));
1627 exports->Set(String::New("repl"), String::New(native_repl));
1628 exports->Set(String::New("sys"), String::New(native_sys));
1629 exports->Set(String::New("tcp"), String::New(native_tcp));
1630 exports->Set(String::New("uri"), String::New(native_uri));
1631 exports->Set(String::New("url"), String::New(native_url));
1632 exports->Set(String::New("utils"), String::New(native_utils));
1633 exports->Set(String::New("path"), String::New(native_path));
1634 exports->Set(String::New("module"), String::New(native_module));
1635 binding_cache->Set(module, exports);
1639 return ThrowException(Exception::Error(String::New("No such module")));
1642 return scope.Close(exports);
1646 static void Load(int argc, char *argv[]) {
1649 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1650 node::EventEmitter::Initialize(process_template);
1652 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1654 // Add a reference to the global object
1655 Local<Object> global = Context::GetCurrent()->Global();
1656 process->Set(String::NewSymbol("global"), global);
1659 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1660 // process.installPrefix
1661 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1664 #define xstr(s) str(s)
1666 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1670 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1671 arguments->Set(Integer::New(0), String::New(argv[0]));
1672 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1673 Local<String> arg = String::New(argv[i]);
1674 arguments->Set(Integer::New(j), arg);
1677 process->Set(String::NewSymbol("ARGV"), arguments);
1678 process->Set(String::NewSymbol("argv"), arguments);
1680 // create process.env
1681 Local<Object> env = Object::New();
1682 for (i = 0; environ[i]; i++) {
1683 // skip entries without a '=' character
1684 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1685 // create the v8 objects
1686 Local<String> field = String::New(environ[i], j);
1687 Local<String> value = Local<String>();
1688 if (environ[i][j] == '=') {
1689 value = String::New(environ[i]+j+1);
1692 env->Set(field, value);
1694 // assign process.ENV
1695 process->Set(String::NewSymbol("ENV"), env);
1696 process->Set(String::NewSymbol("env"), env);
1698 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1700 // define various internal methods
1701 NODE_SET_METHOD(process, "loop", Loop);
1702 NODE_SET_METHOD(process, "unloop", Unloop);
1703 NODE_SET_METHOD(process, "compile", Compile);
1704 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1705 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
1706 NODE_SET_METHOD(process, "reallyExit", Exit);
1707 NODE_SET_METHOD(process, "chdir", Chdir);
1708 NODE_SET_METHOD(process, "cwd", Cwd);
1709 NODE_SET_METHOD(process, "getuid", GetUid);
1710 NODE_SET_METHOD(process, "setuid", SetUid);
1712 NODE_SET_METHOD(process, "setgid", SetGid);
1713 NODE_SET_METHOD(process, "getgid", GetGid);
1715 NODE_SET_METHOD(process, "umask", Umask);
1716 NODE_SET_METHOD(process, "dlopen", DLOpen);
1717 NODE_SET_METHOD(process, "kill", Kill);
1718 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1719 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1721 NODE_SET_METHOD(process, "binding", Binding);
1723 // Assign the EventEmitter. It was created in main().
1724 process->Set(String::NewSymbol("EventEmitter"),
1725 EventEmitter::constructor_template->GetFunction());
1728 // Initialize the C++ modules..................filename of module
1729 IOWatcher::Initialize(process); // io_watcher.cc
1730 // Not in use at the moment.
1731 //IdleWatcher::Initialize(process); // idle_watcher.cc
1732 Timer::Initialize(process); // timer.cc
1733 DefineConstants(process); // constants.cc
1735 // Compile, execute the src/node.js file. (Which was included as static C
1736 // string in node_natives.h. 'natve_node' is the string containing that
1739 // The node.js file returns a function 'f'
1745 Local<Value> f_value = ExecuteString(String::New(native_node),
1746 String::New("node.js"));
1748 if (try_catch.HasCaught()) {
1749 ReportException(try_catch);
1753 assert(f_value->IsFunction());
1754 Local<Function> f = Local<Function>::Cast(f_value);
1756 // Now we call 'f' with the 'process' variable that we've built up with
1757 // all our bindings. Inside node.js we'll take care of assigning things to
1760 // We start the process this way in order to be more modular. Developers
1761 // who do not like how 'src/node.js' setups the module system but do like
1762 // Node's I/O bindings may want to replace 'f' with their own function.
1764 Local<Value> args[1] = { Local<Value>::New(process) };
1766 f->Call(global, 1, args);
1769 if (try_catch.HasCaught()) {
1770 ReportException(try_catch);
1776 static void PrintHelp();
1778 static void ParseDebugOpt(const char* arg) {
1781 use_debug_agent = true;
1782 if (!strcmp (arg, "--debug-brk")) {
1783 debug_wait_connect = true;
1785 } else if (!strcmp(arg, "--debug")) {
1787 } else if (strstr(arg, "--debug-brk=") == arg) {
1788 debug_wait_connect = true;
1789 p = 1 + strchr(arg, '=');
1790 debug_port = atoi(p);
1791 } else if (strstr(arg, "--debug=") == arg) {
1792 p = 1 + strchr(arg, '=');
1793 debug_port = atoi(p);
1795 if (p && debug_port > 1024 && debug_port < 65536)
1798 fprintf(stderr, "Bad debug option.\n");
1799 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1805 static void PrintHelp() {
1806 printf("Usage: node [options] script.js [arguments] \n"
1808 " -v, --version print node's version\n"
1809 " --debug[=port] enable remote debugging via given TCP port\n"
1810 " without stopping the execution\n"
1811 " --debug-brk[=port] as above, but break in script.js and\n"
1812 " wait for remote debugger to connect\n"
1813 " --v8-options print v8 command line options\n"
1814 " --vars print various compiled-in variables\n"
1816 "Enviromental variables:\n"
1817 "NODE_PATH ':'-separated list of directories\n"
1818 " prefixed to the module search path,\n"
1820 "NODE_DEBUG Print additional debugging output.\n"
1822 "Documentation can be found at http://nodejs.org/api.html"
1823 " or with 'man node'\n");
1826 // Parse node command line arguments.
1827 static void ParseArgs(int *argc, char **argv) {
1828 // TODO use parse opts
1829 for (int i = 1; i < *argc; i++) {
1830 const char *arg = argv[i];
1831 if (strstr(arg, "--debug") == arg) {
1833 argv[i] = const_cast<char*>("");
1834 option_end_index = i;
1835 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1836 printf("%s\n", NODE_VERSION);
1838 } else if (strcmp(arg, "--vars") == 0) {
1839 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1840 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1842 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1845 } else if (strcmp(arg, "--v8-options") == 0) {
1846 argv[i] = const_cast<char*>("--help");
1847 option_end_index = i+1;
1848 } else if (argv[i][0] != '-') {
1849 option_end_index = i-1;
1858 int main(int argc, char *argv[]) {
1859 // Parse a few arguments which are specific to Node.
1860 node::ParseArgs(&argc, argv);
1861 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1862 // in the command line))
1863 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1865 // Error out if we don't have a script argument.
1867 fprintf(stderr, "No script was specified.\n");
1872 // Initialize the default ev loop.
1874 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1875 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1876 ev_default_loop(EVBACKEND_SELECT);
1878 ev_default_loop(EVFLAG_AUTO);
1881 ev_prepare_init(&node::next_tick_watcher, node::Tick);
1882 ev_prepare_start(EV_DEFAULT_UC_ &node::next_tick_watcher);
1883 ev_unref(EV_DEFAULT_UC);
1885 ev_idle_init(&node::tick_spinner, node::Spin);
1887 ev_timer_init(&node::gc_timer, node::CheckIdleness, 2*GC_INTERVAL, 2*GC_INTERVAL);
1889 ev_check_init(&node::gc_check, node::Activity);
1890 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1891 ev_unref(EV_DEFAULT_UC);
1893 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1896 // Setup the EIO thread pool
1897 { // It requires 3, yes 3, watchers.
1898 ev_idle_init(&node::eio_poller, node::DoPoll);
1900 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1901 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1902 ev_unref(EV_DEFAULT_UC);
1904 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1905 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1906 ev_unref(EV_DEFAULT_UC);
1908 eio_init(node::EIOWantPoll, node::EIODonePoll);
1909 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1910 // race conditions. See test/mjsunit/test-eio-race.js
1911 eio_set_max_poll_reqs(10);
1915 HandleScope handle_scope;
1917 V8::SetFatalErrorHandler(node::OnFatalError);
1919 // If the --debug flag was specified then initialize the debug thread.
1920 if (node::use_debug_agent) {
1921 // Initialize the async watcher for receiving messages from the debug
1922 // thread and marshal it into the main thread. DebugMessageCallback()
1923 // is called from the main thread to execute a random bit of javascript
1924 // - which will give V8 control so it can handle whatever new message
1925 // had been received on the debug thread.
1926 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1927 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1928 // Set the callback DebugMessageDispatch which is called from the debug
1930 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1931 // Start the async watcher.
1932 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1933 // unref it so that we exit the event loop despite it being active.
1934 ev_unref(EV_DEFAULT_UC);
1936 // Start the debug thread and it's associated TCP server on port 5858.
1937 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1939 // Crappy check that everything went well. FIXME
1941 // Print out some information.
1942 printf("debugger listening on port %d\n", node::debug_port);
1945 // Create the one and only Context.
1946 Persistent<Context> context = Context::New();
1947 Context::Scope context_scope(context);
1949 // Create all the objects, load modules, do everything.
1950 // so your next reading stop should be node::Load()!
1951 node::Load(argc, argv);
1953 node::Stdio::Flush();