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