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_events.h>
18 #include <node_file.h>
19 #include <node_idle_watcher.h>
20 #include <node_http.h>
21 #include <node_signal_handler.h>
22 #include <node_stat.h>
23 #include <node_timer.h>
24 #include <node_child_process.h>
25 #include <node_constants.h>
26 #include <node_stdio.h>
27 #include <node_natives.h>
28 #include <node_version.h>
34 extern char **environ;
38 static Persistent<Object> process;
40 static Persistent<String> dev_symbol;
41 static Persistent<String> ino_symbol;
42 static Persistent<String> mode_symbol;
43 static Persistent<String> nlink_symbol;
44 static Persistent<String> uid_symbol;
45 static Persistent<String> gid_symbol;
46 static Persistent<String> rdev_symbol;
47 static Persistent<String> size_symbol;
48 static Persistent<String> blksize_symbol;
49 static Persistent<String> blocks_symbol;
50 static Persistent<String> atime_symbol;
51 static Persistent<String> mtime_symbol;
52 static Persistent<String> ctime_symbol;
54 static Persistent<String> rss_symbol;
55 static Persistent<String> vsize_symbol;
56 static Persistent<String> heap_total_symbol;
57 static Persistent<String> heap_used_symbol;
59 static Persistent<String> listeners_symbol;
60 static Persistent<String> uncaught_exception_symbol;
61 static Persistent<String> emit_symbol;
63 static int option_end_index = 0;
64 static bool use_debug_agent = false;
65 static bool debug_wait_connect = false;
66 static int debug_port=5858;
69 static ev_async eio_want_poll_notifier;
70 static ev_async eio_done_poll_notifier;
71 static ev_idle eio_poller;
73 static ev_timer gc_timer;
74 #define GC_INTERVAL 2.0
77 // Node calls this every GC_INTERVAL seconds in order to try and call the
78 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
79 // is an effective measure of idleness.
80 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
81 assert(watcher == &gc_timer);
82 assert(revents == EV_TIMER);
83 if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
87 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
88 assert(watcher == &eio_poller);
89 assert(revents == EV_IDLE);
91 //printf("eio_poller\n");
93 if (eio_poll() != -1) {
94 //printf("eio_poller stop\n");
95 ev_idle_stop(EV_DEFAULT_UC_ watcher);
100 // Called from the main thread.
101 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
102 assert(watcher == &eio_want_poll_notifier);
103 assert(revents == EV_ASYNC);
105 //printf("want poll notifier\n");
107 if (eio_poll() == -1) {
108 //printf("eio_poller start\n");
109 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
114 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
115 assert(watcher == &eio_done_poll_notifier);
116 assert(revents == EV_ASYNC);
118 //printf("done poll notifier\n");
120 if (eio_poll() != -1) {
121 //printf("eio_poller stop\n");
122 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
127 // EIOWantPoll() is called from the EIO thread pool each time an EIO
128 // request (that is, one of the node.fs.* functions) has completed.
129 static void EIOWantPoll(void) {
130 // Signal the main thread that eio_poll need to be processed.
131 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
135 static void EIODonePoll(void) {
136 // Signal the main thread that we should stop calling eio_poll().
137 // from the idle watcher.
138 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
142 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
145 if (!encoding_v->IsString()) return _default;
147 String::Utf8Value encoding(encoding_v->ToString());
149 if (strcasecmp(*encoding, "utf8") == 0) {
151 } else if (strcasecmp(*encoding, "utf-8") == 0) {
153 } else if (strcasecmp(*encoding, "ascii") == 0) {
155 } else if (strcasecmp(*encoding, "binary") == 0) {
157 } else if (strcasecmp(*encoding, "raw") == 0) {
158 fprintf(stderr, "'raw' (array of integers) has been removed. "
161 } else if (strcasecmp(*encoding, "raws") == 0) {
162 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
163 "Please update your code.\n");
170 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
173 if (!len) return scope.Close(String::Empty());
175 if (encoding == BINARY) {
176 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
177 uint16_t * twobytebuf = new uint16_t[len];
178 for (size_t i = 0; i < len; i++) {
179 // XXX is the following line platform independent?
180 twobytebuf[i] = cbuf[i];
182 Local<String> chunk = String::New(twobytebuf, len);
183 delete [] twobytebuf; // TODO use ExternalTwoByteString?
184 return scope.Close(chunk);
187 // utf8 or ascii encoding
188 Local<String> chunk = String::New((const char*)buf, len);
189 return scope.Close(chunk);
192 // Returns -1 if the handle was not valid for decoding
193 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
196 if (val->IsArray()) {
197 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
203 Local<String> str = val->ToString();
205 if (encoding == UTF8) return str->Utf8Length();
207 return str->Length();
211 # define MIN(a, b) ((a) < (b) ? (a) : (b))
214 // Returns number of bytes written.
215 ssize_t DecodeWrite(char *buf, size_t buflen,
216 v8::Handle<v8::Value> val,
217 enum encoding encoding) {
221 // A lot of improvement can be made here. See:
222 // http://code.google.com/p/v8/issues/detail?id=270
223 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
224 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
226 if (val->IsArray()) {
227 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
233 Local<String> str = val->ToString();
235 if (encoding == UTF8) {
236 str->WriteUtf8(buf, buflen);
240 if (encoding == ASCII) {
241 str->WriteAscii(buf, 0, buflen);
245 // THIS IS AWFUL!!! FIXME
247 assert(encoding == BINARY);
249 uint16_t * twobytebuf = new uint16_t[buflen];
251 str->Write(twobytebuf, 0, buflen);
253 for (size_t i = 0; i < buflen; i++) {
254 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
259 delete [] twobytebuf;
264 static Persistent<FunctionTemplate> stats_constructor_template;
266 Local<Object> BuildStatsObject(struct stat * s) {
269 if (dev_symbol.IsEmpty()) {
270 dev_symbol = NODE_PSYMBOL("dev");
271 ino_symbol = NODE_PSYMBOL("ino");
272 mode_symbol = NODE_PSYMBOL("mode");
273 nlink_symbol = NODE_PSYMBOL("nlink");
274 uid_symbol = NODE_PSYMBOL("uid");
275 gid_symbol = NODE_PSYMBOL("gid");
276 rdev_symbol = NODE_PSYMBOL("rdev");
277 size_symbol = NODE_PSYMBOL("size");
278 blksize_symbol = NODE_PSYMBOL("blksize");
279 blocks_symbol = NODE_PSYMBOL("blocks");
280 atime_symbol = NODE_PSYMBOL("atime");
281 mtime_symbol = NODE_PSYMBOL("mtime");
282 ctime_symbol = NODE_PSYMBOL("ctime");
285 Local<Object> stats =
286 stats_constructor_template->GetFunction()->NewInstance();
288 /* ID of device containing file */
289 stats->Set(dev_symbol, Integer::New(s->st_dev));
292 stats->Set(ino_symbol, Integer::New(s->st_ino));
295 stats->Set(mode_symbol, Integer::New(s->st_mode));
297 /* number of hard links */
298 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
300 /* user ID of owner */
301 stats->Set(uid_symbol, Integer::New(s->st_uid));
303 /* group ID of owner */
304 stats->Set(gid_symbol, Integer::New(s->st_gid));
306 /* device ID (if special file) */
307 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
309 /* total size, in bytes */
310 stats->Set(size_symbol, Integer::New(s->st_size));
312 /* blocksize for filesystem I/O */
313 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
315 /* number of blocks allocated */
316 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
318 /* time of last access */
319 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
321 /* time of last modification */
322 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
324 /* time of last status change */
325 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
327 return scope.Close(stats);
331 // Extracts a C str from a V8 Utf8Value.
332 const char* ToCString(const v8::String::Utf8Value& value) {
333 return *value ? *value : "<str conversion failed>";
336 static void ReportException(TryCatch &try_catch, bool show_line = false) {
337 Handle<Message> message = try_catch.Message();
338 if (message.IsEmpty()) {
339 fprintf(stderr, "Error: (no message)\n");
344 Handle<Value> error = try_catch.Exception();
345 Handle<String> stack;
347 if (error->IsObject()) {
348 Handle<Object> obj = Handle<Object>::Cast(error);
349 Handle<Value> raw_stack = obj->Get(String::New("stack"));
350 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
354 // Print (filename):(line number): (message).
355 String::Utf8Value filename(message->GetScriptResourceName());
356 const char* filename_string = ToCString(filename);
357 int linenum = message->GetLineNumber();
358 fprintf(stderr, "%s:%i\n", filename_string, linenum);
359 // Print line of source code.
360 String::Utf8Value sourceline(message->GetSourceLine());
361 const char* sourceline_string = ToCString(sourceline);
362 fprintf(stderr, "%s\n", sourceline_string);
363 // Print wavy underline (GetUnderline is deprecated).
364 int start = message->GetStartColumn();
365 for (int i = 0; i < start; i++) {
366 fprintf(stderr, " ");
368 int end = message->GetEndColumn();
369 for (int i = start; i < end; i++) {
370 fprintf(stderr, "^");
372 fprintf(stderr, "\n");
375 if (stack.IsEmpty()) {
376 message->PrintCurrentStackTrace(stderr);
378 String::Utf8Value trace(stack);
379 fprintf(stderr, "%s\n", *trace);
384 // Executes a str within the current v8 context.
385 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
389 Local<Script> script = Script::Compile(source, filename);
390 if (script.IsEmpty()) {
391 ReportException(try_catch);
395 Local<Value> result = script->Run();
396 if (result.IsEmpty()) {
397 ReportException(try_catch);
401 return scope.Close(result);
404 static Handle<Value> ByteLength(const Arguments& args) {
407 if (args.Length() < 1 || !args[0]->IsString()) {
408 return ThrowException(Exception::Error(String::New("Bad argument.")));
411 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
413 return scope.Close(length);
416 static Handle<Value> Loop(const Arguments& args) {
419 // TODO Probably don't need to start this each time.
420 // Avoids failing on test/mjsunit/test-eio-race3.js though
421 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
423 ev_loop(EV_DEFAULT_UC_ 0);
427 static Handle<Value> Chdir(const Arguments& args) {
430 if (args.Length() != 1 || !args[0]->IsString()) {
431 return ThrowException(Exception::Error(String::New("Bad argument.")));
434 String::Utf8Value path(args[0]->ToString());
436 int r = chdir(*path);
439 return ThrowException(Exception::Error(String::New(strerror(errno))));
445 static Handle<Value> Cwd(const Arguments& args) {
448 char output[PATH_MAX];
449 char *r = getcwd(output, PATH_MAX);
451 return ThrowException(Exception::Error(String::New(strerror(errno))));
453 Local<String> cwd = String::New(output);
455 return scope.Close(cwd);
458 static Handle<Value> Umask(const Arguments& args){
461 if(args.Length() < 1 || !args[0]->IsInt32()) {
462 return ThrowException(Exception::TypeError(
463 String::New("argument must be an integer.")));
465 unsigned int mask = args[0]->Uint32Value();
466 unsigned int old = umask((mode_t)mask);
468 return scope.Close(Uint32::New(old));
472 static Handle<Value> GetUid(const Arguments& args) {
475 return scope.Close(Integer::New(uid));
478 static Handle<Value> GetGid(const Arguments& args) {
481 return scope.Close(Integer::New(gid));
485 static Handle<Value> SetGid(const Arguments& args) {
488 if (args.Length() < 1) {
489 return ThrowException(Exception::Error(
490 String::New("setgid requires 1 argument")));
493 Local<Integer> given_gid = args[0]->ToInteger();
494 int gid = given_gid->Int32Value();
496 if ((result = setgid(gid)) != 0) {
497 return ThrowException(Exception::Error(String::New(strerror(errno))));
502 static Handle<Value> SetUid(const Arguments& args) {
505 if (args.Length() < 1) {
506 return ThrowException(Exception::Error(
507 String::New("setuid requires 1 argument")));
510 Local<Integer> given_uid = args[0]->ToInteger();
511 int uid = given_uid->Int32Value();
513 if ((result = setuid(uid)) != 0) {
514 return ThrowException(Exception::Error(String::New(strerror(errno))));
520 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
524 exit(args[0]->IntegerValue());
529 #define HAVE_GETMEM 1
530 #include <unistd.h> /* getpagesize() */
532 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
533 #define PROCFS_FILE_OFFSET_BITS_HACK 1
534 #undef _FILE_OFFSET_BITS
536 #define PROCFS_FILE_OFFSET_BITS_HACK 0
541 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
542 #define _FILE_OFFSET_BITS 64
545 int getmem(size_t *rss, size_t *vsize) {
546 pid_t pid = getpid();
548 size_t page_size = getpagesize();
550 sprintf(pidpath, "/proc/%d/psinfo", pid);
553 FILE *f = fopen(pidpath, "r");
556 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
563 *vsize = (size_t) psinfo.pr_size * page_size;
564 *rss = (size_t) psinfo.pr_rssize * 1024;
574 #define HAVE_GETMEM 1
576 #include <sys/param.h>
577 #include <sys/sysctl.h>
578 #include <sys/user.h>
582 int getmem(size_t *rss, size_t *vsize) {
584 struct kinfo_proc *kinfo = NULL;
590 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
591 if (kd == NULL) goto error;
593 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
594 if (kinfo == NULL) goto error;
596 *rss = kinfo->ki_rssize * PAGE_SIZE;
597 *vsize = kinfo->ki_size;
604 if (kd) kvm_close(kd);
607 #endif // __FreeBSD__
611 #define HAVE_GETMEM 1
612 /* Researched by Tim Becker and Michael Knight
613 * http://blog.kuriositaet.de/?p=257
616 #include <mach/task.h>
617 #include <mach/mach_init.h>
619 int getmem(size_t *rss, size_t *vsize) {
620 struct task_basic_info t_info;
621 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
623 int r = task_info(mach_task_self(),
625 (task_info_t)&t_info,
628 if (r != KERN_SUCCESS) return -1;
630 *rss = t_info.resident_size;
631 *vsize = t_info.virtual_size;
638 # define HAVE_GETMEM 1
639 # include <sys/param.h> /* for MAXPATHLEN */
641 int getmem(size_t *rss, size_t *vsize) {
642 FILE *f = fopen("/proc/self/stat", "r");
647 char buffer[MAXPATHLEN];
648 size_t page_size = getpagesize();
651 if (fscanf(f, "%d ", &itmp) == 0) goto error;
653 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
655 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
657 if (fscanf (f, "%d ", &itmp) == 0) goto error;
659 if (fscanf (f, "%d ", &itmp) == 0) goto error;
661 if (fscanf (f, "%d ", &itmp) == 0) goto error;
663 if (fscanf (f, "%d ", &itmp) == 0) goto error;
664 /* TTY owner process group */
665 if (fscanf (f, "%d ", &itmp) == 0) goto error;
667 if (fscanf (f, "%u ", &itmp) == 0) goto error;
668 /* Minor faults (no memory page) */
669 if (fscanf (f, "%u ", &itmp) == 0) goto error;
670 /* Minor faults, children */
671 if (fscanf (f, "%u ", &itmp) == 0) goto error;
672 /* Major faults (memory page faults) */
673 if (fscanf (f, "%u ", &itmp) == 0) goto error;
674 /* Major faults, children */
675 if (fscanf (f, "%u ", &itmp) == 0) goto error;
677 if (fscanf (f, "%d ", &itmp) == 0) goto error;
679 if (fscanf (f, "%d ", &itmp) == 0) goto error;
680 /* utime, children */
681 if (fscanf (f, "%d ", &itmp) == 0) goto error;
682 /* stime, children */
683 if (fscanf (f, "%d ", &itmp) == 0) goto error;
684 /* jiffies remaining in current time slice */
685 if (fscanf (f, "%d ", &itmp) == 0) goto error;
687 if (fscanf (f, "%d ", &itmp) == 0) goto error;
688 /* jiffies until next timeout */
689 if (fscanf (f, "%u ", &itmp) == 0) goto error;
690 /* jiffies until next SIGALRM */
691 if (fscanf (f, "%u ", &itmp) == 0) goto error;
692 /* start time (jiffies since system boot) */
693 if (fscanf (f, "%d ", &itmp) == 0) goto error;
695 /* Virtual memory size */
696 if (fscanf (f, "%u ", &itmp) == 0) goto error;
697 *vsize = (size_t) itmp;
699 /* Resident set size */
700 if (fscanf (f, "%u ", &itmp) == 0) goto error;
701 *rss = (size_t) itmp * page_size;
704 if (fscanf (f, "%u ", &itmp) == 0) goto error;
706 if (fscanf (f, "%u ", &itmp) == 0) goto error;
708 if (fscanf (f, "%u ", &itmp) == 0) goto error;
710 if (fscanf (f, "%u ", &itmp) == 0) goto error;
722 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
726 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
730 int r = getmem(&rss, &vsize);
733 return ThrowException(Exception::Error(String::New(strerror(errno))));
736 Local<Object> info = Object::New();
738 if (rss_symbol.IsEmpty()) {
739 rss_symbol = NODE_PSYMBOL("rss");
740 vsize_symbol = NODE_PSYMBOL("vsize");
741 heap_total_symbol = NODE_PSYMBOL("heapTotal");
742 heap_used_symbol = NODE_PSYMBOL("heapUsed");
745 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
746 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
749 HeapStatistics v8_heap_stats;
750 V8::GetHeapStatistics(&v8_heap_stats);
751 info->Set(heap_total_symbol,
752 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
753 info->Set(heap_used_symbol,
754 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
756 return scope.Close(info);
761 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
764 if (args.Length() < 1 || !args[0]->IsNumber()) {
765 return ThrowException(Exception::Error(String::New("Bad argument.")));
768 pid_t pid = args[0]->IntegerValue();
772 if (args.Length() >= 2) {
773 if (args[1]->IsNumber()) {
774 sig = args[1]->Int32Value();
775 } else if (args[1]->IsString()) {
776 Local<String> signame = args[1]->ToString();
778 Local<Value> sig_v = process->Get(signame);
779 if (!sig_v->IsNumber()) {
780 return ThrowException(Exception::Error(String::New("Unknown signal")));
782 sig = sig_v->Int32Value();
786 int r = kill(pid, sig);
789 return ThrowException(Exception::Error(String::New(strerror(errno))));
795 typedef void (*extInit)(Handle<Object> exports);
797 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
799 Handle<Value> DLOpen(const v8::Arguments& args) {
802 if (args.Length() < 2) return Undefined();
804 String::Utf8Value filename(args[0]->ToString()); // Cast
805 Local<Object> target = args[1]->ToObject(); // Cast
807 // Actually call dlopen().
808 // FIXME: This is a blocking function and should be called asynchronously!
809 // This function should be moved to file.cc and use libeio to make this
811 void *handle = dlopen(*filename, RTLD_LAZY);
814 if (handle == NULL) {
815 Local<Value> exception = Exception::Error(String::New(dlerror()));
816 return ThrowException(exception);
819 // Get the init() function from the dynamically shared object.
820 void *init_handle = dlsym(handle, "init");
821 // Error out if not found.
822 if (init_handle == NULL) {
823 Local<Value> exception =
824 Exception::Error(String::New("No 'init' symbol found in module."));
825 return ThrowException(exception);
827 extInit init = (extInit)(init_handle); // Cast
829 // Execute the C++ module
835 Handle<Value> Compile(const Arguments& args) {
838 if (args.Length() < 2) {
839 return ThrowException(Exception::TypeError(
840 String::New("needs two arguments.")));
843 Local<String> source = args[0]->ToString();
844 Local<String> filename = args[1]->ToString();
848 Local<Script> script = Script::Compile(source, filename);
849 if (try_catch.HasCaught()) {
850 // Hack because I can't get a proper stacktrace on SyntaxError
851 ReportException(try_catch, true);
855 Local<Value> result = script->Run();
856 if (try_catch.HasCaught()) return try_catch.ReThrow();
858 return scope.Close(result);
861 static void OnFatalError(const char* location, const char* message) {
863 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
865 fprintf(stderr, "FATAL ERROR: %s\n", message);
870 static int uncaught_exception_counter = 0;
872 void FatalException(TryCatch &try_catch) {
875 // Check if uncaught_exception_counter indicates a recursion
876 if (uncaught_exception_counter > 0) {
877 ReportException(try_catch);
881 if (listeners_symbol.IsEmpty()) {
882 listeners_symbol = NODE_PSYMBOL("listeners");
883 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
884 emit_symbol = NODE_PSYMBOL("emit");
887 Local<Value> listeners_v = process->Get(listeners_symbol);
888 assert(listeners_v->IsFunction());
890 Local<Function> listeners = Local<Function>::Cast(listeners_v);
892 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
893 Local<Value> argv[1] = { uncaught_exception_symbol_l };
894 Local<Value> ret = listeners->Call(process, 1, argv);
896 assert(ret->IsArray());
898 Local<Array> listener_array = Local<Array>::Cast(ret);
900 uint32_t length = listener_array->Length();
901 // Report and exit if process has no "uncaughtException" listener
903 ReportException(try_catch);
907 // Otherwise fire the process "uncaughtException" event
908 Local<Value> emit_v = process->Get(emit_symbol);
909 assert(emit_v->IsFunction());
911 Local<Function> emit = Local<Function>::Cast(emit_v);
913 Local<Value> error = try_catch.Exception();
914 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
916 uncaught_exception_counter++;
917 emit->Call(process, 2, event_argv);
918 // Decrement so we know if the next exception is a recursion or not
919 uncaught_exception_counter--;
923 static ev_async debug_watcher;
924 volatile static bool debugger_msg_pending = false;
926 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
928 assert(watcher == &debug_watcher);
929 assert(revents == EV_ASYNC);
930 Debug::ProcessDebugMessages();
933 static void DebugMessageDispatch(void) {
934 // This function is called from V8's debug thread when a debug TCP client
935 // has sent a message.
937 // Send a signal to our main thread saying that it should enter V8 to
938 // handle the message.
939 debugger_msg_pending = true;
940 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
943 static Handle<Value> CheckBreak(const Arguments& args) {
946 // TODO FIXME This function is a hack to wait until V8 is ready to accept
947 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
948 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
949 // get it to halt until Eclipse connects.
951 if (!debug_wait_connect)
954 printf("Waiting for remote debugger connection...\n");
956 const int halfSecond = 50;
957 const int tenMs=10000;
958 debugger_msg_pending = false;
960 if (debugger_msg_pending) {
962 Debug::ProcessDebugMessages();
963 debugger_msg_pending = false;
965 // wait for 500 msec of silence from remote debugger
966 int cnt = halfSecond;
968 debugger_msg_pending = false;
970 if (debugger_msg_pending) {
971 debugger_msg_pending = false;
983 static void Load(int argc, char *argv[]) {
986 Local<FunctionTemplate> process_template = FunctionTemplate::New();
987 node::EventEmitter::Initialize(process_template);
989 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
991 // Add a reference to the global object
992 Local<Object> global = Context::GetCurrent()->Global();
993 process->Set(String::NewSymbol("global"), global);
996 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
997 // process.installPrefix
998 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1001 #define xstr(s) str(s)
1003 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1007 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1008 arguments->Set(Integer::New(0), String::New(argv[0]));
1009 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1010 Local<String> arg = String::New(argv[i]);
1011 arguments->Set(Integer::New(j), arg);
1014 process->Set(String::NewSymbol("ARGV"), arguments);
1015 process->Set(String::NewSymbol("argv"), arguments);
1017 // create process.env
1018 Local<Object> env = Object::New();
1019 for (i = 0; environ[i]; i++) {
1020 // skip entries without a '=' character
1021 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1022 // create the v8 objects
1023 Local<String> field = String::New(environ[i], j);
1024 Local<String> value = Local<String>();
1025 if (environ[i][j] == '=') {
1026 value = String::New(environ[i]+j+1);
1029 env->Set(field, value);
1031 // assign process.ENV
1032 process->Set(String::NewSymbol("ENV"), env);
1033 process->Set(String::NewSymbol("env"), env);
1035 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1037 // define various internal methods
1038 NODE_SET_METHOD(process, "loop", Loop);
1039 NODE_SET_METHOD(process, "compile", Compile);
1040 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1041 NODE_SET_METHOD(process, "reallyExit", Exit);
1042 NODE_SET_METHOD(process, "chdir", Chdir);
1043 NODE_SET_METHOD(process, "cwd", Cwd);
1044 NODE_SET_METHOD(process, "getuid", GetUid);
1045 NODE_SET_METHOD(process, "setuid", SetUid);
1047 NODE_SET_METHOD(process, "setgid", SetGid);
1048 NODE_SET_METHOD(process, "getgid", GetGid);
1050 NODE_SET_METHOD(process, "umask", Umask);
1051 NODE_SET_METHOD(process, "dlopen", DLOpen);
1052 NODE_SET_METHOD(process, "kill", Kill);
1053 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1054 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1056 // Assign the EventEmitter. It was created in main().
1057 process->Set(String::NewSymbol("EventEmitter"),
1058 EventEmitter::constructor_template->GetFunction());
1060 // Initialize the stats object
1061 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1062 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1063 process->Set(String::NewSymbol("Stats"),
1064 stats_constructor_template->GetFunction());
1067 // Initialize the C++ modules..................filename of module
1068 IdleWatcher::Initialize(process); // idle_watcher.cc
1069 Stdio::Initialize(process); // stdio.cc
1070 Timer::Initialize(process); // timer.cc
1071 SignalHandler::Initialize(process); // signal_handler.cc
1072 Stat::Initialize(process); // stat.cc
1073 ChildProcess::Initialize(process); // child_process.cc
1074 DefineConstants(process); // constants.cc
1076 Local<Object> dns = Object::New();
1077 process->Set(String::NewSymbol("dns"), dns);
1078 DNS::Initialize(dns); // dns.cc
1079 Local<Object> fs = Object::New();
1080 process->Set(String::NewSymbol("fs"), fs);
1081 File::Initialize(fs); // file.cc
1082 // Create node.tcp. Note this separate from lib/tcp.js which is the public
1084 Local<Object> tcp = Object::New();
1085 process->Set(String::New("tcp"), tcp);
1086 Server::Initialize(tcp); // tcp.cc
1087 Connection::Initialize(tcp); // tcp.cc
1088 // Create node.http. Note this separate from lib/http.js which is the
1090 Local<Object> http = Object::New();
1091 process->Set(String::New("http"), http);
1092 HTTPServer::Initialize(http); // http.cc
1093 HTTPConnection::Initialize(http); // http.cc
1097 // Compile, execute the src/node.js file. (Which was included as static C
1098 // string in node_natives.h. 'natve_node' is the string containing that
1101 // The node.js file returns a function 'f'
1107 Local<Value> f_value = ExecuteString(String::New(native_node),
1108 String::New("node.js"));
1110 if (try_catch.HasCaught()) {
1111 ReportException(try_catch);
1115 assert(f_value->IsFunction());
1116 Local<Function> f = Local<Function>::Cast(f_value);
1118 // Now we call 'f' with the 'process' variable that we've built up with
1119 // all our bindings. Inside node.js we'll take care of assigning things to
1122 // We start the process this way in order to be more modular. Developers
1123 // who do not like how 'src/node.js' setups the module system but do like
1124 // Node's I/O bindings may want to replace 'f' with their own function.
1126 Local<Value> args[1] = { Local<Value>::New(process) };
1128 f->Call(global, 1, args);
1131 if (try_catch.HasCaught()) {
1132 ReportException(try_catch);
1138 static void PrintHelp();
1140 static void ParseDebugOpt(const char* arg) {
1143 use_debug_agent = true;
1144 if (!strcmp (arg, "--debug-brk")) {
1145 debug_wait_connect = true;
1147 } else if (!strcmp(arg, "--debug")) {
1149 } else if (strstr(arg, "--debug-brk=") == arg) {
1150 debug_wait_connect = true;
1151 p = 1 + strchr(arg, '=');
1152 debug_port = atoi(p);
1153 } else if (strstr(arg, "--debug=") == arg) {
1154 p = 1 + strchr(arg, '=');
1155 debug_port = atoi(p);
1157 if (p && debug_port > 1024 && debug_port < 65536)
1160 fprintf(stderr, "Bad debug option.\n");
1161 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1167 static void PrintHelp() {
1168 printf("Usage: node [options] script.js [arguments] \n"
1169 " -v, --version print node's version\n"
1170 " --debug[=port] enable remote debugging via given TCP port\n"
1171 " without stopping the execution\n"
1172 " --debug-brk[=port] as above, but break in script.js and\n"
1173 " wait for remote debugger to connect\n"
1174 " --cflags print pre-processor and compiler flags\n"
1175 " --v8-options print v8 command line options\n\n"
1176 "Documentation can be found at http://nodejs.org/api.html"
1177 " or with 'man node'\n");
1180 // Parse node command line arguments.
1181 static void ParseArgs(int *argc, char **argv) {
1182 // TODO use parse opts
1183 for (int i = 1; i < *argc; i++) {
1184 const char *arg = argv[i];
1185 if (strstr(arg, "--debug") == arg) {
1187 argv[i] = const_cast<char*>("");
1188 option_end_index = i;
1189 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1190 printf("%s\n", NODE_VERSION);
1192 } else if (strcmp(arg, "--cflags") == 0) {
1193 printf("%s\n", NODE_CFLAGS);
1195 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1198 } else if (strcmp(arg, "--v8-options") == 0) {
1199 argv[i] = const_cast<char*>("--help");
1200 option_end_index = i+1;
1201 } else if (argv[i][0] != '-') {
1202 option_end_index = i-1;
1211 int main(int argc, char *argv[]) {
1212 // Parse a few arguments which are specific to Node.
1213 node::ParseArgs(&argc, argv);
1214 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1215 // in the command line))
1216 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1218 // Error out if we don't have a script argument.
1220 fprintf(stderr, "No script was specified.\n");
1225 // Ignore the SIGPIPE
1226 evcom_ignore_sigpipe();
1228 // Initialize the default ev loop.
1230 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1231 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1232 ev_default_loop(EVBACKEND_SELECT);
1233 #elif defined(__APPLE__)
1234 ev_default_loop(EVBACKEND_KQUEUE);
1236 ev_default_loop(EVFLAG_AUTO);
1240 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1241 // Set the gc_timer to max priority so that it runs before all other
1242 // watchers. In this way it can check if the 'tick' has other pending
1243 // watchers by using ev_pending_count() - if it ran with lower priority
1244 // then the other watchers might run before it - not giving us good idea
1245 // of loop idleness.
1246 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1247 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1248 ev_unref(EV_DEFAULT_UC);
1251 // Setup the EIO thread pool
1252 { // It requires 3, yes 3, watchers.
1253 ev_idle_init(&node::eio_poller, node::DoPoll);
1255 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1256 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1257 ev_unref(EV_DEFAULT_UC);
1259 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1260 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1261 ev_unref(EV_DEFAULT_UC);
1263 eio_init(node::EIOWantPoll, node::EIODonePoll);
1264 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1265 // race conditions. See test/mjsunit/test-eio-race.js
1266 eio_set_max_poll_reqs(10);
1270 HandleScope handle_scope;
1272 V8::SetFatalErrorHandler(node::OnFatalError);
1274 // If the --debug flag was specified then initialize the debug thread.
1275 if (node::use_debug_agent) {
1276 // Initialize the async watcher for receiving messages from the debug
1277 // thread and marshal it into the main thread. DebugMessageCallback()
1278 // is called from the main thread to execute a random bit of javascript
1279 // - which will give V8 control so it can handle whatever new message
1280 // had been received on the debug thread.
1281 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1282 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1283 // Set the callback DebugMessageDispatch which is called from the debug
1285 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1286 // Start the async watcher.
1287 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1288 // unref it so that we exit the event loop despite it being active.
1289 ev_unref(EV_DEFAULT_UC);
1291 // Start the debug thread and it's associated TCP server on port 5858.
1292 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1294 // Crappy check that everything went well. FIXME
1296 // Print out some information.
1297 printf("debugger listening on port %d\n", node::debug_port);
1300 // Create the one and only Context.
1301 Persistent<Context> context = Context::New();
1302 Context::Scope context_scope(context);
1304 // Create all the objects, load modules, do everything.
1305 // so your next reading stop should be node::Load()!
1306 node::Load(argc, argv);
1308 node::Stdio::Flush();