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