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