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