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