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>
39 #include <node_crypto.h>
46 extern char **environ;
50 static Persistent<Object> process;
52 static Persistent<String> dev_symbol;
53 static Persistent<String> ino_symbol;
54 static Persistent<String> mode_symbol;
55 static Persistent<String> nlink_symbol;
56 static Persistent<String> uid_symbol;
57 static Persistent<String> gid_symbol;
58 static Persistent<String> rdev_symbol;
59 static Persistent<String> size_symbol;
60 static Persistent<String> blksize_symbol;
61 static Persistent<String> blocks_symbol;
62 static Persistent<String> atime_symbol;
63 static Persistent<String> mtime_symbol;
64 static Persistent<String> ctime_symbol;
66 static Persistent<String> rss_symbol;
67 static Persistent<String> vsize_symbol;
68 static Persistent<String> heap_total_symbol;
69 static Persistent<String> heap_used_symbol;
71 static Persistent<String> listeners_symbol;
72 static Persistent<String> uncaught_exception_symbol;
73 static Persistent<String> emit_symbol;
75 static int option_end_index = 0;
76 static bool use_debug_agent = false;
77 static bool debug_wait_connect = false;
78 static int debug_port=5858;
80 static ev_prepare next_tick_watcher;
81 static ev_idle tick_spinner;
82 static bool need_tick_cb;
83 static Persistent<String> tick_callback_sym;
85 static ev_async eio_want_poll_notifier;
86 static ev_async eio_done_poll_notifier;
87 static ev_idle eio_poller;
89 // We need to notify V8 when we're idle so that it can run the garbage
90 // collector. The interface to this is V8::IdleNotification(). It returns
91 // true if the heap hasn't be fully compacted, and needs to be run again.
92 // Returning false means that it doesn't have anymore work to do.
94 // We try to wait for a period of GC_INTERVAL (2 seconds) of idleness, where
95 // idleness means that no libev watchers have been executed. Since
96 // everything in node uses libev watchers, this is a pretty good measure of
97 // idleness. This is done with gc_check, which records the timestamp
98 // last_active on every tick of the event loop, and with gc_timer which
99 // executes every few seconds to measure if
100 // last_active + GC_INTERVAL < ev_now()
101 // If we do find a period of idleness, then we start the gc_idle timer which
102 // will very repaidly call IdleNotification until the heap is fully
104 static ev_tstamp last_active;
105 static ev_timer gc_timer;
106 static ev_check gc_check;
107 static ev_idle gc_idle;
108 static bool needs_gc;
109 #define GC_INTERVAL 2.0
112 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
113 assert(watcher == &gc_timer);
114 assert(revents == EV_TIMER);
116 //fprintf(stderr, "check idle\n");
118 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
120 if (idle_time > GC_INTERVAL) {
123 if (!V8::IdleNotification()) {
124 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
128 gc_timer.repeat = GC_INTERVAL;
129 ev_timer_again(EV_DEFAULT_UC_ watcher);
134 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
135 assert(watcher == &gc_idle);
136 assert(revents == EV_IDLE);
138 //fprintf(stderr, "notify idle\n");
140 if (V8::IdleNotification()) {
141 ev_idle_stop(EV_A_ watcher);
147 static void Activity(EV_P_ ev_check *watcher, int revents) {
148 assert(watcher == &gc_check);
149 assert(revents == EV_CHECK);
151 int pending = ev_pending_count(EV_DEFAULT_UC);
153 // Don't count GC watchers as activity.
155 pending -= ev_is_pending(&gc_timer);
156 pending -= ev_is_pending(&gc_idle);
157 pending -= ev_is_pending(&next_tick_watcher);
158 //if (ev_is_pending(&gc_check)) pending--; // This probably never happens?
160 //fprintf(stderr, "activity, pending: %d\n", pending);
163 last_active = ev_now(EV_DEFAULT_UC);
164 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
167 gc_timer.repeat = GC_INTERVAL;
168 ev_timer_again(EV_DEFAULT_UC_ &gc_timer);
176 static Handle<Value> NeedTickCallback(const Arguments& args) {
179 ev_idle_start(EV_DEFAULT_UC_ &tick_spinner);
184 static void Spin(EV_P_ ev_idle *watcher, int revents) {
185 assert(watcher == &tick_spinner);
186 assert(revents == EV_IDLE);
190 static void Tick(EV_P_ ev_prepare *watcher, int revents) {
191 assert(watcher == &next_tick_watcher);
192 assert(revents == EV_PREPARE);
194 // Avoid entering a V8 scope.
195 if (!need_tick_cb) return;
197 need_tick_cb = false;
198 ev_idle_stop(EV_DEFAULT_UC_ &tick_spinner);
202 if (tick_callback_sym.IsEmpty()) {
203 // Lazily set the symbol
205 Persistent<String>::New(String::NewSymbol("_tickCallback"));
208 Local<Value> cb_v = process->Get(tick_callback_sym);
209 if (!cb_v->IsFunction()) return;
210 Local<Function> cb = Local<Function>::Cast(cb_v);
214 cb->Call(process, 0, NULL);
216 if (try_catch.HasCaught()) {
217 FatalException(try_catch);
222 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
223 assert(watcher == &eio_poller);
224 assert(revents == EV_IDLE);
226 //printf("eio_poller\n");
228 if (eio_poll() != -1) {
229 //printf("eio_poller stop\n");
230 ev_idle_stop(EV_DEFAULT_UC_ watcher);
235 // Called from the main thread.
236 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
237 assert(watcher == &eio_want_poll_notifier);
238 assert(revents == EV_ASYNC);
240 //printf("want poll notifier\n");
242 if (eio_poll() == -1) {
243 //printf("eio_poller start\n");
244 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
249 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
250 assert(watcher == &eio_done_poll_notifier);
251 assert(revents == EV_ASYNC);
253 //printf("done poll notifier\n");
255 if (eio_poll() != -1) {
256 //printf("eio_poller stop\n");
257 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
262 // EIOWantPoll() is called from the EIO thread pool each time an EIO
263 // request (that is, one of the node.fs.* functions) has completed.
264 static void EIOWantPoll(void) {
265 // Signal the main thread that eio_poll need to be processed.
266 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
270 static void EIODonePoll(void) {
271 // Signal the main thread that we should stop calling eio_poll().
272 // from the idle watcher.
273 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
277 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
280 if (!encoding_v->IsString()) return _default;
282 String::Utf8Value encoding(encoding_v->ToString());
284 if (strcasecmp(*encoding, "utf8") == 0) {
286 } else if (strcasecmp(*encoding, "utf-8") == 0) {
288 } else if (strcasecmp(*encoding, "ascii") == 0) {
290 } else if (strcasecmp(*encoding, "binary") == 0) {
292 } else if (strcasecmp(*encoding, "raw") == 0) {
293 fprintf(stderr, "'raw' (array of integers) has been removed. "
296 } else if (strcasecmp(*encoding, "raws") == 0) {
297 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
298 "Please update your code.\n");
305 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
308 if (!len) return scope.Close(String::Empty());
310 if (encoding == BINARY) {
311 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
312 uint16_t * twobytebuf = new uint16_t[len];
313 for (size_t i = 0; i < len; i++) {
314 // XXX is the following line platform independent?
315 twobytebuf[i] = cbuf[i];
317 Local<String> chunk = String::New(twobytebuf, len);
318 delete [] twobytebuf; // TODO use ExternalTwoByteString?
319 return scope.Close(chunk);
322 // utf8 or ascii encoding
323 Local<String> chunk = String::New((const char*)buf, len);
324 return scope.Close(chunk);
327 // Returns -1 if the handle was not valid for decoding
328 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
331 if (val->IsArray()) {
332 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
338 Local<String> str = val->ToString();
340 if (encoding == UTF8) return str->Utf8Length();
342 return str->Length();
346 # define MIN(a, b) ((a) < (b) ? (a) : (b))
349 // Returns number of bytes written.
350 ssize_t DecodeWrite(char *buf,
352 v8::Handle<v8::Value> val,
353 enum encoding encoding) {
357 // A lot of improvement can be made here. See:
358 // http://code.google.com/p/v8/issues/detail?id=270
359 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
360 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
362 if (val->IsArray()) {
363 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
369 Local<String> str = val->ToString();
371 if (encoding == UTF8) {
372 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
376 if (encoding == ASCII) {
377 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
381 // THIS IS AWFUL!!! FIXME
383 assert(encoding == BINARY);
385 uint16_t * twobytebuf = new uint16_t[buflen];
387 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
389 for (size_t i = 0; i < buflen; i++) {
390 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
395 delete [] twobytebuf;
400 static Persistent<FunctionTemplate> stats_constructor_template;
402 Local<Object> BuildStatsObject(struct stat * s) {
405 if (dev_symbol.IsEmpty()) {
406 dev_symbol = NODE_PSYMBOL("dev");
407 ino_symbol = NODE_PSYMBOL("ino");
408 mode_symbol = NODE_PSYMBOL("mode");
409 nlink_symbol = NODE_PSYMBOL("nlink");
410 uid_symbol = NODE_PSYMBOL("uid");
411 gid_symbol = NODE_PSYMBOL("gid");
412 rdev_symbol = NODE_PSYMBOL("rdev");
413 size_symbol = NODE_PSYMBOL("size");
414 blksize_symbol = NODE_PSYMBOL("blksize");
415 blocks_symbol = NODE_PSYMBOL("blocks");
416 atime_symbol = NODE_PSYMBOL("atime");
417 mtime_symbol = NODE_PSYMBOL("mtime");
418 ctime_symbol = NODE_PSYMBOL("ctime");
421 Local<Object> stats =
422 stats_constructor_template->GetFunction()->NewInstance();
424 /* ID of device containing file */
425 stats->Set(dev_symbol, Integer::New(s->st_dev));
428 stats->Set(ino_symbol, Integer::New(s->st_ino));
431 stats->Set(mode_symbol, Integer::New(s->st_mode));
433 /* number of hard links */
434 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
436 /* user ID of owner */
437 stats->Set(uid_symbol, Integer::New(s->st_uid));
439 /* group ID of owner */
440 stats->Set(gid_symbol, Integer::New(s->st_gid));
442 /* device ID (if special file) */
443 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
445 /* total size, in bytes */
446 stats->Set(size_symbol, Integer::New(s->st_size));
448 /* blocksize for filesystem I/O */
449 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
451 /* number of blocks allocated */
452 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
454 /* time of last access */
455 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
457 /* time of last modification */
458 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
460 /* time of last status change */
461 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
463 return scope.Close(stats);
467 // Extracts a C str from a V8 Utf8Value.
468 const char* ToCString(const v8::String::Utf8Value& value) {
469 return *value ? *value : "<str conversion failed>";
472 static void ReportException(TryCatch &try_catch, bool show_line = false) {
473 Handle<Message> message = try_catch.Message();
475 Handle<Value> error = try_catch.Exception();
476 Handle<String> stack;
478 if (error->IsObject()) {
479 Handle<Object> obj = Handle<Object>::Cast(error);
480 Handle<Value> raw_stack = obj->Get(String::New("stack"));
481 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
484 if (show_line && !message.IsEmpty()) {
485 // Print (filename):(line number): (message).
486 String::Utf8Value filename(message->GetScriptResourceName());
487 const char* filename_string = ToCString(filename);
488 int linenum = message->GetLineNumber();
489 fprintf(stderr, "%s:%i\n", filename_string, linenum);
490 // Print line of source code.
491 String::Utf8Value sourceline(message->GetSourceLine());
492 const char* sourceline_string = ToCString(sourceline);
493 fprintf(stderr, "%s\n", sourceline_string);
494 // Print wavy underline (GetUnderline is deprecated).
495 int start = message->GetStartColumn();
496 for (int i = 0; i < start; i++) {
497 fprintf(stderr, " ");
499 int end = message->GetEndColumn();
500 for (int i = start; i < end; i++) {
501 fprintf(stderr, "^");
503 fprintf(stderr, "\n");
506 if (stack.IsEmpty()) {
507 message->PrintCurrentStackTrace(stderr);
509 String::Utf8Value trace(stack);
510 fprintf(stderr, "%s\n", *trace);
515 // Executes a str within the current v8 context.
516 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
520 Local<Script> script = Script::Compile(source, filename);
521 if (script.IsEmpty()) {
522 ReportException(try_catch);
526 Local<Value> result = script->Run();
527 if (result.IsEmpty()) {
528 ReportException(try_catch);
532 return scope.Close(result);
535 static Handle<Value> ByteLength(const Arguments& args) {
538 if (args.Length() < 1 || !args[0]->IsString()) {
539 return ThrowException(Exception::Error(String::New("Bad argument.")));
542 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
544 return scope.Close(length);
547 static Handle<Value> Loop(const Arguments& args) {
549 assert(args.Length() == 0);
551 // TODO Probably don't need to start this each time.
552 // Avoids failing on test/mjsunit/test-eio-race3.js though
553 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
555 ev_loop(EV_DEFAULT_UC_ 0);
559 static Handle<Value> Unloop(const Arguments& args) {
560 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
562 int how = EVUNLOOP_ONE;
563 if (args[0]->IsString()) {
564 String::Utf8Value how_s(args[0]->ToString());
565 if (0 == strcmp(*how_s, "all")) {
569 ev_unloop(EV_DEFAULT_ how);
573 static Handle<Value> Chdir(const Arguments& args) {
576 if (args.Length() != 1 || !args[0]->IsString()) {
577 return ThrowException(Exception::Error(String::New("Bad argument.")));
580 String::Utf8Value path(args[0]->ToString());
582 int r = chdir(*path);
585 return ThrowException(Exception::Error(String::New(strerror(errno))));
591 static Handle<Value> Cwd(const Arguments& args) {
593 assert(args.Length() == 0);
595 char output[PATH_MAX];
596 char *r = getcwd(output, PATH_MAX);
598 return ThrowException(Exception::Error(String::New(strerror(errno))));
600 Local<String> cwd = String::New(output);
602 return scope.Close(cwd);
605 static Handle<Value> Umask(const Arguments& args){
608 if(args.Length() < 1) {
612 else if(!args[0]->IsInt32()) {
613 return ThrowException(Exception::TypeError(
614 String::New("argument must be an integer.")));
617 old = umask((mode_t)args[0]->Uint32Value());
619 return scope.Close(Uint32::New(old));
623 static Handle<Value> GetUid(const Arguments& args) {
625 assert(args.Length() == 0);
627 return scope.Close(Integer::New(uid));
630 static Handle<Value> GetGid(const Arguments& args) {
632 assert(args.Length() == 0);
634 return scope.Close(Integer::New(gid));
638 static Handle<Value> SetGid(const Arguments& args) {
641 if (args.Length() < 1) {
642 return ThrowException(Exception::Error(
643 String::New("setgid requires 1 argument")));
646 Local<Integer> given_gid = args[0]->ToInteger();
647 int gid = given_gid->Int32Value();
649 if ((result = setgid(gid)) != 0) {
650 return ThrowException(Exception::Error(String::New(strerror(errno))));
655 static Handle<Value> SetUid(const Arguments& args) {
658 if (args.Length() < 1) {
659 return ThrowException(Exception::Error(
660 String::New("setuid requires 1 argument")));
663 Local<Integer> given_uid = args[0]->ToInteger();
664 int uid = given_uid->Int32Value();
666 if ((result = setuid(uid)) != 0) {
667 return ThrowException(Exception::Error(String::New(strerror(errno))));
673 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
677 exit(args[0]->IntegerValue());
682 #define HAVE_GETMEM 1
683 #include <unistd.h> /* getpagesize() */
685 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
686 #define PROCFS_FILE_OFFSET_BITS_HACK 1
687 #undef _FILE_OFFSET_BITS
689 #define PROCFS_FILE_OFFSET_BITS_HACK 0
694 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
695 #define _FILE_OFFSET_BITS 64
698 int getmem(size_t *rss, size_t *vsize) {
699 pid_t pid = getpid();
701 size_t page_size = getpagesize();
703 sprintf(pidpath, "/proc/%d/psinfo", pid);
706 FILE *f = fopen(pidpath, "r");
709 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
716 *vsize = (size_t) psinfo.pr_size * page_size;
717 *rss = (size_t) psinfo.pr_rssize * 1024;
727 #define HAVE_GETMEM 1
729 #include <sys/param.h>
730 #include <sys/sysctl.h>
731 #include <sys/user.h>
736 int getmem(size_t *rss, size_t *vsize) {
738 struct kinfo_proc *kinfo = NULL;
741 size_t page_size = getpagesize();
745 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
746 if (kd == NULL) goto error;
748 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
749 if (kinfo == NULL) goto error;
751 *rss = kinfo->ki_rssize * page_size;
752 *vsize = kinfo->ki_size;
759 if (kd) kvm_close(kd);
762 #endif // __FreeBSD__
766 #define HAVE_GETMEM 1
767 /* Researched by Tim Becker and Michael Knight
768 * http://blog.kuriositaet.de/?p=257
771 #include <mach/task.h>
772 #include <mach/mach_init.h>
774 int getmem(size_t *rss, size_t *vsize) {
775 struct task_basic_info t_info;
776 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
778 int r = task_info(mach_task_self(),
780 (task_info_t)&t_info,
783 if (r != KERN_SUCCESS) return -1;
785 *rss = t_info.resident_size;
786 *vsize = t_info.virtual_size;
793 # define HAVE_GETMEM 1
794 # include <sys/param.h> /* for MAXPATHLEN */
796 int getmem(size_t *rss, size_t *vsize) {
797 FILE *f = fopen("/proc/self/stat", "r");
802 char buffer[MAXPATHLEN];
803 size_t page_size = getpagesize();
806 if (fscanf(f, "%d ", &itmp) == 0) goto error;
808 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
810 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
812 if (fscanf (f, "%d ", &itmp) == 0) goto error;
814 if (fscanf (f, "%d ", &itmp) == 0) goto error;
816 if (fscanf (f, "%d ", &itmp) == 0) goto error;
818 if (fscanf (f, "%d ", &itmp) == 0) goto error;
819 /* TTY owner process group */
820 if (fscanf (f, "%d ", &itmp) == 0) goto error;
822 if (fscanf (f, "%u ", &itmp) == 0) goto error;
823 /* Minor faults (no memory page) */
824 if (fscanf (f, "%u ", &itmp) == 0) goto error;
825 /* Minor faults, children */
826 if (fscanf (f, "%u ", &itmp) == 0) goto error;
827 /* Major faults (memory page faults) */
828 if (fscanf (f, "%u ", &itmp) == 0) goto error;
829 /* Major faults, children */
830 if (fscanf (f, "%u ", &itmp) == 0) goto error;
832 if (fscanf (f, "%d ", &itmp) == 0) goto error;
834 if (fscanf (f, "%d ", &itmp) == 0) goto error;
835 /* utime, children */
836 if (fscanf (f, "%d ", &itmp) == 0) goto error;
837 /* stime, children */
838 if (fscanf (f, "%d ", &itmp) == 0) goto error;
839 /* jiffies remaining in current time slice */
840 if (fscanf (f, "%d ", &itmp) == 0) goto error;
842 if (fscanf (f, "%d ", &itmp) == 0) goto error;
843 /* jiffies until next timeout */
844 if (fscanf (f, "%u ", &itmp) == 0) goto error;
845 /* jiffies until next SIGALRM */
846 if (fscanf (f, "%u ", &itmp) == 0) goto error;
847 /* start time (jiffies since system boot) */
848 if (fscanf (f, "%d ", &itmp) == 0) goto error;
850 /* Virtual memory size */
851 if (fscanf (f, "%u ", &itmp) == 0) goto error;
852 *vsize = (size_t) itmp;
854 /* Resident set size */
855 if (fscanf (f, "%u ", &itmp) == 0) goto error;
856 *rss = (size_t) itmp * page_size;
859 if (fscanf (f, "%u ", &itmp) == 0) goto error;
861 if (fscanf (f, "%u ", &itmp) == 0) goto error;
863 if (fscanf (f, "%u ", &itmp) == 0) goto error;
865 if (fscanf (f, "%u ", &itmp) == 0) goto error;
877 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
879 assert(args.Length() == 0);
882 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
886 int r = getmem(&rss, &vsize);
889 return ThrowException(Exception::Error(String::New(strerror(errno))));
892 Local<Object> info = Object::New();
894 if (rss_symbol.IsEmpty()) {
895 rss_symbol = NODE_PSYMBOL("rss");
896 vsize_symbol = NODE_PSYMBOL("vsize");
897 heap_total_symbol = NODE_PSYMBOL("heapTotal");
898 heap_used_symbol = NODE_PSYMBOL("heapUsed");
901 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
902 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
905 HeapStatistics v8_heap_stats;
906 V8::GetHeapStatistics(&v8_heap_stats);
907 info->Set(heap_total_symbol,
908 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
909 info->Set(heap_used_symbol,
910 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
912 return scope.Close(info);
917 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
920 if (args.Length() < 1 || !args[0]->IsNumber()) {
921 return ThrowException(Exception::Error(String::New("Bad argument.")));
924 pid_t pid = args[0]->IntegerValue();
928 if (args.Length() >= 2) {
929 if (args[1]->IsNumber()) {
930 sig = args[1]->Int32Value();
931 } else if (args[1]->IsString()) {
932 Local<String> signame = args[1]->ToString();
934 Local<Value> sig_v = process->Get(signame);
935 if (!sig_v->IsNumber()) {
936 return ThrowException(Exception::Error(String::New("Unknown signal")));
938 sig = sig_v->Int32Value();
942 int r = kill(pid, sig);
945 return ThrowException(Exception::Error(String::New(strerror(errno))));
951 typedef void (*extInit)(Handle<Object> exports);
953 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
955 Handle<Value> DLOpen(const v8::Arguments& args) {
958 if (args.Length() < 2) return Undefined();
960 String::Utf8Value filename(args[0]->ToString()); // Cast
961 Local<Object> target = args[1]->ToObject(); // Cast
963 // Actually call dlopen().
964 // FIXME: This is a blocking function and should be called asynchronously!
965 // This function should be moved to file.cc and use libeio to make this
967 void *handle = dlopen(*filename, RTLD_LAZY);
970 if (handle == NULL) {
971 Local<Value> exception = Exception::Error(String::New(dlerror()));
972 return ThrowException(exception);
975 // Get the init() function from the dynamically shared object.
976 void *init_handle = dlsym(handle, "init");
977 // Error out if not found.
978 if (init_handle == NULL) {
979 Local<Value> exception =
980 Exception::Error(String::New("No 'init' symbol found in module."));
981 return ThrowException(exception);
983 extInit init = (extInit)(init_handle); // Cast
985 // Execute the C++ module
991 // evalcx(code, sandbox={})
992 // Executes code in a new context
993 Handle<Value> EvalCX(const Arguments& args) {
996 Local<String> code = args[0]->ToString();
997 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
999 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
1000 : String::New("evalcx");
1001 // Create the new context
1002 Persistent<Context> context = Context::New();
1004 // Enter and compile script
1007 // Copy objects from global context, to our brand new context
1008 Handle<Array> keys = sandbox->GetPropertyNames();
1011 for (i = 0; i < keys->Length(); i++) {
1012 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1013 Handle<Value> value = sandbox->Get(key);
1014 context->Global()->Set(key, value);
1020 Local<Script> script = Script::Compile(code, filename);
1021 Handle<Value> result;
1023 if (script.IsEmpty()) {
1024 result = ThrowException(try_catch.Exception());
1026 result = script->Run();
1027 if (result.IsEmpty()) {
1028 result = ThrowException(try_catch.Exception());
1030 // success! copy changes back onto the sandbox object.
1031 keys = context->Global()->GetPropertyNames();
1032 for (i = 0; i < keys->Length(); i++) {
1033 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1034 Handle<Value> value = context->Global()->Get(key);
1035 sandbox->Set(key, value);
1040 // Clean up, clean up, everybody everywhere!
1041 context->DetachGlobal();
1045 return scope.Close(result);
1048 Handle<Value> Compile(const Arguments& args) {
1051 if (args.Length() < 2) {
1052 return ThrowException(Exception::TypeError(
1053 String::New("needs two arguments.")));
1056 Local<String> source = args[0]->ToString();
1057 Local<String> filename = args[1]->ToString();
1061 Local<Script> script = Script::Compile(source, filename);
1062 if (try_catch.HasCaught()) {
1063 // Hack because I can't get a proper stacktrace on SyntaxError
1064 ReportException(try_catch, true);
1068 Local<Value> result = script->Run();
1069 if (try_catch.HasCaught()) return try_catch.ReThrow();
1071 return scope.Close(result);
1074 static void OnFatalError(const char* location, const char* message) {
1076 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1078 fprintf(stderr, "FATAL ERROR: %s\n", message);
1083 static int uncaught_exception_counter = 0;
1085 void FatalException(TryCatch &try_catch) {
1088 // Check if uncaught_exception_counter indicates a recursion
1089 if (uncaught_exception_counter > 0) {
1090 ReportException(try_catch);
1094 if (listeners_symbol.IsEmpty()) {
1095 listeners_symbol = NODE_PSYMBOL("listeners");
1096 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1097 emit_symbol = NODE_PSYMBOL("emit");
1100 Local<Value> listeners_v = process->Get(listeners_symbol);
1101 assert(listeners_v->IsFunction());
1103 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1105 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1106 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1107 Local<Value> ret = listeners->Call(process, 1, argv);
1109 assert(ret->IsArray());
1111 Local<Array> listener_array = Local<Array>::Cast(ret);
1113 uint32_t length = listener_array->Length();
1114 // Report and exit if process has no "uncaughtException" listener
1116 ReportException(try_catch);
1120 // Otherwise fire the process "uncaughtException" event
1121 Local<Value> emit_v = process->Get(emit_symbol);
1122 assert(emit_v->IsFunction());
1124 Local<Function> emit = Local<Function>::Cast(emit_v);
1126 Local<Value> error = try_catch.Exception();
1127 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1129 uncaught_exception_counter++;
1130 emit->Call(process, 2, event_argv);
1131 // Decrement so we know if the next exception is a recursion or not
1132 uncaught_exception_counter--;
1136 static ev_async debug_watcher;
1137 volatile static bool debugger_msg_pending = false;
1139 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1141 assert(watcher == &debug_watcher);
1142 assert(revents == EV_ASYNC);
1143 Debug::ProcessDebugMessages();
1146 static void DebugMessageDispatch(void) {
1147 // This function is called from V8's debug thread when a debug TCP client
1148 // has sent a message.
1150 // Send a signal to our main thread saying that it should enter V8 to
1151 // handle the message.
1152 debugger_msg_pending = true;
1153 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1156 static Handle<Value> CheckBreak(const Arguments& args) {
1158 assert(args.Length() == 0);
1160 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1161 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1162 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1163 // get it to halt until Eclipse connects.
1165 if (!debug_wait_connect)
1168 printf("Waiting for remote debugger connection...\n");
1170 const int halfSecond = 50;
1171 const int tenMs=10000;
1172 debugger_msg_pending = false;
1174 if (debugger_msg_pending) {
1175 Debug::DebugBreak();
1176 Debug::ProcessDebugMessages();
1177 debugger_msg_pending = false;
1179 // wait for 500 msec of silence from remote debugger
1180 int cnt = halfSecond;
1182 debugger_msg_pending = false;
1184 if (debugger_msg_pending) {
1185 debugger_msg_pending = false;
1196 Persistent<Object> binding_cache;
1198 static Handle<Value> Binding(const Arguments& args) {
1201 Local<String> module = args[0]->ToString();
1202 String::Utf8Value module_v(module);
1204 if (binding_cache.IsEmpty()) {
1205 binding_cache = Persistent<Object>::New(Object::New());
1208 Local<Object> exports;
1210 // TODO DRY THIS UP!
1212 if (!strcmp(*module_v, "stdio")) {
1213 if (binding_cache->Has(module)) {
1214 exports = binding_cache->Get(module)->ToObject();
1216 exports = Object::New();
1217 Stdio::Initialize(exports);
1218 binding_cache->Set(module, exports);
1221 } else if (!strcmp(*module_v, "http")) {
1222 if (binding_cache->Has(module)) {
1223 exports = binding_cache->Get(module)->ToObject();
1225 // Warning: When calling requireBinding('http') from javascript then
1226 // be sure that you call requireBinding('tcp') before it.
1227 assert(binding_cache->Has(String::New("tcp")));
1228 exports = Object::New();
1229 HTTPServer::Initialize(exports);
1230 HTTPConnection::Initialize(exports);
1231 binding_cache->Set(module, exports);
1234 } else if (!strcmp(*module_v, "tcp")) {
1235 if (binding_cache->Has(module)) {
1236 exports = binding_cache->Get(module)->ToObject();
1238 exports = Object::New();
1239 Server::Initialize(exports);
1240 Connection::Initialize(exports);
1241 binding_cache->Set(module, exports);
1244 } else if (!strcmp(*module_v, "cares")) {
1245 if (binding_cache->Has(module)) {
1246 exports = binding_cache->Get(module)->ToObject();
1248 exports = Object::New();
1249 Cares::Initialize(exports);
1250 binding_cache->Set(module, exports);
1253 } else if (!strcmp(*module_v, "fs")) {
1254 if (binding_cache->Has(module)) {
1255 exports = binding_cache->Get(module)->ToObject();
1257 exports = Object::New();
1259 // Initialize the stats object
1260 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1261 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1262 exports->Set(String::NewSymbol("Stats"),
1263 stats_constructor_template->GetFunction());
1264 StatWatcher::Initialize(exports);
1265 File::Initialize(exports);
1266 binding_cache->Set(module, exports);
1269 } else if (!strcmp(*module_v, "signal_watcher")) {
1270 if (binding_cache->Has(module)) {
1271 exports = binding_cache->Get(module)->ToObject();
1273 exports = Object::New();
1274 SignalWatcher::Initialize(exports);
1275 binding_cache->Set(module, exports);
1278 } else if (!strcmp(*module_v, "net")) {
1279 if (binding_cache->Has(module)) {
1280 exports = binding_cache->Get(module)->ToObject();
1282 exports = Object::New();
1284 binding_cache->Set(module, exports);
1287 } else if (!strcmp(*module_v, "http_parser")) {
1288 if (binding_cache->Has(module)) {
1289 exports = binding_cache->Get(module)->ToObject();
1291 exports = Object::New();
1292 InitHttpParser(exports);
1293 binding_cache->Set(module, exports);
1296 } else if (!strcmp(*module_v, "child_process")) {
1297 if (binding_cache->Has(module)) {
1298 exports = binding_cache->Get(module)->ToObject();
1300 exports = Object::New();
1301 ChildProcess::Initialize(exports);
1302 binding_cache->Set(module, exports);
1305 } else if (!strcmp(*module_v, "buffer")) {
1306 if (binding_cache->Has(module)) {
1307 exports = binding_cache->Get(module)->ToObject();
1309 exports = Object::New();
1310 Buffer::Initialize(exports);
1311 binding_cache->Set(module, exports);
1314 } else if (!strcmp(*module_v, "crypto")) {
1315 if (binding_cache->Has(module)) {
1316 exports = binding_cache->Get(module)->ToObject();
1318 exports = Object::New();
1319 InitCrypto(exports);
1320 binding_cache->Set(module, exports);
1323 } else if (!strcmp(*module_v, "natives")) {
1324 if (binding_cache->Has(module)) {
1325 exports = binding_cache->Get(module)->ToObject();
1327 exports = Object::New();
1328 // Explicitly define native sources.
1329 // TODO DRY/automate this?
1330 exports->Set(String::New("assert"), String::New(native_assert));
1331 exports->Set(String::New("buffer"), String::New(native_buffer));
1332 exports->Set(String::New("child_process"),String::New(native_child_process));
1333 exports->Set(String::New("dns"), String::New(native_dns));
1334 exports->Set(String::New("events"), String::New(native_events));
1335 exports->Set(String::New("file"), String::New(native_file));
1336 exports->Set(String::New("freelist"), String::New(native_freelist));
1337 exports->Set(String::New("fs"), String::New(native_fs));
1338 exports->Set(String::New("http"), String::New(native_http));
1339 exports->Set(String::New("http_old"), String::New(native_http_old));
1340 exports->Set(String::New("crypto"), String::New(native_crypto));
1341 exports->Set(String::New("ini"), String::New(native_ini));
1342 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1343 exports->Set(String::New("net"), String::New(native_net));
1344 exports->Set(String::New("posix"), String::New(native_posix));
1345 exports->Set(String::New("querystring"), String::New(native_querystring));
1346 exports->Set(String::New("repl"), String::New(native_repl));
1347 exports->Set(String::New("sys"), String::New(native_sys));
1348 exports->Set(String::New("tcp"), String::New(native_tcp));
1349 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1350 exports->Set(String::New("uri"), String::New(native_uri));
1351 exports->Set(String::New("url"), String::New(native_url));
1352 exports->Set(String::New("utils"), String::New(native_utils));
1353 binding_cache->Set(module, exports);
1358 return ThrowException(Exception::Error(String::New("No such module")));
1361 return scope.Close(exports);
1365 static void Load(int argc, char *argv[]) {
1368 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1369 node::EventEmitter::Initialize(process_template);
1371 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1373 // Add a reference to the global object
1374 Local<Object> global = Context::GetCurrent()->Global();
1375 process->Set(String::NewSymbol("global"), global);
1378 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1379 // process.installPrefix
1380 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1383 #define xstr(s) str(s)
1385 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1389 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1390 arguments->Set(Integer::New(0), String::New(argv[0]));
1391 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1392 Local<String> arg = String::New(argv[i]);
1393 arguments->Set(Integer::New(j), arg);
1396 process->Set(String::NewSymbol("ARGV"), arguments);
1397 process->Set(String::NewSymbol("argv"), arguments);
1399 // create process.env
1400 Local<Object> env = Object::New();
1401 for (i = 0; environ[i]; i++) {
1402 // skip entries without a '=' character
1403 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1404 // create the v8 objects
1405 Local<String> field = String::New(environ[i], j);
1406 Local<String> value = Local<String>();
1407 if (environ[i][j] == '=') {
1408 value = String::New(environ[i]+j+1);
1411 env->Set(field, value);
1413 // assign process.ENV
1414 process->Set(String::NewSymbol("ENV"), env);
1415 process->Set(String::NewSymbol("env"), env);
1417 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1419 // define various internal methods
1420 NODE_SET_METHOD(process, "loop", Loop);
1421 NODE_SET_METHOD(process, "unloop", Unloop);
1422 NODE_SET_METHOD(process, "evalcx", EvalCX);
1423 NODE_SET_METHOD(process, "compile", Compile);
1424 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1425 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
1426 NODE_SET_METHOD(process, "reallyExit", Exit);
1427 NODE_SET_METHOD(process, "chdir", Chdir);
1428 NODE_SET_METHOD(process, "cwd", Cwd);
1429 NODE_SET_METHOD(process, "getuid", GetUid);
1430 NODE_SET_METHOD(process, "setuid", SetUid);
1432 NODE_SET_METHOD(process, "setgid", SetGid);
1433 NODE_SET_METHOD(process, "getgid", GetGid);
1435 NODE_SET_METHOD(process, "umask", Umask);
1436 NODE_SET_METHOD(process, "dlopen", DLOpen);
1437 NODE_SET_METHOD(process, "kill", Kill);
1438 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1439 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1441 NODE_SET_METHOD(process, "binding", Binding);
1443 // Assign the EventEmitter. It was created in main().
1444 process->Set(String::NewSymbol("EventEmitter"),
1445 EventEmitter::constructor_template->GetFunction());
1448 // Initialize the C++ modules..................filename of module
1449 IOWatcher::Initialize(process); // io_watcher.cc
1450 // Not in use at the moment.
1451 //IdleWatcher::Initialize(process); // idle_watcher.cc
1452 Timer::Initialize(process); // timer.cc
1453 DefineConstants(process); // constants.cc
1455 // Compile, execute the src/node.js file. (Which was included as static C
1456 // string in node_natives.h. 'natve_node' is the string containing that
1459 // The node.js file returns a function 'f'
1465 Local<Value> f_value = ExecuteString(String::New(native_node),
1466 String::New("node.js"));
1468 if (try_catch.HasCaught()) {
1469 ReportException(try_catch);
1473 assert(f_value->IsFunction());
1474 Local<Function> f = Local<Function>::Cast(f_value);
1476 // Now we call 'f' with the 'process' variable that we've built up with
1477 // all our bindings. Inside node.js we'll take care of assigning things to
1480 // We start the process this way in order to be more modular. Developers
1481 // who do not like how 'src/node.js' setups the module system but do like
1482 // Node's I/O bindings may want to replace 'f' with their own function.
1484 Local<Value> args[1] = { Local<Value>::New(process) };
1486 f->Call(global, 1, args);
1489 if (try_catch.HasCaught()) {
1490 ReportException(try_catch);
1496 static void PrintHelp();
1498 static void ParseDebugOpt(const char* arg) {
1501 use_debug_agent = true;
1502 if (!strcmp (arg, "--debug-brk")) {
1503 debug_wait_connect = true;
1505 } else if (!strcmp(arg, "--debug")) {
1507 } else if (strstr(arg, "--debug-brk=") == arg) {
1508 debug_wait_connect = true;
1509 p = 1 + strchr(arg, '=');
1510 debug_port = atoi(p);
1511 } else if (strstr(arg, "--debug=") == arg) {
1512 p = 1 + strchr(arg, '=');
1513 debug_port = atoi(p);
1515 if (p && debug_port > 1024 && debug_port < 65536)
1518 fprintf(stderr, "Bad debug option.\n");
1519 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1525 static void PrintHelp() {
1526 printf("Usage: node [options] script.js [arguments] \n"
1528 " -v, --version print node's version\n"
1529 " --debug[=port] enable remote debugging via given TCP port\n"
1530 " without stopping the execution\n"
1531 " --debug-brk[=port] as above, but break in script.js and\n"
1532 " wait for remote debugger to connect\n"
1533 " --v8-options print v8 command line options\n"
1534 " --vars print various compiled-in variables\n"
1536 "Enviromental variables:\n"
1537 "NODE_PATH ':'-separated list of directories\n"
1538 " prefixed to the module search path,\n"
1540 "NODE_DEBUG Print additional debugging output.\n"
1542 "Documentation can be found at http://nodejs.org/api.html"
1543 " or with 'man node'\n");
1546 // Parse node command line arguments.
1547 static void ParseArgs(int *argc, char **argv) {
1548 // TODO use parse opts
1549 for (int i = 1; i < *argc; i++) {
1550 const char *arg = argv[i];
1551 if (strstr(arg, "--debug") == arg) {
1553 argv[i] = const_cast<char*>("");
1554 option_end_index = i;
1555 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1556 printf("%s\n", NODE_VERSION);
1558 } else if (strcmp(arg, "--vars") == 0) {
1559 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1560 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1562 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1565 } else if (strcmp(arg, "--v8-options") == 0) {
1566 argv[i] = const_cast<char*>("--help");
1567 option_end_index = i+1;
1568 } else if (argv[i][0] != '-') {
1569 option_end_index = i-1;
1578 int main(int argc, char *argv[]) {
1579 // Parse a few arguments which are specific to Node.
1580 node::ParseArgs(&argc, argv);
1581 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1582 // in the command line))
1583 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1585 // Error out if we don't have a script argument.
1587 fprintf(stderr, "No script was specified.\n");
1592 // Ignore the SIGPIPE
1593 evcom_ignore_sigpipe();
1595 // Initialize the default ev loop.
1597 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1598 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1599 ev_default_loop(EVBACKEND_SELECT);
1601 ev_default_loop(EVFLAG_AUTO);
1604 ev_prepare_init(&node::next_tick_watcher, node::Tick);
1605 ev_prepare_start(EV_DEFAULT_UC_ &node::next_tick_watcher);
1606 ev_unref(EV_DEFAULT_UC);
1608 ev_idle_init(&node::tick_spinner, node::Spin);
1610 ev_init(&node::gc_timer, node::CheckIdleness);
1611 node::gc_timer.repeat = GC_INTERVAL;
1612 ev_timer_again(EV_DEFAULT_UC_ &node::gc_timer);
1613 ev_unref(EV_DEFAULT_UC);
1615 ev_check_init(&node::gc_check, node::Activity);
1616 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1617 ev_unref(EV_DEFAULT_UC);
1619 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1622 // Setup the EIO thread pool
1623 { // It requires 3, yes 3, watchers.
1624 ev_idle_init(&node::eio_poller, node::DoPoll);
1626 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1627 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1628 ev_unref(EV_DEFAULT_UC);
1630 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1631 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1632 ev_unref(EV_DEFAULT_UC);
1634 eio_init(node::EIOWantPoll, node::EIODonePoll);
1635 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1636 // race conditions. See test/mjsunit/test-eio-race.js
1637 eio_set_max_poll_reqs(10);
1641 HandleScope handle_scope;
1643 V8::SetFatalErrorHandler(node::OnFatalError);
1645 // If the --debug flag was specified then initialize the debug thread.
1646 if (node::use_debug_agent) {
1647 // Initialize the async watcher for receiving messages from the debug
1648 // thread and marshal it into the main thread. DebugMessageCallback()
1649 // is called from the main thread to execute a random bit of javascript
1650 // - which will give V8 control so it can handle whatever new message
1651 // had been received on the debug thread.
1652 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1653 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1654 // Set the callback DebugMessageDispatch which is called from the debug
1656 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1657 // Start the async watcher.
1658 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1659 // unref it so that we exit the event loop despite it being active.
1660 ev_unref(EV_DEFAULT_UC);
1662 // Start the debug thread and it's associated TCP server on port 5858.
1663 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1665 // Crappy check that everything went well. FIXME
1667 // Print out some information.
1668 printf("debugger listening on port %d\n", node::debug_port);
1671 // Create the one and only Context.
1672 Persistent<Context> context = Context::New();
1673 Context::Scope context_scope(context);
1675 // Create all the objects, load modules, do everything.
1676 // so your next reading stop should be node::Load()!
1677 node::Load(argc, argv);
1679 node::Stdio::Flush();