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>
23 #include <node_file.h>
26 # include <node_idle_watcher.h>
28 #include <node_http.h>
29 #include <node_http_parser.h>
30 #include <node_signal_watcher.h>
31 #include <node_stat_watcher.h>
32 #include <node_timer.h>
33 #include <node_child_process.h>
34 #include <node_constants.h>
35 #include <node_stdio.h>
36 #include <node_natives.h>
37 #include <node_version.h>
43 extern char **environ;
47 static Persistent<Object> process;
49 static Persistent<String> dev_symbol;
50 static Persistent<String> ino_symbol;
51 static Persistent<String> mode_symbol;
52 static Persistent<String> nlink_symbol;
53 static Persistent<String> uid_symbol;
54 static Persistent<String> gid_symbol;
55 static Persistent<String> rdev_symbol;
56 static Persistent<String> size_symbol;
57 static Persistent<String> blksize_symbol;
58 static Persistent<String> blocks_symbol;
59 static Persistent<String> atime_symbol;
60 static Persistent<String> mtime_symbol;
61 static Persistent<String> ctime_symbol;
63 static Persistent<String> rss_symbol;
64 static Persistent<String> vsize_symbol;
65 static Persistent<String> heap_total_symbol;
66 static Persistent<String> heap_used_symbol;
68 static Persistent<String> listeners_symbol;
69 static Persistent<String> uncaught_exception_symbol;
70 static Persistent<String> emit_symbol;
72 static int option_end_index = 0;
73 static bool use_debug_agent = false;
74 static bool debug_wait_connect = false;
75 static int debug_port=5858;
77 static ev_prepare next_tick_watcher;
78 static ev_idle tick_spinner;
79 static bool need_tick_cb;
80 static Persistent<String> tick_callback_sym;
82 static ev_async eio_want_poll_notifier;
83 static ev_async eio_done_poll_notifier;
84 static ev_idle eio_poller;
86 // We need to notify V8 when we're idle so that it can run the garbage
87 // collector. The interface to this is V8::IdleNotification(). It returns
88 // true if the heap hasn't be fully compacted, and needs to be run again.
89 // Returning false means that it doesn't have anymore work to do.
91 // We try to wait for a period of GC_INTERVAL (2 seconds) of idleness, where
92 // idleness means that no libev watchers have been executed. Since
93 // everything in node uses libev watchers, this is a pretty good measure of
94 // idleness. This is done with gc_check, which records the timestamp
95 // last_active on every tick of the event loop, and with gc_timer which
96 // executes every few seconds to measure if
97 // last_active + GC_INTERVAL < ev_now()
98 // If we do find a period of idleness, then we start the gc_idle timer which
99 // will very repaidly call IdleNotification until the heap is fully
101 static ev_tstamp last_active;
102 static ev_timer gc_timer;
103 static ev_check gc_check;
104 static ev_idle gc_idle;
105 static bool needs_gc;
106 #define GC_INTERVAL 2.0
109 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
110 assert(watcher == &gc_timer);
111 assert(revents == EV_TIMER);
113 //fprintf(stderr, "check idle\n");
115 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
117 if (idle_time > GC_INTERVAL) {
120 if (!V8::IdleNotification()) {
121 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
125 gc_timer.repeat = GC_INTERVAL;
126 ev_timer_again(EV_DEFAULT_UC_ watcher);
131 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
132 assert(watcher == &gc_idle);
133 assert(revents == EV_IDLE);
135 //fprintf(stderr, "notify idle\n");
137 if (V8::IdleNotification()) {
138 ev_idle_stop(EV_A_ watcher);
144 static void Activity(EV_P_ ev_check *watcher, int revents) {
145 assert(watcher == &gc_check);
146 assert(revents == EV_CHECK);
148 int pending = ev_pending_count(EV_DEFAULT_UC);
150 // Don't count GC watchers as activity.
152 pending -= ev_is_pending(&gc_timer);
153 pending -= ev_is_pending(&gc_idle);
154 pending -= ev_is_pending(&next_tick_watcher);
155 //if (ev_is_pending(&gc_check)) pending--; // This probably never happens?
157 //fprintf(stderr, "activity, pending: %d\n", pending);
160 last_active = ev_now(EV_DEFAULT_UC);
161 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
164 gc_timer.repeat = GC_INTERVAL;
165 ev_timer_again(EV_DEFAULT_UC_ &gc_timer);
173 static Handle<Value> NeedTickCallback(const Arguments& args) {
176 ev_idle_start(EV_DEFAULT_UC_ &tick_spinner);
181 static void Spin(EV_P_ ev_idle *watcher, int revents) {
182 assert(watcher == &tick_spinner);
183 assert(revents == EV_IDLE);
187 static void Tick(EV_P_ ev_prepare *watcher, int revents) {
188 assert(watcher == &next_tick_watcher);
189 assert(revents == EV_PREPARE);
191 // Avoid entering a V8 scope.
192 if (!need_tick_cb) return;
194 need_tick_cb = false;
195 ev_idle_stop(EV_DEFAULT_UC_ &tick_spinner);
199 if (tick_callback_sym.IsEmpty()) {
200 // Lazily set the symbol
202 Persistent<String>::New(String::NewSymbol("_tickCallback"));
205 Local<Value> cb_v = process->Get(tick_callback_sym);
206 if (!cb_v->IsFunction()) return;
207 Local<Function> cb = Local<Function>::Cast(cb_v);
211 cb->Call(process, 0, NULL);
213 if (try_catch.HasCaught()) {
214 FatalException(try_catch);
219 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
220 assert(watcher == &eio_poller);
221 assert(revents == EV_IDLE);
223 //printf("eio_poller\n");
225 if (eio_poll() != -1) {
226 //printf("eio_poller stop\n");
227 ev_idle_stop(EV_DEFAULT_UC_ watcher);
232 // Called from the main thread.
233 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
234 assert(watcher == &eio_want_poll_notifier);
235 assert(revents == EV_ASYNC);
237 //printf("want poll notifier\n");
239 if (eio_poll() == -1) {
240 //printf("eio_poller start\n");
241 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
246 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
247 assert(watcher == &eio_done_poll_notifier);
248 assert(revents == EV_ASYNC);
250 //printf("done poll notifier\n");
252 if (eio_poll() != -1) {
253 //printf("eio_poller stop\n");
254 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
259 // EIOWantPoll() is called from the EIO thread pool each time an EIO
260 // request (that is, one of the node.fs.* functions) has completed.
261 static void EIOWantPoll(void) {
262 // Signal the main thread that eio_poll need to be processed.
263 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
267 static void EIODonePoll(void) {
268 // Signal the main thread that we should stop calling eio_poll().
269 // from the idle watcher.
270 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
274 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
277 if (!encoding_v->IsString()) return _default;
279 String::Utf8Value encoding(encoding_v->ToString());
281 if (strcasecmp(*encoding, "utf8") == 0) {
283 } else if (strcasecmp(*encoding, "utf-8") == 0) {
285 } else if (strcasecmp(*encoding, "ascii") == 0) {
287 } else if (strcasecmp(*encoding, "binary") == 0) {
289 } else if (strcasecmp(*encoding, "raw") == 0) {
290 fprintf(stderr, "'raw' (array of integers) has been removed. "
293 } else if (strcasecmp(*encoding, "raws") == 0) {
294 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
295 "Please update your code.\n");
302 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
305 if (!len) return scope.Close(String::Empty());
307 if (encoding == BINARY) {
308 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
309 uint16_t * twobytebuf = new uint16_t[len];
310 for (size_t i = 0; i < len; i++) {
311 // XXX is the following line platform independent?
312 twobytebuf[i] = cbuf[i];
314 Local<String> chunk = String::New(twobytebuf, len);
315 delete [] twobytebuf; // TODO use ExternalTwoByteString?
316 return scope.Close(chunk);
319 // utf8 or ascii encoding
320 Local<String> chunk = String::New((const char*)buf, len);
321 return scope.Close(chunk);
324 // Returns -1 if the handle was not valid for decoding
325 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
328 if (val->IsArray()) {
329 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
335 Local<String> str = val->ToString();
337 if (encoding == UTF8) return str->Utf8Length();
339 return str->Length();
343 # define MIN(a, b) ((a) < (b) ? (a) : (b))
346 // Returns number of bytes written.
347 ssize_t DecodeWrite(char *buf,
349 v8::Handle<v8::Value> val,
350 enum encoding encoding) {
354 // A lot of improvement can be made here. See:
355 // http://code.google.com/p/v8/issues/detail?id=270
356 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
357 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
359 if (val->IsArray()) {
360 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
366 Local<String> str = val->ToString();
368 if (encoding == UTF8) {
369 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
373 if (encoding == ASCII) {
374 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
378 // THIS IS AWFUL!!! FIXME
380 assert(encoding == BINARY);
382 uint16_t * twobytebuf = new uint16_t[buflen];
384 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
386 for (size_t i = 0; i < buflen; i++) {
387 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
392 delete [] twobytebuf;
397 static Persistent<FunctionTemplate> stats_constructor_template;
399 Local<Object> BuildStatsObject(struct stat * s) {
402 if (dev_symbol.IsEmpty()) {
403 dev_symbol = NODE_PSYMBOL("dev");
404 ino_symbol = NODE_PSYMBOL("ino");
405 mode_symbol = NODE_PSYMBOL("mode");
406 nlink_symbol = NODE_PSYMBOL("nlink");
407 uid_symbol = NODE_PSYMBOL("uid");
408 gid_symbol = NODE_PSYMBOL("gid");
409 rdev_symbol = NODE_PSYMBOL("rdev");
410 size_symbol = NODE_PSYMBOL("size");
411 blksize_symbol = NODE_PSYMBOL("blksize");
412 blocks_symbol = NODE_PSYMBOL("blocks");
413 atime_symbol = NODE_PSYMBOL("atime");
414 mtime_symbol = NODE_PSYMBOL("mtime");
415 ctime_symbol = NODE_PSYMBOL("ctime");
418 Local<Object> stats =
419 stats_constructor_template->GetFunction()->NewInstance();
421 /* ID of device containing file */
422 stats->Set(dev_symbol, Integer::New(s->st_dev));
425 stats->Set(ino_symbol, Integer::New(s->st_ino));
428 stats->Set(mode_symbol, Integer::New(s->st_mode));
430 /* number of hard links */
431 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
433 /* user ID of owner */
434 stats->Set(uid_symbol, Integer::New(s->st_uid));
436 /* group ID of owner */
437 stats->Set(gid_symbol, Integer::New(s->st_gid));
439 /* device ID (if special file) */
440 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
442 /* total size, in bytes */
443 stats->Set(size_symbol, Integer::New(s->st_size));
445 /* blocksize for filesystem I/O */
446 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
448 /* number of blocks allocated */
449 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
451 /* time of last access */
452 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
454 /* time of last modification */
455 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
457 /* time of last status change */
458 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
460 return scope.Close(stats);
464 // Extracts a C str from a V8 Utf8Value.
465 const char* ToCString(const v8::String::Utf8Value& value) {
466 return *value ? *value : "<str conversion failed>";
469 static void ReportException(TryCatch &try_catch, bool show_line = false) {
470 Handle<Message> message = try_catch.Message();
472 Handle<Value> error = try_catch.Exception();
473 Handle<String> stack;
475 if (error->IsObject()) {
476 Handle<Object> obj = Handle<Object>::Cast(error);
477 Handle<Value> raw_stack = obj->Get(String::New("stack"));
478 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
481 if (show_line && !message.IsEmpty()) {
482 // Print (filename):(line number): (message).
483 String::Utf8Value filename(message->GetScriptResourceName());
484 const char* filename_string = ToCString(filename);
485 int linenum = message->GetLineNumber();
486 fprintf(stderr, "%s:%i\n", filename_string, linenum);
487 // Print line of source code.
488 String::Utf8Value sourceline(message->GetSourceLine());
489 const char* sourceline_string = ToCString(sourceline);
490 fprintf(stderr, "%s\n", sourceline_string);
491 // Print wavy underline (GetUnderline is deprecated).
492 int start = message->GetStartColumn();
493 for (int i = 0; i < start; i++) {
494 fprintf(stderr, " ");
496 int end = message->GetEndColumn();
497 for (int i = start; i < end; i++) {
498 fprintf(stderr, "^");
500 fprintf(stderr, "\n");
503 if (stack.IsEmpty()) {
504 message->PrintCurrentStackTrace(stderr);
506 String::Utf8Value trace(stack);
507 fprintf(stderr, "%s\n", *trace);
512 // Executes a str within the current v8 context.
513 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
517 Local<Script> script = Script::Compile(source, filename);
518 if (script.IsEmpty()) {
519 ReportException(try_catch);
523 Local<Value> result = script->Run();
524 if (result.IsEmpty()) {
525 ReportException(try_catch);
529 return scope.Close(result);
532 static Handle<Value> ByteLength(const Arguments& args) {
535 if (args.Length() < 1 || !args[0]->IsString()) {
536 return ThrowException(Exception::Error(String::New("Bad argument.")));
539 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
541 return scope.Close(length);
544 static Handle<Value> Loop(const Arguments& args) {
546 assert(args.Length() == 0);
548 // TODO Probably don't need to start this each time.
549 // Avoids failing on test/mjsunit/test-eio-race3.js though
550 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
552 ev_loop(EV_DEFAULT_UC_ 0);
556 static Handle<Value> Unloop(const Arguments& args) {
557 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
559 int how = EVUNLOOP_ONE;
560 if (args[0]->IsString()) {
561 String::Utf8Value how_s(args[0]->ToString());
562 if (0 == strcmp(*how_s, "all")) {
566 ev_unloop(EV_DEFAULT_ how);
570 static Handle<Value> Chdir(const Arguments& args) {
573 if (args.Length() != 1 || !args[0]->IsString()) {
574 return ThrowException(Exception::Error(String::New("Bad argument.")));
577 String::Utf8Value path(args[0]->ToString());
579 int r = chdir(*path);
582 return ThrowException(Exception::Error(String::New(strerror(errno))));
588 static Handle<Value> Cwd(const Arguments& args) {
590 assert(args.Length() == 0);
592 char output[PATH_MAX];
593 char *r = getcwd(output, PATH_MAX);
595 return ThrowException(Exception::Error(String::New(strerror(errno))));
597 Local<String> cwd = String::New(output);
599 return scope.Close(cwd);
602 static Handle<Value> Umask(const Arguments& args){
605 if(args.Length() < 1) {
609 else if(!args[0]->IsInt32()) {
610 return ThrowException(Exception::TypeError(
611 String::New("argument must be an integer.")));
614 old = umask((mode_t)args[0]->Uint32Value());
616 return scope.Close(Uint32::New(old));
620 static Handle<Value> GetUid(const Arguments& args) {
622 assert(args.Length() == 0);
624 return scope.Close(Integer::New(uid));
627 static Handle<Value> GetGid(const Arguments& args) {
629 assert(args.Length() == 0);
631 return scope.Close(Integer::New(gid));
635 static Handle<Value> SetGid(const Arguments& args) {
638 if (args.Length() < 1) {
639 return ThrowException(Exception::Error(
640 String::New("setgid requires 1 argument")));
643 Local<Integer> given_gid = args[0]->ToInteger();
644 int gid = given_gid->Int32Value();
646 if ((result = setgid(gid)) != 0) {
647 return ThrowException(Exception::Error(String::New(strerror(errno))));
652 static Handle<Value> SetUid(const Arguments& args) {
655 if (args.Length() < 1) {
656 return ThrowException(Exception::Error(
657 String::New("setuid requires 1 argument")));
660 Local<Integer> given_uid = args[0]->ToInteger();
661 int uid = given_uid->Int32Value();
663 if ((result = setuid(uid)) != 0) {
664 return ThrowException(Exception::Error(String::New(strerror(errno))));
670 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
674 exit(args[0]->IntegerValue());
679 #define HAVE_GETMEM 1
680 #include <unistd.h> /* getpagesize() */
682 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
683 #define PROCFS_FILE_OFFSET_BITS_HACK 1
684 #undef _FILE_OFFSET_BITS
686 #define PROCFS_FILE_OFFSET_BITS_HACK 0
691 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
692 #define _FILE_OFFSET_BITS 64
695 int getmem(size_t *rss, size_t *vsize) {
696 pid_t pid = getpid();
698 size_t page_size = getpagesize();
700 sprintf(pidpath, "/proc/%d/psinfo", pid);
703 FILE *f = fopen(pidpath, "r");
706 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
713 *vsize = (size_t) psinfo.pr_size * page_size;
714 *rss = (size_t) psinfo.pr_rssize * 1024;
724 #define HAVE_GETMEM 1
726 #include <sys/param.h>
727 #include <sys/sysctl.h>
728 #include <sys/user.h>
733 int getmem(size_t *rss, size_t *vsize) {
735 struct kinfo_proc *kinfo = NULL;
738 size_t page_size = getpagesize();
742 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
743 if (kd == NULL) goto error;
745 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
746 if (kinfo == NULL) goto error;
748 *rss = kinfo->ki_rssize * page_size;
749 *vsize = kinfo->ki_size;
756 if (kd) kvm_close(kd);
759 #endif // __FreeBSD__
763 #define HAVE_GETMEM 1
764 /* Researched by Tim Becker and Michael Knight
765 * http://blog.kuriositaet.de/?p=257
768 #include <mach/task.h>
769 #include <mach/mach_init.h>
771 int getmem(size_t *rss, size_t *vsize) {
772 struct task_basic_info t_info;
773 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
775 int r = task_info(mach_task_self(),
777 (task_info_t)&t_info,
780 if (r != KERN_SUCCESS) return -1;
782 *rss = t_info.resident_size;
783 *vsize = t_info.virtual_size;
790 # define HAVE_GETMEM 1
791 # include <sys/param.h> /* for MAXPATHLEN */
793 int getmem(size_t *rss, size_t *vsize) {
794 FILE *f = fopen("/proc/self/stat", "r");
799 char buffer[MAXPATHLEN];
800 size_t page_size = getpagesize();
803 if (fscanf(f, "%d ", &itmp) == 0) goto error;
805 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
807 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
809 if (fscanf (f, "%d ", &itmp) == 0) goto error;
811 if (fscanf (f, "%d ", &itmp) == 0) goto error;
813 if (fscanf (f, "%d ", &itmp) == 0) goto error;
815 if (fscanf (f, "%d ", &itmp) == 0) goto error;
816 /* TTY owner process group */
817 if (fscanf (f, "%d ", &itmp) == 0) goto error;
819 if (fscanf (f, "%u ", &itmp) == 0) goto error;
820 /* Minor faults (no memory page) */
821 if (fscanf (f, "%u ", &itmp) == 0) goto error;
822 /* Minor faults, children */
823 if (fscanf (f, "%u ", &itmp) == 0) goto error;
824 /* Major faults (memory page faults) */
825 if (fscanf (f, "%u ", &itmp) == 0) goto error;
826 /* Major faults, children */
827 if (fscanf (f, "%u ", &itmp) == 0) goto error;
829 if (fscanf (f, "%d ", &itmp) == 0) goto error;
831 if (fscanf (f, "%d ", &itmp) == 0) goto error;
832 /* utime, children */
833 if (fscanf (f, "%d ", &itmp) == 0) goto error;
834 /* stime, children */
835 if (fscanf (f, "%d ", &itmp) == 0) goto error;
836 /* jiffies remaining in current time slice */
837 if (fscanf (f, "%d ", &itmp) == 0) goto error;
839 if (fscanf (f, "%d ", &itmp) == 0) goto error;
840 /* jiffies until next timeout */
841 if (fscanf (f, "%u ", &itmp) == 0) goto error;
842 /* jiffies until next SIGALRM */
843 if (fscanf (f, "%u ", &itmp) == 0) goto error;
844 /* start time (jiffies since system boot) */
845 if (fscanf (f, "%d ", &itmp) == 0) goto error;
847 /* Virtual memory size */
848 if (fscanf (f, "%u ", &itmp) == 0) goto error;
849 *vsize = (size_t) itmp;
851 /* Resident set size */
852 if (fscanf (f, "%u ", &itmp) == 0) goto error;
853 *rss = (size_t) itmp * page_size;
856 if (fscanf (f, "%u ", &itmp) == 0) goto error;
858 if (fscanf (f, "%u ", &itmp) == 0) goto error;
860 if (fscanf (f, "%u ", &itmp) == 0) goto error;
862 if (fscanf (f, "%u ", &itmp) == 0) goto error;
874 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
876 assert(args.Length() == 0);
879 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
883 int r = getmem(&rss, &vsize);
886 return ThrowException(Exception::Error(String::New(strerror(errno))));
889 Local<Object> info = Object::New();
891 if (rss_symbol.IsEmpty()) {
892 rss_symbol = NODE_PSYMBOL("rss");
893 vsize_symbol = NODE_PSYMBOL("vsize");
894 heap_total_symbol = NODE_PSYMBOL("heapTotal");
895 heap_used_symbol = NODE_PSYMBOL("heapUsed");
898 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
899 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
902 HeapStatistics v8_heap_stats;
903 V8::GetHeapStatistics(&v8_heap_stats);
904 info->Set(heap_total_symbol,
905 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
906 info->Set(heap_used_symbol,
907 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
909 return scope.Close(info);
914 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
917 if (args.Length() < 1 || !args[0]->IsNumber()) {
918 return ThrowException(Exception::Error(String::New("Bad argument.")));
921 pid_t pid = args[0]->IntegerValue();
925 if (args.Length() >= 2) {
926 if (args[1]->IsNumber()) {
927 sig = args[1]->Int32Value();
928 } else if (args[1]->IsString()) {
929 Local<String> signame = args[1]->ToString();
931 Local<Value> sig_v = process->Get(signame);
932 if (!sig_v->IsNumber()) {
933 return ThrowException(Exception::Error(String::New("Unknown signal")));
935 sig = sig_v->Int32Value();
939 int r = kill(pid, sig);
942 return ThrowException(Exception::Error(String::New(strerror(errno))));
948 typedef void (*extInit)(Handle<Object> exports);
950 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
952 Handle<Value> DLOpen(const v8::Arguments& args) {
955 if (args.Length() < 2) return Undefined();
957 String::Utf8Value filename(args[0]->ToString()); // Cast
958 Local<Object> target = args[1]->ToObject(); // Cast
960 // Actually call dlopen().
961 // FIXME: This is a blocking function and should be called asynchronously!
962 // This function should be moved to file.cc and use libeio to make this
964 void *handle = dlopen(*filename, RTLD_LAZY);
967 if (handle == NULL) {
968 Local<Value> exception = Exception::Error(String::New(dlerror()));
969 return ThrowException(exception);
972 // Get the init() function from the dynamically shared object.
973 void *init_handle = dlsym(handle, "init");
974 // Error out if not found.
975 if (init_handle == NULL) {
976 Local<Value> exception =
977 Exception::Error(String::New("No 'init' symbol found in module."));
978 return ThrowException(exception);
980 extInit init = (extInit)(init_handle); // Cast
982 // Execute the C++ module
988 // evalcx(code, sandbox={})
989 // Executes code in a new context
990 Handle<Value> EvalCX(const Arguments& args) {
993 Local<String> code = args[0]->ToString();
994 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
996 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
997 : String::New("evalcx");
998 // Create the new context
999 Persistent<Context> context = Context::New();
1001 // Enter and compile script
1004 // Copy objects from global context, to our brand new context
1005 Handle<Array> keys = sandbox->GetPropertyNames();
1008 for (i = 0; i < keys->Length(); i++) {
1009 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1010 Handle<Value> value = sandbox->Get(key);
1011 context->Global()->Set(key, value);
1017 Local<Script> script = Script::Compile(code, filename);
1018 Handle<Value> result;
1020 if (script.IsEmpty()) {
1021 result = ThrowException(try_catch.Exception());
1023 result = script->Run();
1024 if (result.IsEmpty()) {
1025 result = ThrowException(try_catch.Exception());
1027 // success! copy changes back onto the sandbox object.
1028 keys = context->Global()->GetPropertyNames();
1029 for (i = 0; i < keys->Length(); i++) {
1030 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1031 Handle<Value> value = context->Global()->Get(key);
1032 sandbox->Set(key, value);
1037 // Clean up, clean up, everybody everywhere!
1038 context->DetachGlobal();
1042 return scope.Close(result);
1045 Handle<Value> Compile(const Arguments& args) {
1048 if (args.Length() < 2) {
1049 return ThrowException(Exception::TypeError(
1050 String::New("needs two arguments.")));
1053 Local<String> source = args[0]->ToString();
1054 Local<String> filename = args[1]->ToString();
1058 Local<Script> script = Script::Compile(source, filename);
1059 if (try_catch.HasCaught()) {
1060 // Hack because I can't get a proper stacktrace on SyntaxError
1061 ReportException(try_catch, true);
1065 Local<Value> result = script->Run();
1066 if (try_catch.HasCaught()) return try_catch.ReThrow();
1068 return scope.Close(result);
1071 static void OnFatalError(const char* location, const char* message) {
1073 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1075 fprintf(stderr, "FATAL ERROR: %s\n", message);
1080 static int uncaught_exception_counter = 0;
1082 void FatalException(TryCatch &try_catch) {
1085 // Check if uncaught_exception_counter indicates a recursion
1086 if (uncaught_exception_counter > 0) {
1087 ReportException(try_catch);
1091 if (listeners_symbol.IsEmpty()) {
1092 listeners_symbol = NODE_PSYMBOL("listeners");
1093 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1094 emit_symbol = NODE_PSYMBOL("emit");
1097 Local<Value> listeners_v = process->Get(listeners_symbol);
1098 assert(listeners_v->IsFunction());
1100 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1102 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1103 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1104 Local<Value> ret = listeners->Call(process, 1, argv);
1106 assert(ret->IsArray());
1108 Local<Array> listener_array = Local<Array>::Cast(ret);
1110 uint32_t length = listener_array->Length();
1111 // Report and exit if process has no "uncaughtException" listener
1113 ReportException(try_catch);
1117 // Otherwise fire the process "uncaughtException" event
1118 Local<Value> emit_v = process->Get(emit_symbol);
1119 assert(emit_v->IsFunction());
1121 Local<Function> emit = Local<Function>::Cast(emit_v);
1123 Local<Value> error = try_catch.Exception();
1124 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1126 uncaught_exception_counter++;
1127 emit->Call(process, 2, event_argv);
1128 // Decrement so we know if the next exception is a recursion or not
1129 uncaught_exception_counter--;
1133 static ev_async debug_watcher;
1134 volatile static bool debugger_msg_pending = false;
1136 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1138 assert(watcher == &debug_watcher);
1139 assert(revents == EV_ASYNC);
1140 Debug::ProcessDebugMessages();
1143 static void DebugMessageDispatch(void) {
1144 // This function is called from V8's debug thread when a debug TCP client
1145 // has sent a message.
1147 // Send a signal to our main thread saying that it should enter V8 to
1148 // handle the message.
1149 debugger_msg_pending = true;
1150 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1153 static Handle<Value> CheckBreak(const Arguments& args) {
1155 assert(args.Length() == 0);
1157 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1158 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1159 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1160 // get it to halt until Eclipse connects.
1162 if (!debug_wait_connect)
1165 printf("Waiting for remote debugger connection...\n");
1167 const int halfSecond = 50;
1168 const int tenMs=10000;
1169 debugger_msg_pending = false;
1171 if (debugger_msg_pending) {
1172 Debug::DebugBreak();
1173 Debug::ProcessDebugMessages();
1174 debugger_msg_pending = false;
1176 // wait for 500 msec of silence from remote debugger
1177 int cnt = halfSecond;
1179 debugger_msg_pending = false;
1181 if (debugger_msg_pending) {
1182 debugger_msg_pending = false;
1193 Persistent<Object> binding_cache;
1195 static Handle<Value> Binding(const Arguments& args) {
1198 Local<String> module = args[0]->ToString();
1199 String::Utf8Value module_v(module);
1201 if (binding_cache.IsEmpty()) {
1202 binding_cache = Persistent<Object>::New(Object::New());
1205 Local<Object> exports;
1207 // TODO DRY THIS UP!
1209 if (!strcmp(*module_v, "stdio")) {
1210 if (binding_cache->Has(module)) {
1211 exports = binding_cache->Get(module)->ToObject();
1213 exports = Object::New();
1214 Stdio::Initialize(exports);
1215 binding_cache->Set(module, exports);
1218 } else if (!strcmp(*module_v, "http")) {
1219 if (binding_cache->Has(module)) {
1220 exports = binding_cache->Get(module)->ToObject();
1222 // Warning: When calling requireBinding('http') from javascript then
1223 // be sure that you call requireBinding('tcp') before it.
1224 assert(binding_cache->Has(String::New("tcp")));
1225 exports = Object::New();
1226 HTTPServer::Initialize(exports);
1227 HTTPConnection::Initialize(exports);
1228 binding_cache->Set(module, exports);
1231 } else if (!strcmp(*module_v, "tcp")) {
1232 if (binding_cache->Has(module)) {
1233 exports = binding_cache->Get(module)->ToObject();
1235 exports = Object::New();
1236 Server::Initialize(exports);
1237 Connection::Initialize(exports);
1238 binding_cache->Set(module, exports);
1241 } else if (!strcmp(*module_v, "cares")) {
1242 if (binding_cache->Has(module)) {
1243 exports = binding_cache->Get(module)->ToObject();
1245 exports = Object::New();
1246 Cares::Initialize(exports);
1247 binding_cache->Set(module, exports);
1250 } else if (!strcmp(*module_v, "fs")) {
1251 if (binding_cache->Has(module)) {
1252 exports = binding_cache->Get(module)->ToObject();
1254 exports = Object::New();
1256 // Initialize the stats object
1257 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1258 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1259 exports->Set(String::NewSymbol("Stats"),
1260 stats_constructor_template->GetFunction());
1261 StatWatcher::Initialize(exports);
1262 File::Initialize(exports);
1263 binding_cache->Set(module, exports);
1266 } else if (!strcmp(*module_v, "signal_watcher")) {
1267 if (binding_cache->Has(module)) {
1268 exports = binding_cache->Get(module)->ToObject();
1270 exports = Object::New();
1271 SignalWatcher::Initialize(exports);
1272 binding_cache->Set(module, exports);
1275 } else if (!strcmp(*module_v, "net")) {
1276 if (binding_cache->Has(module)) {
1277 exports = binding_cache->Get(module)->ToObject();
1279 exports = Object::New();
1281 binding_cache->Set(module, exports);
1284 } else if (!strcmp(*module_v, "http_parser")) {
1285 if (binding_cache->Has(module)) {
1286 exports = binding_cache->Get(module)->ToObject();
1288 exports = Object::New();
1289 InitHttpParser(exports);
1290 binding_cache->Set(module, exports);
1293 } else if (!strcmp(*module_v, "child_process")) {
1294 if (binding_cache->Has(module)) {
1295 exports = binding_cache->Get(module)->ToObject();
1297 exports = Object::New();
1298 ChildProcess::Initialize(exports);
1299 binding_cache->Set(module, exports);
1302 } else if (!strcmp(*module_v, "buffer")) {
1303 if (binding_cache->Has(module)) {
1304 exports = binding_cache->Get(module)->ToObject();
1306 exports = Object::New();
1307 Buffer::Initialize(exports);
1308 binding_cache->Set(module, exports);
1311 } else if (!strcmp(*module_v, "natives")) {
1312 if (binding_cache->Has(module)) {
1313 exports = binding_cache->Get(module)->ToObject();
1315 exports = Object::New();
1316 // Explicitly define native sources.
1317 // TODO DRY/automate this?
1318 exports->Set(String::New("assert"), String::New(native_assert));
1319 exports->Set(String::New("buffer"), String::New(native_buffer));
1320 exports->Set(String::New("child_process"),String::New(native_child_process));
1321 exports->Set(String::New("dns"), String::New(native_dns));
1322 exports->Set(String::New("events"), String::New(native_events));
1323 exports->Set(String::New("file"), String::New(native_file));
1324 exports->Set(String::New("freelist"), String::New(native_freelist));
1325 exports->Set(String::New("fs"), String::New(native_fs));
1326 exports->Set(String::New("http"), String::New(native_http));
1327 exports->Set(String::New("http_old"), String::New(native_http_old));
1328 exports->Set(String::New("ini"), String::New(native_ini));
1329 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1330 exports->Set(String::New("net"), String::New(native_net));
1331 exports->Set(String::New("posix"), String::New(native_posix));
1332 exports->Set(String::New("querystring"), String::New(native_querystring));
1333 exports->Set(String::New("repl"), String::New(native_repl));
1334 exports->Set(String::New("sys"), String::New(native_sys));
1335 exports->Set(String::New("tcp"), String::New(native_tcp));
1336 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1337 exports->Set(String::New("uri"), String::New(native_uri));
1338 exports->Set(String::New("url"), String::New(native_url));
1339 exports->Set(String::New("utils"), String::New(native_utils));
1340 binding_cache->Set(module, exports);
1345 return ThrowException(Exception::Error(String::New("No such module")));
1348 return scope.Close(exports);
1352 static void Load(int argc, char *argv[]) {
1355 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1356 node::EventEmitter::Initialize(process_template);
1358 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1360 // Add a reference to the global object
1361 Local<Object> global = Context::GetCurrent()->Global();
1362 process->Set(String::NewSymbol("global"), global);
1365 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1366 // process.installPrefix
1367 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1370 #define xstr(s) str(s)
1372 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1376 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1377 arguments->Set(Integer::New(0), String::New(argv[0]));
1378 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1379 Local<String> arg = String::New(argv[i]);
1380 arguments->Set(Integer::New(j), arg);
1383 process->Set(String::NewSymbol("ARGV"), arguments);
1384 process->Set(String::NewSymbol("argv"), arguments);
1386 // create process.env
1387 Local<Object> env = Object::New();
1388 for (i = 0; environ[i]; i++) {
1389 // skip entries without a '=' character
1390 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1391 // create the v8 objects
1392 Local<String> field = String::New(environ[i], j);
1393 Local<String> value = Local<String>();
1394 if (environ[i][j] == '=') {
1395 value = String::New(environ[i]+j+1);
1398 env->Set(field, value);
1400 // assign process.ENV
1401 process->Set(String::NewSymbol("ENV"), env);
1402 process->Set(String::NewSymbol("env"), env);
1404 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1406 // define various internal methods
1407 NODE_SET_METHOD(process, "loop", Loop);
1408 NODE_SET_METHOD(process, "unloop", Unloop);
1409 NODE_SET_METHOD(process, "evalcx", EvalCX);
1410 NODE_SET_METHOD(process, "compile", Compile);
1411 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1412 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
1413 NODE_SET_METHOD(process, "reallyExit", Exit);
1414 NODE_SET_METHOD(process, "chdir", Chdir);
1415 NODE_SET_METHOD(process, "cwd", Cwd);
1416 NODE_SET_METHOD(process, "getuid", GetUid);
1417 NODE_SET_METHOD(process, "setuid", SetUid);
1419 NODE_SET_METHOD(process, "setgid", SetGid);
1420 NODE_SET_METHOD(process, "getgid", GetGid);
1422 NODE_SET_METHOD(process, "umask", Umask);
1423 NODE_SET_METHOD(process, "dlopen", DLOpen);
1424 NODE_SET_METHOD(process, "kill", Kill);
1425 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1426 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1428 NODE_SET_METHOD(process, "binding", Binding);
1430 // Assign the EventEmitter. It was created in main().
1431 process->Set(String::NewSymbol("EventEmitter"),
1432 EventEmitter::constructor_template->GetFunction());
1435 // Initialize the C++ modules..................filename of module
1436 IOWatcher::Initialize(process); // io_watcher.cc
1437 // Not in use at the moment.
1438 //IdleWatcher::Initialize(process); // idle_watcher.cc
1439 Timer::Initialize(process); // timer.cc
1440 DefineConstants(process); // constants.cc
1442 // Compile, execute the src/node.js file. (Which was included as static C
1443 // string in node_natives.h. 'natve_node' is the string containing that
1446 // The node.js file returns a function 'f'
1452 Local<Value> f_value = ExecuteString(String::New(native_node),
1453 String::New("node.js"));
1455 if (try_catch.HasCaught()) {
1456 ReportException(try_catch);
1460 assert(f_value->IsFunction());
1461 Local<Function> f = Local<Function>::Cast(f_value);
1463 // Now we call 'f' with the 'process' variable that we've built up with
1464 // all our bindings. Inside node.js we'll take care of assigning things to
1467 // We start the process this way in order to be more modular. Developers
1468 // who do not like how 'src/node.js' setups the module system but do like
1469 // Node's I/O bindings may want to replace 'f' with their own function.
1471 Local<Value> args[1] = { Local<Value>::New(process) };
1473 f->Call(global, 1, args);
1476 if (try_catch.HasCaught()) {
1477 ReportException(try_catch);
1483 static void PrintHelp();
1485 static void ParseDebugOpt(const char* arg) {
1488 use_debug_agent = true;
1489 if (!strcmp (arg, "--debug-brk")) {
1490 debug_wait_connect = true;
1492 } else if (!strcmp(arg, "--debug")) {
1494 } else if (strstr(arg, "--debug-brk=") == arg) {
1495 debug_wait_connect = true;
1496 p = 1 + strchr(arg, '=');
1497 debug_port = atoi(p);
1498 } else if (strstr(arg, "--debug=") == arg) {
1499 p = 1 + strchr(arg, '=');
1500 debug_port = atoi(p);
1502 if (p && debug_port > 1024 && debug_port < 65536)
1505 fprintf(stderr, "Bad debug option.\n");
1506 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1512 static void PrintHelp() {
1513 printf("Usage: node [options] script.js [arguments] \n"
1515 " -v, --version print node's version\n"
1516 " --debug[=port] enable remote debugging via given TCP port\n"
1517 " without stopping the execution\n"
1518 " --debug-brk[=port] as above, but break in script.js and\n"
1519 " wait for remote debugger to connect\n"
1520 " --v8-options print v8 command line options\n"
1521 " --vars print various compiled-in variables\n"
1523 "Enviromental variables:\n"
1524 "NODE_PATH ':'-separated list of directories\n"
1525 " prefixed to the module search path,\n"
1527 "NODE_DEBUG Print additional debugging output.\n"
1529 "Documentation can be found at http://nodejs.org/api.html"
1530 " or with 'man node'\n");
1533 // Parse node command line arguments.
1534 static void ParseArgs(int *argc, char **argv) {
1535 // TODO use parse opts
1536 for (int i = 1; i < *argc; i++) {
1537 const char *arg = argv[i];
1538 if (strstr(arg, "--debug") == arg) {
1540 argv[i] = const_cast<char*>("");
1541 option_end_index = i;
1542 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1543 printf("%s\n", NODE_VERSION);
1545 } else if (strcmp(arg, "--vars") == 0) {
1546 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1547 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1549 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1552 } else if (strcmp(arg, "--v8-options") == 0) {
1553 argv[i] = const_cast<char*>("--help");
1554 option_end_index = i+1;
1555 } else if (argv[i][0] != '-') {
1556 option_end_index = i-1;
1565 int main(int argc, char *argv[]) {
1566 // Parse a few arguments which are specific to Node.
1567 node::ParseArgs(&argc, argv);
1568 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1569 // in the command line))
1570 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1572 // Error out if we don't have a script argument.
1574 fprintf(stderr, "No script was specified.\n");
1579 // Ignore the SIGPIPE
1580 evcom_ignore_sigpipe();
1582 // Initialize the default ev loop.
1584 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1585 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1586 ev_default_loop(EVBACKEND_SELECT);
1588 ev_default_loop(EVFLAG_AUTO);
1591 ev_prepare_init(&node::next_tick_watcher, node::Tick);
1592 ev_prepare_start(EV_DEFAULT_UC_ &node::next_tick_watcher);
1593 ev_unref(EV_DEFAULT_UC);
1595 ev_idle_init(&node::tick_spinner, node::Spin);
1597 ev_init(&node::gc_timer, node::CheckIdleness);
1598 node::gc_timer.repeat = GC_INTERVAL;
1599 ev_timer_again(EV_DEFAULT_UC_ &node::gc_timer);
1600 ev_unref(EV_DEFAULT_UC);
1602 ev_check_init(&node::gc_check, node::Activity);
1603 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1604 ev_unref(EV_DEFAULT_UC);
1606 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1609 // Setup the EIO thread pool
1610 { // It requires 3, yes 3, watchers.
1611 ev_idle_init(&node::eio_poller, node::DoPoll);
1613 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1614 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1615 ev_unref(EV_DEFAULT_UC);
1617 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1618 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1619 ev_unref(EV_DEFAULT_UC);
1621 eio_init(node::EIOWantPoll, node::EIODonePoll);
1622 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1623 // race conditions. See test/mjsunit/test-eio-race.js
1624 eio_set_max_poll_reqs(10);
1628 HandleScope handle_scope;
1630 V8::SetFatalErrorHandler(node::OnFatalError);
1632 // If the --debug flag was specified then initialize the debug thread.
1633 if (node::use_debug_agent) {
1634 // Initialize the async watcher for receiving messages from the debug
1635 // thread and marshal it into the main thread. DebugMessageCallback()
1636 // is called from the main thread to execute a random bit of javascript
1637 // - which will give V8 control so it can handle whatever new message
1638 // had been received on the debug thread.
1639 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1640 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1641 // Set the callback DebugMessageDispatch which is called from the debug
1643 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1644 // Start the async watcher.
1645 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1646 // unref it so that we exit the event loop despite it being active.
1647 ev_unref(EV_DEFAULT_UC);
1649 // Start the debug thread and it's associated TCP server on port 5858.
1650 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1652 // Crappy check that everything went well. FIXME
1654 // Print out some information.
1655 printf("debugger listening on port %d\n", node::debug_port);
1658 // Create the one and only Context.
1659 Persistent<Context> context = Context::New();
1660 Context::Scope context_scope(context);
1662 // Create all the objects, load modules, do everything.
1663 // so your next reading stop should be node::Load()!
1664 node::Load(argc, argv);
1666 node::Stdio::Flush();