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