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