node.cc: EvalCX: Third argument as filename
[platform/upstream/nodejs.git] / src / node.cc
1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
2 #include <node.h>
3
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <limits.h> /* PATH_MAX */
8 #include <assert.h>
9 #include <unistd.h>
10 #include <errno.h>
11 #include <dlfcn.h> /* dlopen(), dlsym() */
12 #include <sys/types.h>
13 #include <unistd.h> /* setuid, getuid */
14
15 #include <node_events.h>
16 #include <node_dns.h>
17 #include <node_net.h>
18 #include <node_file.h>
19 #include <node_idle_watcher.h>
20 #include <node_http.h>
21 #include <node_signal_watcher.h>
22 #include <node_stat_watcher.h>
23 #include <node_timer.h>
24 #include <node_child_process.h>
25 #include <node_constants.h>
26 #include <node_stdio.h>
27 #include <node_natives.h>
28 #include <node_version.h>
29
30 #include <v8-debug.h>
31
32 using namespace v8;
33
34 extern char **environ;
35
36 namespace node {
37
38 static Persistent<Object> process;
39
40 static Persistent<String> dev_symbol;
41 static Persistent<String> ino_symbol;
42 static Persistent<String> mode_symbol;
43 static Persistent<String> nlink_symbol;
44 static Persistent<String> uid_symbol;
45 static Persistent<String> gid_symbol;
46 static Persistent<String> rdev_symbol;
47 static Persistent<String> size_symbol;
48 static Persistent<String> blksize_symbol;
49 static Persistent<String> blocks_symbol;
50 static Persistent<String> atime_symbol;
51 static Persistent<String> mtime_symbol;
52 static Persistent<String> ctime_symbol;
53
54 static Persistent<String> rss_symbol;
55 static Persistent<String> vsize_symbol;
56 static Persistent<String> heap_total_symbol;
57 static Persistent<String> heap_used_symbol;
58
59 static Persistent<String> listeners_symbol;
60 static Persistent<String> uncaught_exception_symbol;
61 static Persistent<String> emit_symbol;
62
63 static int option_end_index = 0;
64 static bool use_debug_agent = false;
65 static bool debug_wait_connect = false;
66 static int debug_port=5858;
67
68
69 static ev_async eio_want_poll_notifier;
70 static ev_async eio_done_poll_notifier;
71 static ev_idle  eio_poller;
72
73 static ev_timer  gc_timer;
74 #define GC_INTERVAL 2.0
75
76
77 // Node calls this every GC_INTERVAL seconds in order to try and call the
78 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
79 // is an effective measure of idleness.
80 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
81   assert(watcher == &gc_timer);
82   assert(revents == EV_TIMER);
83   if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
84 }
85
86
87 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
88   assert(watcher == &eio_poller);
89   assert(revents == EV_IDLE);
90
91   //printf("eio_poller\n");
92
93   if (eio_poll() != -1) {
94     //printf("eio_poller stop\n");
95     ev_idle_stop(EV_DEFAULT_UC_ watcher);
96   }
97 }
98
99
100 // Called from the main thread.
101 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
102   assert(watcher == &eio_want_poll_notifier);
103   assert(revents == EV_ASYNC);
104
105   //printf("want poll notifier\n");
106
107   if (eio_poll() == -1) {
108     //printf("eio_poller start\n");
109     ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
110   }
111 }
112
113
114 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
115   assert(watcher == &eio_done_poll_notifier);
116   assert(revents == EV_ASYNC);
117
118   //printf("done poll notifier\n");
119
120   if (eio_poll() != -1) {
121     //printf("eio_poller stop\n");
122     ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
123   }
124 }
125
126
127 // EIOWantPoll() is called from the EIO thread pool each time an EIO
128 // request (that is, one of the node.fs.* functions) has completed.
129 static void EIOWantPoll(void) {
130   // Signal the main thread that eio_poll need to be processed.
131   ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
132 }
133
134
135 static void EIODonePoll(void) {
136   // Signal the main thread that we should stop calling eio_poll().
137   // from the idle watcher.
138   ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
139 }
140
141
142 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
143   HandleScope scope;
144
145   if (!encoding_v->IsString()) return _default;
146
147   String::Utf8Value encoding(encoding_v->ToString());
148
149   if (strcasecmp(*encoding, "utf8") == 0) {
150     return UTF8;
151   } else if (strcasecmp(*encoding, "utf-8") == 0) {
152     return UTF8;
153   } else if (strcasecmp(*encoding, "ascii") == 0) {
154     return ASCII;
155   } else if (strcasecmp(*encoding, "binary") == 0) {
156     return BINARY;
157   } else if (strcasecmp(*encoding, "raw") == 0) {
158     fprintf(stderr, "'raw' (array of integers) has been removed. "
159                     "Use 'binary'.\n");
160     return BINARY;
161   } else if (strcasecmp(*encoding, "raws") == 0) {
162     fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
163                     "Please update your code.\n");
164     return BINARY;
165   } else {
166     return _default;
167   }
168 }
169
170 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
171   HandleScope scope;
172
173   if (!len) return scope.Close(String::Empty());
174
175   if (encoding == BINARY) {
176     const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
177     uint16_t * twobytebuf = new uint16_t[len];
178     for (size_t i = 0; i < len; i++) {
179       // XXX is the following line platform independent?
180       twobytebuf[i] = cbuf[i];
181     }
182     Local<String> chunk = String::New(twobytebuf, len);
183     delete [] twobytebuf; // TODO use ExternalTwoByteString?
184     return scope.Close(chunk);
185   }
186
187   // utf8 or ascii encoding
188   Local<String> chunk = String::New((const char*)buf, len);
189   return scope.Close(chunk);
190 }
191
192 // Returns -1 if the handle was not valid for decoding
193 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
194   HandleScope scope;
195
196   if (val->IsArray()) {
197     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
198                     "Use 'binary'.\n");
199     assert(0);
200     return -1;
201   }
202
203   Local<String> str = val->ToString();
204
205   if (encoding == UTF8) return str->Utf8Length();
206
207   return str->Length();
208 }
209
210 #ifndef MIN
211 # define MIN(a, b) ((a) < (b) ? (a) : (b))
212 #endif
213
214 // Returns number of bytes written.
215 ssize_t DecodeWrite(char *buf, size_t buflen,
216                     v8::Handle<v8::Value> val,
217                     enum encoding encoding) {
218   HandleScope scope;
219
220   // XXX
221   // A lot of improvement can be made here. See:
222   // http://code.google.com/p/v8/issues/detail?id=270
223   // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
224   // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
225
226   if (val->IsArray()) {
227     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
228                     "Use 'binary'.\n");
229     assert(0);
230     return -1;
231   }
232
233   Local<String> str = val->ToString();
234
235   if (encoding == UTF8) {
236     str->WriteUtf8(buf, buflen);
237     return buflen;
238   }
239
240   if (encoding == ASCII) {
241     str->WriteAscii(buf, 0, buflen);
242     return buflen;
243   }
244
245   // THIS IS AWFUL!!! FIXME
246
247   assert(encoding == BINARY);
248
249   uint16_t * twobytebuf = new uint16_t[buflen];
250
251   str->Write(twobytebuf, 0, buflen);
252
253   for (size_t i = 0; i < buflen; i++) {
254     unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
255     assert(b[1] == 0);
256     buf[i] = b[0];
257   }
258
259   delete [] twobytebuf;
260
261   return buflen;
262 }
263
264 static Persistent<FunctionTemplate> stats_constructor_template;
265
266 Local<Object> BuildStatsObject(struct stat * s) {
267   HandleScope scope;
268
269   if (dev_symbol.IsEmpty()) {
270     dev_symbol = NODE_PSYMBOL("dev");
271     ino_symbol = NODE_PSYMBOL("ino");
272     mode_symbol = NODE_PSYMBOL("mode");
273     nlink_symbol = NODE_PSYMBOL("nlink");
274     uid_symbol = NODE_PSYMBOL("uid");
275     gid_symbol = NODE_PSYMBOL("gid");
276     rdev_symbol = NODE_PSYMBOL("rdev");
277     size_symbol = NODE_PSYMBOL("size");
278     blksize_symbol = NODE_PSYMBOL("blksize");
279     blocks_symbol = NODE_PSYMBOL("blocks");
280     atime_symbol = NODE_PSYMBOL("atime");
281     mtime_symbol = NODE_PSYMBOL("mtime");
282     ctime_symbol = NODE_PSYMBOL("ctime");
283   }
284
285   Local<Object> stats =
286     stats_constructor_template->GetFunction()->NewInstance();
287
288   /* ID of device containing file */
289   stats->Set(dev_symbol, Integer::New(s->st_dev));
290
291   /* inode number */
292   stats->Set(ino_symbol, Integer::New(s->st_ino));
293
294   /* protection */
295   stats->Set(mode_symbol, Integer::New(s->st_mode));
296
297   /* number of hard links */
298   stats->Set(nlink_symbol, Integer::New(s->st_nlink));
299
300   /* user ID of owner */
301   stats->Set(uid_symbol, Integer::New(s->st_uid));
302
303   /* group ID of owner */
304   stats->Set(gid_symbol, Integer::New(s->st_gid));
305
306   /* device ID (if special file) */
307   stats->Set(rdev_symbol, Integer::New(s->st_rdev));
308
309   /* total size, in bytes */
310   stats->Set(size_symbol, Integer::New(s->st_size));
311
312   /* blocksize for filesystem I/O */
313   stats->Set(blksize_symbol, Integer::New(s->st_blksize));
314
315   /* number of blocks allocated */
316   stats->Set(blocks_symbol, Integer::New(s->st_blocks));
317
318   /* time of last access */
319   stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
320
321   /* time of last modification */
322   stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
323
324   /* time of last status change */
325   stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
326
327   return scope.Close(stats);
328 }
329
330
331 // Extracts a C str from a V8 Utf8Value.
332 const char* ToCString(const v8::String::Utf8Value& value) {
333   return *value ? *value : "<str conversion failed>";
334 }
335
336 static void ReportException(TryCatch &try_catch, bool show_line = false) {
337   Handle<Message> message = try_catch.Message();
338
339   Handle<Value> error = try_catch.Exception();
340   Handle<String> stack;
341
342   if (error->IsObject()) {
343     Handle<Object> obj = Handle<Object>::Cast(error);
344     Handle<Value> raw_stack = obj->Get(String::New("stack"));
345     if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
346   }
347
348   if (show_line && !message.IsEmpty()) {
349     // Print (filename):(line number): (message).
350     String::Utf8Value filename(message->GetScriptResourceName());
351     const char* filename_string = ToCString(filename);
352     int linenum = message->GetLineNumber();
353     fprintf(stderr, "%s:%i\n", filename_string, linenum);
354     // Print line of source code.
355     String::Utf8Value sourceline(message->GetSourceLine());
356     const char* sourceline_string = ToCString(sourceline);
357     fprintf(stderr, "%s\n", sourceline_string);
358     // Print wavy underline (GetUnderline is deprecated).
359     int start = message->GetStartColumn();
360     for (int i = 0; i < start; i++) {
361       fprintf(stderr, " ");
362     }
363     int end = message->GetEndColumn();
364     for (int i = start; i < end; i++) {
365       fprintf(stderr, "^");
366     }
367     fprintf(stderr, "\n");
368   }
369
370   if (stack.IsEmpty()) {
371     message->PrintCurrentStackTrace(stderr);
372   } else {
373     String::Utf8Value trace(stack);
374     fprintf(stderr, "%s\n", *trace);
375   }
376   fflush(stderr);
377 }
378
379 // Executes a str within the current v8 context.
380 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
381   HandleScope scope;
382   TryCatch try_catch;
383
384   Local<Script> script = Script::Compile(source, filename);
385   if (script.IsEmpty()) {
386     ReportException(try_catch);
387     exit(1);
388   }
389
390   Local<Value> result = script->Run();
391   if (result.IsEmpty()) {
392     ReportException(try_catch);
393     exit(1);
394   }
395
396   return scope.Close(result);
397 }
398
399 static Handle<Value> ByteLength(const Arguments& args) {
400   HandleScope scope;
401
402   if (args.Length() < 1 || !args[0]->IsString()) {
403     return ThrowException(Exception::Error(String::New("Bad argument.")));
404   }
405
406   Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
407
408   return scope.Close(length);
409 }
410
411 static Handle<Value> Loop(const Arguments& args) {
412   HandleScope scope;
413   assert(args.Length() == 0);
414
415   // TODO Probably don't need to start this each time.
416   // Avoids failing on test/mjsunit/test-eio-race3.js though
417   ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
418
419   ev_loop(EV_DEFAULT_UC_ 0);
420   return Undefined();
421 }
422
423 static Handle<Value> Unloop(const Arguments& args) {
424   fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
425   HandleScope scope;
426   int how = EVUNLOOP_ONE;
427   if (args[0]->IsString()) {
428     String::Utf8Value how_s(args[0]->ToString());
429     if (0 == strcmp(*how_s, "all")) {
430       how = EVUNLOOP_ALL;
431     }
432   }
433   ev_unloop(EV_DEFAULT_ how);
434   return Undefined();
435 }
436
437 static Handle<Value> Chdir(const Arguments& args) {
438   HandleScope scope;
439
440   if (args.Length() != 1 || !args[0]->IsString()) {
441     return ThrowException(Exception::Error(String::New("Bad argument.")));
442   }
443
444   String::Utf8Value path(args[0]->ToString());
445
446   int r = chdir(*path);
447
448   if (r != 0) {
449     return ThrowException(Exception::Error(String::New(strerror(errno))));
450   }
451
452   return Undefined();
453 }
454
455 static Handle<Value> Cwd(const Arguments& args) {
456   HandleScope scope;
457   assert(args.Length() == 0);
458
459   char output[PATH_MAX];
460   char *r = getcwd(output, PATH_MAX);
461   if (r == NULL) {
462     return ThrowException(Exception::Error(String::New(strerror(errno))));
463   }
464   Local<String> cwd = String::New(output);
465
466   return scope.Close(cwd);
467 }
468
469 static Handle<Value> Umask(const Arguments& args){
470   HandleScope scope;
471   unsigned int old;
472   if(args.Length() < 1) {
473     old = umask(0);
474     umask((mode_t)old);
475   }
476   else if(!args[0]->IsInt32()) {
477     return ThrowException(Exception::TypeError(
478           String::New("argument must be an integer.")));
479   }
480   else {
481     old = umask((mode_t)args[0]->Uint32Value());
482   }
483   return scope.Close(Uint32::New(old));
484 }
485
486
487 static Handle<Value> GetUid(const Arguments& args) {
488   HandleScope scope;
489   assert(args.Length() == 0);
490   int uid = getuid();
491   return scope.Close(Integer::New(uid));
492 }
493
494 static Handle<Value> GetGid(const Arguments& args) {
495   HandleScope scope;
496   assert(args.Length() == 0);
497   int gid = getgid();
498   return scope.Close(Integer::New(gid));
499 }
500
501
502 static Handle<Value> SetGid(const Arguments& args) {
503   HandleScope scope;
504
505   if (args.Length() < 1) {
506     return ThrowException(Exception::Error(
507       String::New("setgid requires 1 argument")));
508   }
509
510   Local<Integer> given_gid = args[0]->ToInteger();
511   int gid = given_gid->Int32Value();
512   int result;
513   if ((result = setgid(gid)) != 0) {
514     return ThrowException(Exception::Error(String::New(strerror(errno))));
515   }
516   return Undefined();
517 }
518
519 static Handle<Value> SetUid(const Arguments& args) {
520   HandleScope scope;
521
522   if (args.Length() < 1) {
523     return ThrowException(Exception::Error(
524           String::New("setuid requires 1 argument")));
525   }
526
527   Local<Integer> given_uid = args[0]->ToInteger();
528   int uid = given_uid->Int32Value();
529   int result;
530   if ((result = setuid(uid)) != 0) {
531     return ThrowException(Exception::Error(String::New(strerror(errno))));
532   }
533   return Undefined();
534 }
535
536
537 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
538   HandleScope scope;
539   fflush(stderr);
540   Stdio::Flush();
541   exit(args[0]->IntegerValue());
542   return Undefined();
543 }
544
545 #ifdef __sun
546 #define HAVE_GETMEM 1
547 #include <unistd.h> /* getpagesize() */
548
549 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
550 #define PROCFS_FILE_OFFSET_BITS_HACK 1
551 #undef _FILE_OFFSET_BITS
552 #else
553 #define PROCFS_FILE_OFFSET_BITS_HACK 0
554 #endif
555
556 #include <procfs.h>
557
558 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
559 #define _FILE_OFFSET_BITS 64
560 #endif
561
562 int getmem(size_t *rss, size_t *vsize) {
563   pid_t pid = getpid();
564
565   size_t page_size = getpagesize();
566   char pidpath[1024];
567   sprintf(pidpath, "/proc/%d/psinfo", pid);
568
569   psinfo_t psinfo;
570   FILE *f = fopen(pidpath, "r");
571   if (!f) return -1;
572
573   if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
574     fclose (f);
575     return -1;
576   }
577
578   /* XXX correct? */
579
580   *vsize = (size_t) psinfo.pr_size * page_size;
581   *rss = (size_t) psinfo.pr_rssize * 1024;
582
583   fclose (f);
584
585   return 0;
586 }
587 #endif
588
589
590 #ifdef __FreeBSD__
591 #define HAVE_GETMEM 1
592 #include <kvm.h>
593 #include <sys/param.h>
594 #include <sys/sysctl.h>
595 #include <sys/user.h>
596 #include <fcntl.h>
597 #include <unistd.h>
598
599 int getmem(size_t *rss, size_t *vsize) {
600   kvm_t *kd = NULL;
601   struct kinfo_proc *kinfo = NULL;
602   pid_t pid;
603   int nprocs;
604   size_t page_size = getpagesize();
605
606   pid = getpid();
607
608   kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
609   if (kd == NULL) goto error;
610
611   kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
612   if (kinfo == NULL) goto error;
613
614   *rss = kinfo->ki_rssize * page_size;
615   *vsize = kinfo->ki_size;
616
617   kvm_close(kd);
618
619   return 0;
620
621 error:
622   if (kd) kvm_close(kd);
623   return -1;
624 }
625 #endif  // __FreeBSD__
626
627
628 #ifdef __APPLE__
629 #define HAVE_GETMEM 1
630 /* Researched by Tim Becker and Michael Knight
631  * http://blog.kuriositaet.de/?p=257
632  */
633
634 #include <mach/task.h>
635 #include <mach/mach_init.h>
636
637 int getmem(size_t *rss, size_t *vsize) {
638   struct task_basic_info t_info;
639   mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
640
641   int r = task_info(mach_task_self(),
642                     TASK_BASIC_INFO,
643                     (task_info_t)&t_info,
644                     &t_info_count);
645
646   if (r != KERN_SUCCESS) return -1;
647
648   *rss = t_info.resident_size;
649   *vsize  = t_info.virtual_size;
650
651   return 0;
652 }
653 #endif  // __APPLE__
654
655 #ifdef __linux__
656 # define HAVE_GETMEM 1
657 # include <sys/param.h> /* for MAXPATHLEN */
658
659 int getmem(size_t *rss, size_t *vsize) {
660   FILE *f = fopen("/proc/self/stat", "r");
661   if (!f) return -1;
662
663   int itmp;
664   char ctmp;
665   char buffer[MAXPATHLEN];
666   size_t page_size = getpagesize();
667
668   /* PID */
669   if (fscanf(f, "%d ", &itmp) == 0) goto error;
670   /* Exec file */
671   if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
672   /* State */
673   if (fscanf (f, "%c ", &ctmp) == 0) goto error;
674   /* Parent process */
675   if (fscanf (f, "%d ", &itmp) == 0) goto error;
676   /* Process group */
677   if (fscanf (f, "%d ", &itmp) == 0) goto error;
678   /* Session id */
679   if (fscanf (f, "%d ", &itmp) == 0) goto error;
680   /* TTY */
681   if (fscanf (f, "%d ", &itmp) == 0) goto error;
682   /* TTY owner process group */
683   if (fscanf (f, "%d ", &itmp) == 0) goto error;
684   /* Flags */
685   if (fscanf (f, "%u ", &itmp) == 0) goto error;
686   /* Minor faults (no memory page) */
687   if (fscanf (f, "%u ", &itmp) == 0) goto error;
688   /* Minor faults, children */
689   if (fscanf (f, "%u ", &itmp) == 0) goto error;
690   /* Major faults (memory page faults) */
691   if (fscanf (f, "%u ", &itmp) == 0) goto error;
692   /* Major faults, children */
693   if (fscanf (f, "%u ", &itmp) == 0) goto error;
694   /* utime */
695   if (fscanf (f, "%d ", &itmp) == 0) goto error;
696   /* stime */
697   if (fscanf (f, "%d ", &itmp) == 0) goto error;
698   /* utime, children */
699   if (fscanf (f, "%d ", &itmp) == 0) goto error;
700   /* stime, children */
701   if (fscanf (f, "%d ", &itmp) == 0) goto error;
702   /* jiffies remaining in current time slice */
703   if (fscanf (f, "%d ", &itmp) == 0) goto error;
704   /* 'nice' value */
705   if (fscanf (f, "%d ", &itmp) == 0) goto error;
706   /* jiffies until next timeout */
707   if (fscanf (f, "%u ", &itmp) == 0) goto error;
708   /* jiffies until next SIGALRM */
709   if (fscanf (f, "%u ", &itmp) == 0) goto error;
710   /* start time (jiffies since system boot) */
711   if (fscanf (f, "%d ", &itmp) == 0) goto error;
712
713   /* Virtual memory size */
714   if (fscanf (f, "%u ", &itmp) == 0) goto error;
715   *vsize = (size_t) itmp;
716
717   /* Resident set size */
718   if (fscanf (f, "%u ", &itmp) == 0) goto error;
719   *rss = (size_t) itmp * page_size;
720
721   /* rlim */
722   if (fscanf (f, "%u ", &itmp) == 0) goto error;
723   /* Start of text */
724   if (fscanf (f, "%u ", &itmp) == 0) goto error;
725   /* End of text */
726   if (fscanf (f, "%u ", &itmp) == 0) goto error;
727   /* Start of stack */
728   if (fscanf (f, "%u ", &itmp) == 0) goto error;
729
730   fclose (f);
731
732   return 0;
733
734 error:
735   fclose (f);
736   return -1;
737 }
738 #endif  // __linux__
739
740 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
741   HandleScope scope;
742   assert(args.Length() == 0);
743
744 #ifndef HAVE_GETMEM
745   return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
746 #else
747   size_t rss, vsize;
748
749   int r = getmem(&rss, &vsize);
750
751   if (r != 0) {
752     return ThrowException(Exception::Error(String::New(strerror(errno))));
753   }
754
755   Local<Object> info = Object::New();
756
757   if (rss_symbol.IsEmpty()) {
758     rss_symbol = NODE_PSYMBOL("rss");
759     vsize_symbol = NODE_PSYMBOL("vsize");
760     heap_total_symbol = NODE_PSYMBOL("heapTotal");
761     heap_used_symbol = NODE_PSYMBOL("heapUsed");
762   }
763
764   info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
765   info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
766
767   // V8 memory usage
768   HeapStatistics v8_heap_stats;
769   V8::GetHeapStatistics(&v8_heap_stats);
770   info->Set(heap_total_symbol,
771             Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
772   info->Set(heap_used_symbol,
773             Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
774
775   return scope.Close(info);
776 #endif
777 }
778
779
780 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
781   HandleScope scope;
782
783   if (args.Length() < 1 || !args[0]->IsNumber()) {
784     return ThrowException(Exception::Error(String::New("Bad argument.")));
785   }
786
787   pid_t pid = args[0]->IntegerValue();
788
789   int sig = SIGTERM;
790
791   if (args.Length() >= 2) {
792     if (args[1]->IsNumber()) {
793       sig = args[1]->Int32Value();
794     } else if (args[1]->IsString()) {
795       Local<String> signame = args[1]->ToString();
796
797       Local<Value> sig_v = process->Get(signame);
798       if (!sig_v->IsNumber()) {
799         return ThrowException(Exception::Error(String::New("Unknown signal")));
800       }
801       sig = sig_v->Int32Value();
802     }
803   }
804
805   int r = kill(pid, sig);
806
807   if (r != 0) {
808     return ThrowException(Exception::Error(String::New(strerror(errno))));
809   }
810
811   return Undefined();
812 }
813
814 typedef void (*extInit)(Handle<Object> exports);
815
816 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
817 // objects.
818 Handle<Value> DLOpen(const v8::Arguments& args) {
819   HandleScope scope;
820
821   if (args.Length() < 2) return Undefined();
822
823   String::Utf8Value filename(args[0]->ToString()); // Cast
824   Local<Object> target = args[1]->ToObject(); // Cast
825
826   // Actually call dlopen().
827   // FIXME: This is a blocking function and should be called asynchronously!
828   // This function should be moved to file.cc and use libeio to make this
829   // system call.
830   void *handle = dlopen(*filename, RTLD_LAZY);
831
832   // Handle errors.
833   if (handle == NULL) {
834     Local<Value> exception = Exception::Error(String::New(dlerror()));
835     return ThrowException(exception);
836   }
837
838   // Get the init() function from the dynamically shared object.
839   void *init_handle = dlsym(handle, "init");
840   // Error out if not found.
841   if (init_handle == NULL) {
842     Local<Value> exception =
843       Exception::Error(String::New("No 'init' symbol found in module."));
844     return ThrowException(exception);
845   }
846   extInit init = (extInit)(init_handle); // Cast
847
848   // Execute the C++ module
849   init(target);
850
851   return Undefined();
852 }
853
854 // evalcx(code, sandbox={})
855 // Executes code in a new context
856 Handle<Value> EvalCX(const Arguments& args) {
857   HandleScope scope;
858
859   Local<String> code = args[0]->ToString();
860   Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
861                                             : Object::New();
862   Local<String> filename = args.Length() > 2 ? args[2]->ToString()
863                                              : String::New("evalcx");
864   // Create the new context
865   Persistent<Context> context = Context::New();
866
867   // Enter and compile script
868   context->Enter();
869
870   // Copy objects from global context, to our brand new context
871   Handle<Array> keys = sandbox->GetPropertyNames();
872
873   unsigned int i;
874   for (i = 0; i < keys->Length(); i++) {
875     Handle<String> key = keys->Get(Integer::New(i))->ToString();
876     Handle<Value> value = sandbox->Get(key);
877     context->Global()->Set(key, value);
878   }
879
880   // Catch errors
881   TryCatch try_catch;
882
883   Local<Script> script = Script::Compile(code, filename);
884   Handle<Value> result;
885
886   if (script.IsEmpty()) {
887     result = ThrowException(try_catch.Exception());
888   } else {
889     result = script->Run();
890     if (result.IsEmpty()) {
891       result = ThrowException(try_catch.Exception());
892     } else {
893       // success! copy changes back onto the sandbox object.
894       keys = context->Global()->GetPropertyNames();
895       for (i = 0; i < keys->Length(); i++) {
896         Handle<String> key = keys->Get(Integer::New(i))->ToString();
897         Handle<Value> value = context->Global()->Get(key);
898         sandbox->Set(key, value);
899       }
900     }
901   }
902
903   // Clean up, clean up, everybody everywhere!
904   context->DetachGlobal();
905   context->Exit();
906   context.Dispose();
907
908   return scope.Close(result);
909 }
910
911 Handle<Value> Compile(const Arguments& args) {
912   HandleScope scope;
913
914   if (args.Length() < 2) {
915     return ThrowException(Exception::TypeError(
916           String::New("needs two arguments.")));
917   }
918
919   Local<String> source = args[0]->ToString();
920   Local<String> filename = args[1]->ToString();
921
922   TryCatch try_catch;
923
924   Local<Script> script = Script::Compile(source, filename);
925   if (try_catch.HasCaught()) {
926     // Hack because I can't get a proper stacktrace on SyntaxError
927     ReportException(try_catch, true);
928     exit(1);
929   }
930
931   Local<Value> result = script->Run();
932   if (try_catch.HasCaught()) return try_catch.ReThrow();
933
934   return scope.Close(result);
935 }
936
937 static void OnFatalError(const char* location, const char* message) {
938   if (location) {
939     fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
940   } else {
941     fprintf(stderr, "FATAL ERROR: %s\n", message);
942   }
943   exit(1);
944 }
945
946 static int uncaught_exception_counter = 0;
947
948 void FatalException(TryCatch &try_catch) {
949   HandleScope scope;
950
951   // Check if uncaught_exception_counter indicates a recursion
952   if (uncaught_exception_counter > 0) {
953     ReportException(try_catch);
954     exit(1);
955   }
956
957   if (listeners_symbol.IsEmpty()) {
958     listeners_symbol = NODE_PSYMBOL("listeners");
959     uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
960     emit_symbol = NODE_PSYMBOL("emit");
961   }
962
963   Local<Value> listeners_v = process->Get(listeners_symbol);
964   assert(listeners_v->IsFunction());
965
966   Local<Function> listeners = Local<Function>::Cast(listeners_v);
967
968   Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
969   Local<Value> argv[1] = { uncaught_exception_symbol_l  };
970   Local<Value> ret = listeners->Call(process, 1, argv);
971
972   assert(ret->IsArray());
973
974   Local<Array> listener_array = Local<Array>::Cast(ret);
975
976   uint32_t length = listener_array->Length();
977   // Report and exit if process has no "uncaughtException" listener
978   if (length == 0) {
979     ReportException(try_catch);
980     exit(1);
981   }
982
983   // Otherwise fire the process "uncaughtException" event
984   Local<Value> emit_v = process->Get(emit_symbol);
985   assert(emit_v->IsFunction());
986
987   Local<Function> emit = Local<Function>::Cast(emit_v);
988
989   Local<Value> error = try_catch.Exception();
990   Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
991
992   uncaught_exception_counter++;
993   emit->Call(process, 2, event_argv);
994   // Decrement so we know if the next exception is a recursion or not
995   uncaught_exception_counter--;
996 }
997
998
999 static ev_async debug_watcher;
1000 volatile static bool debugger_msg_pending = false;
1001
1002 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1003   HandleScope scope;
1004   assert(watcher == &debug_watcher);
1005   assert(revents == EV_ASYNC);
1006   Debug::ProcessDebugMessages();
1007 }
1008
1009 static void DebugMessageDispatch(void) {
1010   // This function is called from V8's debug thread when a debug TCP client
1011   // has sent a message.
1012
1013   // Send a signal to our main thread saying that it should enter V8 to
1014   // handle the message.
1015   debugger_msg_pending = true;
1016   ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1017 }
1018
1019 static Handle<Value> CheckBreak(const Arguments& args) {
1020   HandleScope scope;
1021   assert(args.Length() == 0);
1022
1023   // TODO FIXME This function is a hack to wait until V8 is ready to accept
1024   // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1025   // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1026   // get it to halt until Eclipse connects.
1027
1028   if (!debug_wait_connect)
1029     return Undefined();
1030
1031   printf("Waiting for remote debugger connection...\n");
1032
1033   const int halfSecond = 50;
1034   const int tenMs=10000;
1035   debugger_msg_pending = false;
1036   for (;;) {
1037     if (debugger_msg_pending) {
1038       Debug::DebugBreak();
1039       Debug::ProcessDebugMessages();
1040       debugger_msg_pending = false;
1041
1042       // wait for 500 msec of silence from remote debugger
1043       int cnt = halfSecond;
1044         while (cnt --) {
1045         debugger_msg_pending = false;
1046         usleep(tenMs);
1047         if (debugger_msg_pending) {
1048           debugger_msg_pending = false;
1049           cnt = halfSecond;
1050         }
1051       }
1052       break;
1053     }
1054     usleep(tenMs);
1055   }
1056   return Undefined();
1057 }
1058
1059 Persistent<Object> binding_cache;
1060
1061 static Handle<Value> Binding(const Arguments& args) {
1062   HandleScope scope;
1063
1064   Local<String> module = args[0]->ToString();
1065   String::Utf8Value module_v(module);
1066
1067   if (binding_cache.IsEmpty()) {
1068     binding_cache = Persistent<Object>::New(Object::New());
1069   }
1070
1071   Local<Object> exports;
1072
1073   if (!strcmp(*module_v, "http")) {
1074     if (binding_cache->Has(module)) {
1075       exports = binding_cache->Get(module)->ToObject();
1076     } else {
1077       // Warning: When calling requireBinding('http') from javascript then
1078       // be sure that you call requireBinding('tcp') before it.
1079       assert(binding_cache->Has(String::New("tcp")));
1080       exports = Object::New();
1081       HTTPServer::Initialize(exports);
1082       HTTPConnection::Initialize(exports);
1083       binding_cache->Set(module, exports);
1084     }
1085
1086   } else if (!strcmp(*module_v, "tcp")) {
1087     if (binding_cache->Has(module)) {
1088       exports = binding_cache->Get(module)->ToObject();
1089     } else {
1090       exports = Object::New();
1091       Server::Initialize(exports);
1092       Connection::Initialize(exports);
1093       binding_cache->Set(module, exports);
1094     }
1095
1096   } else if (!strcmp(*module_v, "dns")) {
1097     if (binding_cache->Has(module)) {
1098       exports = binding_cache->Get(module)->ToObject();
1099     } else {
1100       exports = Object::New();
1101       DNS::Initialize(exports);
1102       binding_cache->Set(module, exports);
1103     }
1104
1105   } else if (!strcmp(*module_v, "fs")) {
1106     if (binding_cache->Has(module)) {
1107       exports = binding_cache->Get(module)->ToObject();
1108     } else {
1109       exports = Object::New();
1110
1111       // Initialize the stats object
1112       Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1113       stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1114       exports->Set(String::NewSymbol("Stats"),
1115                    stats_constructor_template->GetFunction());
1116       StatWatcher::Initialize(exports);
1117       File::Initialize(exports);
1118       binding_cache->Set(module, exports);
1119     }
1120
1121   } else if (!strcmp(*module_v, "signal_watcher")) {
1122     if (binding_cache->Has(module)) {
1123       exports = binding_cache->Get(module)->ToObject();
1124     } else {
1125       exports = Object::New();
1126       SignalWatcher::Initialize(exports);
1127       binding_cache->Set(module, exports);
1128     }
1129
1130   } else if (!strcmp(*module_v, "natives")) {
1131     if (binding_cache->Has(module)) {
1132       exports = binding_cache->Get(module)->ToObject();
1133     } else {
1134       exports = Object::New();
1135       // Explicitly define native sources.
1136       // TODO DRY/automate this?
1137       exports->Set(String::New("assert"),       String::New(native_assert));
1138       exports->Set(String::New("dns"),          String::New(native_dns));
1139       exports->Set(String::New("events"),       String::New(native_events));
1140       exports->Set(String::New("file"),         String::New(native_file));
1141       exports->Set(String::New("fs"),           String::New(native_fs));
1142       exports->Set(String::New("http"),         String::New(native_http));
1143       exports->Set(String::New("ini"),          String::New(native_ini));
1144       exports->Set(String::New("mjsunit"),      String::New(native_mjsunit));
1145       exports->Set(String::New("multipart"),    String::New(native_multipart));
1146       exports->Set(String::New("posix"),        String::New(native_posix));
1147       exports->Set(String::New("querystring"),  String::New(native_querystring));
1148       exports->Set(String::New("repl"),         String::New(native_repl));
1149       exports->Set(String::New("sys"),          String::New(native_sys));
1150       exports->Set(String::New("tcp"),          String::New(native_tcp));
1151       exports->Set(String::New("uri"),          String::New(native_uri));
1152       exports->Set(String::New("url"),          String::New(native_url));
1153       exports->Set(String::New("utils"),        String::New(native_utils));
1154       binding_cache->Set(module, exports);
1155     }
1156
1157   } else {
1158     assert(0);
1159     return ThrowException(Exception::Error(String::New("No such module")));
1160   }
1161
1162   return scope.Close(exports);
1163 }
1164
1165
1166 static void Load(int argc, char *argv[]) {
1167   HandleScope scope;
1168
1169   Local<FunctionTemplate> process_template = FunctionTemplate::New();
1170   node::EventEmitter::Initialize(process_template);
1171
1172   process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1173
1174   // Add a reference to the global object
1175   Local<Object> global = Context::GetCurrent()->Global();
1176   process->Set(String::NewSymbol("global"), global);
1177
1178   // process.version
1179   process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1180   // process.installPrefix
1181   process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1182
1183   // process.platform
1184 #define xstr(s) str(s)
1185 #define str(s) #s
1186   process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1187
1188   // process.argv
1189   int i, j;
1190   Local<Array> arguments = Array::New(argc - option_end_index + 1);
1191   arguments->Set(Integer::New(0), String::New(argv[0]));
1192   for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1193     Local<String> arg = String::New(argv[i]);
1194     arguments->Set(Integer::New(j), arg);
1195   }
1196   // assign it
1197   process->Set(String::NewSymbol("ARGV"), arguments);
1198   process->Set(String::NewSymbol("argv"), arguments);
1199
1200   // create process.env
1201   Local<Object> env = Object::New();
1202   for (i = 0; environ[i]; i++) {
1203     // skip entries without a '=' character
1204     for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1205     // create the v8 objects
1206     Local<String> field = String::New(environ[i], j);
1207     Local<String> value = Local<String>();
1208     if (environ[i][j] == '=') {
1209       value = String::New(environ[i]+j+1);
1210     }
1211     // assign them
1212     env->Set(field, value);
1213   }
1214   // assign process.ENV
1215   process->Set(String::NewSymbol("ENV"), env);
1216   process->Set(String::NewSymbol("env"), env);
1217
1218   process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1219
1220   // define various internal methods
1221   NODE_SET_METHOD(process, "loop", Loop);
1222   NODE_SET_METHOD(process, "unloop", Unloop);
1223   NODE_SET_METHOD(process, "evalcx", EvalCX);
1224   NODE_SET_METHOD(process, "compile", Compile);
1225   NODE_SET_METHOD(process, "_byteLength", ByteLength);
1226   NODE_SET_METHOD(process, "reallyExit", Exit);
1227   NODE_SET_METHOD(process, "chdir", Chdir);
1228   NODE_SET_METHOD(process, "cwd", Cwd);
1229   NODE_SET_METHOD(process, "getuid", GetUid);
1230   NODE_SET_METHOD(process, "setuid", SetUid);
1231
1232   NODE_SET_METHOD(process, "setgid", SetGid);
1233   NODE_SET_METHOD(process, "getgid", GetGid);
1234
1235   NODE_SET_METHOD(process, "umask", Umask);
1236   NODE_SET_METHOD(process, "dlopen", DLOpen);
1237   NODE_SET_METHOD(process, "kill", Kill);
1238   NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1239   NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1240
1241   NODE_SET_METHOD(process, "binding", Binding);
1242
1243   // Assign the EventEmitter. It was created in main().
1244   process->Set(String::NewSymbol("EventEmitter"),
1245                EventEmitter::constructor_template->GetFunction());
1246
1247
1248
1249   // Initialize the C++ modules..................filename of module
1250   IdleWatcher::Initialize(process);            // idle_watcher.cc
1251   Stdio::Initialize(process);                  // stdio.cc
1252   Timer::Initialize(process);                  // timer.cc
1253   ChildProcess::Initialize(process);           // child_process.cc
1254   DefineConstants(process);                    // constants.cc
1255
1256   // Compile, execute the src/node.js file. (Which was included as static C
1257   // string in node_natives.h. 'natve_node' is the string containing that
1258   // source code.)
1259
1260   // The node.js file returns a function 'f'
1261
1262 #ifndef NDEBUG
1263   TryCatch try_catch;
1264 #endif
1265
1266   Local<Value> f_value = ExecuteString(String::New(native_node),
1267                                        String::New("node.js"));
1268 #ifndef NDEBUG
1269   if (try_catch.HasCaught())  {
1270     ReportException(try_catch);
1271     exit(10);
1272   }
1273 #endif
1274   assert(f_value->IsFunction());
1275   Local<Function> f = Local<Function>::Cast(f_value);
1276
1277   // Now we call 'f' with the 'process' variable that we've built up with
1278   // all our bindings. Inside node.js we'll take care of assigning things to
1279   // their places.
1280
1281   // We start the process this way in order to be more modular. Developers
1282   // who do not like how 'src/node.js' setups the module system but do like
1283   // Node's I/O bindings may want to replace 'f' with their own function.
1284
1285   Local<Value> args[1] = { Local<Value>::New(process) };
1286
1287   f->Call(global, 1, args);
1288
1289 #ifndef NDEBUG
1290   if (try_catch.HasCaught())  {
1291     ReportException(try_catch);
1292     exit(11);
1293   }
1294 #endif
1295 }
1296
1297 static void PrintHelp();
1298
1299 static void ParseDebugOpt(const char* arg) {
1300   const char *p = 0;
1301
1302   use_debug_agent = true;
1303   if (!strcmp (arg, "--debug-brk")) {
1304     debug_wait_connect = true;
1305     return;
1306   } else if (!strcmp(arg, "--debug")) {
1307     return;
1308   } else if (strstr(arg, "--debug-brk=") == arg) {
1309     debug_wait_connect = true;
1310     p = 1 + strchr(arg, '=');
1311     debug_port = atoi(p);
1312   } else if (strstr(arg, "--debug=") == arg) {
1313     p = 1 + strchr(arg, '=');
1314     debug_port = atoi(p);
1315   }
1316   if (p && debug_port > 1024 && debug_port <  65536)
1317       return;
1318
1319   fprintf(stderr, "Bad debug option.\n");
1320   if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1321
1322   PrintHelp();
1323   exit(1);
1324 }
1325
1326 static void PrintHelp() {
1327   printf("Usage: node [options] script.js [arguments] \n"
1328          "Options:\n"
1329          "  -v, --version      print node's version\n"
1330          "  --debug[=port]     enable remote debugging via given TCP port\n"
1331          "                     without stopping the execution\n"
1332          "  --debug-brk[=port] as above, but break in script.js and\n"
1333          "                     wait for remote debugger to connect\n"
1334          "  --v8-options       print v8 command line options\n"
1335          "  --vars             print various compiled-in variables\n"
1336          "\n"
1337          "Enviromental variables:\n"
1338          "NODE_PATH            ':'-separated list of directories\n"
1339          "                     prefixed to the module search path,\n"
1340          "                     require.paths.\n"
1341          "NODE_DEBUG           Print additional debugging output.\n"
1342          "\n"
1343          "Documentation can be found at http://nodejs.org/api.html"
1344          " or with 'man node'\n");
1345 }
1346
1347 // Parse node command line arguments.
1348 static void ParseArgs(int *argc, char **argv) {
1349   // TODO use parse opts
1350   for (int i = 1; i < *argc; i++) {
1351     const char *arg = argv[i];
1352     if (strstr(arg, "--debug") == arg) {
1353       ParseDebugOpt(arg);
1354       argv[i] = const_cast<char*>("");
1355       option_end_index = i;
1356     } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1357       printf("%s\n", NODE_VERSION);
1358       exit(0);
1359     } else if (strcmp(arg, "--vars") == 0) {
1360       printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1361       printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1362       exit(0);
1363     } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1364       PrintHelp();
1365       exit(0);
1366     } else if (strcmp(arg, "--v8-options") == 0) {
1367       argv[i] = const_cast<char*>("--help");
1368       option_end_index = i+1;
1369     } else if (argv[i][0] != '-') {
1370       option_end_index = i-1;
1371       break;
1372     }
1373   }
1374 }
1375
1376 }  // namespace node
1377
1378
1379 int main(int argc, char *argv[]) {
1380   // Parse a few arguments which are specific to Node.
1381   node::ParseArgs(&argc, argv);
1382   // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1383   // in the command line))
1384   V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1385
1386   // Error out if we don't have a script argument.
1387   if (argc < 2) {
1388     fprintf(stderr, "No script was specified.\n");
1389     node::PrintHelp();
1390     return 1;
1391   }
1392
1393   // Ignore the SIGPIPE
1394   evcom_ignore_sigpipe();
1395
1396   // Initialize the default ev loop.
1397 #ifdef __sun
1398   // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1399   // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1400   ev_default_loop(EVBACKEND_SELECT);
1401 #else
1402   ev_default_loop(EVFLAG_AUTO);
1403 #endif
1404
1405
1406   ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1407   // Set the gc_timer to max priority so that it runs before all other
1408   // watchers. In this way it can check if the 'tick' has other pending
1409   // watchers by using ev_pending_count() - if it ran with lower priority
1410   // then the other watchers might run before it - not giving us good idea
1411   // of loop idleness.
1412   ev_set_priority(&node::gc_timer, EV_MAXPRI);
1413   ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1414   ev_unref(EV_DEFAULT_UC);
1415
1416
1417   // Setup the EIO thread pool
1418   { // It requires 3, yes 3, watchers.
1419     ev_idle_init(&node::eio_poller, node::DoPoll);
1420
1421     ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1422     ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1423     ev_unref(EV_DEFAULT_UC);
1424
1425     ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1426     ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1427     ev_unref(EV_DEFAULT_UC);
1428
1429     eio_init(node::EIOWantPoll, node::EIODonePoll);
1430     // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1431     // race conditions. See test/mjsunit/test-eio-race.js
1432     eio_set_max_poll_reqs(10);
1433   }
1434
1435   V8::Initialize();
1436   HandleScope handle_scope;
1437
1438   V8::SetFatalErrorHandler(node::OnFatalError);
1439
1440   // If the --debug flag was specified then initialize the debug thread.
1441   if (node::use_debug_agent) {
1442     // Initialize the async watcher for receiving messages from the debug
1443     // thread and marshal it into the main thread. DebugMessageCallback()
1444     // is called from the main thread to execute a random bit of javascript
1445     // - which will give V8 control so it can handle whatever new message
1446     // had been received on the debug thread.
1447     ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1448     ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1449     // Set the callback DebugMessageDispatch which is called from the debug
1450     // thread.
1451     Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1452     // Start the async watcher.
1453     ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1454     // unref it so that we exit the event loop despite it being active.
1455     ev_unref(EV_DEFAULT_UC);
1456
1457     // Start the debug thread and it's associated TCP server on port 5858.
1458     bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1459
1460     // Crappy check that everything went well. FIXME
1461     assert(r);
1462     // Print out some information.
1463     printf("debugger listening on port %d\n", node::debug_port);
1464   }
1465
1466   // Create the one and only Context.
1467   Persistent<Context> context = Context::New();
1468   Context::Scope context_scope(context);
1469
1470   // Create all the objects, load modules, do everything.
1471   // so your next reading stop should be node::Load()!
1472   node::Load(argc, argv);
1473
1474   node::Stdio::Flush();
1475
1476 #ifndef NDEBUG
1477   // Clean up.
1478   context.Dispose();
1479   V8::Dispose();
1480 #endif  // NDEBUG
1481   return 0;
1482 }
1483