1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
7 #include <limits.h> /* PATH_MAX */
11 #include <dlfcn.h> /* dlopen(), dlsym() */
12 #include <sys/types.h>
13 #include <unistd.h> /* setuid, getuid */
15 #include <node_buffer.h>
16 #include <node_io_watcher.h>
17 #include <node_net2.h>
18 #include <node_events.h>
21 #include <node_file.h>
22 #include <node_idle_watcher.h>
23 #include <node_http.h>
24 #include <node_http_parser.h>
25 #include <node_signal_handler.h>
26 #include <node_stat.h>
27 #include <node_timer.h>
28 #include <node_child_process.h>
29 #include <node_constants.h>
30 #include <node_stdio.h>
31 #include <node_natives.h>
32 #include <node_version.h>
38 extern char **environ;
42 static Persistent<Object> process;
44 static Persistent<String> dev_symbol;
45 static Persistent<String> ino_symbol;
46 static Persistent<String> mode_symbol;
47 static Persistent<String> nlink_symbol;
48 static Persistent<String> uid_symbol;
49 static Persistent<String> gid_symbol;
50 static Persistent<String> rdev_symbol;
51 static Persistent<String> size_symbol;
52 static Persistent<String> blksize_symbol;
53 static Persistent<String> blocks_symbol;
54 static Persistent<String> atime_symbol;
55 static Persistent<String> mtime_symbol;
56 static Persistent<String> ctime_symbol;
58 static Persistent<String> rss_symbol;
59 static Persistent<String> vsize_symbol;
60 static Persistent<String> heap_total_symbol;
61 static Persistent<String> heap_used_symbol;
63 static Persistent<String> listeners_symbol;
64 static Persistent<String> uncaught_exception_symbol;
65 static Persistent<String> emit_symbol;
67 static int option_end_index = 0;
68 static bool use_debug_agent = false;
69 static bool debug_wait_connect = false;
70 static int debug_port=5858;
73 static ev_async eio_want_poll_notifier;
74 static ev_async eio_done_poll_notifier;
75 static ev_idle eio_poller;
77 static ev_timer gc_timer;
78 #define GC_INTERVAL 2.0
81 // Node calls this every GC_INTERVAL seconds in order to try and call the
82 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
83 // is an effective measure of idleness.
84 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
85 assert(watcher == &gc_timer);
86 assert(revents == EV_TIMER);
87 if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
91 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
92 assert(watcher == &eio_poller);
93 assert(revents == EV_IDLE);
95 //printf("eio_poller\n");
97 if (eio_poll() != -1) {
98 //printf("eio_poller stop\n");
99 ev_idle_stop(EV_DEFAULT_UC_ watcher);
104 // Called from the main thread.
105 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
106 assert(watcher == &eio_want_poll_notifier);
107 assert(revents == EV_ASYNC);
109 //printf("want poll notifier\n");
111 if (eio_poll() == -1) {
112 //printf("eio_poller start\n");
113 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
118 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
119 assert(watcher == &eio_done_poll_notifier);
120 assert(revents == EV_ASYNC);
122 //printf("done poll notifier\n");
124 if (eio_poll() != -1) {
125 //printf("eio_poller stop\n");
126 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
131 // EIOWantPoll() is called from the EIO thread pool each time an EIO
132 // request (that is, one of the node.fs.* functions) has completed.
133 static void EIOWantPoll(void) {
134 // Signal the main thread that eio_poll need to be processed.
135 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
139 static void EIODonePoll(void) {
140 // Signal the main thread that we should stop calling eio_poll().
141 // from the idle watcher.
142 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
146 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
149 if (!encoding_v->IsString()) return _default;
151 String::Utf8Value encoding(encoding_v->ToString());
153 if (strcasecmp(*encoding, "utf8") == 0) {
155 } else if (strcasecmp(*encoding, "utf-8") == 0) {
157 } else if (strcasecmp(*encoding, "ascii") == 0) {
159 } else if (strcasecmp(*encoding, "binary") == 0) {
161 } else if (strcasecmp(*encoding, "raw") == 0) {
162 fprintf(stderr, "'raw' (array of integers) has been removed. "
165 } else if (strcasecmp(*encoding, "raws") == 0) {
166 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
167 "Please update your code.\n");
174 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
177 if (!len) return scope.Close(String::Empty());
179 if (encoding == BINARY) {
180 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
181 uint16_t * twobytebuf = new uint16_t[len];
182 for (size_t i = 0; i < len; i++) {
183 // XXX is the following line platform independent?
184 twobytebuf[i] = cbuf[i];
186 Local<String> chunk = String::New(twobytebuf, len);
187 delete [] twobytebuf; // TODO use ExternalTwoByteString?
188 return scope.Close(chunk);
191 // utf8 or ascii encoding
192 Local<String> chunk = String::New((const char*)buf, len);
193 return scope.Close(chunk);
196 // Returns -1 if the handle was not valid for decoding
197 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
200 if (val->IsArray()) {
201 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
207 Local<String> str = val->ToString();
209 if (encoding == UTF8) return str->Utf8Length();
211 return str->Length();
215 # define MIN(a, b) ((a) < (b) ? (a) : (b))
218 // Returns number of bytes written.
219 ssize_t DecodeWrite(char *buf, size_t buflen,
220 v8::Handle<v8::Value> val,
221 enum encoding encoding) {
225 // A lot of improvement can be made here. See:
226 // http://code.google.com/p/v8/issues/detail?id=270
227 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
228 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
230 if (val->IsArray()) {
231 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
237 Local<String> str = val->ToString();
239 if (encoding == UTF8) {
240 str->WriteUtf8(buf, buflen);
244 if (encoding == ASCII) {
245 str->WriteAscii(buf, 0, buflen);
249 // THIS IS AWFUL!!! FIXME
251 assert(encoding == BINARY);
253 uint16_t * twobytebuf = new uint16_t[buflen];
255 str->Write(twobytebuf, 0, buflen);
257 for (size_t i = 0; i < buflen; i++) {
258 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
263 delete [] twobytebuf;
268 static Persistent<FunctionTemplate> stats_constructor_template;
270 Local<Object> BuildStatsObject(struct stat * s) {
273 if (dev_symbol.IsEmpty()) {
274 dev_symbol = NODE_PSYMBOL("dev");
275 ino_symbol = NODE_PSYMBOL("ino");
276 mode_symbol = NODE_PSYMBOL("mode");
277 nlink_symbol = NODE_PSYMBOL("nlink");
278 uid_symbol = NODE_PSYMBOL("uid");
279 gid_symbol = NODE_PSYMBOL("gid");
280 rdev_symbol = NODE_PSYMBOL("rdev");
281 size_symbol = NODE_PSYMBOL("size");
282 blksize_symbol = NODE_PSYMBOL("blksize");
283 blocks_symbol = NODE_PSYMBOL("blocks");
284 atime_symbol = NODE_PSYMBOL("atime");
285 mtime_symbol = NODE_PSYMBOL("mtime");
286 ctime_symbol = NODE_PSYMBOL("ctime");
289 Local<Object> stats =
290 stats_constructor_template->GetFunction()->NewInstance();
292 /* ID of device containing file */
293 stats->Set(dev_symbol, Integer::New(s->st_dev));
296 stats->Set(ino_symbol, Integer::New(s->st_ino));
299 stats->Set(mode_symbol, Integer::New(s->st_mode));
301 /* number of hard links */
302 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
304 /* user ID of owner */
305 stats->Set(uid_symbol, Integer::New(s->st_uid));
307 /* group ID of owner */
308 stats->Set(gid_symbol, Integer::New(s->st_gid));
310 /* device ID (if special file) */
311 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
313 /* total size, in bytes */
314 stats->Set(size_symbol, Integer::New(s->st_size));
316 /* blocksize for filesystem I/O */
317 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
319 /* number of blocks allocated */
320 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
322 /* time of last access */
323 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
325 /* time of last modification */
326 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
328 /* time of last status change */
329 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
331 return scope.Close(stats);
335 // Extracts a C str from a V8 Utf8Value.
336 const char* ToCString(const v8::String::Utf8Value& value) {
337 return *value ? *value : "<str conversion failed>";
340 static void ReportException(TryCatch &try_catch, bool show_line = false) {
341 Handle<Message> message = try_catch.Message();
342 if (message.IsEmpty()) {
343 fprintf(stderr, "Error: (no message)\n");
348 Handle<Value> error = try_catch.Exception();
349 Handle<String> stack;
351 if (error->IsObject()) {
352 Handle<Object> obj = Handle<Object>::Cast(error);
353 Handle<Value> raw_stack = obj->Get(String::New("stack"));
354 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
358 // Print (filename):(line number): (message).
359 String::Utf8Value filename(message->GetScriptResourceName());
360 const char* filename_string = ToCString(filename);
361 int linenum = message->GetLineNumber();
362 fprintf(stderr, "%s:%i\n", filename_string, linenum);
363 // Print line of source code.
364 String::Utf8Value sourceline(message->GetSourceLine());
365 const char* sourceline_string = ToCString(sourceline);
366 fprintf(stderr, "%s\n", sourceline_string);
367 // Print wavy underline (GetUnderline is deprecated).
368 int start = message->GetStartColumn();
369 for (int i = 0; i < start; i++) {
370 fprintf(stderr, " ");
372 int end = message->GetEndColumn();
373 for (int i = start; i < end; i++) {
374 fprintf(stderr, "^");
376 fprintf(stderr, "\n");
379 if (stack.IsEmpty()) {
380 message->PrintCurrentStackTrace(stderr);
382 String::Utf8Value trace(stack);
383 fprintf(stderr, "%s\n", *trace);
388 // Executes a str within the current v8 context.
389 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
393 Local<Script> script = Script::Compile(source, filename);
394 if (script.IsEmpty()) {
395 ReportException(try_catch);
399 Local<Value> result = script->Run();
400 if (result.IsEmpty()) {
401 ReportException(try_catch);
405 return scope.Close(result);
408 static Handle<Value> ByteLength(const Arguments& args) {
411 if (args.Length() < 1 || !args[0]->IsString()) {
412 return ThrowException(Exception::Error(String::New("Bad argument.")));
415 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
417 return scope.Close(length);
420 static Handle<Value> Loop(const Arguments& args) {
423 // TODO Probably don't need to start this each time.
424 // Avoids failing on test/mjsunit/test-eio-race3.js though
425 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
427 ev_loop(EV_DEFAULT_UC_ 0);
431 static Handle<Value> Unloop(const Arguments& args) {
433 int how = EVUNLOOP_ONE;
434 if (args[0]->IsString()) {
435 String::Utf8Value how_s(args[0]->ToString());
436 if (0 == strcmp(*how_s, "all")) {
440 ev_unloop(EV_DEFAULT_ how);
444 static Handle<Value> Chdir(const Arguments& args) {
447 if (args.Length() != 1 || !args[0]->IsString()) {
448 return ThrowException(Exception::Error(String::New("Bad argument.")));
451 String::Utf8Value path(args[0]->ToString());
453 int r = chdir(*path);
456 return ThrowException(Exception::Error(String::New(strerror(errno))));
462 static Handle<Value> Cwd(const Arguments& args) {
465 char output[PATH_MAX];
466 char *r = getcwd(output, PATH_MAX);
468 return ThrowException(Exception::Error(String::New(strerror(errno))));
470 Local<String> cwd = String::New(output);
472 return scope.Close(cwd);
475 static Handle<Value> Umask(const Arguments& args){
478 if(args.Length() < 1 || !args[0]->IsInt32()) {
479 return ThrowException(Exception::TypeError(
480 String::New("argument must be an integer.")));
482 unsigned int mask = args[0]->Uint32Value();
483 unsigned int old = umask((mode_t)mask);
485 return scope.Close(Uint32::New(old));
489 static Handle<Value> GetUid(const Arguments& args) {
492 return scope.Close(Integer::New(uid));
495 static Handle<Value> GetGid(const Arguments& args) {
498 return scope.Close(Integer::New(gid));
502 static Handle<Value> SetGid(const Arguments& args) {
505 if (args.Length() < 1) {
506 return ThrowException(Exception::Error(
507 String::New("setgid requires 1 argument")));
510 Local<Integer> given_gid = args[0]->ToInteger();
511 int gid = given_gid->Int32Value();
513 if ((result == setgid(gid)) != 0) {
514 return ThrowException(Exception::Error(String::New(strerror(errno))));
519 static Handle<Value> SetUid(const Arguments& args) {
522 if (args.Length() < 1) {
523 return ThrowException(Exception::Error(
524 String::New("setuid requires 1 argument")));
527 Local<Integer> given_uid = args[0]->ToInteger();
528 int uid = given_uid->Int32Value();
530 if ((result = setuid(uid)) != 0) {
531 return ThrowException(Exception::Error(String::New(strerror(errno))));
537 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
541 exit(args[0]->IntegerValue());
546 #define HAVE_GETMEM 1
547 #include <unistd.h> /* getpagesize() */
549 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
550 #define PROCFS_FILE_OFFSET_BITS_HACK 1
551 #undef _FILE_OFFSET_BITS
553 #define PROCFS_FILE_OFFSET_BITS_HACK 0
558 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
559 #define _FILE_OFFSET_BITS 64
562 int getmem(size_t *rss, size_t *vsize) {
563 pid_t pid = getpid();
565 size_t page_size = getpagesize();
567 sprintf(pidpath, "/proc/%d/psinfo", pid);
570 FILE *f = fopen(pidpath, "r");
573 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
580 *vsize = (size_t) psinfo.pr_size * page_size;
581 *rss = (size_t) psinfo.pr_rssize * 1024;
591 #define HAVE_GETMEM 1
593 #include <sys/param.h>
594 #include <sys/sysctl.h>
595 #include <sys/user.h>
599 int getmem(size_t *rss, size_t *vsize) {
601 struct kinfo_proc *kinfo = NULL;
607 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
608 if (kd == NULL) goto error;
610 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
611 if (kinfo == NULL) goto error;
613 *rss = kinfo->ki_rssize * PAGE_SIZE;
614 *vsize = kinfo->ki_size;
621 if (kd) kvm_close(kd);
624 #endif // __FreeBSD__
628 #define HAVE_GETMEM 1
629 /* Researched by Tim Becker and Michael Knight
630 * http://blog.kuriositaet.de/?p=257
633 #include <mach/task.h>
634 #include <mach/mach_init.h>
636 int getmem(size_t *rss, size_t *vsize) {
637 struct task_basic_info t_info;
638 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
640 int r = task_info(mach_task_self(),
642 (task_info_t)&t_info,
645 if (r != KERN_SUCCESS) return -1;
647 *rss = t_info.resident_size;
648 *vsize = t_info.virtual_size;
655 # define HAVE_GETMEM 1
656 # include <sys/param.h> /* for MAXPATHLEN */
658 int getmem(size_t *rss, size_t *vsize) {
659 FILE *f = fopen("/proc/self/stat", "r");
664 char buffer[MAXPATHLEN];
665 size_t page_size = getpagesize();
668 if (fscanf(f, "%d ", &itmp) == 0) goto error;
670 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
672 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
674 if (fscanf (f, "%d ", &itmp) == 0) goto error;
676 if (fscanf (f, "%d ", &itmp) == 0) goto error;
678 if (fscanf (f, "%d ", &itmp) == 0) goto error;
680 if (fscanf (f, "%d ", &itmp) == 0) goto error;
681 /* TTY owner process group */
682 if (fscanf (f, "%d ", &itmp) == 0) goto error;
684 if (fscanf (f, "%u ", &itmp) == 0) goto error;
685 /* Minor faults (no memory page) */
686 if (fscanf (f, "%u ", &itmp) == 0) goto error;
687 /* Minor faults, children */
688 if (fscanf (f, "%u ", &itmp) == 0) goto error;
689 /* Major faults (memory page faults) */
690 if (fscanf (f, "%u ", &itmp) == 0) goto error;
691 /* Major faults, children */
692 if (fscanf (f, "%u ", &itmp) == 0) goto error;
694 if (fscanf (f, "%d ", &itmp) == 0) goto error;
696 if (fscanf (f, "%d ", &itmp) == 0) goto error;
697 /* utime, children */
698 if (fscanf (f, "%d ", &itmp) == 0) goto error;
699 /* stime, children */
700 if (fscanf (f, "%d ", &itmp) == 0) goto error;
701 /* jiffies remaining in current time slice */
702 if (fscanf (f, "%d ", &itmp) == 0) goto error;
704 if (fscanf (f, "%d ", &itmp) == 0) goto error;
705 /* jiffies until next timeout */
706 if (fscanf (f, "%u ", &itmp) == 0) goto error;
707 /* jiffies until next SIGALRM */
708 if (fscanf (f, "%u ", &itmp) == 0) goto error;
709 /* start time (jiffies since system boot) */
710 if (fscanf (f, "%d ", &itmp) == 0) goto error;
712 /* Virtual memory size */
713 if (fscanf (f, "%u ", &itmp) == 0) goto error;
714 *vsize = (size_t) itmp;
716 /* Resident set size */
717 if (fscanf (f, "%u ", &itmp) == 0) goto error;
718 *rss = (size_t) itmp * page_size;
721 if (fscanf (f, "%u ", &itmp) == 0) goto error;
723 if (fscanf (f, "%u ", &itmp) == 0) goto error;
725 if (fscanf (f, "%u ", &itmp) == 0) goto error;
727 if (fscanf (f, "%u ", &itmp) == 0) goto error;
739 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
743 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
747 int r = getmem(&rss, &vsize);
750 return ThrowException(Exception::Error(String::New(strerror(errno))));
753 Local<Object> info = Object::New();
755 if (rss_symbol.IsEmpty()) {
756 rss_symbol = NODE_PSYMBOL("rss");
757 vsize_symbol = NODE_PSYMBOL("vsize");
758 heap_total_symbol = NODE_PSYMBOL("heapTotal");
759 heap_used_symbol = NODE_PSYMBOL("heapUsed");
762 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
763 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
766 HeapStatistics v8_heap_stats;
767 V8::GetHeapStatistics(&v8_heap_stats);
768 info->Set(heap_total_symbol,
769 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
770 info->Set(heap_used_symbol,
771 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
773 return scope.Close(info);
778 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
781 if (args.Length() < 1 || !args[0]->IsNumber()) {
782 return ThrowException(Exception::Error(String::New("Bad argument.")));
785 pid_t pid = args[0]->IntegerValue();
789 if (args.Length() >= 2) {
790 if (args[1]->IsNumber()) {
791 sig = args[1]->Int32Value();
792 } else if (args[1]->IsString()) {
793 Local<String> signame = args[1]->ToString();
795 Local<Value> sig_v = process->Get(signame);
796 if (!sig_v->IsNumber()) {
797 return ThrowException(Exception::Error(String::New("Unknown signal")));
799 sig = sig_v->Int32Value();
803 int r = kill(pid, sig);
806 return ThrowException(Exception::Error(String::New(strerror(errno))));
812 typedef void (*extInit)(Handle<Object> exports);
814 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
816 Handle<Value> DLOpen(const v8::Arguments& args) {
819 if (args.Length() < 2) return Undefined();
821 String::Utf8Value filename(args[0]->ToString()); // Cast
822 Local<Object> target = args[1]->ToObject(); // Cast
824 // Actually call dlopen().
825 // FIXME: This is a blocking function and should be called asynchronously!
826 // This function should be moved to file.cc and use libeio to make this
828 void *handle = dlopen(*filename, RTLD_LAZY);
831 if (handle == NULL) {
832 Local<Value> exception = Exception::Error(String::New(dlerror()));
833 return ThrowException(exception);
836 // Get the init() function from the dynamically shared object.
837 void *init_handle = dlsym(handle, "init");
838 // Error out if not found.
839 if (init_handle == NULL) {
840 Local<Value> exception =
841 Exception::Error(String::New("No 'init' symbol found in module."));
842 return ThrowException(exception);
844 extInit init = (extInit)(init_handle); // Cast
846 // Execute the C++ module
852 Handle<Value> Compile(const Arguments& args) {
855 if (args.Length() < 2) {
856 return ThrowException(Exception::TypeError(
857 String::New("needs two arguments.")));
860 Local<String> source = args[0]->ToString();
861 Local<String> filename = args[1]->ToString();
865 Local<Script> script = Script::Compile(source, filename);
866 if (try_catch.HasCaught()) {
867 // Hack because I can't get a proper stacktrace on SyntaxError
868 ReportException(try_catch, true);
872 Local<Value> result = script->Run();
873 if (try_catch.HasCaught()) return try_catch.ReThrow();
875 return scope.Close(result);
878 static void OnFatalError(const char* location, const char* message) {
880 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
882 fprintf(stderr, "FATAL ERROR: %s\n", message);
887 static int uncaught_exception_counter = 0;
889 void FatalException(TryCatch &try_catch) {
892 // Check if uncaught_exception_counter indicates a recursion
893 if (uncaught_exception_counter > 0) {
894 ReportException(try_catch);
898 if (listeners_symbol.IsEmpty()) {
899 listeners_symbol = NODE_PSYMBOL("listeners");
900 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
901 emit_symbol = NODE_PSYMBOL("emit");
904 Local<Value> listeners_v = process->Get(listeners_symbol);
905 assert(listeners_v->IsFunction());
907 Local<Function> listeners = Local<Function>::Cast(listeners_v);
909 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
910 Local<Value> argv[1] = { uncaught_exception_symbol_l };
911 Local<Value> ret = listeners->Call(process, 1, argv);
913 assert(ret->IsArray());
915 Local<Array> listener_array = Local<Array>::Cast(ret);
917 uint32_t length = listener_array->Length();
918 // Report and exit if process has no "uncaughtException" listener
920 ReportException(try_catch);
924 // Otherwise fire the process "uncaughtException" event
925 Local<Value> emit_v = process->Get(emit_symbol);
926 assert(emit_v->IsFunction());
928 Local<Function> emit = Local<Function>::Cast(emit_v);
930 Local<Value> error = try_catch.Exception();
931 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
933 uncaught_exception_counter++;
934 emit->Call(process, 2, event_argv);
935 // Decrement so we know if the next exception is a recursion or not
936 uncaught_exception_counter--;
940 static ev_async debug_watcher;
941 volatile static bool debugger_msg_pending = false;
943 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
945 assert(watcher == &debug_watcher);
946 assert(revents == EV_ASYNC);
947 Debug::ProcessDebugMessages();
950 static void DebugMessageDispatch(void) {
951 // This function is called from V8's debug thread when a debug TCP client
952 // has sent a message.
954 // Send a signal to our main thread saying that it should enter V8 to
955 // handle the message.
956 debugger_msg_pending = true;
957 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
960 static Handle<Value> CheckBreak(const Arguments& args) {
963 // TODO FIXME This function is a hack to wait until V8 is ready to accept
964 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
965 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
966 // get it to halt until Eclipse connects.
968 if (!debug_wait_connect)
971 printf("Waiting for remote debugger connection...\n");
973 const int halfSecond = 50;
974 const int tenMs=10000;
975 debugger_msg_pending = false;
977 if (debugger_msg_pending) {
979 Debug::ProcessDebugMessages();
980 debugger_msg_pending = false;
982 // wait for 500 msec of silence from remote debugger
983 int cnt = halfSecond;
985 debugger_msg_pending = false;
987 if (debugger_msg_pending) {
988 debugger_msg_pending = false;
1000 static void Load(int argc, char *argv[]) {
1003 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1004 node::EventEmitter::Initialize(process_template);
1006 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1008 // Add a reference to the global object
1009 Local<Object> global = Context::GetCurrent()->Global();
1010 process->Set(String::NewSymbol("global"), global);
1013 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1014 // process.installPrefix
1015 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1018 #define xstr(s) str(s)
1020 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1024 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1025 arguments->Set(Integer::New(0), String::New(argv[0]));
1026 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1027 Local<String> arg = String::New(argv[i]);
1028 arguments->Set(Integer::New(j), arg);
1031 process->Set(String::NewSymbol("ARGV"), arguments);
1032 process->Set(String::NewSymbol("argv"), arguments);
1034 // create process.env
1035 Local<Object> env = Object::New();
1036 for (i = 0; environ[i]; i++) {
1037 // skip entries without a '=' character
1038 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1039 // create the v8 objects
1040 Local<String> field = String::New(environ[i], j);
1041 Local<String> value = Local<String>();
1042 if (environ[i][j] == '=') {
1043 value = String::New(environ[i]+j+1);
1046 env->Set(field, value);
1048 // assign process.ENV
1049 process->Set(String::NewSymbol("ENV"), env);
1050 process->Set(String::NewSymbol("env"), env);
1052 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1054 // define various internal methods
1055 NODE_SET_METHOD(process, "loop", Loop);
1056 NODE_SET_METHOD(process, "unloop", Unloop);
1057 NODE_SET_METHOD(process, "compile", Compile);
1058 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1059 NODE_SET_METHOD(process, "reallyExit", Exit);
1060 NODE_SET_METHOD(process, "chdir", Chdir);
1061 NODE_SET_METHOD(process, "cwd", Cwd);
1062 NODE_SET_METHOD(process, "getuid", GetUid);
1063 NODE_SET_METHOD(process, "setuid", SetUid);
1065 NODE_SET_METHOD(process, "setgid", SetGid);
1066 NODE_SET_METHOD(process, "getgid", GetGid);
1068 NODE_SET_METHOD(process, "umask", Umask);
1069 NODE_SET_METHOD(process, "dlopen", DLOpen);
1070 NODE_SET_METHOD(process, "kill", Kill);
1071 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1072 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1074 // Assign the EventEmitter. It was created in main().
1075 process->Set(String::NewSymbol("EventEmitter"),
1076 EventEmitter::constructor_template->GetFunction());
1078 // Initialize the stats object
1079 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1080 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1081 process->Set(String::NewSymbol("Stats"),
1082 stats_constructor_template->GetFunction());
1085 // Initialize the C++ modules..................filename of module
1086 Buffer::Initialize(process); // buffer.cc
1087 IOWatcher::Initialize(process); // io_watcher.cc
1088 IdleWatcher::Initialize(process); // idle_watcher.cc
1089 Timer::Initialize(process); // timer.cc
1090 Stat::Initialize(process); // stat.cc
1091 SignalHandler::Initialize(process); // signal_handler.cc
1093 InitNet2(process); // net2.cc
1094 InitHttpParser(process); // http_parser.cc
1096 Stdio::Initialize(process); // stdio.cc
1097 ChildProcess::Initialize(process); // child_process.cc
1098 DefineConstants(process); // constants.cc
1100 Local<Object> dns = Object::New();
1101 process->Set(String::NewSymbol("dns"), dns);
1102 DNS::Initialize(dns); // dns.cc
1103 Local<Object> fs = Object::New();
1104 process->Set(String::NewSymbol("fs"), fs);
1105 File::Initialize(fs); // file.cc
1106 // Create node.tcp. Note this separate from lib/tcp.js which is the public
1108 Local<Object> tcp = Object::New();
1109 process->Set(String::New("tcp"), tcp);
1110 Server::Initialize(tcp); // tcp.cc
1111 Connection::Initialize(tcp); // tcp.cc
1112 // Create node.http. Note this separate from lib/http.js which is the
1114 Local<Object> http = Object::New();
1115 process->Set(String::New("http"), http);
1116 HTTPServer::Initialize(http); // http.cc
1117 HTTPConnection::Initialize(http); // http.cc
1121 // Compile, execute the src/node.js file. (Which was included as static C
1122 // string in node_natives.h. 'natve_node' is the string containing that
1125 // The node.js file returns a function 'f'
1131 Local<Value> f_value = ExecuteString(String::New(native_node),
1132 String::New("node.js"));
1134 if (try_catch.HasCaught()) {
1135 ReportException(try_catch);
1139 assert(f_value->IsFunction());
1140 Local<Function> f = Local<Function>::Cast(f_value);
1142 // Now we call 'f' with the 'process' variable that we've built up with
1143 // all our bindings. Inside node.js we'll take care of assigning things to
1146 // We start the process this way in order to be more modular. Developers
1147 // who do not like how 'src/node.js' setups the module system but do like
1148 // Node's I/O bindings may want to replace 'f' with their own function.
1150 Local<Value> args[1] = { Local<Value>::New(process) };
1152 f->Call(global, 1, args);
1155 if (try_catch.HasCaught()) {
1156 ReportException(try_catch);
1162 static void PrintHelp();
1164 static void ParseDebugOpt(const char* arg) {
1167 use_debug_agent = true;
1168 if (!strcmp (arg, "--debug-brk")) {
1169 debug_wait_connect = true;
1171 } else if (!strcmp(arg, "--debug")) {
1173 } else if (strstr(arg, "--debug-brk=") == arg) {
1174 debug_wait_connect = true;
1175 p = 1 + strchr(arg, '=');
1176 debug_port = atoi(p);
1177 } else if (strstr(arg, "--debug=") == arg) {
1178 p = 1 + strchr(arg, '=');
1179 debug_port = atoi(p);
1181 if (p && debug_port > 1024 && debug_port < 65536)
1184 fprintf(stderr, "Bad debug option.\n");
1185 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1191 static void PrintHelp() {
1192 printf("Usage: node [options] script.js [arguments] \n"
1193 " -v, --version print node's version\n"
1194 " --debug[=port] enable remote debugging via given TCP port\n"
1195 " without stopping the execution\n"
1196 " --debug-brk[=port] as above, but break in script.js and\n"
1197 " wait for remote debugger to connect\n"
1198 " --cflags print pre-processor and compiler flags\n"
1199 " --v8-options print v8 command line options\n\n"
1200 "Documentation can be found at http://nodejs.org/api.html"
1201 " or with 'man node'\n");
1204 // Parse node command line arguments.
1205 static void ParseArgs(int *argc, char **argv) {
1206 // TODO use parse opts
1207 for (int i = 1; i < *argc; i++) {
1208 const char *arg = argv[i];
1209 if (strstr(arg, "--debug") == arg) {
1211 argv[i] = const_cast<char*>("");
1212 option_end_index = i;
1213 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1214 printf("%s\n", NODE_VERSION);
1216 } else if (strcmp(arg, "--cflags") == 0) {
1217 printf("%s\n", NODE_CFLAGS);
1219 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1222 } else if (strcmp(arg, "--v8-options") == 0) {
1223 argv[i] = const_cast<char*>("--help");
1224 option_end_index = i+1;
1225 } else if (argv[i][0] != '-') {
1226 option_end_index = i-1;
1235 int main(int argc, char *argv[]) {
1236 // Parse a few arguments which are specific to Node.
1237 node::ParseArgs(&argc, argv);
1238 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1239 // in the command line))
1240 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1242 // Error out if we don't have a script argument.
1244 fprintf(stderr, "No script was specified.\n");
1249 // Ignore the SIGPIPE
1250 evcom_ignore_sigpipe();
1252 // Initialize the default ev loop.
1254 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1255 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1256 ev_default_loop(EVBACKEND_SELECT);
1258 ev_default_loop(EVFLAG_AUTO);
1262 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1263 // Set the gc_timer to max priority so that it runs before all other
1264 // watchers. In this way it can check if the 'tick' has other pending
1265 // watchers by using ev_pending_count() - if it ran with lower priority
1266 // then the other watchers might run before it - not giving us good idea
1267 // of loop idleness.
1268 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1269 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1270 ev_unref(EV_DEFAULT_UC);
1273 // Setup the EIO thread pool
1274 { // It requires 3, yes 3, watchers.
1275 ev_idle_init(&node::eio_poller, node::DoPoll);
1277 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1278 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1279 ev_unref(EV_DEFAULT_UC);
1281 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1282 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1283 ev_unref(EV_DEFAULT_UC);
1285 eio_init(node::EIOWantPoll, node::EIODonePoll);
1286 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1287 // race conditions. See test/mjsunit/test-eio-race.js
1288 eio_set_max_poll_reqs(10);
1292 HandleScope handle_scope;
1294 V8::SetFatalErrorHandler(node::OnFatalError);
1296 // If the --debug flag was specified then initialize the debug thread.
1297 if (node::use_debug_agent) {
1298 // Initialize the async watcher for receiving messages from the debug
1299 // thread and marshal it into the main thread. DebugMessageCallback()
1300 // is called from the main thread to execute a random bit of javascript
1301 // - which will give V8 control so it can handle whatever new message
1302 // had been received on the debug thread.
1303 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1304 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1305 // Set the callback DebugMessageDispatch which is called from the debug
1307 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1308 // Start the async watcher.
1309 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1310 // unref it so that we exit the event loop despite it being active.
1311 ev_unref(EV_DEFAULT_UC);
1313 // Start the debug thread and it's associated TCP server on port 5858.
1314 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1316 // Crappy check that everything went well. FIXME
1318 // Print out some information.
1319 printf("debugger listening on port %d\n", node::debug_port);
1322 // Create the one and only Context.
1323 Persistent<Context> context = Context::New();
1324 Context::Scope context_scope(context);
1326 // Create all the objects, load modules, do everything.
1327 // so your next reading stop should be node::Load()!
1328 node::Load(argc, argv);
1330 node::Stdio::Flush();