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);
307 # if EAGAIN != EWOULDBLOCK
308 ERRNO_CASE(EWOULDBLOCK);
313 ERRNO_CASE(EALREADY);
329 ERRNO_CASE(ECANCELED);
337 ERRNO_CASE(ECONNABORTED);
341 ERRNO_CASE(ECONNREFUSED);
345 ERRNO_CASE(ECONNRESET);
353 ERRNO_CASE(EDESTADDRREQ);
377 ERRNO_CASE(EHOSTUNREACH);
389 ERRNO_CASE(EINPROGRESS);
425 ERRNO_CASE(EMSGSIZE);
429 ERRNO_CASE(EMULTIHOP);
433 ERRNO_CASE(ENAMETOOLONG);
437 ERRNO_CASE(ENETDOWN);
441 ERRNO_CASE(ENETRESET);
445 ERRNO_CASE(ENETUNREACH);
489 ERRNO_CASE(ENOPROTOOPT);
509 ERRNO_CASE(ENOTCONN);
517 ERRNO_CASE(ENOTEMPTY);
521 ERRNO_CASE(ENOTSOCK);
528 ERRNO_CASE(EOPNOTSUPP);
542 ERRNO_CASE(EOVERFLOW);
557 #ifdef EPROTONOSUPPORT
558 ERRNO_CASE(EPROTONOSUPPORT);
562 ERRNO_CASE(EPROTOTYPE);
590 ERRNO_CASE(ETIMEDOUT);
606 Local<Value> ErrnoException(int errorno,
609 Local<String> estring = String::NewSymbol(errno_string(errorno));
610 if (!msg[0]) msg = strerror(errorno);
611 Local<String> message = String::NewSymbol(msg);
613 Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
614 Local<String> cons2 = String::Concat(cons1, message);
616 Local<Value> e = Exception::Error(cons2);
618 Local<Object> obj = e->ToObject();
620 if (errno_symbol.IsEmpty()) {
621 syscall_symbol = NODE_PSYMBOL("syscall");
622 errno_symbol = NODE_PSYMBOL("errno");
625 obj->Set(errno_symbol, Integer::New(errorno));
626 if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
631 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
634 if (!encoding_v->IsString()) return _default;
636 String::Utf8Value encoding(encoding_v->ToString());
638 if (strcasecmp(*encoding, "utf8") == 0) {
640 } else if (strcasecmp(*encoding, "utf-8") == 0) {
642 } else if (strcasecmp(*encoding, "ascii") == 0) {
644 } else if (strcasecmp(*encoding, "binary") == 0) {
646 } else if (strcasecmp(*encoding, "raw") == 0) {
647 fprintf(stderr, "'raw' (array of integers) has been removed. "
650 } else if (strcasecmp(*encoding, "raws") == 0) {
651 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
652 "Please update your code.\n");
659 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
662 if (!len) return scope.Close(String::Empty());
664 if (encoding == BINARY) {
665 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
666 uint16_t * twobytebuf = new uint16_t[len];
667 for (size_t i = 0; i < len; i++) {
668 // XXX is the following line platform independent?
669 twobytebuf[i] = cbuf[i];
671 Local<String> chunk = String::New(twobytebuf, len);
672 delete [] twobytebuf; // TODO use ExternalTwoByteString?
673 return scope.Close(chunk);
676 // utf8 or ascii encoding
677 Local<String> chunk = String::New((const char*)buf, len);
678 return scope.Close(chunk);
681 // Returns -1 if the handle was not valid for decoding
682 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
685 if (val->IsArray()) {
686 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
692 Local<String> str = val->ToString();
694 if (encoding == UTF8) return str->Utf8Length();
696 return str->Length();
700 # define MIN(a, b) ((a) < (b) ? (a) : (b))
703 // Returns number of bytes written.
704 ssize_t DecodeWrite(char *buf,
706 v8::Handle<v8::Value> val,
707 enum encoding encoding) {
711 // A lot of improvement can be made here. See:
712 // http://code.google.com/p/v8/issues/detail?id=270
713 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
714 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
716 if (val->IsArray()) {
717 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
723 Local<String> str = val->ToString();
725 if (encoding == UTF8) {
726 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
730 if (encoding == ASCII) {
731 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
735 // THIS IS AWFUL!!! FIXME
737 assert(encoding == BINARY);
739 uint16_t * twobytebuf = new uint16_t[buflen];
741 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
743 for (size_t i = 0; i < buflen; i++) {
744 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
749 delete [] twobytebuf;
754 static Persistent<FunctionTemplate> stats_constructor_template;
756 Local<Object> BuildStatsObject(struct stat * s) {
759 if (dev_symbol.IsEmpty()) {
760 dev_symbol = NODE_PSYMBOL("dev");
761 ino_symbol = NODE_PSYMBOL("ino");
762 mode_symbol = NODE_PSYMBOL("mode");
763 nlink_symbol = NODE_PSYMBOL("nlink");
764 uid_symbol = NODE_PSYMBOL("uid");
765 gid_symbol = NODE_PSYMBOL("gid");
766 rdev_symbol = NODE_PSYMBOL("rdev");
767 size_symbol = NODE_PSYMBOL("size");
768 blksize_symbol = NODE_PSYMBOL("blksize");
769 blocks_symbol = NODE_PSYMBOL("blocks");
770 atime_symbol = NODE_PSYMBOL("atime");
771 mtime_symbol = NODE_PSYMBOL("mtime");
772 ctime_symbol = NODE_PSYMBOL("ctime");
775 Local<Object> stats =
776 stats_constructor_template->GetFunction()->NewInstance();
778 /* ID of device containing file */
779 stats->Set(dev_symbol, Integer::New(s->st_dev));
782 stats->Set(ino_symbol, Integer::New(s->st_ino));
785 stats->Set(mode_symbol, Integer::New(s->st_mode));
787 /* number of hard links */
788 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
790 /* user ID of owner */
791 stats->Set(uid_symbol, Integer::New(s->st_uid));
793 /* group ID of owner */
794 stats->Set(gid_symbol, Integer::New(s->st_gid));
796 /* device ID (if special file) */
797 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
799 /* total size, in bytes */
800 stats->Set(size_symbol, Integer::New(s->st_size));
802 /* blocksize for filesystem I/O */
803 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
805 /* number of blocks allocated */
806 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
808 /* time of last access */
809 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
811 /* time of last modification */
812 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
814 /* time of last status change */
815 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
817 return scope.Close(stats);
821 // Extracts a C str from a V8 Utf8Value.
822 const char* ToCString(const v8::String::Utf8Value& value) {
823 return *value ? *value : "<str conversion failed>";
826 static void ReportException(TryCatch &try_catch, bool show_line = false) {
827 Handle<Message> message = try_catch.Message();
829 Handle<Value> error = try_catch.Exception();
830 Handle<String> stack;
832 if (error->IsObject()) {
833 Handle<Object> obj = Handle<Object>::Cast(error);
834 Handle<Value> raw_stack = obj->Get(String::New("stack"));
835 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
838 if (show_line && !message.IsEmpty()) {
839 // Print (filename):(line number): (message).
840 String::Utf8Value filename(message->GetScriptResourceName());
841 const char* filename_string = ToCString(filename);
842 int linenum = message->GetLineNumber();
843 fprintf(stderr, "%s:%i\n", filename_string, linenum);
844 // Print line of source code.
845 String::Utf8Value sourceline(message->GetSourceLine());
846 const char* sourceline_string = ToCString(sourceline);
847 fprintf(stderr, "%s\n", sourceline_string);
848 // Print wavy underline (GetUnderline is deprecated).
849 int start = message->GetStartColumn();
850 for (int i = 0; i < start; i++) {
851 fprintf(stderr, " ");
853 int end = message->GetEndColumn();
854 for (int i = start; i < end; i++) {
855 fprintf(stderr, "^");
857 fprintf(stderr, "\n");
860 if (stack.IsEmpty()) {
861 message->PrintCurrentStackTrace(stderr);
863 String::Utf8Value trace(stack);
864 fprintf(stderr, "%s\n", *trace);
869 // Executes a str within the current v8 context.
870 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
874 Local<v8::Script> script = v8::Script::Compile(source, filename);
875 if (script.IsEmpty()) {
876 ReportException(try_catch);
880 Local<Value> result = script->Run();
881 if (result.IsEmpty()) {
882 ReportException(try_catch);
886 return scope.Close(result);
889 static Handle<Value> ByteLength(const Arguments& args) {
892 if (args.Length() < 1 || !args[0]->IsString()) {
893 return ThrowException(Exception::Error(String::New("Bad argument.")));
896 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
898 return scope.Close(length);
901 static Handle<Value> Loop(const Arguments& args) {
903 assert(args.Length() == 0);
905 // TODO Probably don't need to start this each time.
906 // Avoids failing on test/mjsunit/test-eio-race3.js though
907 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
909 ev_loop(EV_DEFAULT_UC_ 0);
913 static Handle<Value> Unloop(const Arguments& args) {
914 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
916 int how = EVUNLOOP_ONE;
917 if (args[0]->IsString()) {
918 String::Utf8Value how_s(args[0]->ToString());
919 if (0 == strcmp(*how_s, "all")) {
923 ev_unloop(EV_DEFAULT_ how);
927 static Handle<Value> Chdir(const Arguments& args) {
930 if (args.Length() != 1 || !args[0]->IsString()) {
931 return ThrowException(Exception::Error(String::New("Bad argument.")));
934 String::Utf8Value path(args[0]->ToString());
936 int r = chdir(*path);
939 return ThrowException(Exception::Error(String::New(strerror(errno))));
945 static Handle<Value> Cwd(const Arguments& args) {
947 assert(args.Length() == 0);
949 char output[PATH_MAX];
950 char *r = getcwd(output, PATH_MAX);
952 return ThrowException(Exception::Error(String::New(strerror(errno))));
954 Local<String> cwd = String::New(output);
956 return scope.Close(cwd);
959 static Handle<Value> Umask(const Arguments& args){
962 if(args.Length() < 1) {
966 else if(!args[0]->IsInt32()) {
967 return ThrowException(Exception::TypeError(
968 String::New("argument must be an integer.")));
971 old = umask((mode_t)args[0]->Uint32Value());
973 return scope.Close(Uint32::New(old));
977 static Handle<Value> GetUid(const Arguments& args) {
979 assert(args.Length() == 0);
981 return scope.Close(Integer::New(uid));
984 static Handle<Value> GetGid(const Arguments& args) {
986 assert(args.Length() == 0);
988 return scope.Close(Integer::New(gid));
992 static Handle<Value> SetGid(const Arguments& args) {
995 if (args.Length() < 1) {
996 return ThrowException(Exception::Error(
997 String::New("setgid requires 1 argument")));
1000 Local<Integer> given_gid = args[0]->ToInteger();
1001 int gid = given_gid->Int32Value();
1003 if ((result = setgid(gid)) != 0) {
1004 return ThrowException(Exception::Error(String::New(strerror(errno))));
1009 static Handle<Value> SetUid(const Arguments& args) {
1012 if (args.Length() < 1) {
1013 return ThrowException(Exception::Error(
1014 String::New("setuid requires 1 argument")));
1017 Local<Integer> given_uid = args[0]->ToInteger();
1018 int uid = given_uid->Int32Value();
1020 if ((result = setuid(uid)) != 0) {
1021 return ThrowException(Exception::Error(String::New(strerror(errno))));
1027 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
1031 exit(args[0]->IntegerValue());
1036 #define HAVE_GETMEM 1
1037 #include <unistd.h> /* getpagesize() */
1039 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
1040 #define PROCFS_FILE_OFFSET_BITS_HACK 1
1041 #undef _FILE_OFFSET_BITS
1043 #define PROCFS_FILE_OFFSET_BITS_HACK 0
1048 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
1049 #define _FILE_OFFSET_BITS 64
1052 int getmem(size_t *rss, size_t *vsize) {
1053 pid_t pid = getpid();
1055 size_t page_size = getpagesize();
1057 sprintf(pidpath, "/proc/%d/psinfo", pid);
1060 FILE *f = fopen(pidpath, "r");
1063 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
1070 *vsize = (size_t) psinfo.pr_size * page_size;
1071 *rss = (size_t) psinfo.pr_rssize * 1024;
1081 #define HAVE_GETMEM 1
1083 #include <sys/param.h>
1084 #include <sys/sysctl.h>
1085 #include <sys/user.h>
1090 int getmem(size_t *rss, size_t *vsize) {
1092 struct kinfo_proc *kinfo = NULL;
1095 size_t page_size = getpagesize();
1099 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
1100 if (kd == NULL) goto error;
1102 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
1103 if (kinfo == NULL) goto error;
1105 *rss = kinfo->ki_rssize * page_size;
1106 *vsize = kinfo->ki_size;
1113 if (kd) kvm_close(kd);
1116 #endif // __FreeBSD__
1120 #define HAVE_GETMEM 1
1121 /* Researched by Tim Becker and Michael Knight
1122 * http://blog.kuriositaet.de/?p=257
1125 #include <mach/task.h>
1126 #include <mach/mach_init.h>
1128 int getmem(size_t *rss, size_t *vsize) {
1129 struct task_basic_info t_info;
1130 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
1132 int r = task_info(mach_task_self(),
1134 (task_info_t)&t_info,
1137 if (r != KERN_SUCCESS) return -1;
1139 *rss = t_info.resident_size;
1140 *vsize = t_info.virtual_size;
1147 # define HAVE_GETMEM 1
1148 # include <sys/param.h> /* for MAXPATHLEN */
1150 int getmem(size_t *rss, size_t *vsize) {
1151 FILE *f = fopen("/proc/self/stat", "r");
1156 char buffer[MAXPATHLEN];
1157 size_t page_size = getpagesize();
1160 if (fscanf(f, "%d ", &itmp) == 0) goto error;
1162 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
1164 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
1165 /* Parent process */
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;
1172 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1173 /* TTY owner process group */
1174 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1176 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1177 /* Minor faults (no memory page) */
1178 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1179 /* Minor faults, children */
1180 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1181 /* Major faults (memory page faults) */
1182 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1183 /* Major faults, children */
1184 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1186 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1188 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1189 /* utime, children */
1190 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1191 /* stime, children */
1192 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1193 /* jiffies remaining in current time slice */
1194 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1196 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1197 /* jiffies until next timeout */
1198 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1199 /* jiffies until next SIGALRM */
1200 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1201 /* start time (jiffies since system boot) */
1202 if (fscanf (f, "%d ", &itmp) == 0) goto error;
1204 /* Virtual memory size */
1205 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1206 *vsize = (size_t) itmp;
1208 /* Resident set size */
1209 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1210 *rss = (size_t) itmp * page_size;
1213 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1215 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1217 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1218 /* Start of stack */
1219 if (fscanf (f, "%u ", &itmp) == 0) goto error;
1231 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
1233 assert(args.Length() == 0);
1236 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
1240 int r = getmem(&rss, &vsize);
1243 return ThrowException(Exception::Error(String::New(strerror(errno))));
1246 Local<Object> info = Object::New();
1248 if (rss_symbol.IsEmpty()) {
1249 rss_symbol = NODE_PSYMBOL("rss");
1250 vsize_symbol = NODE_PSYMBOL("vsize");
1251 heap_total_symbol = NODE_PSYMBOL("heapTotal");
1252 heap_used_symbol = NODE_PSYMBOL("heapUsed");
1255 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
1256 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
1259 HeapStatistics v8_heap_stats;
1260 V8::GetHeapStatistics(&v8_heap_stats);
1261 info->Set(heap_total_symbol,
1262 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
1263 info->Set(heap_used_symbol,
1264 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
1266 return scope.Close(info);
1271 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
1274 if (args.Length() < 1 || !args[0]->IsNumber()) {
1275 return ThrowException(Exception::Error(String::New("Bad argument.")));
1278 pid_t pid = args[0]->IntegerValue();
1282 if (args.Length() >= 2) {
1283 if (args[1]->IsNumber()) {
1284 sig = args[1]->Int32Value();
1285 } else if (args[1]->IsString()) {
1286 Local<String> signame = args[1]->ToString();
1288 Local<Value> sig_v = process->Get(signame);
1289 if (!sig_v->IsNumber()) {
1290 return ThrowException(Exception::Error(String::New("Unknown signal")));
1292 sig = sig_v->Int32Value();
1296 int r = kill(pid, sig);
1299 return ThrowException(Exception::Error(String::New(strerror(errno))));
1305 typedef void (*extInit)(Handle<Object> exports);
1307 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
1309 Handle<Value> DLOpen(const v8::Arguments& args) {
1312 if (args.Length() < 2) return Undefined();
1314 String::Utf8Value filename(args[0]->ToString()); // Cast
1315 Local<Object> target = args[1]->ToObject(); // Cast
1317 // Actually call dlopen().
1318 // FIXME: This is a blocking function and should be called asynchronously!
1319 // This function should be moved to file.cc and use libeio to make this
1321 void *handle = dlopen(*filename, RTLD_LAZY);
1324 if (handle == NULL) {
1325 Local<Value> exception = Exception::Error(String::New(dlerror()));
1326 return ThrowException(exception);
1329 // Get the init() function from the dynamically shared object.
1330 void *init_handle = dlsym(handle, "init");
1331 // Error out if not found.
1332 if (init_handle == NULL) {
1333 Local<Value> exception =
1334 Exception::Error(String::New("No 'init' symbol found in module."));
1335 return ThrowException(exception);
1337 extInit init = (extInit)(init_handle); // Cast
1339 // Execute the C++ module
1346 Handle<Value> Compile(const Arguments& args) {
1349 if (args.Length() < 2) {
1350 return ThrowException(Exception::TypeError(
1351 String::New("needs two arguments.")));
1354 Local<String> source = args[0]->ToString();
1355 Local<String> filename = args[1]->ToString();
1359 Local<v8::Script> script = v8::Script::Compile(source, filename);
1360 if (try_catch.HasCaught()) {
1361 // Hack because I can't get a proper stacktrace on SyntaxError
1362 ReportException(try_catch, true);
1366 Local<Value> result = script->Run();
1367 if (try_catch.HasCaught()) return try_catch.ReThrow();
1369 return scope.Close(result);
1372 static void OnFatalError(const char* location, const char* message) {
1374 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1376 fprintf(stderr, "FATAL ERROR: %s\n", message);
1381 static int uncaught_exception_counter = 0;
1383 void FatalException(TryCatch &try_catch) {
1386 // Check if uncaught_exception_counter indicates a recursion
1387 if (uncaught_exception_counter > 0) {
1388 ReportException(try_catch);
1392 if (listeners_symbol.IsEmpty()) {
1393 listeners_symbol = NODE_PSYMBOL("listeners");
1394 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1395 emit_symbol = NODE_PSYMBOL("emit");
1398 Local<Value> listeners_v = process->Get(listeners_symbol);
1399 assert(listeners_v->IsFunction());
1401 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1403 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1404 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1405 Local<Value> ret = listeners->Call(process, 1, argv);
1407 assert(ret->IsArray());
1409 Local<Array> listener_array = Local<Array>::Cast(ret);
1411 uint32_t length = listener_array->Length();
1412 // Report and exit if process has no "uncaughtException" listener
1414 ReportException(try_catch);
1418 // Otherwise fire the process "uncaughtException" event
1419 Local<Value> emit_v = process->Get(emit_symbol);
1420 assert(emit_v->IsFunction());
1422 Local<Function> emit = Local<Function>::Cast(emit_v);
1424 Local<Value> error = try_catch.Exception();
1425 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1427 uncaught_exception_counter++;
1428 emit->Call(process, 2, event_argv);
1429 // Decrement so we know if the next exception is a recursion or not
1430 uncaught_exception_counter--;
1434 static ev_async debug_watcher;
1435 volatile static bool debugger_msg_pending = false;
1437 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1439 assert(watcher == &debug_watcher);
1440 assert(revents == EV_ASYNC);
1441 Debug::ProcessDebugMessages();
1444 static void DebugMessageDispatch(void) {
1445 // This function is called from V8's debug thread when a debug TCP client
1446 // has sent a message.
1448 // Send a signal to our main thread saying that it should enter V8 to
1449 // handle the message.
1450 debugger_msg_pending = true;
1451 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1454 static Handle<Value> CheckBreak(const Arguments& args) {
1456 assert(args.Length() == 0);
1458 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1459 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1460 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1461 // get it to halt until Eclipse connects.
1463 if (!debug_wait_connect)
1466 printf("Waiting for remote debugger connection...\n");
1468 const int halfSecond = 50;
1469 const int tenMs=10000;
1470 debugger_msg_pending = false;
1472 if (debugger_msg_pending) {
1473 Debug::DebugBreak();
1474 Debug::ProcessDebugMessages();
1475 debugger_msg_pending = false;
1477 // wait for 500 msec of silence from remote debugger
1478 int cnt = halfSecond;
1480 debugger_msg_pending = false;
1482 if (debugger_msg_pending) {
1483 debugger_msg_pending = false;
1494 Persistent<Object> binding_cache;
1496 static Handle<Value> Binding(const Arguments& args) {
1499 Local<String> module = args[0]->ToString();
1500 String::Utf8Value module_v(module);
1502 if (binding_cache.IsEmpty()) {
1503 binding_cache = Persistent<Object>::New(Object::New());
1506 Local<Object> exports;
1508 // TODO DRY THIS UP!
1510 if (!strcmp(*module_v, "stdio")) {
1511 if (binding_cache->Has(module)) {
1512 exports = binding_cache->Get(module)->ToObject();
1514 exports = Object::New();
1515 Stdio::Initialize(exports);
1516 binding_cache->Set(module, exports);
1519 } else if (!strcmp(*module_v, "cares")) {
1520 if (binding_cache->Has(module)) {
1521 exports = binding_cache->Get(module)->ToObject();
1523 exports = Object::New();
1524 Cares::Initialize(exports);
1525 binding_cache->Set(module, exports);
1528 } else if (!strcmp(*module_v, "fs")) {
1529 if (binding_cache->Has(module)) {
1530 exports = binding_cache->Get(module)->ToObject();
1532 exports = Object::New();
1534 // Initialize the stats object
1535 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1536 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1537 exports->Set(String::NewSymbol("Stats"),
1538 stats_constructor_template->GetFunction());
1539 StatWatcher::Initialize(exports);
1540 File::Initialize(exports);
1541 binding_cache->Set(module, exports);
1544 } else if (!strcmp(*module_v, "signal_watcher")) {
1545 if (binding_cache->Has(module)) {
1546 exports = binding_cache->Get(module)->ToObject();
1548 exports = Object::New();
1549 SignalWatcher::Initialize(exports);
1550 binding_cache->Set(module, exports);
1553 } else if (!strcmp(*module_v, "net")) {
1554 if (binding_cache->Has(module)) {
1555 exports = binding_cache->Get(module)->ToObject();
1557 exports = Object::New();
1559 binding_cache->Set(module, exports);
1562 } else if (!strcmp(*module_v, "http_parser")) {
1563 if (binding_cache->Has(module)) {
1564 exports = binding_cache->Get(module)->ToObject();
1566 exports = Object::New();
1567 InitHttpParser(exports);
1568 binding_cache->Set(module, exports);
1571 } else if (!strcmp(*module_v, "child_process")) {
1572 if (binding_cache->Has(module)) {
1573 exports = binding_cache->Get(module)->ToObject();
1575 exports = Object::New();
1576 ChildProcess::Initialize(exports);
1577 binding_cache->Set(module, exports);
1580 } else if (!strcmp(*module_v, "buffer")) {
1581 if (binding_cache->Has(module)) {
1582 exports = binding_cache->Get(module)->ToObject();
1584 exports = Object::New();
1585 Buffer::Initialize(exports);
1586 binding_cache->Set(module, exports);
1589 } else if (!strcmp(*module_v, "crypto")) {
1590 if (binding_cache->Has(module)) {
1591 exports = binding_cache->Get(module)->ToObject();
1593 exports = Object::New();
1594 InitCrypto(exports);
1595 binding_cache->Set(module, exports);
1598 } else if (!strcmp(*module_v, "evals")) {
1599 if (binding_cache->Has(module)) {
1600 exports = binding_cache->Get(module)->ToObject();
1602 exports = Object::New();
1603 node::Script::Initialize(exports);
1604 binding_cache->Set(module, exports);
1607 } else if (!strcmp(*module_v, "natives")) {
1608 if (binding_cache->Has(module)) {
1609 exports = binding_cache->Get(module)->ToObject();
1611 exports = Object::New();
1612 // Explicitly define native sources.
1613 // TODO DRY/automate this?
1614 exports->Set(String::New("assert"), String::New(native_assert));
1615 exports->Set(String::New("buffer"), String::New(native_buffer));
1616 exports->Set(String::New("child_process"),String::New(native_child_process));
1617 exports->Set(String::New("dns"), String::New(native_dns));
1618 exports->Set(String::New("events"), String::New(native_events));
1619 exports->Set(String::New("file"), String::New(native_file));
1620 exports->Set(String::New("freelist"), String::New(native_freelist));
1621 exports->Set(String::New("fs"), String::New(native_fs));
1622 exports->Set(String::New("http"), String::New(native_http));
1623 exports->Set(String::New("crypto"), String::New(native_crypto));
1624 exports->Set(String::New("ini"), String::New(native_ini));
1625 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1626 exports->Set(String::New("net"), String::New(native_net));
1627 exports->Set(String::New("posix"), String::New(native_posix));
1628 exports->Set(String::New("querystring"), String::New(native_querystring));
1629 exports->Set(String::New("repl"), String::New(native_repl));
1630 exports->Set(String::New("sys"), String::New(native_sys));
1631 exports->Set(String::New("tcp"), String::New(native_tcp));
1632 exports->Set(String::New("uri"), String::New(native_uri));
1633 exports->Set(String::New("url"), String::New(native_url));
1634 exports->Set(String::New("utils"), String::New(native_utils));
1635 exports->Set(String::New("path"), String::New(native_path));
1636 exports->Set(String::New("module"), String::New(native_module));
1637 binding_cache->Set(module, exports);
1641 return ThrowException(Exception::Error(String::New("No such module")));
1644 return scope.Close(exports);
1648 static void Load(int argc, char *argv[]) {
1651 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1652 node::EventEmitter::Initialize(process_template);
1654 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1656 // Add a reference to the global object
1657 Local<Object> global = Context::GetCurrent()->Global();
1658 process->Set(String::NewSymbol("global"), global);
1661 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1662 // process.installPrefix
1663 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1666 #define xstr(s) str(s)
1668 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1672 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1673 arguments->Set(Integer::New(0), String::New(argv[0]));
1674 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1675 Local<String> arg = String::New(argv[i]);
1676 arguments->Set(Integer::New(j), arg);
1679 process->Set(String::NewSymbol("ARGV"), arguments);
1680 process->Set(String::NewSymbol("argv"), arguments);
1682 // create process.env
1683 Local<Object> env = Object::New();
1684 for (i = 0; environ[i]; i++) {
1685 // skip entries without a '=' character
1686 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1687 // create the v8 objects
1688 Local<String> field = String::New(environ[i], j);
1689 Local<String> value = Local<String>();
1690 if (environ[i][j] == '=') {
1691 value = String::New(environ[i]+j+1);
1694 env->Set(field, value);
1696 // assign process.ENV
1697 process->Set(String::NewSymbol("ENV"), env);
1698 process->Set(String::NewSymbol("env"), env);
1700 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1702 // define various internal methods
1703 NODE_SET_METHOD(process, "loop", Loop);
1704 NODE_SET_METHOD(process, "unloop", Unloop);
1705 NODE_SET_METHOD(process, "compile", Compile);
1706 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1707 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
1708 NODE_SET_METHOD(process, "reallyExit", Exit);
1709 NODE_SET_METHOD(process, "chdir", Chdir);
1710 NODE_SET_METHOD(process, "cwd", Cwd);
1711 NODE_SET_METHOD(process, "getuid", GetUid);
1712 NODE_SET_METHOD(process, "setuid", SetUid);
1714 NODE_SET_METHOD(process, "setgid", SetGid);
1715 NODE_SET_METHOD(process, "getgid", GetGid);
1717 NODE_SET_METHOD(process, "umask", Umask);
1718 NODE_SET_METHOD(process, "dlopen", DLOpen);
1719 NODE_SET_METHOD(process, "kill", Kill);
1720 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1721 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1723 NODE_SET_METHOD(process, "binding", Binding);
1725 // Assign the EventEmitter. It was created in main().
1726 process->Set(String::NewSymbol("EventEmitter"),
1727 EventEmitter::constructor_template->GetFunction());
1730 // Initialize the C++ modules..................filename of module
1731 IOWatcher::Initialize(process); // io_watcher.cc
1732 // Not in use at the moment.
1733 //IdleWatcher::Initialize(process); // idle_watcher.cc
1734 Timer::Initialize(process); // timer.cc
1735 DefineConstants(process); // constants.cc
1737 // Compile, execute the src/node.js file. (Which was included as static C
1738 // string in node_natives.h. 'natve_node' is the string containing that
1741 // The node.js file returns a function 'f'
1747 Local<Value> f_value = ExecuteString(String::New(native_node),
1748 String::New("node.js"));
1750 if (try_catch.HasCaught()) {
1751 ReportException(try_catch);
1755 assert(f_value->IsFunction());
1756 Local<Function> f = Local<Function>::Cast(f_value);
1758 // Now we call 'f' with the 'process' variable that we've built up with
1759 // all our bindings. Inside node.js we'll take care of assigning things to
1762 // We start the process this way in order to be more modular. Developers
1763 // who do not like how 'src/node.js' setups the module system but do like
1764 // Node's I/O bindings may want to replace 'f' with their own function.
1766 Local<Value> args[1] = { Local<Value>::New(process) };
1768 f->Call(global, 1, args);
1771 if (try_catch.HasCaught()) {
1772 ReportException(try_catch);
1778 static void PrintHelp();
1780 static void ParseDebugOpt(const char* arg) {
1783 use_debug_agent = true;
1784 if (!strcmp (arg, "--debug-brk")) {
1785 debug_wait_connect = true;
1787 } else if (!strcmp(arg, "--debug")) {
1789 } else if (strstr(arg, "--debug-brk=") == arg) {
1790 debug_wait_connect = true;
1791 p = 1 + strchr(arg, '=');
1792 debug_port = atoi(p);
1793 } else if (strstr(arg, "--debug=") == arg) {
1794 p = 1 + strchr(arg, '=');
1795 debug_port = atoi(p);
1797 if (p && debug_port > 1024 && debug_port < 65536)
1800 fprintf(stderr, "Bad debug option.\n");
1801 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1807 static void PrintHelp() {
1808 printf("Usage: node [options] script.js [arguments] \n"
1810 " -v, --version print node's version\n"
1811 " --debug[=port] enable remote debugging via given TCP port\n"
1812 " without stopping the execution\n"
1813 " --debug-brk[=port] as above, but break in script.js and\n"
1814 " wait for remote debugger to connect\n"
1815 " --v8-options print v8 command line options\n"
1816 " --vars print various compiled-in variables\n"
1818 "Enviromental variables:\n"
1819 "NODE_PATH ':'-separated list of directories\n"
1820 " prefixed to the module search path,\n"
1822 "NODE_DEBUG Print additional debugging output.\n"
1824 "Documentation can be found at http://nodejs.org/api.html"
1825 " or with 'man node'\n");
1828 // Parse node command line arguments.
1829 static void ParseArgs(int *argc, char **argv) {
1830 // TODO use parse opts
1831 for (int i = 1; i < *argc; i++) {
1832 const char *arg = argv[i];
1833 if (strstr(arg, "--debug") == arg) {
1835 argv[i] = const_cast<char*>("");
1836 option_end_index = i;
1837 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1838 printf("%s\n", NODE_VERSION);
1840 } else if (strcmp(arg, "--vars") == 0) {
1841 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1842 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1844 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1847 } else if (strcmp(arg, "--v8-options") == 0) {
1848 argv[i] = const_cast<char*>("--help");
1849 option_end_index = i+1;
1850 } else if (argv[i][0] != '-') {
1851 option_end_index = i-1;
1860 int main(int argc, char *argv[]) {
1861 // Parse a few arguments which are specific to Node.
1862 node::ParseArgs(&argc, argv);
1863 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1864 // in the command line))
1865 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1867 // Error out if we don't have a script argument.
1869 fprintf(stderr, "No script was specified.\n");
1874 // Initialize the default ev loop.
1876 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1877 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1878 ev_default_loop(EVBACKEND_SELECT);
1880 ev_default_loop(EVFLAG_AUTO);
1883 ev_prepare_init(&node::next_tick_watcher, node::Tick);
1884 ev_prepare_start(EV_DEFAULT_UC_ &node::next_tick_watcher);
1885 ev_unref(EV_DEFAULT_UC);
1887 ev_idle_init(&node::tick_spinner, node::Spin);
1889 ev_timer_init(&node::gc_timer, node::CheckIdleness, 2*GC_INTERVAL, 2*GC_INTERVAL);
1891 ev_check_init(&node::gc_check, node::Activity);
1892 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1893 ev_unref(EV_DEFAULT_UC);
1895 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1898 // Setup the EIO thread pool
1899 { // It requires 3, yes 3, watchers.
1900 ev_idle_init(&node::eio_poller, node::DoPoll);
1902 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1903 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1904 ev_unref(EV_DEFAULT_UC);
1906 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1907 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1908 ev_unref(EV_DEFAULT_UC);
1910 eio_init(node::EIOWantPoll, node::EIODonePoll);
1911 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1912 // race conditions. See test/mjsunit/test-eio-race.js
1913 eio_set_max_poll_reqs(10);
1917 HandleScope handle_scope;
1919 V8::SetFatalErrorHandler(node::OnFatalError);
1921 // If the --debug flag was specified then initialize the debug thread.
1922 if (node::use_debug_agent) {
1923 // Initialize the async watcher for receiving messages from the debug
1924 // thread and marshal it into the main thread. DebugMessageCallback()
1925 // is called from the main thread to execute a random bit of javascript
1926 // - which will give V8 control so it can handle whatever new message
1927 // had been received on the debug thread.
1928 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1929 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1930 // Set the callback DebugMessageDispatch which is called from the debug
1932 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1933 // Start the async watcher.
1934 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1935 // unref it so that we exit the event loop despite it being active.
1936 ev_unref(EV_DEFAULT_UC);
1938 // Start the debug thread and it's associated TCP server on port 5858.
1939 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1941 // Crappy check that everything went well. FIXME
1943 // Print out some information.
1944 printf("debugger listening on port %d\n", node::debug_port);
1947 // Create the one and only Context.
1948 Persistent<Context> context = Context::New();
1949 Context::Scope context_scope(context);
1951 // Create all the objects, load modules, do everything.
1952 // so your next reading stop should be node::Load()!
1953 node::Load(argc, argv);
1955 node::Stdio::Flush();