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 #define GC_INTERVAL 1.0
110 static void gc_timer_start () {
111 if (!ev_is_active(&gc_timer)) {
112 ev_timer_start(EV_DEFAULT_UC_ &gc_timer);
113 ev_unref(EV_DEFAULT_UC);
117 static void gc_timer_stop () {
118 if (ev_is_active(&gc_timer)) {
119 ev_ref(EV_DEFAULT_UC);
120 ev_timer_stop(EV_DEFAULT_UC_ &gc_timer);
125 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
126 assert(watcher == &gc_timer);
127 assert(revents == EV_TIMER);
129 //fprintf(stderr, "check idle\n");
131 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
133 if (idle_time > GC_INTERVAL) {
134 if (!V8::IdleNotification()) {
135 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
142 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
143 assert(watcher == &gc_idle);
144 assert(revents == EV_IDLE);
146 //fprintf(stderr, "notify idle\n");
148 if (V8::IdleNotification()) {
149 ev_idle_stop(EV_A_ watcher);
155 static void Activity(EV_P_ ev_check *watcher, int revents) {
156 assert(watcher == &gc_check);
157 assert(revents == EV_CHECK);
159 int pending = ev_pending_count(EV_DEFAULT_UC);
161 // Don't count GC watchers as activity.
163 if (ev_is_pending(&gc_timer)) pending--;
164 if (ev_is_pending(&gc_idle)) pending--;
165 if (ev_is_pending(&gc_check)) pending--;
167 assert(pending >= 0);
169 //fprintf(stderr, "activity, pending: %d\n", pending);
172 last_active = ev_now(EV_DEFAULT_UC);
173 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
179 static Handle<Value> NeedTickCallback(const Arguments& args) {
182 ev_idle_start(EV_DEFAULT_UC_ &tick_spinner);
187 static void Spin(EV_P_ ev_idle *watcher, int revents) {
188 assert(watcher == &tick_spinner);
189 assert(revents == EV_IDLE);
193 static void Tick(EV_P_ ev_prepare *watcher, int revents) {
194 assert(watcher == &next_tick_watcher);
195 assert(revents == EV_PREPARE);
197 // Avoid entering a V8 scope.
198 if (!need_tick_cb) return;
200 need_tick_cb = false;
201 ev_idle_stop(EV_DEFAULT_UC_ &tick_spinner);
205 if (tick_callback_sym.IsEmpty()) {
206 // Lazily set the symbol
208 Persistent<String>::New(String::NewSymbol("_tickCallback"));
211 Local<Value> cb_v = process->Get(tick_callback_sym);
212 if (!cb_v->IsFunction()) return;
213 Local<Function> cb = Local<Function>::Cast(cb_v);
217 cb->Call(process, 0, NULL);
219 if (try_catch.HasCaught()) {
220 FatalException(try_catch);
225 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
226 assert(watcher == &eio_poller);
227 assert(revents == EV_IDLE);
229 //printf("eio_poller\n");
231 if (eio_poll() != -1) {
232 //printf("eio_poller stop\n");
233 ev_idle_stop(EV_DEFAULT_UC_ watcher);
238 // Called from the main thread.
239 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
240 assert(watcher == &eio_want_poll_notifier);
241 assert(revents == EV_ASYNC);
243 //printf("want poll notifier\n");
245 if (eio_poll() == -1) {
246 //printf("eio_poller start\n");
247 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
252 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
253 assert(watcher == &eio_done_poll_notifier);
254 assert(revents == EV_ASYNC);
256 //printf("done poll notifier\n");
258 if (eio_poll() != -1) {
259 //printf("eio_poller stop\n");
260 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
265 // EIOWantPoll() is called from the EIO thread pool each time an EIO
266 // request (that is, one of the node.fs.* functions) has completed.
267 static void EIOWantPoll(void) {
268 // Signal the main thread that eio_poll need to be processed.
269 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
273 static void EIODonePoll(void) {
274 // Signal the main thread that we should stop calling eio_poll().
275 // from the idle watcher.
276 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
280 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
283 if (!encoding_v->IsString()) return _default;
285 String::Utf8Value encoding(encoding_v->ToString());
287 if (strcasecmp(*encoding, "utf8") == 0) {
289 } else if (strcasecmp(*encoding, "utf-8") == 0) {
291 } else if (strcasecmp(*encoding, "ascii") == 0) {
293 } else if (strcasecmp(*encoding, "binary") == 0) {
295 } else if (strcasecmp(*encoding, "raw") == 0) {
296 fprintf(stderr, "'raw' (array of integers) has been removed. "
299 } else if (strcasecmp(*encoding, "raws") == 0) {
300 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
301 "Please update your code.\n");
308 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
311 if (!len) return scope.Close(String::Empty());
313 if (encoding == BINARY) {
314 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
315 uint16_t * twobytebuf = new uint16_t[len];
316 for (size_t i = 0; i < len; i++) {
317 // XXX is the following line platform independent?
318 twobytebuf[i] = cbuf[i];
320 Local<String> chunk = String::New(twobytebuf, len);
321 delete [] twobytebuf; // TODO use ExternalTwoByteString?
322 return scope.Close(chunk);
325 // utf8 or ascii encoding
326 Local<String> chunk = String::New((const char*)buf, len);
327 return scope.Close(chunk);
330 // Returns -1 if the handle was not valid for decoding
331 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
334 if (val->IsArray()) {
335 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
341 Local<String> str = val->ToString();
343 if (encoding == UTF8) return str->Utf8Length();
345 return str->Length();
349 # define MIN(a, b) ((a) < (b) ? (a) : (b))
352 // Returns number of bytes written.
353 ssize_t DecodeWrite(char *buf,
355 v8::Handle<v8::Value> val,
356 enum encoding encoding) {
360 // A lot of improvement can be made here. See:
361 // http://code.google.com/p/v8/issues/detail?id=270
362 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
363 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
365 if (val->IsArray()) {
366 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
372 Local<String> str = val->ToString();
374 if (encoding == UTF8) {
375 str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
379 if (encoding == ASCII) {
380 str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
384 // THIS IS AWFUL!!! FIXME
386 assert(encoding == BINARY);
388 uint16_t * twobytebuf = new uint16_t[buflen];
390 str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
392 for (size_t i = 0; i < buflen; i++) {
393 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
398 delete [] twobytebuf;
403 static Persistent<FunctionTemplate> stats_constructor_template;
405 Local<Object> BuildStatsObject(struct stat * s) {
408 if (dev_symbol.IsEmpty()) {
409 dev_symbol = NODE_PSYMBOL("dev");
410 ino_symbol = NODE_PSYMBOL("ino");
411 mode_symbol = NODE_PSYMBOL("mode");
412 nlink_symbol = NODE_PSYMBOL("nlink");
413 uid_symbol = NODE_PSYMBOL("uid");
414 gid_symbol = NODE_PSYMBOL("gid");
415 rdev_symbol = NODE_PSYMBOL("rdev");
416 size_symbol = NODE_PSYMBOL("size");
417 blksize_symbol = NODE_PSYMBOL("blksize");
418 blocks_symbol = NODE_PSYMBOL("blocks");
419 atime_symbol = NODE_PSYMBOL("atime");
420 mtime_symbol = NODE_PSYMBOL("mtime");
421 ctime_symbol = NODE_PSYMBOL("ctime");
424 Local<Object> stats =
425 stats_constructor_template->GetFunction()->NewInstance();
427 /* ID of device containing file */
428 stats->Set(dev_symbol, Integer::New(s->st_dev));
431 stats->Set(ino_symbol, Integer::New(s->st_ino));
434 stats->Set(mode_symbol, Integer::New(s->st_mode));
436 /* number of hard links */
437 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
439 /* user ID of owner */
440 stats->Set(uid_symbol, Integer::New(s->st_uid));
442 /* group ID of owner */
443 stats->Set(gid_symbol, Integer::New(s->st_gid));
445 /* device ID (if special file) */
446 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
448 /* total size, in bytes */
449 stats->Set(size_symbol, Integer::New(s->st_size));
451 /* blocksize for filesystem I/O */
452 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
454 /* number of blocks allocated */
455 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
457 /* time of last access */
458 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
460 /* time of last modification */
461 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
463 /* time of last status change */
464 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
466 return scope.Close(stats);
470 // Extracts a C str from a V8 Utf8Value.
471 const char* ToCString(const v8::String::Utf8Value& value) {
472 return *value ? *value : "<str conversion failed>";
475 static void ReportException(TryCatch &try_catch, bool show_line = false) {
476 Handle<Message> message = try_catch.Message();
478 Handle<Value> error = try_catch.Exception();
479 Handle<String> stack;
481 if (error->IsObject()) {
482 Handle<Object> obj = Handle<Object>::Cast(error);
483 Handle<Value> raw_stack = obj->Get(String::New("stack"));
484 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
487 if (show_line && !message.IsEmpty()) {
488 // Print (filename):(line number): (message).
489 String::Utf8Value filename(message->GetScriptResourceName());
490 const char* filename_string = ToCString(filename);
491 int linenum = message->GetLineNumber();
492 fprintf(stderr, "%s:%i\n", filename_string, linenum);
493 // Print line of source code.
494 String::Utf8Value sourceline(message->GetSourceLine());
495 const char* sourceline_string = ToCString(sourceline);
496 fprintf(stderr, "%s\n", sourceline_string);
497 // Print wavy underline (GetUnderline is deprecated).
498 int start = message->GetStartColumn();
499 for (int i = 0; i < start; i++) {
500 fprintf(stderr, " ");
502 int end = message->GetEndColumn();
503 for (int i = start; i < end; i++) {
504 fprintf(stderr, "^");
506 fprintf(stderr, "\n");
509 if (stack.IsEmpty()) {
510 message->PrintCurrentStackTrace(stderr);
512 String::Utf8Value trace(stack);
513 fprintf(stderr, "%s\n", *trace);
518 // Executes a str within the current v8 context.
519 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
523 Local<Script> script = Script::Compile(source, filename);
524 if (script.IsEmpty()) {
525 ReportException(try_catch);
529 Local<Value> result = script->Run();
530 if (result.IsEmpty()) {
531 ReportException(try_catch);
535 return scope.Close(result);
538 static Handle<Value> ByteLength(const Arguments& args) {
541 if (args.Length() < 1 || !args[0]->IsString()) {
542 return ThrowException(Exception::Error(String::New("Bad argument.")));
545 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
547 return scope.Close(length);
550 static Handle<Value> Loop(const Arguments& args) {
552 assert(args.Length() == 0);
554 // TODO Probably don't need to start this each time.
555 // Avoids failing on test/mjsunit/test-eio-race3.js though
556 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
558 ev_loop(EV_DEFAULT_UC_ 0);
562 static Handle<Value> Unloop(const Arguments& args) {
563 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
565 int how = EVUNLOOP_ONE;
566 if (args[0]->IsString()) {
567 String::Utf8Value how_s(args[0]->ToString());
568 if (0 == strcmp(*how_s, "all")) {
572 ev_unloop(EV_DEFAULT_ how);
576 static Handle<Value> Chdir(const Arguments& args) {
579 if (args.Length() != 1 || !args[0]->IsString()) {
580 return ThrowException(Exception::Error(String::New("Bad argument.")));
583 String::Utf8Value path(args[0]->ToString());
585 int r = chdir(*path);
588 return ThrowException(Exception::Error(String::New(strerror(errno))));
594 static Handle<Value> Cwd(const Arguments& args) {
596 assert(args.Length() == 0);
598 char output[PATH_MAX];
599 char *r = getcwd(output, PATH_MAX);
601 return ThrowException(Exception::Error(String::New(strerror(errno))));
603 Local<String> cwd = String::New(output);
605 return scope.Close(cwd);
608 static Handle<Value> Umask(const Arguments& args){
611 if(args.Length() < 1) {
615 else if(!args[0]->IsInt32()) {
616 return ThrowException(Exception::TypeError(
617 String::New("argument must be an integer.")));
620 old = umask((mode_t)args[0]->Uint32Value());
622 return scope.Close(Uint32::New(old));
626 static Handle<Value> GetUid(const Arguments& args) {
628 assert(args.Length() == 0);
630 return scope.Close(Integer::New(uid));
633 static Handle<Value> GetGid(const Arguments& args) {
635 assert(args.Length() == 0);
637 return scope.Close(Integer::New(gid));
641 static Handle<Value> SetGid(const Arguments& args) {
644 if (args.Length() < 1) {
645 return ThrowException(Exception::Error(
646 String::New("setgid requires 1 argument")));
649 Local<Integer> given_gid = args[0]->ToInteger();
650 int gid = given_gid->Int32Value();
652 if ((result = setgid(gid)) != 0) {
653 return ThrowException(Exception::Error(String::New(strerror(errno))));
658 static Handle<Value> SetUid(const Arguments& args) {
661 if (args.Length() < 1) {
662 return ThrowException(Exception::Error(
663 String::New("setuid requires 1 argument")));
666 Local<Integer> given_uid = args[0]->ToInteger();
667 int uid = given_uid->Int32Value();
669 if ((result = setuid(uid)) != 0) {
670 return ThrowException(Exception::Error(String::New(strerror(errno))));
676 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
680 exit(args[0]->IntegerValue());
685 #define HAVE_GETMEM 1
686 #include <unistd.h> /* getpagesize() */
688 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
689 #define PROCFS_FILE_OFFSET_BITS_HACK 1
690 #undef _FILE_OFFSET_BITS
692 #define PROCFS_FILE_OFFSET_BITS_HACK 0
697 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
698 #define _FILE_OFFSET_BITS 64
701 int getmem(size_t *rss, size_t *vsize) {
702 pid_t pid = getpid();
704 size_t page_size = getpagesize();
706 sprintf(pidpath, "/proc/%d/psinfo", pid);
709 FILE *f = fopen(pidpath, "r");
712 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
719 *vsize = (size_t) psinfo.pr_size * page_size;
720 *rss = (size_t) psinfo.pr_rssize * 1024;
730 #define HAVE_GETMEM 1
732 #include <sys/param.h>
733 #include <sys/sysctl.h>
734 #include <sys/user.h>
739 int getmem(size_t *rss, size_t *vsize) {
741 struct kinfo_proc *kinfo = NULL;
744 size_t page_size = getpagesize();
748 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
749 if (kd == NULL) goto error;
751 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
752 if (kinfo == NULL) goto error;
754 *rss = kinfo->ki_rssize * page_size;
755 *vsize = kinfo->ki_size;
762 if (kd) kvm_close(kd);
765 #endif // __FreeBSD__
769 #define HAVE_GETMEM 1
770 /* Researched by Tim Becker and Michael Knight
771 * http://blog.kuriositaet.de/?p=257
774 #include <mach/task.h>
775 #include <mach/mach_init.h>
777 int getmem(size_t *rss, size_t *vsize) {
778 struct task_basic_info t_info;
779 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
781 int r = task_info(mach_task_self(),
783 (task_info_t)&t_info,
786 if (r != KERN_SUCCESS) return -1;
788 *rss = t_info.resident_size;
789 *vsize = t_info.virtual_size;
796 # define HAVE_GETMEM 1
797 # include <sys/param.h> /* for MAXPATHLEN */
799 int getmem(size_t *rss, size_t *vsize) {
800 FILE *f = fopen("/proc/self/stat", "r");
805 char buffer[MAXPATHLEN];
806 size_t page_size = getpagesize();
809 if (fscanf(f, "%d ", &itmp) == 0) goto error;
811 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
813 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
815 if (fscanf (f, "%d ", &itmp) == 0) goto error;
817 if (fscanf (f, "%d ", &itmp) == 0) goto error;
819 if (fscanf (f, "%d ", &itmp) == 0) goto error;
821 if (fscanf (f, "%d ", &itmp) == 0) goto error;
822 /* TTY owner process group */
823 if (fscanf (f, "%d ", &itmp) == 0) goto error;
825 if (fscanf (f, "%u ", &itmp) == 0) goto error;
826 /* Minor faults (no memory page) */
827 if (fscanf (f, "%u ", &itmp) == 0) goto error;
828 /* Minor faults, children */
829 if (fscanf (f, "%u ", &itmp) == 0) goto error;
830 /* Major faults (memory page faults) */
831 if (fscanf (f, "%u ", &itmp) == 0) goto error;
832 /* Major faults, children */
833 if (fscanf (f, "%u ", &itmp) == 0) goto error;
835 if (fscanf (f, "%d ", &itmp) == 0) goto error;
837 if (fscanf (f, "%d ", &itmp) == 0) goto error;
838 /* utime, children */
839 if (fscanf (f, "%d ", &itmp) == 0) goto error;
840 /* stime, children */
841 if (fscanf (f, "%d ", &itmp) == 0) goto error;
842 /* jiffies remaining in current time slice */
843 if (fscanf (f, "%d ", &itmp) == 0) goto error;
845 if (fscanf (f, "%d ", &itmp) == 0) goto error;
846 /* jiffies until next timeout */
847 if (fscanf (f, "%u ", &itmp) == 0) goto error;
848 /* jiffies until next SIGALRM */
849 if (fscanf (f, "%u ", &itmp) == 0) goto error;
850 /* start time (jiffies since system boot) */
851 if (fscanf (f, "%d ", &itmp) == 0) goto error;
853 /* Virtual memory size */
854 if (fscanf (f, "%u ", &itmp) == 0) goto error;
855 *vsize = (size_t) itmp;
857 /* Resident set size */
858 if (fscanf (f, "%u ", &itmp) == 0) goto error;
859 *rss = (size_t) itmp * page_size;
862 if (fscanf (f, "%u ", &itmp) == 0) goto error;
864 if (fscanf (f, "%u ", &itmp) == 0) goto error;
866 if (fscanf (f, "%u ", &itmp) == 0) goto error;
868 if (fscanf (f, "%u ", &itmp) == 0) goto error;
880 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
882 assert(args.Length() == 0);
885 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
889 int r = getmem(&rss, &vsize);
892 return ThrowException(Exception::Error(String::New(strerror(errno))));
895 Local<Object> info = Object::New();
897 if (rss_symbol.IsEmpty()) {
898 rss_symbol = NODE_PSYMBOL("rss");
899 vsize_symbol = NODE_PSYMBOL("vsize");
900 heap_total_symbol = NODE_PSYMBOL("heapTotal");
901 heap_used_symbol = NODE_PSYMBOL("heapUsed");
904 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
905 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
908 HeapStatistics v8_heap_stats;
909 V8::GetHeapStatistics(&v8_heap_stats);
910 info->Set(heap_total_symbol,
911 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
912 info->Set(heap_used_symbol,
913 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
915 return scope.Close(info);
920 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
923 if (args.Length() < 1 || !args[0]->IsNumber()) {
924 return ThrowException(Exception::Error(String::New("Bad argument.")));
927 pid_t pid = args[0]->IntegerValue();
931 if (args.Length() >= 2) {
932 if (args[1]->IsNumber()) {
933 sig = args[1]->Int32Value();
934 } else if (args[1]->IsString()) {
935 Local<String> signame = args[1]->ToString();
937 Local<Value> sig_v = process->Get(signame);
938 if (!sig_v->IsNumber()) {
939 return ThrowException(Exception::Error(String::New("Unknown signal")));
941 sig = sig_v->Int32Value();
945 int r = kill(pid, sig);
948 return ThrowException(Exception::Error(String::New(strerror(errno))));
954 typedef void (*extInit)(Handle<Object> exports);
956 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
958 Handle<Value> DLOpen(const v8::Arguments& args) {
961 if (args.Length() < 2) return Undefined();
963 String::Utf8Value filename(args[0]->ToString()); // Cast
964 Local<Object> target = args[1]->ToObject(); // Cast
966 // Actually call dlopen().
967 // FIXME: This is a blocking function and should be called asynchronously!
968 // This function should be moved to file.cc and use libeio to make this
970 void *handle = dlopen(*filename, RTLD_LAZY);
973 if (handle == NULL) {
974 Local<Value> exception = Exception::Error(String::New(dlerror()));
975 return ThrowException(exception);
978 // Get the init() function from the dynamically shared object.
979 void *init_handle = dlsym(handle, "init");
980 // Error out if not found.
981 if (init_handle == NULL) {
982 Local<Value> exception =
983 Exception::Error(String::New("No 'init' symbol found in module."));
984 return ThrowException(exception);
986 extInit init = (extInit)(init_handle); // Cast
988 // Execute the C++ module
994 // evalcx(code, sandbox={})
995 // Executes code in a new context
996 Handle<Value> EvalCX(const Arguments& args) {
999 Local<String> code = args[0]->ToString();
1000 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
1002 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
1003 : String::New("evalcx");
1004 // Create the new context
1005 Persistent<Context> context = Context::New();
1007 // Enter and compile script
1010 // Copy objects from global context, to our brand new context
1011 Handle<Array> keys = sandbox->GetPropertyNames();
1014 for (i = 0; i < keys->Length(); i++) {
1015 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1016 Handle<Value> value = sandbox->Get(key);
1017 context->Global()->Set(key, value);
1023 Local<Script> script = Script::Compile(code, filename);
1024 Handle<Value> result;
1026 if (script.IsEmpty()) {
1027 result = ThrowException(try_catch.Exception());
1029 result = script->Run();
1030 if (result.IsEmpty()) {
1031 result = ThrowException(try_catch.Exception());
1033 // success! copy changes back onto the sandbox object.
1034 keys = context->Global()->GetPropertyNames();
1035 for (i = 0; i < keys->Length(); i++) {
1036 Handle<String> key = keys->Get(Integer::New(i))->ToString();
1037 Handle<Value> value = context->Global()->Get(key);
1038 sandbox->Set(key, value);
1043 // Clean up, clean up, everybody everywhere!
1044 context->DetachGlobal();
1048 return scope.Close(result);
1051 Handle<Value> Compile(const Arguments& args) {
1054 if (args.Length() < 2) {
1055 return ThrowException(Exception::TypeError(
1056 String::New("needs two arguments.")));
1059 Local<String> source = args[0]->ToString();
1060 Local<String> filename = args[1]->ToString();
1064 Local<Script> script = Script::Compile(source, filename);
1065 if (try_catch.HasCaught()) {
1066 // Hack because I can't get a proper stacktrace on SyntaxError
1067 ReportException(try_catch, true);
1071 Local<Value> result = script->Run();
1072 if (try_catch.HasCaught()) return try_catch.ReThrow();
1074 return scope.Close(result);
1077 static void OnFatalError(const char* location, const char* message) {
1079 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1081 fprintf(stderr, "FATAL ERROR: %s\n", message);
1086 static int uncaught_exception_counter = 0;
1088 void FatalException(TryCatch &try_catch) {
1091 // Check if uncaught_exception_counter indicates a recursion
1092 if (uncaught_exception_counter > 0) {
1093 ReportException(try_catch);
1097 if (listeners_symbol.IsEmpty()) {
1098 listeners_symbol = NODE_PSYMBOL("listeners");
1099 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1100 emit_symbol = NODE_PSYMBOL("emit");
1103 Local<Value> listeners_v = process->Get(listeners_symbol);
1104 assert(listeners_v->IsFunction());
1106 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1108 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1109 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1110 Local<Value> ret = listeners->Call(process, 1, argv);
1112 assert(ret->IsArray());
1114 Local<Array> listener_array = Local<Array>::Cast(ret);
1116 uint32_t length = listener_array->Length();
1117 // Report and exit if process has no "uncaughtException" listener
1119 ReportException(try_catch);
1123 // Otherwise fire the process "uncaughtException" event
1124 Local<Value> emit_v = process->Get(emit_symbol);
1125 assert(emit_v->IsFunction());
1127 Local<Function> emit = Local<Function>::Cast(emit_v);
1129 Local<Value> error = try_catch.Exception();
1130 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1132 uncaught_exception_counter++;
1133 emit->Call(process, 2, event_argv);
1134 // Decrement so we know if the next exception is a recursion or not
1135 uncaught_exception_counter--;
1139 static ev_async debug_watcher;
1140 volatile static bool debugger_msg_pending = false;
1142 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1144 assert(watcher == &debug_watcher);
1145 assert(revents == EV_ASYNC);
1146 Debug::ProcessDebugMessages();
1149 static void DebugMessageDispatch(void) {
1150 // This function is called from V8's debug thread when a debug TCP client
1151 // has sent a message.
1153 // Send a signal to our main thread saying that it should enter V8 to
1154 // handle the message.
1155 debugger_msg_pending = true;
1156 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1159 static Handle<Value> CheckBreak(const Arguments& args) {
1161 assert(args.Length() == 0);
1163 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1164 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1165 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1166 // get it to halt until Eclipse connects.
1168 if (!debug_wait_connect)
1171 printf("Waiting for remote debugger connection...\n");
1173 const int halfSecond = 50;
1174 const int tenMs=10000;
1175 debugger_msg_pending = false;
1177 if (debugger_msg_pending) {
1178 Debug::DebugBreak();
1179 Debug::ProcessDebugMessages();
1180 debugger_msg_pending = false;
1182 // wait for 500 msec of silence from remote debugger
1183 int cnt = halfSecond;
1185 debugger_msg_pending = false;
1187 if (debugger_msg_pending) {
1188 debugger_msg_pending = false;
1199 Persistent<Object> binding_cache;
1201 static Handle<Value> Binding(const Arguments& args) {
1204 Local<String> module = args[0]->ToString();
1205 String::Utf8Value module_v(module);
1207 if (binding_cache.IsEmpty()) {
1208 binding_cache = Persistent<Object>::New(Object::New());
1211 Local<Object> exports;
1213 // TODO DRY THIS UP!
1215 if (!strcmp(*module_v, "stdio")) {
1216 if (binding_cache->Has(module)) {
1217 exports = binding_cache->Get(module)->ToObject();
1219 exports = Object::New();
1220 Stdio::Initialize(exports);
1221 binding_cache->Set(module, exports);
1224 } else if (!strcmp(*module_v, "http")) {
1225 if (binding_cache->Has(module)) {
1226 exports = binding_cache->Get(module)->ToObject();
1228 // Warning: When calling requireBinding('http') from javascript then
1229 // be sure that you call requireBinding('tcp') before it.
1230 assert(binding_cache->Has(String::New("tcp")));
1231 exports = Object::New();
1232 HTTPServer::Initialize(exports);
1233 HTTPConnection::Initialize(exports);
1234 binding_cache->Set(module, exports);
1237 } else if (!strcmp(*module_v, "tcp")) {
1238 if (binding_cache->Has(module)) {
1239 exports = binding_cache->Get(module)->ToObject();
1241 exports = Object::New();
1242 Server::Initialize(exports);
1243 Connection::Initialize(exports);
1244 binding_cache->Set(module, exports);
1247 } else if (!strcmp(*module_v, "cares")) {
1248 if (binding_cache->Has(module)) {
1249 exports = binding_cache->Get(module)->ToObject();
1251 exports = Object::New();
1252 Cares::Initialize(exports);
1253 binding_cache->Set(module, exports);
1256 } else if (!strcmp(*module_v, "fs")) {
1257 if (binding_cache->Has(module)) {
1258 exports = binding_cache->Get(module)->ToObject();
1260 exports = Object::New();
1262 // Initialize the stats object
1263 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1264 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1265 exports->Set(String::NewSymbol("Stats"),
1266 stats_constructor_template->GetFunction());
1267 StatWatcher::Initialize(exports);
1268 File::Initialize(exports);
1269 binding_cache->Set(module, exports);
1272 } else if (!strcmp(*module_v, "signal_watcher")) {
1273 if (binding_cache->Has(module)) {
1274 exports = binding_cache->Get(module)->ToObject();
1276 exports = Object::New();
1277 SignalWatcher::Initialize(exports);
1278 binding_cache->Set(module, exports);
1281 } else if (!strcmp(*module_v, "net")) {
1282 if (binding_cache->Has(module)) {
1283 exports = binding_cache->Get(module)->ToObject();
1285 exports = Object::New();
1287 binding_cache->Set(module, exports);
1290 } else if (!strcmp(*module_v, "http_parser")) {
1291 if (binding_cache->Has(module)) {
1292 exports = binding_cache->Get(module)->ToObject();
1294 exports = Object::New();
1295 InitHttpParser(exports);
1296 binding_cache->Set(module, exports);
1299 } else if (!strcmp(*module_v, "child_process")) {
1300 if (binding_cache->Has(module)) {
1301 exports = binding_cache->Get(module)->ToObject();
1303 exports = Object::New();
1304 ChildProcess::Initialize(exports);
1305 binding_cache->Set(module, exports);
1308 } else if (!strcmp(*module_v, "buffer")) {
1309 if (binding_cache->Has(module)) {
1310 exports = binding_cache->Get(module)->ToObject();
1312 exports = Object::New();
1313 Buffer::Initialize(exports);
1314 binding_cache->Set(module, exports);
1317 } else if (!strcmp(*module_v, "crypto")) {
1318 if (binding_cache->Has(module)) {
1319 exports = binding_cache->Get(module)->ToObject();
1321 exports = Object::New();
1322 InitCrypto(exports);
1323 binding_cache->Set(module, exports);
1326 } else if (!strcmp(*module_v, "natives")) {
1327 if (binding_cache->Has(module)) {
1328 exports = binding_cache->Get(module)->ToObject();
1330 exports = Object::New();
1331 // Explicitly define native sources.
1332 // TODO DRY/automate this?
1333 exports->Set(String::New("assert"), String::New(native_assert));
1334 exports->Set(String::New("buffer"), String::New(native_buffer));
1335 exports->Set(String::New("child_process"),String::New(native_child_process));
1336 exports->Set(String::New("dns"), String::New(native_dns));
1337 exports->Set(String::New("events"), String::New(native_events));
1338 exports->Set(String::New("file"), String::New(native_file));
1339 exports->Set(String::New("freelist"), String::New(native_freelist));
1340 exports->Set(String::New("fs"), String::New(native_fs));
1341 exports->Set(String::New("http"), String::New(native_http));
1342 exports->Set(String::New("http_old"), String::New(native_http_old));
1343 exports->Set(String::New("crypto"), String::New(native_crypto));
1344 exports->Set(String::New("ini"), String::New(native_ini));
1345 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1346 exports->Set(String::New("net"), String::New(native_net));
1347 exports->Set(String::New("posix"), String::New(native_posix));
1348 exports->Set(String::New("querystring"), String::New(native_querystring));
1349 exports->Set(String::New("repl"), String::New(native_repl));
1350 exports->Set(String::New("sys"), String::New(native_sys));
1351 exports->Set(String::New("tcp"), String::New(native_tcp));
1352 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1353 exports->Set(String::New("uri"), String::New(native_uri));
1354 exports->Set(String::New("url"), String::New(native_url));
1355 exports->Set(String::New("utils"), String::New(native_utils));
1356 binding_cache->Set(module, exports);
1361 return ThrowException(Exception::Error(String::New("No such module")));
1364 return scope.Close(exports);
1368 static void Load(int argc, char *argv[]) {
1371 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1372 node::EventEmitter::Initialize(process_template);
1374 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1376 // Add a reference to the global object
1377 Local<Object> global = Context::GetCurrent()->Global();
1378 process->Set(String::NewSymbol("global"), global);
1381 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1382 // process.installPrefix
1383 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1386 #define xstr(s) str(s)
1388 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1392 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1393 arguments->Set(Integer::New(0), String::New(argv[0]));
1394 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1395 Local<String> arg = String::New(argv[i]);
1396 arguments->Set(Integer::New(j), arg);
1399 process->Set(String::NewSymbol("ARGV"), arguments);
1400 process->Set(String::NewSymbol("argv"), arguments);
1402 // create process.env
1403 Local<Object> env = Object::New();
1404 for (i = 0; environ[i]; i++) {
1405 // skip entries without a '=' character
1406 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1407 // create the v8 objects
1408 Local<String> field = String::New(environ[i], j);
1409 Local<String> value = Local<String>();
1410 if (environ[i][j] == '=') {
1411 value = String::New(environ[i]+j+1);
1414 env->Set(field, value);
1416 // assign process.ENV
1417 process->Set(String::NewSymbol("ENV"), env);
1418 process->Set(String::NewSymbol("env"), env);
1420 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1422 // define various internal methods
1423 NODE_SET_METHOD(process, "loop", Loop);
1424 NODE_SET_METHOD(process, "unloop", Unloop);
1425 NODE_SET_METHOD(process, "evalcx", EvalCX);
1426 NODE_SET_METHOD(process, "compile", Compile);
1427 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1428 NODE_SET_METHOD(process, "_needTickCallback", NeedTickCallback);
1429 NODE_SET_METHOD(process, "reallyExit", Exit);
1430 NODE_SET_METHOD(process, "chdir", Chdir);
1431 NODE_SET_METHOD(process, "cwd", Cwd);
1432 NODE_SET_METHOD(process, "getuid", GetUid);
1433 NODE_SET_METHOD(process, "setuid", SetUid);
1435 NODE_SET_METHOD(process, "setgid", SetGid);
1436 NODE_SET_METHOD(process, "getgid", GetGid);
1438 NODE_SET_METHOD(process, "umask", Umask);
1439 NODE_SET_METHOD(process, "dlopen", DLOpen);
1440 NODE_SET_METHOD(process, "kill", Kill);
1441 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1442 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1444 NODE_SET_METHOD(process, "binding", Binding);
1446 // Assign the EventEmitter. It was created in main().
1447 process->Set(String::NewSymbol("EventEmitter"),
1448 EventEmitter::constructor_template->GetFunction());
1451 // Initialize the C++ modules..................filename of module
1452 IOWatcher::Initialize(process); // io_watcher.cc
1453 // Not in use at the moment.
1454 //IdleWatcher::Initialize(process); // idle_watcher.cc
1455 Timer::Initialize(process); // timer.cc
1456 DefineConstants(process); // constants.cc
1458 // Compile, execute the src/node.js file. (Which was included as static C
1459 // string in node_natives.h. 'natve_node' is the string containing that
1462 // The node.js file returns a function 'f'
1468 Local<Value> f_value = ExecuteString(String::New(native_node),
1469 String::New("node.js"));
1471 if (try_catch.HasCaught()) {
1472 ReportException(try_catch);
1476 assert(f_value->IsFunction());
1477 Local<Function> f = Local<Function>::Cast(f_value);
1479 // Now we call 'f' with the 'process' variable that we've built up with
1480 // all our bindings. Inside node.js we'll take care of assigning things to
1483 // We start the process this way in order to be more modular. Developers
1484 // who do not like how 'src/node.js' setups the module system but do like
1485 // Node's I/O bindings may want to replace 'f' with their own function.
1487 Local<Value> args[1] = { Local<Value>::New(process) };
1489 f->Call(global, 1, args);
1492 if (try_catch.HasCaught()) {
1493 ReportException(try_catch);
1499 static void PrintHelp();
1501 static void ParseDebugOpt(const char* arg) {
1504 use_debug_agent = true;
1505 if (!strcmp (arg, "--debug-brk")) {
1506 debug_wait_connect = true;
1508 } else if (!strcmp(arg, "--debug")) {
1510 } else if (strstr(arg, "--debug-brk=") == arg) {
1511 debug_wait_connect = true;
1512 p = 1 + strchr(arg, '=');
1513 debug_port = atoi(p);
1514 } else if (strstr(arg, "--debug=") == arg) {
1515 p = 1 + strchr(arg, '=');
1516 debug_port = atoi(p);
1518 if (p && debug_port > 1024 && debug_port < 65536)
1521 fprintf(stderr, "Bad debug option.\n");
1522 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1528 static void PrintHelp() {
1529 printf("Usage: node [options] script.js [arguments] \n"
1531 " -v, --version print node's version\n"
1532 " --debug[=port] enable remote debugging via given TCP port\n"
1533 " without stopping the execution\n"
1534 " --debug-brk[=port] as above, but break in script.js and\n"
1535 " wait for remote debugger to connect\n"
1536 " --v8-options print v8 command line options\n"
1537 " --vars print various compiled-in variables\n"
1539 "Enviromental variables:\n"
1540 "NODE_PATH ':'-separated list of directories\n"
1541 " prefixed to the module search path,\n"
1543 "NODE_DEBUG Print additional debugging output.\n"
1545 "Documentation can be found at http://nodejs.org/api.html"
1546 " or with 'man node'\n");
1549 // Parse node command line arguments.
1550 static void ParseArgs(int *argc, char **argv) {
1551 // TODO use parse opts
1552 for (int i = 1; i < *argc; i++) {
1553 const char *arg = argv[i];
1554 if (strstr(arg, "--debug") == arg) {
1556 argv[i] = const_cast<char*>("");
1557 option_end_index = i;
1558 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1559 printf("%s\n", NODE_VERSION);
1561 } else if (strcmp(arg, "--vars") == 0) {
1562 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1563 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1565 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1568 } else if (strcmp(arg, "--v8-options") == 0) {
1569 argv[i] = const_cast<char*>("--help");
1570 option_end_index = i+1;
1571 } else if (argv[i][0] != '-') {
1572 option_end_index = i-1;
1581 int main(int argc, char *argv[]) {
1582 // Parse a few arguments which are specific to Node.
1583 node::ParseArgs(&argc, argv);
1584 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1585 // in the command line))
1586 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1588 // Error out if we don't have a script argument.
1590 fprintf(stderr, "No script was specified.\n");
1595 // Ignore the SIGPIPE
1596 evcom_ignore_sigpipe();
1598 // Initialize the default ev loop.
1600 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1601 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1602 ev_default_loop(EVBACKEND_SELECT);
1604 ev_default_loop(EVFLAG_AUTO);
1607 ev_prepare_init(&node::next_tick_watcher, node::Tick);
1608 ev_prepare_start(EV_DEFAULT_UC_ &node::next_tick_watcher);
1609 ev_unref(EV_DEFAULT_UC);
1611 ev_idle_init(&node::tick_spinner, node::Spin);
1613 ev_timer_init(&node::gc_timer, node::CheckIdleness, 2*GC_INTERVAL, 2*GC_INTERVAL);
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();