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