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>
22 #include <node_cares.h>
24 #include <node_file.h>
25 #include <node_idle_watcher.h>
26 #include <node_http.h>
27 #include <node_http_parser.h>
28 #include <node_signal_watcher.h>
29 #include <node_stat_watcher.h>
30 #include <node_timer.h>
31 #include <node_child_process.h>
32 #include <node_constants.h>
33 #include <node_stdio.h>
34 #include <node_natives.h>
35 #include <node_version.h>
41 extern char **environ;
45 static Persistent<Object> process;
47 static Persistent<String> dev_symbol;
48 static Persistent<String> ino_symbol;
49 static Persistent<String> mode_symbol;
50 static Persistent<String> nlink_symbol;
51 static Persistent<String> uid_symbol;
52 static Persistent<String> gid_symbol;
53 static Persistent<String> rdev_symbol;
54 static Persistent<String> size_symbol;
55 static Persistent<String> blksize_symbol;
56 static Persistent<String> blocks_symbol;
57 static Persistent<String> atime_symbol;
58 static Persistent<String> mtime_symbol;
59 static Persistent<String> ctime_symbol;
61 static Persistent<String> rss_symbol;
62 static Persistent<String> vsize_symbol;
63 static Persistent<String> heap_total_symbol;
64 static Persistent<String> heap_used_symbol;
66 static Persistent<String> listeners_symbol;
67 static Persistent<String> uncaught_exception_symbol;
68 static Persistent<String> emit_symbol;
70 static int option_end_index = 0;
71 static bool use_debug_agent = false;
72 static bool debug_wait_connect = false;
73 static int debug_port=5858;
76 static ev_async eio_want_poll_notifier;
77 static ev_async eio_done_poll_notifier;
78 static ev_idle eio_poller;
80 // We need to notify V8 when we're idle so that it can run the garbage
81 // collector. The interface to this is V8::IdleNotification(). It returns
82 // true if the heap hasn't be fully compacted, and needs to be run again.
83 // Returning false means that it doesn't have anymore work to do.
85 // We try to wait for a period of GC_INTERVAL (2 seconds) of idleness, where
86 // idleness means that no libev watchers have been executed. Since
87 // everything in node uses libev watchers, this is a pretty good measure of
88 // idleness. This is done with gc_check, which records the timestamp
89 // last_active on every tick of the event loop, and with gc_timer which
90 // executes every few seconds to measure if
91 // last_active + GC_INTERVAL < ev_now()
92 // If we do find a period of idleness, then we start the gc_idle timer which
93 // will very repaidly call IdleNotification until the heap is fully
95 static ev_tstamp last_active;
96 static ev_timer gc_timer;
97 static ev_check gc_check;
98 static ev_idle gc_idle;
100 #define GC_INTERVAL 2.0
103 static void CheckIdleness(EV_P_ ev_timer *watcher, int revents) {
104 assert(watcher == &gc_timer);
105 assert(revents == EV_TIMER);
107 //fprintf(stderr, "check idle\n");
109 ev_tstamp idle_time = ev_now(EV_DEFAULT_UC) - last_active;
111 if (idle_time > GC_INTERVAL) {
114 if (!V8::IdleNotification()) {
115 ev_idle_start(EV_DEFAULT_UC_ &gc_idle);
119 gc_timer.repeat = GC_INTERVAL;
120 ev_timer_again(EV_DEFAULT_UC_ watcher);
125 static void NotifyIdleness(EV_P_ ev_idle *watcher, int revents) {
126 assert(watcher == &gc_idle);
127 assert(revents == EV_IDLE);
129 //fprintf(stderr, "notify idle\n");
131 if (V8::IdleNotification()) {
132 ev_idle_stop(EV_A_ watcher);
138 static void Activity(EV_P_ ev_check *watcher, int revents) {
139 assert(watcher == &gc_check);
140 assert(revents == EV_CHECK);
142 int pending = ev_pending_count(EV_DEFAULT_UC);
144 // Don't count GC watchers as activity.
146 pending -= ev_is_pending(&gc_timer);
147 pending -= ev_is_pending(&gc_idle);
148 //if (ev_is_pending(&gc_check)) pending--; // This probably never happens?
150 //fprintf(stderr, "activity, pending: %d\n", pending);
153 last_active = ev_now(EV_DEFAULT_UC);
154 ev_idle_stop(EV_DEFAULT_UC_ &gc_idle);
157 gc_timer.repeat = GC_INTERVAL;
158 ev_timer_again(EV_DEFAULT_UC_ &gc_timer);
166 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
167 assert(watcher == &eio_poller);
168 assert(revents == EV_IDLE);
170 //printf("eio_poller\n");
172 if (eio_poll() != -1) {
173 //printf("eio_poller stop\n");
174 ev_idle_stop(EV_DEFAULT_UC_ watcher);
179 // Called from the main thread.
180 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
181 assert(watcher == &eio_want_poll_notifier);
182 assert(revents == EV_ASYNC);
184 //printf("want poll notifier\n");
186 if (eio_poll() == -1) {
187 //printf("eio_poller start\n");
188 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
193 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
194 assert(watcher == &eio_done_poll_notifier);
195 assert(revents == EV_ASYNC);
197 //printf("done poll notifier\n");
199 if (eio_poll() != -1) {
200 //printf("eio_poller stop\n");
201 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
206 // EIOWantPoll() is called from the EIO thread pool each time an EIO
207 // request (that is, one of the node.fs.* functions) has completed.
208 static void EIOWantPoll(void) {
209 // Signal the main thread that eio_poll need to be processed.
210 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
214 static void EIODonePoll(void) {
215 // Signal the main thread that we should stop calling eio_poll().
216 // from the idle watcher.
217 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
221 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
224 if (!encoding_v->IsString()) return _default;
226 String::Utf8Value encoding(encoding_v->ToString());
228 if (strcasecmp(*encoding, "utf8") == 0) {
230 } else if (strcasecmp(*encoding, "utf-8") == 0) {
232 } else if (strcasecmp(*encoding, "ascii") == 0) {
234 } else if (strcasecmp(*encoding, "binary") == 0) {
236 } else if (strcasecmp(*encoding, "raw") == 0) {
237 fprintf(stderr, "'raw' (array of integers) has been removed. "
240 } else if (strcasecmp(*encoding, "raws") == 0) {
241 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
242 "Please update your code.\n");
249 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
252 if (!len) return scope.Close(String::Empty());
254 if (encoding == BINARY) {
255 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
256 uint16_t * twobytebuf = new uint16_t[len];
257 for (size_t i = 0; i < len; i++) {
258 // XXX is the following line platform independent?
259 twobytebuf[i] = cbuf[i];
261 Local<String> chunk = String::New(twobytebuf, len);
262 delete [] twobytebuf; // TODO use ExternalTwoByteString?
263 return scope.Close(chunk);
266 // utf8 or ascii encoding
267 Local<String> chunk = String::New((const char*)buf, len);
268 return scope.Close(chunk);
271 // Returns -1 if the handle was not valid for decoding
272 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
275 if (val->IsArray()) {
276 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
282 Local<String> str = val->ToString();
284 if (encoding == UTF8) return str->Utf8Length();
286 return str->Length();
290 # define MIN(a, b) ((a) < (b) ? (a) : (b))
293 // Returns number of bytes written.
294 ssize_t DecodeWrite(char *buf,
296 v8::Handle<v8::Value> val,
297 enum encoding encoding) {
301 // A lot of improvement can be made here. See:
302 // http://code.google.com/p/v8/issues/detail?id=270
303 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
304 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
306 if (val->IsArray()) {
307 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
313 Local<String> str = val->ToString();
315 if (encoding == UTF8) {
316 str->WriteUtf8(buf, buflen);
320 if (encoding == ASCII) {
321 str->WriteAscii(buf, 0, buflen);
325 // THIS IS AWFUL!!! FIXME
327 assert(encoding == BINARY);
329 uint16_t * twobytebuf = new uint16_t[buflen];
332 str->Write(twobytebuf, 0, buflen);
334 for (size_t i = 0; i < buflen; i++) {
335 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
340 delete [] twobytebuf;
345 static Persistent<FunctionTemplate> stats_constructor_template;
347 Local<Object> BuildStatsObject(struct stat * s) {
350 if (dev_symbol.IsEmpty()) {
351 dev_symbol = NODE_PSYMBOL("dev");
352 ino_symbol = NODE_PSYMBOL("ino");
353 mode_symbol = NODE_PSYMBOL("mode");
354 nlink_symbol = NODE_PSYMBOL("nlink");
355 uid_symbol = NODE_PSYMBOL("uid");
356 gid_symbol = NODE_PSYMBOL("gid");
357 rdev_symbol = NODE_PSYMBOL("rdev");
358 size_symbol = NODE_PSYMBOL("size");
359 blksize_symbol = NODE_PSYMBOL("blksize");
360 blocks_symbol = NODE_PSYMBOL("blocks");
361 atime_symbol = NODE_PSYMBOL("atime");
362 mtime_symbol = NODE_PSYMBOL("mtime");
363 ctime_symbol = NODE_PSYMBOL("ctime");
366 Local<Object> stats =
367 stats_constructor_template->GetFunction()->NewInstance();
369 /* ID of device containing file */
370 stats->Set(dev_symbol, Integer::New(s->st_dev));
373 stats->Set(ino_symbol, Integer::New(s->st_ino));
376 stats->Set(mode_symbol, Integer::New(s->st_mode));
378 /* number of hard links */
379 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
381 /* user ID of owner */
382 stats->Set(uid_symbol, Integer::New(s->st_uid));
384 /* group ID of owner */
385 stats->Set(gid_symbol, Integer::New(s->st_gid));
387 /* device ID (if special file) */
388 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
390 /* total size, in bytes */
391 stats->Set(size_symbol, Integer::New(s->st_size));
393 /* blocksize for filesystem I/O */
394 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
396 /* number of blocks allocated */
397 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
399 /* time of last access */
400 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
402 /* time of last modification */
403 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
405 /* time of last status change */
406 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
408 return scope.Close(stats);
412 // Extracts a C str from a V8 Utf8Value.
413 const char* ToCString(const v8::String::Utf8Value& value) {
414 return *value ? *value : "<str conversion failed>";
417 static void ReportException(TryCatch &try_catch, bool show_line = false) {
418 Handle<Message> message = try_catch.Message();
420 Handle<Value> error = try_catch.Exception();
421 Handle<String> stack;
423 if (error->IsObject()) {
424 Handle<Object> obj = Handle<Object>::Cast(error);
425 Handle<Value> raw_stack = obj->Get(String::New("stack"));
426 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
429 if (show_line && !message.IsEmpty()) {
430 // Print (filename):(line number): (message).
431 String::Utf8Value filename(message->GetScriptResourceName());
432 const char* filename_string = ToCString(filename);
433 int linenum = message->GetLineNumber();
434 fprintf(stderr, "%s:%i\n", filename_string, linenum);
435 // Print line of source code.
436 String::Utf8Value sourceline(message->GetSourceLine());
437 const char* sourceline_string = ToCString(sourceline);
438 fprintf(stderr, "%s\n", sourceline_string);
439 // Print wavy underline (GetUnderline is deprecated).
440 int start = message->GetStartColumn();
441 for (int i = 0; i < start; i++) {
442 fprintf(stderr, " ");
444 int end = message->GetEndColumn();
445 for (int i = start; i < end; i++) {
446 fprintf(stderr, "^");
448 fprintf(stderr, "\n");
451 if (stack.IsEmpty()) {
452 message->PrintCurrentStackTrace(stderr);
454 String::Utf8Value trace(stack);
455 fprintf(stderr, "%s\n", *trace);
460 // Executes a str within the current v8 context.
461 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
465 Local<Script> script = Script::Compile(source, filename);
466 if (script.IsEmpty()) {
467 ReportException(try_catch);
471 Local<Value> result = script->Run();
472 if (result.IsEmpty()) {
473 ReportException(try_catch);
477 return scope.Close(result);
480 static Handle<Value> ByteLength(const Arguments& args) {
483 if (args.Length() < 1 || !args[0]->IsString()) {
484 return ThrowException(Exception::Error(String::New("Bad argument.")));
487 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
489 return scope.Close(length);
492 static Handle<Value> Loop(const Arguments& args) {
494 assert(args.Length() == 0);
496 // TODO Probably don't need to start this each time.
497 // Avoids failing on test/mjsunit/test-eio-race3.js though
498 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
500 ev_loop(EV_DEFAULT_UC_ 0);
504 static Handle<Value> Unloop(const Arguments& args) {
505 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
507 int how = EVUNLOOP_ONE;
508 if (args[0]->IsString()) {
509 String::Utf8Value how_s(args[0]->ToString());
510 if (0 == strcmp(*how_s, "all")) {
514 ev_unloop(EV_DEFAULT_ how);
518 static Handle<Value> Chdir(const Arguments& args) {
521 if (args.Length() != 1 || !args[0]->IsString()) {
522 return ThrowException(Exception::Error(String::New("Bad argument.")));
525 String::Utf8Value path(args[0]->ToString());
527 int r = chdir(*path);
530 return ThrowException(Exception::Error(String::New(strerror(errno))));
536 static Handle<Value> Cwd(const Arguments& args) {
538 assert(args.Length() == 0);
540 char output[PATH_MAX];
541 char *r = getcwd(output, PATH_MAX);
543 return ThrowException(Exception::Error(String::New(strerror(errno))));
545 Local<String> cwd = String::New(output);
547 return scope.Close(cwd);
550 static Handle<Value> Umask(const Arguments& args){
553 if(args.Length() < 1) {
557 else if(!args[0]->IsInt32()) {
558 return ThrowException(Exception::TypeError(
559 String::New("argument must be an integer.")));
562 old = umask((mode_t)args[0]->Uint32Value());
564 return scope.Close(Uint32::New(old));
568 static Handle<Value> GetUid(const Arguments& args) {
570 assert(args.Length() == 0);
572 return scope.Close(Integer::New(uid));
575 static Handle<Value> GetGid(const Arguments& args) {
577 assert(args.Length() == 0);
579 return scope.Close(Integer::New(gid));
583 static Handle<Value> SetGid(const Arguments& args) {
586 if (args.Length() < 1) {
587 return ThrowException(Exception::Error(
588 String::New("setgid requires 1 argument")));
591 Local<Integer> given_gid = args[0]->ToInteger();
592 int gid = given_gid->Int32Value();
594 if ((result = setgid(gid)) != 0) {
595 return ThrowException(Exception::Error(String::New(strerror(errno))));
600 static Handle<Value> SetUid(const Arguments& args) {
603 if (args.Length() < 1) {
604 return ThrowException(Exception::Error(
605 String::New("setuid requires 1 argument")));
608 Local<Integer> given_uid = args[0]->ToInteger();
609 int uid = given_uid->Int32Value();
611 if ((result = setuid(uid)) != 0) {
612 return ThrowException(Exception::Error(String::New(strerror(errno))));
618 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
622 exit(args[0]->IntegerValue());
627 #define HAVE_GETMEM 1
628 #include <unistd.h> /* getpagesize() */
630 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
631 #define PROCFS_FILE_OFFSET_BITS_HACK 1
632 #undef _FILE_OFFSET_BITS
634 #define PROCFS_FILE_OFFSET_BITS_HACK 0
639 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
640 #define _FILE_OFFSET_BITS 64
643 int getmem(size_t *rss, size_t *vsize) {
644 pid_t pid = getpid();
646 size_t page_size = getpagesize();
648 sprintf(pidpath, "/proc/%d/psinfo", pid);
651 FILE *f = fopen(pidpath, "r");
654 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
661 *vsize = (size_t) psinfo.pr_size * page_size;
662 *rss = (size_t) psinfo.pr_rssize * 1024;
672 #define HAVE_GETMEM 1
674 #include <sys/param.h>
675 #include <sys/sysctl.h>
676 #include <sys/user.h>
681 int getmem(size_t *rss, size_t *vsize) {
683 struct kinfo_proc *kinfo = NULL;
686 size_t page_size = getpagesize();
690 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open");
691 if (kd == NULL) goto error;
693 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
694 if (kinfo == NULL) goto error;
696 *rss = kinfo->ki_rssize * page_size;
697 *vsize = kinfo->ki_size;
704 if (kd) kvm_close(kd);
707 #endif // __FreeBSD__
711 #define HAVE_GETMEM 1
712 /* Researched by Tim Becker and Michael Knight
713 * http://blog.kuriositaet.de/?p=257
716 #include <mach/task.h>
717 #include <mach/mach_init.h>
719 int getmem(size_t *rss, size_t *vsize) {
720 struct task_basic_info t_info;
721 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
723 int r = task_info(mach_task_self(),
725 (task_info_t)&t_info,
728 if (r != KERN_SUCCESS) return -1;
730 *rss = t_info.resident_size;
731 *vsize = t_info.virtual_size;
738 # define HAVE_GETMEM 1
739 # include <sys/param.h> /* for MAXPATHLEN */
741 int getmem(size_t *rss, size_t *vsize) {
742 FILE *f = fopen("/proc/self/stat", "r");
747 char buffer[MAXPATHLEN];
748 size_t page_size = getpagesize();
751 if (fscanf(f, "%d ", &itmp) == 0) goto error;
753 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
755 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
757 if (fscanf (f, "%d ", &itmp) == 0) goto error;
759 if (fscanf (f, "%d ", &itmp) == 0) goto error;
761 if (fscanf (f, "%d ", &itmp) == 0) goto error;
763 if (fscanf (f, "%d ", &itmp) == 0) goto error;
764 /* TTY owner process group */
765 if (fscanf (f, "%d ", &itmp) == 0) goto error;
767 if (fscanf (f, "%u ", &itmp) == 0) goto error;
768 /* Minor faults (no memory page) */
769 if (fscanf (f, "%u ", &itmp) == 0) goto error;
770 /* Minor faults, children */
771 if (fscanf (f, "%u ", &itmp) == 0) goto error;
772 /* Major faults (memory page faults) */
773 if (fscanf (f, "%u ", &itmp) == 0) goto error;
774 /* Major faults, children */
775 if (fscanf (f, "%u ", &itmp) == 0) goto error;
777 if (fscanf (f, "%d ", &itmp) == 0) goto error;
779 if (fscanf (f, "%d ", &itmp) == 0) goto error;
780 /* utime, children */
781 if (fscanf (f, "%d ", &itmp) == 0) goto error;
782 /* stime, children */
783 if (fscanf (f, "%d ", &itmp) == 0) goto error;
784 /* jiffies remaining in current time slice */
785 if (fscanf (f, "%d ", &itmp) == 0) goto error;
787 if (fscanf (f, "%d ", &itmp) == 0) goto error;
788 /* jiffies until next timeout */
789 if (fscanf (f, "%u ", &itmp) == 0) goto error;
790 /* jiffies until next SIGALRM */
791 if (fscanf (f, "%u ", &itmp) == 0) goto error;
792 /* start time (jiffies since system boot) */
793 if (fscanf (f, "%d ", &itmp) == 0) goto error;
795 /* Virtual memory size */
796 if (fscanf (f, "%u ", &itmp) == 0) goto error;
797 *vsize = (size_t) itmp;
799 /* Resident set size */
800 if (fscanf (f, "%u ", &itmp) == 0) goto error;
801 *rss = (size_t) itmp * page_size;
804 if (fscanf (f, "%u ", &itmp) == 0) goto error;
806 if (fscanf (f, "%u ", &itmp) == 0) goto error;
808 if (fscanf (f, "%u ", &itmp) == 0) goto error;
810 if (fscanf (f, "%u ", &itmp) == 0) goto error;
822 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
824 assert(args.Length() == 0);
827 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
831 int r = getmem(&rss, &vsize);
834 return ThrowException(Exception::Error(String::New(strerror(errno))));
837 Local<Object> info = Object::New();
839 if (rss_symbol.IsEmpty()) {
840 rss_symbol = NODE_PSYMBOL("rss");
841 vsize_symbol = NODE_PSYMBOL("vsize");
842 heap_total_symbol = NODE_PSYMBOL("heapTotal");
843 heap_used_symbol = NODE_PSYMBOL("heapUsed");
846 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
847 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
850 HeapStatistics v8_heap_stats;
851 V8::GetHeapStatistics(&v8_heap_stats);
852 info->Set(heap_total_symbol,
853 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
854 info->Set(heap_used_symbol,
855 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
857 return scope.Close(info);
862 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
865 if (args.Length() < 1 || !args[0]->IsNumber()) {
866 return ThrowException(Exception::Error(String::New("Bad argument.")));
869 pid_t pid = args[0]->IntegerValue();
873 if (args.Length() >= 2) {
874 if (args[1]->IsNumber()) {
875 sig = args[1]->Int32Value();
876 } else if (args[1]->IsString()) {
877 Local<String> signame = args[1]->ToString();
879 Local<Value> sig_v = process->Get(signame);
880 if (!sig_v->IsNumber()) {
881 return ThrowException(Exception::Error(String::New("Unknown signal")));
883 sig = sig_v->Int32Value();
887 int r = kill(pid, sig);
890 return ThrowException(Exception::Error(String::New(strerror(errno))));
896 typedef void (*extInit)(Handle<Object> exports);
898 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
900 Handle<Value> DLOpen(const v8::Arguments& args) {
903 if (args.Length() < 2) return Undefined();
905 String::Utf8Value filename(args[0]->ToString()); // Cast
906 Local<Object> target = args[1]->ToObject(); // Cast
908 // Actually call dlopen().
909 // FIXME: This is a blocking function and should be called asynchronously!
910 // This function should be moved to file.cc and use libeio to make this
912 void *handle = dlopen(*filename, RTLD_LAZY);
915 if (handle == NULL) {
916 Local<Value> exception = Exception::Error(String::New(dlerror()));
917 return ThrowException(exception);
920 // Get the init() function from the dynamically shared object.
921 void *init_handle = dlsym(handle, "init");
922 // Error out if not found.
923 if (init_handle == NULL) {
924 Local<Value> exception =
925 Exception::Error(String::New("No 'init' symbol found in module."));
926 return ThrowException(exception);
928 extInit init = (extInit)(init_handle); // Cast
930 // Execute the C++ module
936 // evalcx(code, sandbox={})
937 // Executes code in a new context
938 Handle<Value> EvalCX(const Arguments& args) {
941 Local<String> code = args[0]->ToString();
942 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
944 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
945 : String::New("evalcx");
946 // Create the new context
947 Persistent<Context> context = Context::New();
949 // Enter and compile script
952 // Copy objects from global context, to our brand new context
953 Handle<Array> keys = sandbox->GetPropertyNames();
956 for (i = 0; i < keys->Length(); i++) {
957 Handle<String> key = keys->Get(Integer::New(i))->ToString();
958 Handle<Value> value = sandbox->Get(key);
959 context->Global()->Set(key, value);
965 Local<Script> script = Script::Compile(code, filename);
966 Handle<Value> result;
968 if (script.IsEmpty()) {
969 result = ThrowException(try_catch.Exception());
971 result = script->Run();
972 if (result.IsEmpty()) {
973 result = ThrowException(try_catch.Exception());
975 // success! copy changes back onto the sandbox object.
976 keys = context->Global()->GetPropertyNames();
977 for (i = 0; i < keys->Length(); i++) {
978 Handle<String> key = keys->Get(Integer::New(i))->ToString();
979 Handle<Value> value = context->Global()->Get(key);
980 sandbox->Set(key, value);
985 // Clean up, clean up, everybody everywhere!
986 context->DetachGlobal();
990 return scope.Close(result);
993 Handle<Value> Compile(const Arguments& args) {
996 if (args.Length() < 2) {
997 return ThrowException(Exception::TypeError(
998 String::New("needs two arguments.")));
1001 Local<String> source = args[0]->ToString();
1002 Local<String> filename = args[1]->ToString();
1006 Local<Script> script = Script::Compile(source, filename);
1007 if (try_catch.HasCaught()) {
1008 // Hack because I can't get a proper stacktrace on SyntaxError
1009 ReportException(try_catch, true);
1013 Local<Value> result = script->Run();
1014 if (try_catch.HasCaught()) return try_catch.ReThrow();
1016 return scope.Close(result);
1019 static void OnFatalError(const char* location, const char* message) {
1021 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1023 fprintf(stderr, "FATAL ERROR: %s\n", message);
1028 static int uncaught_exception_counter = 0;
1030 void FatalException(TryCatch &try_catch) {
1033 // Check if uncaught_exception_counter indicates a recursion
1034 if (uncaught_exception_counter > 0) {
1035 ReportException(try_catch);
1039 if (listeners_symbol.IsEmpty()) {
1040 listeners_symbol = NODE_PSYMBOL("listeners");
1041 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
1042 emit_symbol = NODE_PSYMBOL("emit");
1045 Local<Value> listeners_v = process->Get(listeners_symbol);
1046 assert(listeners_v->IsFunction());
1048 Local<Function> listeners = Local<Function>::Cast(listeners_v);
1050 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
1051 Local<Value> argv[1] = { uncaught_exception_symbol_l };
1052 Local<Value> ret = listeners->Call(process, 1, argv);
1054 assert(ret->IsArray());
1056 Local<Array> listener_array = Local<Array>::Cast(ret);
1058 uint32_t length = listener_array->Length();
1059 // Report and exit if process has no "uncaughtException" listener
1061 ReportException(try_catch);
1065 // Otherwise fire the process "uncaughtException" event
1066 Local<Value> emit_v = process->Get(emit_symbol);
1067 assert(emit_v->IsFunction());
1069 Local<Function> emit = Local<Function>::Cast(emit_v);
1071 Local<Value> error = try_catch.Exception();
1072 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1074 uncaught_exception_counter++;
1075 emit->Call(process, 2, event_argv);
1076 // Decrement so we know if the next exception is a recursion or not
1077 uncaught_exception_counter--;
1081 static ev_async debug_watcher;
1082 volatile static bool debugger_msg_pending = false;
1084 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1086 assert(watcher == &debug_watcher);
1087 assert(revents == EV_ASYNC);
1088 Debug::ProcessDebugMessages();
1091 static void DebugMessageDispatch(void) {
1092 // This function is called from V8's debug thread when a debug TCP client
1093 // has sent a message.
1095 // Send a signal to our main thread saying that it should enter V8 to
1096 // handle the message.
1097 debugger_msg_pending = true;
1098 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1101 static Handle<Value> CheckBreak(const Arguments& args) {
1103 assert(args.Length() == 0);
1105 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1106 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1107 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1108 // get it to halt until Eclipse connects.
1110 if (!debug_wait_connect)
1113 printf("Waiting for remote debugger connection...\n");
1115 const int halfSecond = 50;
1116 const int tenMs=10000;
1117 debugger_msg_pending = false;
1119 if (debugger_msg_pending) {
1120 Debug::DebugBreak();
1121 Debug::ProcessDebugMessages();
1122 debugger_msg_pending = false;
1124 // wait for 500 msec of silence from remote debugger
1125 int cnt = halfSecond;
1127 debugger_msg_pending = false;
1129 if (debugger_msg_pending) {
1130 debugger_msg_pending = false;
1141 Persistent<Object> binding_cache;
1143 static Handle<Value> Binding(const Arguments& args) {
1146 Local<String> module = args[0]->ToString();
1147 String::Utf8Value module_v(module);
1149 if (binding_cache.IsEmpty()) {
1150 binding_cache = Persistent<Object>::New(Object::New());
1153 Local<Object> exports;
1155 // TODO DRY THIS UP!
1157 if (!strcmp(*module_v, "stdio")) {
1158 if (binding_cache->Has(module)) {
1159 exports = binding_cache->Get(module)->ToObject();
1161 exports = Object::New();
1162 Stdio::Initialize(exports);
1163 binding_cache->Set(module, exports);
1166 } else if (!strcmp(*module_v, "http")) {
1167 if (binding_cache->Has(module)) {
1168 exports = binding_cache->Get(module)->ToObject();
1170 // Warning: When calling requireBinding('http') from javascript then
1171 // be sure that you call requireBinding('tcp') before it.
1172 assert(binding_cache->Has(String::New("tcp")));
1173 exports = Object::New();
1174 HTTPServer::Initialize(exports);
1175 HTTPConnection::Initialize(exports);
1176 binding_cache->Set(module, exports);
1179 } else if (!strcmp(*module_v, "tcp")) {
1180 if (binding_cache->Has(module)) {
1181 exports = binding_cache->Get(module)->ToObject();
1183 exports = Object::New();
1184 Server::Initialize(exports);
1185 Connection::Initialize(exports);
1186 binding_cache->Set(module, exports);
1189 } else if (!strcmp(*module_v, "dns")) {
1190 if (binding_cache->Has(module)) {
1191 exports = binding_cache->Get(module)->ToObject();
1193 exports = Object::New();
1194 DNS::Initialize(exports);
1195 binding_cache->Set(module, exports);
1198 } else if (!strcmp(*module_v, "cares")) {
1199 if (binding_cache->Has(module)) {
1200 exports = binding_cache->Get(module)->ToObject();
1202 exports = Object::New();
1203 Cares::Initialize(exports);
1204 binding_cache->Set(module, exports);
1207 } else if (!strcmp(*module_v, "fs")) {
1208 if (binding_cache->Has(module)) {
1209 exports = binding_cache->Get(module)->ToObject();
1211 exports = Object::New();
1213 // Initialize the stats object
1214 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1215 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1216 exports->Set(String::NewSymbol("Stats"),
1217 stats_constructor_template->GetFunction());
1218 StatWatcher::Initialize(exports);
1219 File::Initialize(exports);
1220 binding_cache->Set(module, exports);
1223 } else if (!strcmp(*module_v, "signal_watcher")) {
1224 if (binding_cache->Has(module)) {
1225 exports = binding_cache->Get(module)->ToObject();
1227 exports = Object::New();
1228 SignalWatcher::Initialize(exports);
1229 binding_cache->Set(module, exports);
1232 } else if (!strcmp(*module_v, "net")) {
1233 if (binding_cache->Has(module)) {
1234 exports = binding_cache->Get(module)->ToObject();
1236 exports = Object::New();
1238 binding_cache->Set(module, exports);
1241 } else if (!strcmp(*module_v, "http_parser")) {
1242 if (binding_cache->Has(module)) {
1243 exports = binding_cache->Get(module)->ToObject();
1245 exports = Object::New();
1246 InitHttpParser(exports);
1247 binding_cache->Set(module, exports);
1250 } else if (!strcmp(*module_v, "child_process")) {
1251 if (binding_cache->Has(module)) {
1252 exports = binding_cache->Get(module)->ToObject();
1254 exports = Object::New();
1255 ChildProcess::Initialize(exports);
1256 binding_cache->Set(module, exports);
1259 } else if (!strcmp(*module_v, "buffer")) {
1260 if (binding_cache->Has(module)) {
1261 exports = binding_cache->Get(module)->ToObject();
1263 exports = Object::New();
1264 Buffer::Initialize(exports);
1265 binding_cache->Set(module, exports);
1268 } else if (!strcmp(*module_v, "natives")) {
1269 if (binding_cache->Has(module)) {
1270 exports = binding_cache->Get(module)->ToObject();
1272 exports = Object::New();
1273 // Explicitly define native sources.
1274 // TODO DRY/automate this?
1275 exports->Set(String::New("assert"), String::New(native_assert));
1276 exports->Set(String::New("buffer"), String::New(native_buffer));
1277 exports->Set(String::New("child_process"),String::New(native_child_process));
1278 exports->Set(String::New("dns"), String::New(native_dns));
1279 exports->Set(String::New("dns_cares"), String::New(native_dns_cares));
1280 exports->Set(String::New("events"), String::New(native_events));
1281 exports->Set(String::New("file"), String::New(native_file));
1282 exports->Set(String::New("fs"), String::New(native_fs));
1283 exports->Set(String::New("http"), String::New(native_http));
1284 exports->Set(String::New("http_old"), String::New(native_http_old));
1285 exports->Set(String::New("ini"), String::New(native_ini));
1286 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1287 exports->Set(String::New("net"), String::New(native_net));
1288 exports->Set(String::New("posix"), String::New(native_posix));
1289 exports->Set(String::New("querystring"), String::New(native_querystring));
1290 exports->Set(String::New("repl"), String::New(native_repl));
1291 exports->Set(String::New("sys"), String::New(native_sys));
1292 exports->Set(String::New("tcp"), String::New(native_tcp));
1293 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1294 exports->Set(String::New("uri"), String::New(native_uri));
1295 exports->Set(String::New("url"), String::New(native_url));
1296 exports->Set(String::New("utils"), String::New(native_utils));
1297 binding_cache->Set(module, exports);
1302 return ThrowException(Exception::Error(String::New("No such module")));
1305 return scope.Close(exports);
1309 static void Load(int argc, char *argv[]) {
1312 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1313 node::EventEmitter::Initialize(process_template);
1315 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1317 // Add a reference to the global object
1318 Local<Object> global = Context::GetCurrent()->Global();
1319 process->Set(String::NewSymbol("global"), global);
1322 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1323 // process.installPrefix
1324 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1327 #define xstr(s) str(s)
1329 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1333 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1334 arguments->Set(Integer::New(0), String::New(argv[0]));
1335 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1336 Local<String> arg = String::New(argv[i]);
1337 arguments->Set(Integer::New(j), arg);
1340 process->Set(String::NewSymbol("ARGV"), arguments);
1341 process->Set(String::NewSymbol("argv"), arguments);
1343 // create process.env
1344 Local<Object> env = Object::New();
1345 for (i = 0; environ[i]; i++) {
1346 // skip entries without a '=' character
1347 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1348 // create the v8 objects
1349 Local<String> field = String::New(environ[i], j);
1350 Local<String> value = Local<String>();
1351 if (environ[i][j] == '=') {
1352 value = String::New(environ[i]+j+1);
1355 env->Set(field, value);
1357 // assign process.ENV
1358 process->Set(String::NewSymbol("ENV"), env);
1359 process->Set(String::NewSymbol("env"), env);
1361 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1363 // define various internal methods
1364 NODE_SET_METHOD(process, "loop", Loop);
1365 NODE_SET_METHOD(process, "unloop", Unloop);
1366 NODE_SET_METHOD(process, "evalcx", EvalCX);
1367 NODE_SET_METHOD(process, "compile", Compile);
1368 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1369 NODE_SET_METHOD(process, "reallyExit", Exit);
1370 NODE_SET_METHOD(process, "chdir", Chdir);
1371 NODE_SET_METHOD(process, "cwd", Cwd);
1372 NODE_SET_METHOD(process, "getuid", GetUid);
1373 NODE_SET_METHOD(process, "setuid", SetUid);
1375 NODE_SET_METHOD(process, "setgid", SetGid);
1376 NODE_SET_METHOD(process, "getgid", GetGid);
1378 NODE_SET_METHOD(process, "umask", Umask);
1379 NODE_SET_METHOD(process, "dlopen", DLOpen);
1380 NODE_SET_METHOD(process, "kill", Kill);
1381 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1382 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1384 NODE_SET_METHOD(process, "binding", Binding);
1386 // Assign the EventEmitter. It was created in main().
1387 process->Set(String::NewSymbol("EventEmitter"),
1388 EventEmitter::constructor_template->GetFunction());
1392 // Initialize the C++ modules..................filename of module
1393 IOWatcher::Initialize(process); // io_watcher.cc
1394 IdleWatcher::Initialize(process); // idle_watcher.cc
1395 Timer::Initialize(process); // timer.cc
1396 DefineConstants(process); // constants.cc
1398 // Compile, execute the src/node.js file. (Which was included as static C
1399 // string in node_natives.h. 'natve_node' is the string containing that
1402 // The node.js file returns a function 'f'
1408 Local<Value> f_value = ExecuteString(String::New(native_node),
1409 String::New("node.js"));
1411 if (try_catch.HasCaught()) {
1412 ReportException(try_catch);
1416 assert(f_value->IsFunction());
1417 Local<Function> f = Local<Function>::Cast(f_value);
1419 // Now we call 'f' with the 'process' variable that we've built up with
1420 // all our bindings. Inside node.js we'll take care of assigning things to
1423 // We start the process this way in order to be more modular. Developers
1424 // who do not like how 'src/node.js' setups the module system but do like
1425 // Node's I/O bindings may want to replace 'f' with their own function.
1427 Local<Value> args[1] = { Local<Value>::New(process) };
1429 f->Call(global, 1, args);
1432 if (try_catch.HasCaught()) {
1433 ReportException(try_catch);
1439 static void PrintHelp();
1441 static void ParseDebugOpt(const char* arg) {
1444 use_debug_agent = true;
1445 if (!strcmp (arg, "--debug-brk")) {
1446 debug_wait_connect = true;
1448 } else if (!strcmp(arg, "--debug")) {
1450 } else if (strstr(arg, "--debug-brk=") == arg) {
1451 debug_wait_connect = true;
1452 p = 1 + strchr(arg, '=');
1453 debug_port = atoi(p);
1454 } else if (strstr(arg, "--debug=") == arg) {
1455 p = 1 + strchr(arg, '=');
1456 debug_port = atoi(p);
1458 if (p && debug_port > 1024 && debug_port < 65536)
1461 fprintf(stderr, "Bad debug option.\n");
1462 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1468 static void PrintHelp() {
1469 printf("Usage: node [options] script.js [arguments] \n"
1471 " -v, --version print node's version\n"
1472 " --debug[=port] enable remote debugging via given TCP port\n"
1473 " without stopping the execution\n"
1474 " --debug-brk[=port] as above, but break in script.js and\n"
1475 " wait for remote debugger to connect\n"
1476 " --v8-options print v8 command line options\n"
1477 " --vars print various compiled-in variables\n"
1479 "Enviromental variables:\n"
1480 "NODE_PATH ':'-separated list of directories\n"
1481 " prefixed to the module search path,\n"
1483 "NODE_DEBUG Print additional debugging output.\n"
1485 "Documentation can be found at http://nodejs.org/api.html"
1486 " or with 'man node'\n");
1489 // Parse node command line arguments.
1490 static void ParseArgs(int *argc, char **argv) {
1491 // TODO use parse opts
1492 for (int i = 1; i < *argc; i++) {
1493 const char *arg = argv[i];
1494 if (strstr(arg, "--debug") == arg) {
1496 argv[i] = const_cast<char*>("");
1497 option_end_index = i;
1498 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1499 printf("%s\n", NODE_VERSION);
1501 } else if (strcmp(arg, "--vars") == 0) {
1502 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1503 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1505 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1508 } else if (strcmp(arg, "--v8-options") == 0) {
1509 argv[i] = const_cast<char*>("--help");
1510 option_end_index = i+1;
1511 } else if (argv[i][0] != '-') {
1512 option_end_index = i-1;
1521 int main(int argc, char *argv[]) {
1522 // Parse a few arguments which are specific to Node.
1523 node::ParseArgs(&argc, argv);
1524 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1525 // in the command line))
1526 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1528 // Error out if we don't have a script argument.
1530 fprintf(stderr, "No script was specified.\n");
1535 // Ignore the SIGPIPE
1536 evcom_ignore_sigpipe();
1538 // Initialize the default ev loop.
1540 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1541 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1542 ev_default_loop(EVBACKEND_SELECT);
1544 ev_default_loop(EVFLAG_AUTO);
1548 ev_init(&node::gc_timer, node::CheckIdleness);
1549 node::gc_timer.repeat = GC_INTERVAL;
1550 ev_timer_again(EV_DEFAULT_UC_ &node::gc_timer);
1551 ev_unref(EV_DEFAULT_UC);
1553 ev_check_init(&node::gc_check, node::Activity);
1554 ev_check_start(EV_DEFAULT_UC_ &node::gc_check);
1555 ev_unref(EV_DEFAULT_UC);
1557 ev_idle_init(&node::gc_idle, node::NotifyIdleness);
1560 // Setup the EIO thread pool
1561 { // It requires 3, yes 3, watchers.
1562 ev_idle_init(&node::eio_poller, node::DoPoll);
1564 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1565 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1566 ev_unref(EV_DEFAULT_UC);
1568 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1569 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1570 ev_unref(EV_DEFAULT_UC);
1572 eio_init(node::EIOWantPoll, node::EIODonePoll);
1573 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1574 // race conditions. See test/mjsunit/test-eio-race.js
1575 eio_set_max_poll_reqs(10);
1579 HandleScope handle_scope;
1581 V8::SetFatalErrorHandler(node::OnFatalError);
1583 // If the --debug flag was specified then initialize the debug thread.
1584 if (node::use_debug_agent) {
1585 // Initialize the async watcher for receiving messages from the debug
1586 // thread and marshal it into the main thread. DebugMessageCallback()
1587 // is called from the main thread to execute a random bit of javascript
1588 // - which will give V8 control so it can handle whatever new message
1589 // had been received on the debug thread.
1590 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1591 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1592 // Set the callback DebugMessageDispatch which is called from the debug
1594 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1595 // Start the async watcher.
1596 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1597 // unref it so that we exit the event loop despite it being active.
1598 ev_unref(EV_DEFAULT_UC);
1600 // Start the debug thread and it's associated TCP server on port 5858.
1601 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1603 // Crappy check that everything went well. FIXME
1605 // Print out some information.
1606 printf("debugger listening on port %d\n", node::debug_port);
1609 // Create the one and only Context.
1610 Persistent<Context> context = Context::New();
1611 Context::Scope context_scope(context);
1613 // Create all the objects, load modules, do everything.
1614 // so your next reading stop should be node::Load()!
1615 node::Load(argc, argv);
1617 node::Stdio::Flush();