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