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 dash_dash_index = 0;
64 static bool use_debug_agent = false;
67 static ev_async eio_want_poll_notifier;
68 static ev_async eio_done_poll_notifier;
69 static ev_idle eio_poller;
71 static ev_timer gc_timer;
72 #define GC_INTERVAL 2.0
75 // Node calls this every GC_INTERVAL seconds in order to try and call the
76 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
77 // is an effective measure of idleness.
78 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
79 assert(watcher == &gc_timer);
80 assert(revents == EV_TIMER);
81 if (ev_pending_count() == 0) V8::IdleNotification();
85 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
86 assert(watcher == &eio_poller);
87 assert(revents == EV_IDLE);
89 //printf("eio_poller\n");
91 if (eio_poll() != -1) {
92 //printf("eio_poller stop\n");
93 ev_idle_stop(EV_DEFAULT_UC_ watcher);
98 // Called from the main thread.
99 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
100 assert(watcher == &eio_want_poll_notifier);
101 assert(revents == EV_ASYNC);
103 //printf("want poll notifier\n");
105 if (eio_poll() == -1) {
106 //printf("eio_poller start\n");
107 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
112 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
113 assert(watcher == &eio_done_poll_notifier);
114 assert(revents == EV_ASYNC);
116 //printf("done poll notifier\n");
118 if (eio_poll() != -1) {
119 //printf("eio_poller stop\n");
120 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
125 // EIOWantPoll() is called from the EIO thread pool each time an EIO
126 // request (that is, one of the node.fs.* functions) has completed.
127 static void EIOWantPoll(void) {
128 // Signal the main thread that eio_poll need to be processed.
129 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
133 static void EIODonePoll(void) {
134 // Signal the main thread that we should stop calling eio_poll().
135 // from the idle watcher.
136 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
140 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
143 if (!encoding_v->IsString()) return _default;
145 String::Utf8Value encoding(encoding_v->ToString());
147 if (strcasecmp(*encoding, "utf8") == 0) {
149 } else if (strcasecmp(*encoding, "utf-8") == 0) {
151 } else if (strcasecmp(*encoding, "ascii") == 0) {
153 } else if (strcasecmp(*encoding, "binary") == 0) {
155 } else if (strcasecmp(*encoding, "raw") == 0) {
156 fprintf(stderr, "'raw' (array of integers) has been removed. "
159 } else if (strcasecmp(*encoding, "raws") == 0) {
160 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
161 "Please update your code.\n");
168 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
171 if (!len) return scope.Close(Null());
173 if (encoding == BINARY) {
174 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
175 uint16_t * twobytebuf = new uint16_t[len];
176 for (size_t i = 0; i < len; i++) {
177 // XXX is the following line platform independent?
178 twobytebuf[i] = cbuf[i];
180 Local<String> chunk = String::New(twobytebuf, len);
181 delete [] twobytebuf; // TODO use ExternalTwoByteString?
182 return scope.Close(chunk);
185 // utf8 or ascii encoding
186 Local<String> chunk = String::New((const char*)buf, len);
187 return scope.Close(chunk);
190 // Returns -1 if the handle was not valid for decoding
191 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
194 if (val->IsArray()) {
195 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
201 Local<String> str = val->ToString();
203 if (encoding == UTF8) return str->Utf8Length();
205 return str->Length();
209 # define MIN(a, b) ((a) < (b) ? (a) : (b))
212 // Returns number of bytes written.
213 ssize_t DecodeWrite(char *buf, size_t buflen,
214 v8::Handle<v8::Value> val,
215 enum encoding encoding) {
219 // A lot of improvement can be made here. See:
220 // http://code.google.com/p/v8/issues/detail?id=270
221 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
222 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
224 if (val->IsArray()) {
225 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
231 Local<String> str = val->ToString();
233 if (encoding == UTF8) {
234 str->WriteUtf8(buf, buflen);
238 if (encoding == ASCII) {
239 str->WriteAscii(buf, 0, buflen);
243 // THIS IS AWFUL!!! FIXME
245 assert(encoding == BINARY);
247 uint16_t * twobytebuf = new uint16_t[buflen];
249 str->Write(twobytebuf, 0, buflen);
251 for (size_t i = 0; i < buflen; i++) {
252 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
257 delete [] twobytebuf;
262 static Persistent<FunctionTemplate> stats_constructor_template;
264 Local<Object> BuildStatsObject(struct stat * s) {
267 if (dev_symbol.IsEmpty()) {
268 dev_symbol = NODE_PSYMBOL("dev");
269 ino_symbol = NODE_PSYMBOL("ino");
270 mode_symbol = NODE_PSYMBOL("mode");
271 nlink_symbol = NODE_PSYMBOL("nlink");
272 uid_symbol = NODE_PSYMBOL("uid");
273 gid_symbol = NODE_PSYMBOL("gid");
274 rdev_symbol = NODE_PSYMBOL("rdev");
275 size_symbol = NODE_PSYMBOL("size");
276 blksize_symbol = NODE_PSYMBOL("blksize");
277 blocks_symbol = NODE_PSYMBOL("blocks");
278 atime_symbol = NODE_PSYMBOL("atime");
279 mtime_symbol = NODE_PSYMBOL("mtime");
280 ctime_symbol = NODE_PSYMBOL("ctime");
283 Local<Object> stats =
284 stats_constructor_template->GetFunction()->NewInstance();
286 /* ID of device containing file */
287 stats->Set(dev_symbol, Integer::New(s->st_dev));
290 stats->Set(ino_symbol, Integer::New(s->st_ino));
293 stats->Set(mode_symbol, Integer::New(s->st_mode));
295 /* number of hard links */
296 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
298 /* user ID of owner */
299 stats->Set(uid_symbol, Integer::New(s->st_uid));
301 /* group ID of owner */
302 stats->Set(gid_symbol, Integer::New(s->st_gid));
304 /* device ID (if special file) */
305 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
307 /* total size, in bytes */
308 stats->Set(size_symbol, Integer::New(s->st_size));
310 /* blocksize for filesystem I/O */
311 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
313 /* number of blocks allocated */
314 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
316 /* time of last access */
317 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
319 /* time of last modification */
320 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
322 /* time of last status change */
323 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
325 return scope.Close(stats);
329 // Extracts a C str from a V8 Utf8Value.
330 const char* ToCString(const v8::String::Utf8Value& value) {
331 return *value ? *value : "<str conversion failed>";
334 static void ReportException(TryCatch &try_catch, bool show_line = false) {
335 Handle<Message> message = try_catch.Message();
336 if (message.IsEmpty()) {
337 fprintf(stderr, "Error: (no message)\n");
342 Handle<Value> error = try_catch.Exception();
343 Handle<String> stack;
345 if (error->IsObject()) {
346 Handle<Object> obj = Handle<Object>::Cast(error);
347 Handle<Value> raw_stack = obj->Get(String::New("stack"));
348 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
352 // Print (filename):(line number): (message).
353 String::Utf8Value filename(message->GetScriptResourceName());
354 const char* filename_string = ToCString(filename);
355 int linenum = message->GetLineNumber();
356 fprintf(stderr, "%s:%i\n", filename_string, linenum);
357 // Print line of source code.
358 String::Utf8Value sourceline(message->GetSourceLine());
359 const char* sourceline_string = ToCString(sourceline);
360 fprintf(stderr, "%s\n", sourceline_string);
361 // Print wavy underline (GetUnderline is deprecated).
362 int start = message->GetStartColumn();
363 for (int i = 0; i < start; i++) {
364 fprintf(stderr, " ");
366 int end = message->GetEndColumn();
367 for (int i = start; i < end; i++) {
368 fprintf(stderr, "^");
370 fprintf(stderr, "\n");
373 if (stack.IsEmpty()) {
374 message->PrintCurrentStackTrace(stderr);
376 String::Utf8Value trace(stack);
377 fprintf(stderr, "%s\n", *trace);
382 // Executes a str within the current v8 context.
383 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
387 Local<Script> script = Script::Compile(source, filename);
388 if (script.IsEmpty()) {
389 ReportException(try_catch);
393 Local<Value> result = script->Run();
394 if (result.IsEmpty()) {
395 ReportException(try_catch);
399 return scope.Close(result);
402 static Handle<Value> ByteLength(const Arguments& args) {
405 if (args.Length() < 1 || !args[0]->IsString()) {
406 return ThrowException(Exception::Error(String::New("Bad argument.")));
409 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
411 return scope.Close(length);
414 static Handle<Value> Loop(const Arguments& args) {
417 // TODO Probably don't need to start this each time.
418 // Avoids failing on test/mjsunit/test-eio-race3.js though
419 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
421 ev_loop(EV_DEFAULT_UC_ 0);
425 static Handle<Value> Unloop(const Arguments& args) {
427 int how = EVUNLOOP_ONE;
428 if (args[0]->IsString()) {
429 String::Utf8Value how_s(args[0]->ToString());
430 if (0 == strcmp(*how_s, "all")) {
434 ev_unloop(EV_DEFAULT_ how);
438 static Handle<Value> Chdir(const Arguments& args) {
441 if (args.Length() != 1 || !args[0]->IsString()) {
442 return ThrowException(Exception::Error(String::New("Bad argument.")));
445 String::Utf8Value path(args[0]->ToString());
447 int r = chdir(*path);
450 return ThrowException(Exception::Error(String::New(strerror(errno))));
456 static Handle<Value> Cwd(const Arguments& args) {
459 char output[PATH_MAX];
460 char *r = getcwd(output, PATH_MAX);
462 return ThrowException(Exception::Error(String::New(strerror(errno))));
464 Local<String> cwd = String::New(output);
466 return scope.Close(cwd);
469 static Handle<Value> Umask(const Arguments& args){
472 if(args.Length() < 1 || !args[0]->IsInt32()) {
473 return ThrowException(Exception::TypeError(
474 String::New("argument must be an integer.")));
476 unsigned int mask = args[0]->Uint32Value();
477 unsigned int old = umask((mode_t)mask);
479 return scope.Close(Uint32::New(old));
483 static Handle<Value> GetUid(const Arguments& args) {
486 return scope.Close(Integer::New(uid));
490 static Handle<Value> SetUid(const Arguments& args) {
493 if (args.Length() < 1) {
494 return ThrowException(Exception::Error(
495 String::New("setuid requires 1 argument")));
498 Local<Integer> given_uid = args[0]->ToInteger();
499 int uid = given_uid->Int32Value();
501 if ((result = setuid(uid)) != 0) {
502 return ThrowException(Exception::Error(String::New(strerror(errno))));
508 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
512 exit(args[0]->IntegerValue());
517 #define HAVE_GETMEM 1
518 #include <unistd.h> /* getpagesize() */
520 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
521 #define PROCFS_FILE_OFFSET_BITS_HACK 1
522 #undef _FILE_OFFSET_BITS
524 #define PROCFS_FILE_OFFSET_BITS_HACK 0
529 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
530 #define _FILE_OFFSET_BITS 64
533 int getmem(size_t *rss, size_t *vsize) {
534 pid_t pid = getpid();
536 size_t page_size = getpagesize();
538 sprintf(pidpath, "/proc/%d/psinfo", pid);
541 FILE *f = fopen(pidpath, "r");
544 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
551 *vsize = (size_t) psinfo.pr_size * page_size;
552 *rss = (size_t) psinfo.pr_rssize * 1024;
562 #define HAVE_GETMEM 1
564 #include <sys/param.h>
565 #include <sys/sysctl.h>
566 #include <sys/user.h>
570 int getmem(size_t *rss, size_t *vsize) {
572 struct kinfo_proc *kinfo = NULL;
578 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
579 if (kd == NULL) goto error;
581 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
582 if (kinfo == NULL) goto error;
584 *rss = kinfo->ki_rssize * PAGE_SIZE;
585 *vsize = kinfo->ki_size;
592 if (kd) kvm_close(kd);
595 #endif // __FreeBSD__
599 #define HAVE_GETMEM 1
600 /* Researched by Tim Becker and Michael Knight
601 * http://blog.kuriositaet.de/?p=257
604 #include <mach/task.h>
605 #include <mach/mach_init.h>
607 int getmem(size_t *rss, size_t *vsize) {
608 struct task_basic_info t_info;
609 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
611 int r = task_info(mach_task_self(),
613 (task_info_t)&t_info,
616 if (r != KERN_SUCCESS) return -1;
618 *rss = t_info.resident_size;
619 *vsize = t_info.virtual_size;
626 # define HAVE_GETMEM 1
627 # include <sys/param.h> /* for MAXPATHLEN */
629 int getmem(size_t *rss, size_t *vsize) {
630 FILE *f = fopen("/proc/self/stat", "r");
635 char buffer[MAXPATHLEN];
636 size_t page_size = getpagesize();
639 if (fscanf(f, "%d ", &itmp) == 0) goto error;
641 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
643 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
645 if (fscanf (f, "%d ", &itmp) == 0) goto error;
647 if (fscanf (f, "%d ", &itmp) == 0) goto error;
649 if (fscanf (f, "%d ", &itmp) == 0) goto error;
651 if (fscanf (f, "%d ", &itmp) == 0) goto error;
652 /* TTY owner process group */
653 if (fscanf (f, "%d ", &itmp) == 0) goto error;
655 if (fscanf (f, "%u ", &itmp) == 0) goto error;
656 /* Minor faults (no memory page) */
657 if (fscanf (f, "%u ", &itmp) == 0) goto error;
658 /* Minor faults, children */
659 if (fscanf (f, "%u ", &itmp) == 0) goto error;
660 /* Major faults (memory page faults) */
661 if (fscanf (f, "%u ", &itmp) == 0) goto error;
662 /* Major faults, children */
663 if (fscanf (f, "%u ", &itmp) == 0) goto error;
665 if (fscanf (f, "%d ", &itmp) == 0) goto error;
667 if (fscanf (f, "%d ", &itmp) == 0) goto error;
668 /* utime, children */
669 if (fscanf (f, "%d ", &itmp) == 0) goto error;
670 /* stime, children */
671 if (fscanf (f, "%d ", &itmp) == 0) goto error;
672 /* jiffies remaining in current time slice */
673 if (fscanf (f, "%d ", &itmp) == 0) goto error;
675 if (fscanf (f, "%d ", &itmp) == 0) goto error;
676 /* jiffies until next timeout */
677 if (fscanf (f, "%u ", &itmp) == 0) goto error;
678 /* jiffies until next SIGALRM */
679 if (fscanf (f, "%u ", &itmp) == 0) goto error;
680 /* start time (jiffies since system boot) */
681 if (fscanf (f, "%d ", &itmp) == 0) goto error;
683 /* Virtual memory size */
684 if (fscanf (f, "%u ", &itmp) == 0) goto error;
685 *vsize = (size_t) itmp;
687 /* Resident set size */
688 if (fscanf (f, "%u ", &itmp) == 0) goto error;
689 *rss = (size_t) itmp * page_size;
692 if (fscanf (f, "%u ", &itmp) == 0) goto error;
694 if (fscanf (f, "%u ", &itmp) == 0) goto error;
696 if (fscanf (f, "%u ", &itmp) == 0) goto error;
698 if (fscanf (f, "%u ", &itmp) == 0) goto error;
710 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
714 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
718 int r = getmem(&rss, &vsize);
721 return ThrowException(Exception::Error(String::New(strerror(errno))));
724 Local<Object> info = Object::New();
726 if (rss_symbol.IsEmpty()) {
727 rss_symbol = NODE_PSYMBOL("rss");
728 vsize_symbol = NODE_PSYMBOL("vsize");
729 heap_total_symbol = NODE_PSYMBOL("heapTotal");
730 heap_used_symbol = NODE_PSYMBOL("heapUsed");
733 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
734 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
737 HeapStatistics v8_heap_stats;
738 V8::GetHeapStatistics(&v8_heap_stats);
739 info->Set(heap_total_symbol,
740 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
741 info->Set(heap_used_symbol,
742 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
744 return scope.Close(info);
749 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
752 if (args.Length() < 1 || !args[0]->IsNumber()) {
753 return ThrowException(Exception::Error(String::New("Bad argument.")));
756 pid_t pid = args[0]->IntegerValue();
760 if (args.Length() >= 2) {
761 if (args[1]->IsNumber()) {
762 sig = args[1]->Int32Value();
763 } else if (args[1]->IsString()) {
764 Local<String> signame = args[1]->ToString();
766 Local<Value> sig_v = process->Get(signame);
767 if (!sig_v->IsNumber()) {
768 return ThrowException(Exception::Error(String::New("Unknown signal")));
770 sig = sig_v->Int32Value();
774 int r = kill(pid, sig);
777 return ThrowException(Exception::Error(String::New(strerror(errno))));
783 typedef void (*extInit)(Handle<Object> exports);
785 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
787 Handle<Value> DLOpen(const v8::Arguments& args) {
790 if (args.Length() < 2) return Undefined();
792 String::Utf8Value filename(args[0]->ToString()); // Cast
793 Local<Object> target = args[1]->ToObject(); // Cast
795 // Actually call dlopen().
796 // FIXME: This is a blocking function and should be called asynchronously!
797 // This function should be moved to file.cc and use libeio to make this
799 void *handle = dlopen(*filename, RTLD_LAZY);
802 if (handle == NULL) {
803 Local<Value> exception = Exception::Error(String::New(dlerror()));
804 return ThrowException(exception);
807 // Get the init() function from the dynamically shared object.
808 void *init_handle = dlsym(handle, "init");
809 // Error out if not found.
810 if (init_handle == NULL) {
811 Local<Value> exception =
812 Exception::Error(String::New("No 'init' symbol found in module."));
813 return ThrowException(exception);
815 extInit init = (extInit)(init_handle); // Cast
817 // Execute the C++ module
823 Handle<Value> Compile(const Arguments& args) {
826 if (args.Length() < 2) {
827 return ThrowException(Exception::TypeError(
828 String::New("needs two arguments.")));
831 Local<String> source = args[0]->ToString();
832 Local<String> filename = args[1]->ToString();
836 Local<Script> script = Script::Compile(source, filename);
837 if (try_catch.HasCaught()) {
838 // Hack because I can't get a proper stacktrace on SyntaxError
839 ReportException(try_catch, true);
843 Local<Value> result = script->Run();
844 if (try_catch.HasCaught()) return try_catch.ReThrow();
846 return scope.Close(result);
849 static void OnFatalError(const char* location, const char* message) {
851 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
853 fprintf(stderr, "FATAL ERROR: %s\n", message);
858 static int uncaught_exception_counter = 0;
860 void FatalException(TryCatch &try_catch) {
863 // Check if uncaught_exception_counter indicates a recursion
864 if (uncaught_exception_counter > 0) {
865 ReportException(try_catch);
869 if (listeners_symbol.IsEmpty()) {
870 listeners_symbol = NODE_PSYMBOL("listeners");
871 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
872 emit_symbol = NODE_PSYMBOL("emit");
875 Local<Value> listeners_v = process->Get(listeners_symbol);
876 assert(listeners_v->IsFunction());
878 Local<Function> listeners = Local<Function>::Cast(listeners_v);
880 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
881 Local<Value> argv[1] = { uncaught_exception_symbol_l };
882 Local<Value> ret = listeners->Call(process, 1, argv);
884 assert(ret->IsArray());
886 Local<Array> listener_array = Local<Array>::Cast(ret);
888 uint32_t length = listener_array->Length();
889 // Report and exit if process has no "uncaughtException" listener
891 ReportException(try_catch);
895 // Otherwise fire the process "uncaughtException" event
896 Local<Value> emit_v = process->Get(emit_symbol);
897 assert(emit_v->IsFunction());
899 Local<Function> emit = Local<Function>::Cast(emit_v);
901 Local<Value> error = try_catch.Exception();
902 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
904 uncaught_exception_counter++;
905 emit->Call(process, 2, event_argv);
906 // Decrement so we know if the next exception is a recursion or not
907 uncaught_exception_counter--;
911 static ev_async debug_watcher;
913 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
915 assert(watcher == &debug_watcher);
916 assert(revents == EV_ASYNC);
917 Debug::ProcessDebugMessages();
920 static void DebugMessageDispatch(void) {
921 // This function is called from V8's debug thread when a debug TCP client
922 // has sent a message.
924 // Send a signal to our main thread saying that it should enter V8 to
925 // handle the message.
926 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
930 static void Load(int argc, char *argv[]) {
933 Local<FunctionTemplate> process_template = FunctionTemplate::New();
934 node::EventEmitter::Initialize(process_template);
936 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
938 // Add a reference to the global object
939 Local<Object> global = Context::GetCurrent()->Global();
940 process->Set(String::NewSymbol("global"), global);
943 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
944 // process.installPrefix
945 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
948 #define xstr(s) str(s)
950 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
954 Local<Array> arguments = Array::New(argc - dash_dash_index + 1);
955 arguments->Set(Integer::New(0), String::New(argv[0]));
956 for (j = 1, i = dash_dash_index + 1; i < argc; j++, i++) {
957 Local<String> arg = String::New(argv[i]);
958 arguments->Set(Integer::New(j), arg);
961 process->Set(String::NewSymbol("ARGV"), arguments);
962 process->Set(String::NewSymbol("argv"), arguments);
964 // create process.env
965 Local<Object> env = Object::New();
966 for (i = 0; environ[i]; i++) {
967 // skip entries without a '=' character
968 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
969 // create the v8 objects
970 Local<String> field = String::New(environ[i], j);
971 Local<String> value = Local<String>();
972 if (environ[i][j] == '=') {
973 value = String::New(environ[i]+j+1);
976 env->Set(field, value);
978 // assign process.ENV
979 process->Set(String::NewSymbol("ENV"), env);
980 process->Set(String::NewSymbol("env"), env);
982 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
984 // define various internal methods
985 NODE_SET_METHOD(process, "loop", Loop);
986 NODE_SET_METHOD(process, "unloop", Unloop);
987 NODE_SET_METHOD(process, "compile", Compile);
988 NODE_SET_METHOD(process, "_byteLength", ByteLength);
989 NODE_SET_METHOD(process, "reallyExit", Exit);
990 NODE_SET_METHOD(process, "chdir", Chdir);
991 NODE_SET_METHOD(process, "cwd", Cwd);
992 NODE_SET_METHOD(process, "getuid", GetUid);
993 NODE_SET_METHOD(process, "setuid", SetUid);
994 NODE_SET_METHOD(process, "umask", Umask);
995 NODE_SET_METHOD(process, "dlopen", DLOpen);
996 NODE_SET_METHOD(process, "kill", Kill);
997 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
999 // Assign the EventEmitter. It was created in main().
1000 process->Set(String::NewSymbol("EventEmitter"),
1001 EventEmitter::constructor_template->GetFunction());
1003 // Initialize the stats object
1004 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1005 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1006 process->Set(String::NewSymbol("Stats"),
1007 stats_constructor_template->GetFunction());
1010 // Initialize the C++ modules..................filename of module
1011 IdleWatcher::Initialize(process); // idle_watcher.cc
1012 Stdio::Initialize(process); // stdio.cc
1013 Timer::Initialize(process); // timer.cc
1014 SignalHandler::Initialize(process); // signal_handler.cc
1015 Stat::Initialize(process); // stat.cc
1016 ChildProcess::Initialize(process); // child_process.cc
1017 DefineConstants(process); // constants.cc
1019 Local<Object> dns = Object::New();
1020 process->Set(String::NewSymbol("dns"), dns);
1021 DNS::Initialize(dns); // dns.cc
1022 Local<Object> fs = Object::New();
1023 process->Set(String::NewSymbol("fs"), fs);
1024 File::Initialize(fs); // file.cc
1025 // Create node.tcp. Note this separate from lib/tcp.js which is the public
1027 Local<Object> tcp = Object::New();
1028 process->Set(String::New("tcp"), tcp);
1029 Server::Initialize(tcp); // tcp.cc
1030 Connection::Initialize(tcp); // tcp.cc
1031 // Create node.http. Note this separate from lib/http.js which is the
1033 Local<Object> http = Object::New();
1034 process->Set(String::New("http"), http);
1035 HTTPServer::Initialize(http); // http.cc
1036 HTTPConnection::Initialize(http); // http.cc
1040 // Compile, execute the src/node.js file. (Which was included as static C
1041 // string in node_natives.h. 'natve_node' is the string containing that
1044 // The node.js file returns a function 'f'
1050 Local<Value> f_value = ExecuteString(String::New(native_node),
1051 String::New("node.js"));
1053 if (try_catch.HasCaught()) {
1054 ReportException(try_catch);
1058 assert(f_value->IsFunction());
1059 Local<Function> f = Local<Function>::Cast(f_value);
1061 // Now we call 'f' with the 'process' variable that we've built up with
1062 // all our bindings. Inside node.js we'll take care of assigning things to
1065 // We start the process this way in order to be more modular. Developers
1066 // who do not like how 'src/node.js' setups the module system but do like
1067 // Node's I/O bindings may want to replace 'f' with their own function.
1069 Local<Value> args[1] = { Local<Value>::New(process) };
1070 f->Call(global, 1, args);
1073 if (try_catch.HasCaught()) {
1074 ReportException(try_catch);
1080 static void PrintHelp() {
1081 printf("Usage: node [options] [--] script.js [arguments] \n"
1082 " -v, --version print node's version\n"
1083 " --debug enable remote debugging\n" // TODO specify port
1084 " --cflags print pre-processor and compiler flags\n"
1085 " --v8-options print v8 command line options\n\n"
1086 "Documentation can be found at http://nodejs.org/api.html"
1087 " or with 'man node'\n");
1090 // Parse node command line arguments.
1091 static void ParseArgs(int *argc, char **argv) {
1092 // TODO use parse opts
1093 for (int i = 1; i < *argc; i++) {
1094 const char *arg = argv[i];
1095 if (strcmp(arg, "--") == 0) {
1096 dash_dash_index = i;
1098 } else if (strcmp(arg, "--debug") == 0) {
1099 argv[i] = reinterpret_cast<const char*>("");
1100 use_debug_agent = true;
1101 dash_dash_index = i;
1102 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1103 printf("%s\n", NODE_VERSION);
1105 } else if (strcmp(arg, "--cflags") == 0) {
1106 printf("%s\n", NODE_CFLAGS);
1108 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1111 } else if (strcmp(arg, "--v8-options") == 0) {
1112 argv[i] = reinterpret_cast<const char*>("--help");
1113 dash_dash_index = i+1;
1121 int main(int argc, char *argv[]) {
1122 // Parse a few arguments which are specific to Node.
1123 node::ParseArgs(&argc, argv);
1124 // Parse the rest of the args (up to the 'dash_dash_index' (where '--' was
1125 // in the command line))
1126 V8::SetFlagsFromCommandLine(&node::dash_dash_index, argv, false);
1128 // Error out if we don't have a script argument.
1130 fprintf(stderr, "No script was specified.\n");
1135 // Ignore the SIGPIPE
1136 evcom_ignore_sigpipe();
1138 // Initialize the default ev loop.
1139 ev_default_loop(EVFLAG_AUTO);
1142 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1143 // Set the gc_timer to max priority so that it runs before all other
1144 // watchers. In this way it can check if the 'tick' has other pending
1145 // watchers by using ev_pending_count() - if it ran with lower priority
1146 // then the other watchers might run before it - not giving us good idea
1147 // of loop idleness.
1148 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1149 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1150 ev_unref(EV_DEFAULT_UC);
1153 // Setup the EIO thread pool
1154 { // It requires 3, yes 3, watchers.
1155 ev_idle_init(&node::eio_poller, node::DoPoll);
1157 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1158 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1159 ev_unref(EV_DEFAULT_UC);
1161 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1162 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1163 ev_unref(EV_DEFAULT_UC);
1165 eio_init(node::EIOWantPoll, node::EIODonePoll);
1166 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1167 // race conditions. See test/mjsunit/test-eio-race.js
1168 eio_set_max_poll_reqs(10);
1172 HandleScope handle_scope;
1174 V8::SetFatalErrorHandler(node::OnFatalError);
1176 // If the --debug flag was specified then initialize the debug thread.
1177 if (node::use_debug_agent) {
1178 // Initialize the async watcher for receiving messages from the debug
1179 // thread and marshal it into the main thread. DebugMessageCallback()
1180 // is called from the main thread to execute a random bit of javascript
1181 // - which will give V8 control so it can handle whatever new message
1182 // had been received on the debug thread.
1183 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1184 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1185 // Set the callback DebugMessageDispatch which is called from the debug
1187 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1188 // Start the async watcher.
1189 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1190 // unref it so that we exit the event loop despite it being active.
1191 ev_unref(EV_DEFAULT_UC);
1193 // Start the debug thread and it's associated TCP server on port 5858.
1194 bool r = Debug::EnableAgent("node " NODE_VERSION, 5858);
1195 // Crappy check that everything went well. FIXME
1197 // Print out some information. REMOVEME
1198 printf("debugger listening on port 5858\n"
1199 "Use 'd8 --remote_debugger' to access it.\n");
1202 // Create the one and only Context.
1203 Persistent<Context> context = Context::New();
1204 Context::Scope context_scope(context);
1206 // Create all the objects, load modules, do everything.
1207 // so your next reading stop should be node::Load()!
1208 node::Load(argc, argv);
1210 node::Stdio::Flush();