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