1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
9 #include <limits.h> /* PATH_MAX */
13 #include <dlfcn.h> /* dlopen(), dlsym() */
14 #include <sys/types.h>
15 #include <unistd.h> /* setuid, getuid */
17 #include <node_buffer.h>
18 #include <node_io_watcher.h>
19 #include <node_net2.h>
20 #include <node_events.h>
21 #include <node_cares.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_watcher.h>
28 #include <node_stat_watcher.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>
40 extern char **environ;
44 static Persistent<Object> process;
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;
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;
65 static Persistent<String> listeners_symbol;
66 static Persistent<String> uncaught_exception_symbol;
67 static Persistent<String> emit_symbol;
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;
75 static ev_async eio_want_poll_notifier;
76 static ev_async eio_done_poll_notifier;
77 static ev_idle eio_poller;
79 // We need to notify V8 when we're idle so that it can run the garbage
80 // collector. The interface to this is V8::IdleNotification(). It returns
81 // true if the heap hasn't be fully compacted, and needs to be run again.
82 // Returning false means that it doesn't have anymore work to do.
84 // We try to wait for a period of GC_INTERVAL (2 seconds) of idleness, where
85 // idleness means that no libev watchers have been executed. Since
86 // everything in node uses libev watchers, this is a pretty good measure of
87 // idleness. This is done with gc_check, which records the timestamp
88 // last_active on every tick of the event loop, and with gc_timer which
89 // executes every few seconds to measure if
90 // last_active + GC_INTERVAL < ev_now()
91 // If we do find a period of idleness, then we start the gc_idle timer which
92 // will very repaidly call IdleNotification until the heap is fully
94 static ev_tstamp last_active;
95 static ev_timer gc_timer;
96 static ev_check gc_check;
97 static ev_idle gc_idle;
99 #define GC_INTERVAL 2.0
102 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
103 assert(watcher == &gc_timer);
104 assert(revents == EV_TIMER);
106 //fprintf(stderr, "check idle\n");
108 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
110 if (idle_time > GC_INTERVAL) {
113 if (!V8::IdleNotification()) {
114 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
118 gc_timer.repeat = GC_INTERVAL;
119 ev_timer_again(EV_DEFAULT_UC_ watcher);
124 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
125 assert(watcher == &gc_idle);
126 assert(revents == EV_IDLE);
128 //fprintf(stderr, "notify idle\n");
130 if (V8::IdleNotification()) {
131 ev_idle_stop(EV_A_ watcher);
137 static void Activity(EV_P_ ev_check *watcher, int revents) {
138 assert(watcher == &gc_check);
139 assert(revents == EV_CHECK);
141 int pending = ev_pending_count(EV_DEFAULT_UC);
143 // Don't count GC watchers as activity.
145 pending -= ev_is_pending(&gc_timer);
146 pending -= ev_is_pending(&gc_idle);
147 //if (ev_is_pending(&gc_check)) pending--; // This probably never happens?
149 //fprintf(stderr, "activity, pending: %d\n", pending);
152 last_active = ev_now(EV_DEFAULT_UC);
153 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
156 gc_timer.repeat = GC_INTERVAL;
157 ev_timer_again(EV_DEFAULT_UC_ &gc_timer);
165 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
166 assert(watcher == &eio_poller);
167 assert(revents == EV_IDLE);
169 //printf("eio_poller\n");
171 if (eio_poll() != -1) {
172 //printf("eio_poller stop\n");
173 ev_idle_stop(EV_DEFAULT_UC_ watcher);
178 // Called from the main thread.
179 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
180 assert(watcher == &eio_want_poll_notifier);
181 assert(revents == EV_ASYNC);
183 //printf("want poll notifier\n");
185 if (eio_poll() == -1) {
186 //printf("eio_poller start\n");
187 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
192 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
193 assert(watcher == &eio_done_poll_notifier);
194 assert(revents == EV_ASYNC);
196 //printf("done poll notifier\n");
198 if (eio_poll() != -1) {
199 //printf("eio_poller stop\n");
200 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
205 // EIOWantPoll() is called from the EIO thread pool each time an EIO
206 // request (that is, one of the node.fs.* functions) has completed.
207 static void EIOWantPoll(void) {
208 // Signal the main thread that eio_poll need to be processed.
209 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
213 static void EIODonePoll(void) {
214 // Signal the main thread that we should stop calling eio_poll().
215 // from the idle watcher.
216 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
220 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
223 if (!encoding_v->IsString()) return _default;
225 String::Utf8Value encoding(encoding_v->ToString());
227 if (strcasecmp(*encoding, "utf8") == 0) {
229 } else if (strcasecmp(*encoding, "utf-8") == 0) {
231 } else if (strcasecmp(*encoding, "ascii") == 0) {
233 } else if (strcasecmp(*encoding, "binary") == 0) {
235 } else if (strcasecmp(*encoding, "raw") == 0) {
236 fprintf(stderr, "'raw' (array of integers) has been removed. "
239 } else if (strcasecmp(*encoding, "raws") == 0) {
240 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
241 "Please update your code.\n");
248 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
251 if (!len) return scope.Close(String::Empty());
253 if (encoding == BINARY) {
254 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
255 uint16_t * twobytebuf = new uint16_t[len];
256 for (size_t i = 0; i < len; i++) {
257 // XXX is the following line platform independent?
258 twobytebuf[i] = cbuf[i];
260 Local<String> chunk = String::New(twobytebuf, len);
261 delete [] twobytebuf; // TODO use ExternalTwoByteString?
262 return scope.Close(chunk);
265 // utf8 or ascii encoding
266 Local<String> chunk = String::New((const char*)buf, len);
267 return scope.Close(chunk);
270 // Returns -1 if the handle was not valid for decoding
271 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
274 if (val->IsArray()) {
275 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
281 Local<String> str = val->ToString();
283 if (encoding == UTF8) return str->Utf8Length();
285 return str->Length();
289 # define MIN(a, b) ((a) < (b) ? (a) : (b))
292 // Returns number of bytes written.
293 ssize_t DecodeWrite(char *buf,
295 v8::Handle<v8::Value> val,
296 enum encoding encoding) {
300 // A lot of improvement can be made here. See:
301 // http://code.google.com/p/v8/issues/detail?id=270
302 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
303 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
305 if (val->IsArray()) {
306 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
312 Local<String> str = val->ToString();
314 if (encoding == UTF8) {
315 str->WriteUtf8(buf, buflen);
319 if (encoding == ASCII) {
320 str->WriteAscii(buf, 0, buflen);
324 // THIS IS AWFUL!!! FIXME
326 assert(encoding == BINARY);
328 uint16_t * twobytebuf = new uint16_t[buflen];
331 str->Write(twobytebuf, 0, buflen);
333 for (size_t i = 0; i < buflen; i++) {
334 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
339 delete [] twobytebuf;
344 static Persistent<FunctionTemplate> stats_constructor_template;
346 Local<Object> BuildStatsObject(struct stat * s) {
349 if (dev_symbol.IsEmpty()) {
350 dev_symbol = NODE_PSYMBOL("dev");
351 ino_symbol = NODE_PSYMBOL("ino");
352 mode_symbol = NODE_PSYMBOL("mode");
353 nlink_symbol = NODE_PSYMBOL("nlink");
354 uid_symbol = NODE_PSYMBOL("uid");
355 gid_symbol = NODE_PSYMBOL("gid");
356 rdev_symbol = NODE_PSYMBOL("rdev");
357 size_symbol = NODE_PSYMBOL("size");
358 blksize_symbol = NODE_PSYMBOL("blksize");
359 blocks_symbol = NODE_PSYMBOL("blocks");
360 atime_symbol = NODE_PSYMBOL("atime");
361 mtime_symbol = NODE_PSYMBOL("mtime");
362 ctime_symbol = NODE_PSYMBOL("ctime");
365 Local<Object> stats =
366 stats_constructor_template->GetFunction()->NewInstance();
368 /* ID of device containing file */
369 stats->Set(dev_symbol, Integer::New(s->st_dev));
372 stats->Set(ino_symbol, Integer::New(s->st_ino));
375 stats->Set(mode_symbol, Integer::New(s->st_mode));
377 /* number of hard links */
378 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
380 /* user ID of owner */
381 stats->Set(uid_symbol, Integer::New(s->st_uid));
383 /* group ID of owner */
384 stats->Set(gid_symbol, Integer::New(s->st_gid));
386 /* device ID (if special file) */
387 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
389 /* total size, in bytes */
390 stats->Set(size_symbol, Integer::New(s->st_size));
392 /* blocksize for filesystem I/O */
393 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
395 /* number of blocks allocated */
396 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
398 /* time of last access */
399 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
401 /* time of last modification */
402 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
404 /* time of last status change */
405 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
407 return scope.Close(stats);
411 // Extracts a C str from a V8 Utf8Value.
412 const char* ToCString(const v8::String::Utf8Value& value) {
413 return *value ? *value : "<str conversion failed>";
416 static void ReportException(TryCatch &try_catch, bool show_line = false) {
417 Handle<Message> message = try_catch.Message();
419 Handle<Value> error = try_catch.Exception();
420 Handle<String> stack;
422 if (error->IsObject()) {
423 Handle<Object> obj = Handle<Object>::Cast(error);
424 Handle<Value> raw_stack = obj->Get(String::New("stack"));
425 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
428 if (show_line && !message.IsEmpty()) {
429 // Print (filename):(line number): (message).
430 String::Utf8Value filename(message->GetScriptResourceName());
431 const char* filename_string = ToCString(filename);
432 int linenum = message->GetLineNumber();
433 fprintf(stderr, "%s:%i\n", filename_string, linenum);
434 // Print line of source code.
435 String::Utf8Value sourceline(message->GetSourceLine());
436 const char* sourceline_string = ToCString(sourceline);
437 fprintf(stderr, "%s\n", sourceline_string);
438 // Print wavy underline (GetUnderline is deprecated).
439 int start = message->GetStartColumn();
440 for (int i = 0; i < start; i++) {
441 fprintf(stderr, " ");
443 int end = message->GetEndColumn();
444 for (int i = start; i < end; i++) {
445 fprintf(stderr, "^");
447 fprintf(stderr, "\n");
450 if (stack.IsEmpty()) {
451 message->PrintCurrentStackTrace(stderr);
453 String::Utf8Value trace(stack);
454 fprintf(stderr, "%s\n", *trace);
459 // Executes a str within the current v8 context.
460 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
464 Local<Script> script = Script::Compile(source, filename);
465 if (script.IsEmpty()) {
466 ReportException(try_catch);
470 Local<Value> result = script->Run();
471 if (result.IsEmpty()) {
472 ReportException(try_catch);
476 return scope.Close(result);
479 static Handle<Value> ByteLength(const Arguments& args) {
482 if (args.Length() < 1 || !args[0]->IsString()) {
483 return ThrowException(Exception::Error(String::New("Bad argument.")));
486 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
488 return scope.Close(length);
491 static Handle<Value> Loop(const Arguments& args) {
493 assert(args.Length() == 0);
495 // TODO Probably don't need to start this each time.
496 // Avoids failing on test/mjsunit/test-eio-race3.js though
497 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
499 ev_loop(EV_DEFAULT_UC_ 0);
503 static Handle<Value> Unloop(const Arguments& args) {
504 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
506 int how = EVUNLOOP_ONE;
507 if (args[0]->IsString()) {
508 String::Utf8Value how_s(args[0]->ToString());
509 if (0 == strcmp(*how_s, "all")) {
513 ev_unloop(EV_DEFAULT_ how);
517 static Handle<Value> Chdir(const Arguments& args) {
520 if (args.Length() != 1 || !args[0]->IsString()) {
521 return ThrowException(Exception::Error(String::New("Bad argument.")));
524 String::Utf8Value path(args[0]->ToString());
526 int r = chdir(*path);
529 return ThrowException(Exception::Error(String::New(strerror(errno))));
535 static Handle<Value> Cwd(const Arguments& args) {
537 assert(args.Length() == 0);
539 char output[PATH_MAX];
540 char *r = getcwd(output, PATH_MAX);
542 return ThrowException(Exception::Error(String::New(strerror(errno))));
544 Local<String> cwd = String::New(output);
546 return scope.Close(cwd);
549 static Handle<Value> Umask(const Arguments& args){
552 if(args.Length() < 1) {
556 else if(!args[0]->IsInt32()) {
557 return ThrowException(Exception::TypeError(
558 String::New("argument must be an integer.")));
561 old = umask((mode_t)args[0]->Uint32Value());
563 return scope.Close(Uint32::New(old));
567 static Handle<Value> GetUid(const Arguments& args) {
569 assert(args.Length() == 0);
571 return scope.Close(Integer::New(uid));
574 static Handle<Value> GetGid(const Arguments& args) {
576 assert(args.Length() == 0);
578 return scope.Close(Integer::New(gid));
582 static Handle<Value> SetGid(const Arguments& args) {
585 if (args.Length() < 1) {
586 return ThrowException(Exception::Error(
587 String::New("setgid requires 1 argument")));
590 Local<Integer> given_gid = args[0]->ToInteger();
591 int gid = given_gid->Int32Value();
593 if ((result = setgid(gid)) != 0) {
594 return ThrowException(Exception::Error(String::New(strerror(errno))));
599 static Handle<Value> SetUid(const Arguments& args) {
602 if (args.Length() < 1) {
603 return ThrowException(Exception::Error(
604 String::New("setuid requires 1 argument")));
607 Local<Integer> given_uid = args[0]->ToInteger();
608 int uid = given_uid->Int32Value();
610 if ((result = setuid(uid)) != 0) {
611 return ThrowException(Exception::Error(String::New(strerror(errno))));
617 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
621 exit(args[0]->IntegerValue());
626 #define HAVE_GETMEM 1
627 #include <unistd.h> /* getpagesize() */
629 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
630 #define PROCFS_FILE_OFFSET_BITS_HACK 1
631 #undef _FILE_OFFSET_BITS
633 #define PROCFS_FILE_OFFSET_BITS_HACK 0
638 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
639 #define _FILE_OFFSET_BITS 64
642 int getmem(size_t *rss, size_t *vsize) {
643 pid_t pid = getpid();
645 size_t page_size = getpagesize();
647 sprintf(pidpath, "/proc/%d/psinfo", pid);
650 FILE *f = fopen(pidpath, "r");
653 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
660 *vsize = (size_t) psinfo.pr_size * page_size;
661 *rss = (size_t) psinfo.pr_rssize * 1024;
671 #define HAVE_GETMEM 1
673 #include <sys/param.h>
674 #include <sys/sysctl.h>
675 #include <sys/user.h>
680 int getmem(size_t *rss, size_t *vsize) {
682 struct kinfo_proc *kinfo = NULL;
685 size_t page_size = getpagesize();
689 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
690 if (kd == NULL) goto error;
692 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
693 if (kinfo == NULL) goto error;
695 *rss = kinfo->ki_rssize * page_size;
696 *vsize = kinfo->ki_size;
703 if (kd) kvm_close(kd);
706 #endif // __FreeBSD__
710 #define HAVE_GETMEM 1
711 /* Researched by Tim Becker and Michael Knight
712 * http://blog.kuriositaet.de/?p=257
715 #include <mach/task.h>
716 #include <mach/mach_init.h>
718 int getmem(size_t *rss, size_t *vsize) {
719 struct task_basic_info t_info;
720 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
722 int r = task_info(mach_task_self(),
724 (task_info_t)&t_info,
727 if (r != KERN_SUCCESS) return -1;
729 *rss = t_info.resident_size;
730 *vsize = t_info.virtual_size;
737 # define HAVE_GETMEM 1
738 # include <sys/param.h> /* for MAXPATHLEN */
740 int getmem(size_t *rss, size_t *vsize) {
741 FILE *f = fopen("/proc/self/stat", "r");
746 char buffer[MAXPATHLEN];
747 size_t page_size = getpagesize();
750 if (fscanf(f, "%d ", &itmp) == 0) goto error;
752 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
754 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
756 if (fscanf (f, "%d ", &itmp) == 0) goto error;
758 if (fscanf (f, "%d ", &itmp) == 0) goto error;
760 if (fscanf (f, "%d ", &itmp) == 0) goto error;
762 if (fscanf (f, "%d ", &itmp) == 0) goto error;
763 /* TTY owner process group */
764 if (fscanf (f, "%d ", &itmp) == 0) goto error;
766 if (fscanf (f, "%u ", &itmp) == 0) goto error;
767 /* Minor faults (no memory page) */
768 if (fscanf (f, "%u ", &itmp) == 0) goto error;
769 /* Minor faults, children */
770 if (fscanf (f, "%u ", &itmp) == 0) goto error;
771 /* Major faults (memory page faults) */
772 if (fscanf (f, "%u ", &itmp) == 0) goto error;
773 /* Major faults, children */
774 if (fscanf (f, "%u ", &itmp) == 0) goto error;
776 if (fscanf (f, "%d ", &itmp) == 0) goto error;
778 if (fscanf (f, "%d ", &itmp) == 0) goto error;
779 /* utime, children */
780 if (fscanf (f, "%d ", &itmp) == 0) goto error;
781 /* stime, children */
782 if (fscanf (f, "%d ", &itmp) == 0) goto error;
783 /* jiffies remaining in current time slice */
784 if (fscanf (f, "%d ", &itmp) == 0) goto error;
786 if (fscanf (f, "%d ", &itmp) == 0) goto error;
787 /* jiffies until next timeout */
788 if (fscanf (f, "%u ", &itmp) == 0) goto error;
789 /* jiffies until next SIGALRM */
790 if (fscanf (f, "%u ", &itmp) == 0) goto error;
791 /* start time (jiffies since system boot) */
792 if (fscanf (f, "%d ", &itmp) == 0) goto error;
794 /* Virtual memory size */
795 if (fscanf (f, "%u ", &itmp) == 0) goto error;
796 *vsize = (size_t) itmp;
798 /* Resident set size */
799 if (fscanf (f, "%u ", &itmp) == 0) goto error;
800 *rss = (size_t) itmp * page_size;
803 if (fscanf (f, "%u ", &itmp) == 0) goto error;
805 if (fscanf (f, "%u ", &itmp) == 0) goto error;
807 if (fscanf (f, "%u ", &itmp) == 0) goto error;
809 if (fscanf (f, "%u ", &itmp) == 0) goto error;
821 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
823 assert(args.Length() == 0);
826 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
830 int r = getmem(&rss, &vsize);
833 return ThrowException(Exception::Error(String::New(strerror(errno))));
836 Local<Object> info = Object::New();
838 if (rss_symbol.IsEmpty()) {
839 rss_symbol = NODE_PSYMBOL("rss");
840 vsize_symbol = NODE_PSYMBOL("vsize");
841 heap_total_symbol = NODE_PSYMBOL("heapTotal");
842 heap_used_symbol = NODE_PSYMBOL("heapUsed");
845 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
846 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
849 HeapStatistics v8_heap_stats;
850 V8::GetHeapStatistics(&v8_heap_stats);
851 info->Set(heap_total_symbol,
852 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
853 info->Set(heap_used_symbol,
854 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
856 return scope.Close(info);
861 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
864 if (args.Length() < 1 || !args[0]->IsNumber()) {
865 return ThrowException(Exception::Error(String::New("Bad argument.")));
868 pid_t pid = args[0]->IntegerValue();
872 if (args.Length() >= 2) {
873 if (args[1]->IsNumber()) {
874 sig = args[1]->Int32Value();
875 } else if (args[1]->IsString()) {
876 Local<String> signame = args[1]->ToString();
878 Local<Value> sig_v = process->Get(signame);
879 if (!sig_v->IsNumber()) {
880 return ThrowException(Exception::Error(String::New("Unknown signal")));
882 sig = sig_v->Int32Value();
886 int r = kill(pid, sig);
889 return ThrowException(Exception::Error(String::New(strerror(errno))));
895 typedef void (*extInit)(Handle<Object> exports);
897 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
899 Handle<Value> DLOpen(const v8::Arguments& args) {
902 if (args.Length() < 2) return Undefined();
904 String::Utf8Value filename(args[0]->ToString()); // Cast
905 Local<Object> target = args[1]->ToObject(); // Cast
907 // Actually call dlopen().
908 // FIXME: This is a blocking function and should be called asynchronously!
909 // This function should be moved to file.cc and use libeio to make this
911 void *handle = dlopen(*filename, RTLD_LAZY);
914 if (handle == NULL) {
915 Local<Value> exception = Exception::Error(String::New(dlerror()));
916 return ThrowException(exception);
919 // Get the init() function from the dynamically shared object.
920 void *init_handle = dlsym(handle, "init");
921 // Error out if not found.
922 if (init_handle == NULL) {
923 Local<Value> exception =
924 Exception::Error(String::New("No 'init' symbol found in module."));
925 return ThrowException(exception);
927 extInit init = (extInit)(init_handle); // Cast
929 // Execute the C++ module
935 // evalcx(code, sandbox={})
936 // Executes code in a new context
937 Handle<Value> EvalCX(const Arguments& args) {
940 Local<String> code = args[0]->ToString();
941 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
943 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
944 : String::New("evalcx");
945 // Create the new context
946 Persistent<Context> context = Context::New();
948 // Enter and compile script
951 // Copy objects from global context, to our brand new context
952 Handle<Array> keys = sandbox->GetPropertyNames();
955 for (i = 0; i < keys->Length(); i++) {
956 Handle<String> key = keys->Get(Integer::New(i))->ToString();
957 Handle<Value> value = sandbox->Get(key);
958 context->Global()->Set(key, value);
964 Local<Script> script = Script::Compile(code, filename);
965 Handle<Value> result;
967 if (script.IsEmpty()) {
968 result = ThrowException(try_catch.Exception());
970 result = script->Run();
971 if (result.IsEmpty()) {
972 result = ThrowException(try_catch.Exception());
974 // success! copy changes back onto the sandbox object.
975 keys = context->Global()->GetPropertyNames();
976 for (i = 0; i < keys->Length(); i++) {
977 Handle<String> key = keys->Get(Integer::New(i))->ToString();
978 Handle<Value> value = context->Global()->Get(key);
979 sandbox->Set(key, value);
984 // Clean up, clean up, everybody everywhere!
985 context->DetachGlobal();
989 return scope.Close(result);
992 Handle<Value> Compile(const Arguments& args) {
995 if (args.Length() < 2) {
996 return ThrowException(Exception::TypeError(
997 String::New("needs two arguments.")));
1000 Local<String> source = args[0]->ToString();
1001 Local<String> filename = args[1]->ToString();
1005 Local<Script> script = Script::Compile(source, filename);
1006 if (try_catch.HasCaught()) {
1007 // Hack because I can't get a proper stacktrace on SyntaxError
1008 ReportException(try_catch, true);
1012 Local<Value> result = script->Run();
1013 if (try_catch.HasCaught()) return try_catch.ReThrow();
1015 return scope.Close(result);
1018 static void OnFatalError(const char* location, const char* message) {
1020 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1022 fprintf(stderr, "FATAL ERROR: %s\n", message);
1027 static int uncaught_exception_counter = 0;
1029 void FatalException(TryCatch &try_catch) {
1032 // Check if uncaught_exception_counter indicates a recursion
1033 if (uncaught_exception_counter > 0) {
1034 ReportException(try_catch);
1038 if (listeners_symbol.IsEmpty()) {
1039 listeners_symbol = NODE_PSYMBOL("listeners");
1040 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1041 emit_symbol = NODE_PSYMBOL("emit");
1044 Local<Value> listeners_v = process->Get(listeners_symbol);
1045 assert(listeners_v->IsFunction());
1047 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1049 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1050 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1051 Local<Value> ret = listeners->Call(process, 1, argv);
1053 assert(ret->IsArray());
1055 Local<Array> listener_array = Local<Array>::Cast(ret);
1057 uint32_t length = listener_array->Length();
1058 // Report and exit if process has no "uncaughtException" listener
1060 ReportException(try_catch);
1064 // Otherwise fire the process "uncaughtException" event
1065 Local<Value> emit_v = process->Get(emit_symbol);
1066 assert(emit_v->IsFunction());
1068 Local<Function> emit = Local<Function>::Cast(emit_v);
1070 Local<Value> error = try_catch.Exception();
1071 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1073 uncaught_exception_counter++;
1074 emit->Call(process, 2, event_argv);
1075 // Decrement so we know if the next exception is a recursion or not
1076 uncaught_exception_counter--;
1080 static ev_async debug_watcher;
1081 volatile static bool debugger_msg_pending = false;
1083 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1085 assert(watcher == &debug_watcher);
1086 assert(revents == EV_ASYNC);
1087 Debug::ProcessDebugMessages();
1090 static void DebugMessageDispatch(void) {
1091 // This function is called from V8's debug thread when a debug TCP client
1092 // has sent a message.
1094 // Send a signal to our main thread saying that it should enter V8 to
1095 // handle the message.
1096 debugger_msg_pending = true;
1097 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1100 static Handle<Value> CheckBreak(const Arguments& args) {
1102 assert(args.Length() == 0);
1104 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1105 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1106 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1107 // get it to halt until Eclipse connects.
1109 if (!debug_wait_connect)
1112 printf("Waiting for remote debugger connection...\n");
1114 const int halfSecond = 50;
1115 const int tenMs=10000;
1116 debugger_msg_pending = false;
1118 if (debugger_msg_pending) {
1119 Debug::DebugBreak();
1120 Debug::ProcessDebugMessages();
1121 debugger_msg_pending = false;
1123 // wait for 500 msec of silence from remote debugger
1124 int cnt = halfSecond;
1126 debugger_msg_pending = false;
1128 if (debugger_msg_pending) {
1129 debugger_msg_pending = false;
1140 Persistent<Object> binding_cache;
1142 static Handle<Value> Binding(const Arguments& args) {
1145 Local<String> module = args[0]->ToString();
1146 String::Utf8Value module_v(module);
1148 if (binding_cache.IsEmpty()) {
1149 binding_cache = Persistent<Object>::New(Object::New());
1152 Local<Object> exports;
1154 // TODO DRY THIS UP!
1156 if (!strcmp(*module_v, "stdio")) {
1157 if (binding_cache->Has(module)) {
1158 exports = binding_cache->Get(module)->ToObject();
1160 exports = Object::New();
1161 Stdio::Initialize(exports);
1162 binding_cache->Set(module, exports);
1165 } else if (!strcmp(*module_v, "http")) {
1166 if (binding_cache->Has(module)) {
1167 exports = binding_cache->Get(module)->ToObject();
1169 // Warning: When calling requireBinding('http') from javascript then
1170 // be sure that you call requireBinding('tcp') before it.
1171 assert(binding_cache->Has(String::New("tcp")));
1172 exports = Object::New();
1173 HTTPServer::Initialize(exports);
1174 HTTPConnection::Initialize(exports);
1175 binding_cache->Set(module, exports);
1178 } else if (!strcmp(*module_v, "tcp")) {
1179 if (binding_cache->Has(module)) {
1180 exports = binding_cache->Get(module)->ToObject();
1182 exports = Object::New();
1183 Server::Initialize(exports);
1184 Connection::Initialize(exports);
1185 binding_cache->Set(module, exports);
1188 } else if (!strcmp(*module_v, "cares")) {
1189 if (binding_cache->Has(module)) {
1190 exports = binding_cache->Get(module)->ToObject();
1192 exports = Object::New();
1193 Cares::Initialize(exports);
1194 binding_cache->Set(module, exports);
1197 } else if (!strcmp(*module_v, "fs")) {
1198 if (binding_cache->Has(module)) {
1199 exports = binding_cache->Get(module)->ToObject();
1201 exports = Object::New();
1203 // Initialize the stats object
1204 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1205 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1206 exports->Set(String::NewSymbol("Stats"),
1207 stats_constructor_template->GetFunction());
1208 StatWatcher::Initialize(exports);
1209 File::Initialize(exports);
1210 binding_cache->Set(module, exports);
1213 } else if (!strcmp(*module_v, "signal_watcher")) {
1214 if (binding_cache->Has(module)) {
1215 exports = binding_cache->Get(module)->ToObject();
1217 exports = Object::New();
1218 SignalWatcher::Initialize(exports);
1219 binding_cache->Set(module, exports);
1222 } else if (!strcmp(*module_v, "net")) {
1223 if (binding_cache->Has(module)) {
1224 exports = binding_cache->Get(module)->ToObject();
1226 exports = Object::New();
1228 binding_cache->Set(module, exports);
1231 } else if (!strcmp(*module_v, "http_parser")) {
1232 if (binding_cache->Has(module)) {
1233 exports = binding_cache->Get(module)->ToObject();
1235 exports = Object::New();
1236 InitHttpParser(exports);
1237 binding_cache->Set(module, exports);
1240 } else if (!strcmp(*module_v, "child_process")) {
1241 if (binding_cache->Has(module)) {
1242 exports = binding_cache->Get(module)->ToObject();
1244 exports = Object::New();
1245 ChildProcess::Initialize(exports);
1246 binding_cache->Set(module, exports);
1249 } else if (!strcmp(*module_v, "buffer")) {
1250 if (binding_cache->Has(module)) {
1251 exports = binding_cache->Get(module)->ToObject();
1253 exports = Object::New();
1254 Buffer::Initialize(exports);
1255 binding_cache->Set(module, exports);
1258 } else if (!strcmp(*module_v, "natives")) {
1259 if (binding_cache->Has(module)) {
1260 exports = binding_cache->Get(module)->ToObject();
1262 exports = Object::New();
1263 // Explicitly define native sources.
1264 // TODO DRY/automate this?
1265 exports->Set(String::New("assert"), String::New(native_assert));
1266 exports->Set(String::New("buffer"), String::New(native_buffer));
1267 exports->Set(String::New("child_process"),String::New(native_child_process));
1268 exports->Set(String::New("dns"), String::New(native_dns));
1269 exports->Set(String::New("events"), String::New(native_events));
1270 exports->Set(String::New("file"), String::New(native_file));
1271 exports->Set(String::New("fs"), String::New(native_fs));
1272 exports->Set(String::New("http"), String::New(native_http));
1273 exports->Set(String::New("http_old"), String::New(native_http_old));
1274 exports->Set(String::New("ini"), String::New(native_ini));
1275 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1276 exports->Set(String::New("net"), String::New(native_net));
1277 exports->Set(String::New("posix"), String::New(native_posix));
1278 exports->Set(String::New("querystring"), String::New(native_querystring));
1279 exports->Set(String::New("repl"), String::New(native_repl));
1280 exports->Set(String::New("sys"), String::New(native_sys));
1281 exports->Set(String::New("tcp"), String::New(native_tcp));
1282 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1283 exports->Set(String::New("uri"), String::New(native_uri));
1284 exports->Set(String::New("url"), String::New(native_url));
1285 exports->Set(String::New("utils"), String::New(native_utils));
1286 binding_cache->Set(module, exports);
1291 return ThrowException(Exception::Error(String::New("No such module")));
1294 return scope.Close(exports);
1298 static void Load(int argc, char *argv[]) {
1301 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1302 node::EventEmitter::Initialize(process_template);
1304 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1306 // Add a reference to the global object
1307 Local<Object> global = Context::GetCurrent()->Global();
1308 process->Set(String::NewSymbol("global"), global);
1311 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1312 // process.installPrefix
1313 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1316 #define xstr(s) str(s)
1318 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1322 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1323 arguments->Set(Integer::New(0), String::New(argv[0]));
1324 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1325 Local<String> arg = String::New(argv[i]);
1326 arguments->Set(Integer::New(j), arg);
1329 process->Set(String::NewSymbol("ARGV"), arguments);
1330 process->Set(String::NewSymbol("argv"), arguments);
1332 // create process.env
1333 Local<Object> env = Object::New();
1334 for (i = 0; environ[i]; i++) {
1335 // skip entries without a '=' character
1336 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1337 // create the v8 objects
1338 Local<String> field = String::New(environ[i], j);
1339 Local<String> value = Local<String>();
1340 if (environ[i][j] == '=') {
1341 value = String::New(environ[i]+j+1);
1344 env->Set(field, value);
1346 // assign process.ENV
1347 process->Set(String::NewSymbol("ENV"), env);
1348 process->Set(String::NewSymbol("env"), env);
1350 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1352 // define various internal methods
1353 NODE_SET_METHOD(process, "loop", Loop);
1354 NODE_SET_METHOD(process, "unloop", Unloop);
1355 NODE_SET_METHOD(process, "evalcx", EvalCX);
1356 NODE_SET_METHOD(process, "compile", Compile);
1357 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1358 NODE_SET_METHOD(process, "reallyExit", Exit);
1359 NODE_SET_METHOD(process, "chdir", Chdir);
1360 NODE_SET_METHOD(process, "cwd", Cwd);
1361 NODE_SET_METHOD(process, "getuid", GetUid);
1362 NODE_SET_METHOD(process, "setuid", SetUid);
1364 NODE_SET_METHOD(process, "setgid", SetGid);
1365 NODE_SET_METHOD(process, "getgid", GetGid);
1367 NODE_SET_METHOD(process, "umask", Umask);
1368 NODE_SET_METHOD(process, "dlopen", DLOpen);
1369 NODE_SET_METHOD(process, "kill", Kill);
1370 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1371 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1373 NODE_SET_METHOD(process, "binding", Binding);
1375 // Assign the EventEmitter. It was created in main().
1376 process->Set(String::NewSymbol("EventEmitter"),
1377 EventEmitter::constructor_template->GetFunction());
1381 // Initialize the C++ modules..................filename of module
1382 IOWatcher::Initialize(process); // io_watcher.cc
1383 IdleWatcher::Initialize(process); // idle_watcher.cc
1384 Timer::Initialize(process); // timer.cc
1385 DefineConstants(process); // constants.cc
1387 // Compile, execute the src/node.js file. (Which was included as static C
1388 // string in node_natives.h. 'natve_node' is the string containing that
1391 // The node.js file returns a function 'f'
1397 Local<Value> f_value = ExecuteString(String::New(native_node),
1398 String::New("node.js"));
1400 if (try_catch.HasCaught()) {
1401 ReportException(try_catch);
1405 assert(f_value->IsFunction());
1406 Local<Function> f = Local<Function>::Cast(f_value);
1408 // Now we call 'f' with the 'process' variable that we've built up with
1409 // all our bindings. Inside node.js we'll take care of assigning things to
1412 // We start the process this way in order to be more modular. Developers
1413 // who do not like how 'src/node.js' setups the module system but do like
1414 // Node's I/O bindings may want to replace 'f' with their own function.
1416 Local<Value> args[1] = { Local<Value>::New(process) };
1418 f->Call(global, 1, args);
1421 if (try_catch.HasCaught()) {
1422 ReportException(try_catch);
1428 static void PrintHelp();
1430 static void ParseDebugOpt(const char* arg) {
1433 use_debug_agent = true;
1434 if (!strcmp (arg, "--debug-brk")) {
1435 debug_wait_connect = true;
1437 } else if (!strcmp(arg, "--debug")) {
1439 } else if (strstr(arg, "--debug-brk=") == arg) {
1440 debug_wait_connect = true;
1441 p = 1 + strchr(arg, '=');
1442 debug_port = atoi(p);
1443 } else if (strstr(arg, "--debug=") == arg) {
1444 p = 1 + strchr(arg, '=');
1445 debug_port = atoi(p);
1447 if (p && debug_port > 1024 && debug_port < 65536)
1450 fprintf(stderr, "Bad debug option.\n");
1451 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1457 static void PrintHelp() {
1458 printf("Usage: node [options] script.js [arguments] \n"
1460 " -v, --version print node's version\n"
1461 " --debug[=port] enable remote debugging via given TCP port\n"
1462 " without stopping the execution\n"
1463 " --debug-brk[=port] as above, but break in script.js and\n"
1464 " wait for remote debugger to connect\n"
1465 " --v8-options print v8 command line options\n"
1466 " --vars print various compiled-in variables\n"
1468 "Enviromental variables:\n"
1469 "NODE_PATH ':'-separated list of directories\n"
1470 " prefixed to the module search path,\n"
1472 "NODE_DEBUG Print additional debugging output.\n"
1474 "Documentation can be found at http://nodejs.org/api.html"
1475 " or with 'man node'\n");
1478 // Parse node command line arguments.
1479 static void ParseArgs(int *argc, char **argv) {
1480 // TODO use parse opts
1481 for (int i = 1; i < *argc; i++) {
1482 const char *arg = argv[i];
1483 if (strstr(arg, "--debug") == arg) {
1485 argv[i] = const_cast<char*>("");
1486 option_end_index = i;
1487 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1488 printf("%s\n", NODE_VERSION);
1490 } else if (strcmp(arg, "--vars") == 0) {
1491 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1492 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1494 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1497 } else if (strcmp(arg, "--v8-options") == 0) {
1498 argv[i] = const_cast<char*>("--help");
1499 option_end_index = i+1;
1500 } else if (argv[i][0] != '-') {
1501 option_end_index = i-1;
1510 int main(int argc, char *argv[]) {
1511 // Parse a few arguments which are specific to Node.
1512 node::ParseArgs(&argc, argv);
1513 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1514 // in the command line))
1515 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1517 // Error out if we don't have a script argument.
1519 fprintf(stderr, "No script was specified.\n");
1524 // Ignore the SIGPIPE
1525 evcom_ignore_sigpipe();
1527 // Initialize the default ev loop.
1529 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1530 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1531 ev_default_loop(EVBACKEND_SELECT);
1533 ev_default_loop(EVFLAG_AUTO);
1537 ev_init(&node::gc_timer, node::CheckIdleness);
1538 node::gc_timer.repeat = GC_INTERVAL;
1539 ev_timer_again(EV_DEFAULT_UC_ &node::gc_timer);
1540 ev_unref(EV_DEFAULT_UC);
1542 ev_check_init(&node::gc_check, node::Activity);
1543 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1544 ev_unref(EV_DEFAULT_UC);
1546 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1549 // Setup the EIO thread pool
1550 { // It requires 3, yes 3, watchers.
1551 ev_idle_init(&node::eio_poller, node::DoPoll);
1553 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1554 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1555 ev_unref(EV_DEFAULT_UC);
1557 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1558 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1559 ev_unref(EV_DEFAULT_UC);
1561 eio_init(node::EIOWantPoll, node::EIODonePoll);
1562 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1563 // race conditions. See test/mjsunit/test-eio-race.js
1564 eio_set_max_poll_reqs(10);
1568 HandleScope handle_scope;
1570 V8::SetFatalErrorHandler(node::OnFatalError);
1572 // If the --debug flag was specified then initialize the debug thread.
1573 if (node::use_debug_agent) {
1574 // Initialize the async watcher for receiving messages from the debug
1575 // thread and marshal it into the main thread. DebugMessageCallback()
1576 // is called from the main thread to execute a random bit of javascript
1577 // - which will give V8 control so it can handle whatever new message
1578 // had been received on the debug thread.
1579 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1580 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1581 // Set the callback DebugMessageDispatch which is called from the debug
1583 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1584 // Start the async watcher.
1585 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1586 // unref it so that we exit the event loop despite it being active.
1587 ev_unref(EV_DEFAULT_UC);
1589 // Start the debug thread and it's associated TCP server on port 5858.
1590 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1592 // Crappy check that everything went well. FIXME
1594 // Print out some information.
1595 printf("debugger listening on port %d\n", node::debug_port);
1598 // Create the one and only Context.
1599 Persistent<Context> context = Context::New();
1600 Context::Scope context_scope(context);
1602 // Create all the objects, load modules, do everything.
1603 // so your next reading stop should be node::Load()!
1604 node::Load(argc, argv);
1606 node::Stdio::Flush();