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