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