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