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