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