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