1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
9 #include <limits.h> /* PATH_MAX */
13 #include <dlfcn.h> /* dlopen(), dlsym() */
14 #include <sys/types.h>
15 #include <unistd.h> /* setuid, getuid */
17 #include <node_buffer.h>
18 #include <node_io_watcher.h>
19 #include <node_net2.h>
20 #include <node_events.h>
23 #include <node_file.h>
24 #include <node_idle_watcher.h>
25 #include <node_http.h>
26 #include <node_http_parser.h>
27 #include <node_signal_handler.h>
28 #include <node_stat.h>
29 #include <node_timer.h>
30 #include <node_child_process.h>
31 #include <node_constants.h>
32 #include <node_stdio.h>
33 #include <node_natives.h>
34 #include <node_version.h>
40 extern char **environ;
44 static Persistent<Object> process;
46 static Persistent<String> dev_symbol;
47 static Persistent<String> ino_symbol;
48 static Persistent<String> mode_symbol;
49 static Persistent<String> nlink_symbol;
50 static Persistent<String> uid_symbol;
51 static Persistent<String> gid_symbol;
52 static Persistent<String> rdev_symbol;
53 static Persistent<String> size_symbol;
54 static Persistent<String> blksize_symbol;
55 static Persistent<String> blocks_symbol;
56 static Persistent<String> atime_symbol;
57 static Persistent<String> mtime_symbol;
58 static Persistent<String> ctime_symbol;
60 static Persistent<String> rss_symbol;
61 static Persistent<String> vsize_symbol;
62 static Persistent<String> heap_total_symbol;
63 static Persistent<String> heap_used_symbol;
65 static Persistent<String> listeners_symbol;
66 static Persistent<String> uncaught_exception_symbol;
67 static Persistent<String> emit_symbol;
69 static int option_end_index = 0;
70 static bool use_debug_agent = false;
71 static bool debug_wait_connect = false;
72 static int debug_port=5858;
75 static ev_async eio_want_poll_notifier;
76 static ev_async eio_done_poll_notifier;
77 static ev_idle eio_poller;
79 static ev_timer gc_timer;
80 #define GC_INTERVAL 2.0
83 // Node calls this every GC_INTERVAL seconds in order to try and call the
84 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
85 // is an effective measure of idleness.
86 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
87 assert(watcher == &gc_timer);
88 assert(revents == EV_TIMER);
89 if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
93 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
94 assert(watcher == &eio_poller);
95 assert(revents == EV_IDLE);
97 //printf("eio_poller\n");
99 if (eio_poll() != -1) {
100 //printf("eio_poller stop\n");
101 ev_idle_stop(EV_DEFAULT_UC_ watcher);
106 // Called from the main thread.
107 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
108 assert(watcher == &eio_want_poll_notifier);
109 assert(revents == EV_ASYNC);
111 //printf("want poll notifier\n");
113 if (eio_poll() == -1) {
114 //printf("eio_poller start\n");
115 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
120 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
121 assert(watcher == &eio_done_poll_notifier);
122 assert(revents == EV_ASYNC);
124 //printf("done poll notifier\n");
126 if (eio_poll() != -1) {
127 //printf("eio_poller stop\n");
128 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
133 // EIOWantPoll() is called from the EIO thread pool each time an EIO
134 // request (that is, one of the node.fs.* functions) has completed.
135 static void EIOWantPoll(void) {
136 // Signal the main thread that eio_poll need to be processed.
137 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
141 static void EIODonePoll(void) {
142 // Signal the main thread that we should stop calling eio_poll().
143 // from the idle watcher.
144 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
148 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
151 if (!encoding_v->IsString()) return _default;
153 String::Utf8Value encoding(encoding_v->ToString());
155 if (strcasecmp(*encoding, "utf8") == 0) {
157 } else if (strcasecmp(*encoding, "utf-8") == 0) {
159 } else if (strcasecmp(*encoding, "ascii") == 0) {
161 } else if (strcasecmp(*encoding, "binary") == 0) {
163 } else if (strcasecmp(*encoding, "raw") == 0) {
164 fprintf(stderr, "'raw' (array of integers) has been removed. "
167 } else if (strcasecmp(*encoding, "raws") == 0) {
168 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
169 "Please update your code.\n");
176 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
179 if (!len) return scope.Close(String::Empty());
181 if (encoding == BINARY) {
182 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
183 uint16_t * twobytebuf = new uint16_t[len];
184 for (size_t i = 0; i < len; i++) {
185 // XXX is the following line platform independent?
186 twobytebuf[i] = cbuf[i];
188 Local<String> chunk = String::New(twobytebuf, len);
189 delete [] twobytebuf; // TODO use ExternalTwoByteString?
190 return scope.Close(chunk);
193 // utf8 or ascii encoding
194 Local<String> chunk = String::New((const char*)buf, len);
195 return scope.Close(chunk);
198 // Returns -1 if the handle was not valid for decoding
199 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
202 if (val->IsArray()) {
203 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
209 Local<String> str = val->ToString();
211 if (encoding == UTF8) return str->Utf8Length();
213 return str->Length();
217 # define MIN(a, b) ((a) < (b) ? (a) : (b))
220 // Returns number of bytes written.
221 ssize_t DecodeWrite(char *buf, size_t buflen,
222 v8::Handle<v8::Value> val,
223 enum encoding encoding) {
227 // A lot of improvement can be made here. See:
228 // http://code.google.com/p/v8/issues/detail?id=270
229 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
230 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
232 if (val->IsArray()) {
233 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
239 Local<String> str = val->ToString();
241 if (encoding == UTF8) {
242 str->WriteUtf8(buf, buflen);
246 if (encoding == ASCII) {
247 str->WriteAscii(buf, 0, buflen);
251 // THIS IS AWFUL!!! FIXME
253 assert(encoding == BINARY);
255 uint16_t * twobytebuf = new uint16_t[buflen];
257 str->Write(twobytebuf, 0, buflen);
259 for (size_t i = 0; i < buflen; i++) {
260 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
265 delete [] twobytebuf;
270 static Persistent<FunctionTemplate> stats_constructor_template;
272 Local<Object> BuildStatsObject(struct stat * s) {
275 if (dev_symbol.IsEmpty()) {
276 dev_symbol = NODE_PSYMBOL("dev");
277 ino_symbol = NODE_PSYMBOL("ino");
278 mode_symbol = NODE_PSYMBOL("mode");
279 nlink_symbol = NODE_PSYMBOL("nlink");
280 uid_symbol = NODE_PSYMBOL("uid");
281 gid_symbol = NODE_PSYMBOL("gid");
282 rdev_symbol = NODE_PSYMBOL("rdev");
283 size_symbol = NODE_PSYMBOL("size");
284 blksize_symbol = NODE_PSYMBOL("blksize");
285 blocks_symbol = NODE_PSYMBOL("blocks");
286 atime_symbol = NODE_PSYMBOL("atime");
287 mtime_symbol = NODE_PSYMBOL("mtime");
288 ctime_symbol = NODE_PSYMBOL("ctime");
291 Local<Object> stats =
292 stats_constructor_template->GetFunction()->NewInstance();
294 /* ID of device containing file */
295 stats->Set(dev_symbol, Integer::New(s->st_dev));
298 stats->Set(ino_symbol, Integer::New(s->st_ino));
301 stats->Set(mode_symbol, Integer::New(s->st_mode));
303 /* number of hard links */
304 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
306 /* user ID of owner */
307 stats->Set(uid_symbol, Integer::New(s->st_uid));
309 /* group ID of owner */
310 stats->Set(gid_symbol, Integer::New(s->st_gid));
312 /* device ID (if special file) */
313 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
315 /* total size, in bytes */
316 stats->Set(size_symbol, Integer::New(s->st_size));
318 /* blocksize for filesystem I/O */
319 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
321 /* number of blocks allocated */
322 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
324 /* time of last access */
325 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
327 /* time of last modification */
328 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
330 /* time of last status change */
331 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
333 return scope.Close(stats);
337 // Extracts a C str from a V8 Utf8Value.
338 const char* ToCString(const v8::String::Utf8Value& value) {
339 return *value ? *value : "<str conversion failed>";
342 static void ReportException(TryCatch &try_catch, bool show_line = false) {
343 Handle<Message> message = try_catch.Message();
345 Handle<Value> error = try_catch.Exception();
346 Handle<String> stack;
348 if (error->IsObject()) {
349 Handle<Object> obj = Handle<Object>::Cast(error);
350 Handle<Value> raw_stack = obj->Get(String::New("stack"));
351 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
354 if (show_line && !message.IsEmpty()) {
355 // Print (filename):(line number): (message).
356 String::Utf8Value filename(message->GetScriptResourceName());
357 const char* filename_string = ToCString(filename);
358 int linenum = message->GetLineNumber();
359 fprintf(stderr, "%s:%i\n", filename_string, linenum);
360 // Print line of source code.
361 String::Utf8Value sourceline(message->GetSourceLine());
362 const char* sourceline_string = ToCString(sourceline);
363 fprintf(stderr, "%s\n", sourceline_string);
364 // Print wavy underline (GetUnderline is deprecated).
365 int start = message->GetStartColumn();
366 for (int i = 0; i < start; i++) {
367 fprintf(stderr, " ");
369 int end = message->GetEndColumn();
370 for (int i = start; i < end; i++) {
371 fprintf(stderr, "^");
373 fprintf(stderr, "\n");
376 if (stack.IsEmpty()) {
377 message->PrintCurrentStackTrace(stderr);
379 String::Utf8Value trace(stack);
380 fprintf(stderr, "%s\n", *trace);
385 // Executes a str within the current v8 context.
386 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
390 Local<Script> script = Script::Compile(source, filename);
391 if (script.IsEmpty()) {
392 ReportException(try_catch);
396 Local<Value> result = script->Run();
397 if (result.IsEmpty()) {
398 ReportException(try_catch);
402 return scope.Close(result);
405 static Handle<Value> ByteLength(const Arguments& args) {
408 if (args.Length() < 1 || !args[0]->IsString()) {
409 return ThrowException(Exception::Error(String::New("Bad argument.")));
412 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
414 return scope.Close(length);
417 static Handle<Value> Loop(const Arguments& args) {
420 // TODO Probably don't need to start this each time.
421 // Avoids failing on test/mjsunit/test-eio-race3.js though
422 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
424 ev_loop(EV_DEFAULT_UC_ 0);
428 static Handle<Value> Unloop(const Arguments& args) {
429 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
431 int how = EVUNLOOP_ONE;
432 if (args[0]->IsString()) {
433 String::Utf8Value how_s(args[0]->ToString());
434 if (0 == strcmp(*how_s, "all")) {
438 ev_unloop(EV_DEFAULT_ how);
442 static Handle<Value> Chdir(const Arguments& args) {
445 if (args.Length() != 1 || !args[0]->IsString()) {
446 return ThrowException(Exception::Error(String::New("Bad argument.")));
449 String::Utf8Value path(args[0]->ToString());
451 int r = chdir(*path);
454 return ThrowException(Exception::Error(String::New(strerror(errno))));
460 static Handle<Value> Cwd(const Arguments& args) {
463 char output[PATH_MAX];
464 char *r = getcwd(output, PATH_MAX);
466 return ThrowException(Exception::Error(String::New(strerror(errno))));
468 Local<String> cwd = String::New(output);
470 return scope.Close(cwd);
473 static Handle<Value> Umask(const Arguments& args){
476 if(args.Length() < 1) {
480 else if(!args[0]->IsInt32()) {
481 return ThrowException(Exception::TypeError(
482 String::New("argument must be an integer.")));
485 old = umask((mode_t)args[0]->Uint32Value());
487 return scope.Close(Uint32::New(old));
491 static Handle<Value> GetUid(const Arguments& args) {
494 return scope.Close(Integer::New(uid));
497 static Handle<Value> GetGid(const Arguments& args) {
500 return scope.Close(Integer::New(gid));
504 static Handle<Value> SetGid(const Arguments& args) {
507 if (args.Length() < 1) {
508 return ThrowException(Exception::Error(
509 String::New("setgid requires 1 argument")));
512 Local<Integer> given_gid = args[0]->ToInteger();
513 int gid = given_gid->Int32Value();
515 if ((result = setgid(gid)) != 0) {
516 return ThrowException(Exception::Error(String::New(strerror(errno))));
521 static Handle<Value> SetUid(const Arguments& args) {
524 if (args.Length() < 1) {
525 return ThrowException(Exception::Error(
526 String::New("setuid requires 1 argument")));
529 Local<Integer> given_uid = args[0]->ToInteger();
530 int uid = given_uid->Int32Value();
532 if ((result = setuid(uid)) != 0) {
533 return ThrowException(Exception::Error(String::New(strerror(errno))));
539 NowGetter (Local<String> property, const AccessorInfo& info)
542 return scope.Close(Integer::New(ev_now(EV_DEFAULT_UC)));
546 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
550 exit(args[0]->IntegerValue());
555 #define HAVE_GETMEM 1
556 #include <unistd.h> /* getpagesize() */
558 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
559 #define PROCFS_FILE_OFFSET_BITS_HACK 1
560 #undef _FILE_OFFSET_BITS
562 #define PROCFS_FILE_OFFSET_BITS_HACK 0
567 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
568 #define _FILE_OFFSET_BITS 64
571 int getmem(size_t *rss, size_t *vsize) {
572 pid_t pid = getpid();
574 size_t page_size = getpagesize();
576 sprintf(pidpath, "/proc/%d/psinfo", pid);
579 FILE *f = fopen(pidpath, "r");
582 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
589 *vsize = (size_t) psinfo.pr_size * page_size;
590 *rss = (size_t) psinfo.pr_rssize * 1024;
600 #define HAVE_GETMEM 1
602 #include <sys/param.h>
603 #include <sys/sysctl.h>
604 #include <sys/user.h>
608 int getmem(size_t *rss, size_t *vsize) {
610 struct kinfo_proc *kinfo = NULL;
613 size_t page_size = getpagesize();
617 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
618 if (kd == NULL) goto error;
620 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
621 if (kinfo == NULL) goto error;
623 *rss = kinfo->ki_rssize * page_size;
624 *vsize = kinfo->ki_size;
631 if (kd) kvm_close(kd);
634 #endif // __FreeBSD__
638 #define HAVE_GETMEM 1
639 /* Researched by Tim Becker and Michael Knight
640 * http://blog.kuriositaet.de/?p=257
643 #include <mach/task.h>
644 #include <mach/mach_init.h>
646 int getmem(size_t *rss, size_t *vsize) {
647 struct task_basic_info t_info;
648 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
650 int r = task_info(mach_task_self(),
652 (task_info_t)&t_info,
655 if (r != KERN_SUCCESS) return -1;
657 *rss = t_info.resident_size;
658 *vsize = t_info.virtual_size;
665 # define HAVE_GETMEM 1
666 # include <sys/param.h> /* for MAXPATHLEN */
668 int getmem(size_t *rss, size_t *vsize) {
669 FILE *f = fopen("/proc/self/stat", "r");
674 char buffer[MAXPATHLEN];
675 size_t page_size = getpagesize();
678 if (fscanf(f, "%d ", &itmp) == 0) goto error;
680 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
682 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
684 if (fscanf (f, "%d ", &itmp) == 0) goto error;
686 if (fscanf (f, "%d ", &itmp) == 0) goto error;
688 if (fscanf (f, "%d ", &itmp) == 0) goto error;
690 if (fscanf (f, "%d ", &itmp) == 0) goto error;
691 /* TTY owner process group */
692 if (fscanf (f, "%d ", &itmp) == 0) goto error;
694 if (fscanf (f, "%u ", &itmp) == 0) goto error;
695 /* Minor faults (no memory page) */
696 if (fscanf (f, "%u ", &itmp) == 0) goto error;
697 /* Minor faults, children */
698 if (fscanf (f, "%u ", &itmp) == 0) goto error;
699 /* Major faults (memory page faults) */
700 if (fscanf (f, "%u ", &itmp) == 0) goto error;
701 /* Major faults, children */
702 if (fscanf (f, "%u ", &itmp) == 0) goto error;
704 if (fscanf (f, "%d ", &itmp) == 0) goto error;
706 if (fscanf (f, "%d ", &itmp) == 0) goto error;
707 /* utime, children */
708 if (fscanf (f, "%d ", &itmp) == 0) goto error;
709 /* stime, children */
710 if (fscanf (f, "%d ", &itmp) == 0) goto error;
711 /* jiffies remaining in current time slice */
712 if (fscanf (f, "%d ", &itmp) == 0) goto error;
714 if (fscanf (f, "%d ", &itmp) == 0) goto error;
715 /* jiffies until next timeout */
716 if (fscanf (f, "%u ", &itmp) == 0) goto error;
717 /* jiffies until next SIGALRM */
718 if (fscanf (f, "%u ", &itmp) == 0) goto error;
719 /* start time (jiffies since system boot) */
720 if (fscanf (f, "%d ", &itmp) == 0) goto error;
722 /* Virtual memory size */
723 if (fscanf (f, "%u ", &itmp) == 0) goto error;
724 *vsize = (size_t) itmp;
726 /* Resident set size */
727 if (fscanf (f, "%u ", &itmp) == 0) goto error;
728 *rss = (size_t) itmp * page_size;
731 if (fscanf (f, "%u ", &itmp) == 0) goto error;
733 if (fscanf (f, "%u ", &itmp) == 0) goto error;
735 if (fscanf (f, "%u ", &itmp) == 0) goto error;
737 if (fscanf (f, "%u ", &itmp) == 0) goto error;
749 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
753 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
757 int r = getmem(&rss, &vsize);
760 return ThrowException(Exception::Error(String::New(strerror(errno))));
763 Local<Object> info = Object::New();
765 if (rss_symbol.IsEmpty()) {
766 rss_symbol = NODE_PSYMBOL("rss");
767 vsize_symbol = NODE_PSYMBOL("vsize");
768 heap_total_symbol = NODE_PSYMBOL("heapTotal");
769 heap_used_symbol = NODE_PSYMBOL("heapUsed");
772 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
773 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
776 HeapStatistics v8_heap_stats;
777 V8::GetHeapStatistics(&v8_heap_stats);
778 info->Set(heap_total_symbol,
779 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
780 info->Set(heap_used_symbol,
781 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
783 return scope.Close(info);
788 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
791 if (args.Length() < 1 || !args[0]->IsNumber()) {
792 return ThrowException(Exception::Error(String::New("Bad argument.")));
795 pid_t pid = args[0]->IntegerValue();
799 if (args.Length() >= 2) {
800 if (args[1]->IsNumber()) {
801 sig = args[1]->Int32Value();
802 } else if (args[1]->IsString()) {
803 Local<String> signame = args[1]->ToString();
805 Local<Value> sig_v = process->Get(signame);
806 if (!sig_v->IsNumber()) {
807 return ThrowException(Exception::Error(String::New("Unknown signal")));
809 sig = sig_v->Int32Value();
813 int r = kill(pid, sig);
816 return ThrowException(Exception::Error(String::New(strerror(errno))));
822 typedef void (*extInit)(Handle<Object> exports);
824 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
826 Handle<Value> DLOpen(const v8::Arguments& args) {
829 if (args.Length() < 2) return Undefined();
831 String::Utf8Value filename(args[0]->ToString()); // Cast
832 Local<Object> target = args[1]->ToObject(); // Cast
834 // Actually call dlopen().
835 // FIXME: This is a blocking function and should be called asynchronously!
836 // This function should be moved to file.cc and use libeio to make this
838 void *handle = dlopen(*filename, RTLD_LAZY);
841 if (handle == NULL) {
842 Local<Value> exception = Exception::Error(String::New(dlerror()));
843 return ThrowException(exception);
846 // Get the init() function from the dynamically shared object.
847 void *init_handle = dlsym(handle, "init");
848 // Error out if not found.
849 if (init_handle == NULL) {
850 Local<Value> exception =
851 Exception::Error(String::New("No 'init' symbol found in module."));
852 return ThrowException(exception);
854 extInit init = (extInit)(init_handle); // Cast
856 // Execute the C++ module
862 // evalcx(code, sandbox={})
863 // Executes code in a new context
864 Handle<Value> EvalCX(const Arguments& args) {
867 Local<String> code = args[0]->ToString();
868 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
870 // Create the new context
871 Persistent<Context> context = Context::New();
873 // Copy objects from global context, to our brand new context
874 Handle<Array> keys = sandbox->GetPropertyNames();
877 for (i = 0; i < keys->Length(); i++) {
878 Handle<String> key = keys->Get(Integer::New(i))->ToString();
879 Handle<Value> value = sandbox->Get(key);
880 context->Global()->Set(key, value->ToObject()->Clone());
883 // Enter and compile script
889 Local<Script> script = Script::Compile(code, String::New("evalcx"));
890 Handle<Value> result;
892 if (script.IsEmpty()) {
893 result = ThrowException(try_catch.Exception());
895 result = script->Run();
896 if (result.IsEmpty()) {
897 result = ThrowException(try_catch.Exception());
901 // Clean up, clean up, everybody everywhere!
902 context->DetachGlobal();
906 return scope.Close(result);
909 Handle<Value> Compile(const Arguments& args) {
912 if (args.Length() < 2) {
913 return ThrowException(Exception::TypeError(
914 String::New("needs two arguments.")));
917 Local<String> source = args[0]->ToString();
918 Local<String> filename = args[1]->ToString();
922 Local<Script> script = Script::Compile(source, filename);
923 if (try_catch.HasCaught()) {
924 // Hack because I can't get a proper stacktrace on SyntaxError
925 ReportException(try_catch, true);
929 Local<Value> result = script->Run();
930 if (try_catch.HasCaught()) return try_catch.ReThrow();
932 return scope.Close(result);
935 static void OnFatalError(const char* location, const char* message) {
937 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
939 fprintf(stderr, "FATAL ERROR: %s\n", message);
944 static int uncaught_exception_counter = 0;
946 void FatalException(TryCatch &try_catch) {
949 // Check if uncaught_exception_counter indicates a recursion
950 if (uncaught_exception_counter > 0) {
951 ReportException(try_catch);
955 if (listeners_symbol.IsEmpty()) {
956 listeners_symbol = NODE_PSYMBOL("listeners");
957 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
958 emit_symbol = NODE_PSYMBOL("emit");
961 Local<Value> listeners_v = process->Get(listeners_symbol);
962 assert(listeners_v->IsFunction());
964 Local<Function> listeners = Local<Function>::Cast(listeners_v);
966 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
967 Local<Value> argv[1] = { uncaught_exception_symbol_l };
968 Local<Value> ret = listeners->Call(process, 1, argv);
970 assert(ret->IsArray());
972 Local<Array> listener_array = Local<Array>::Cast(ret);
974 uint32_t length = listener_array->Length();
975 // Report and exit if process has no "uncaughtException" listener
977 ReportException(try_catch);
981 // Otherwise fire the process "uncaughtException" event
982 Local<Value> emit_v = process->Get(emit_symbol);
983 assert(emit_v->IsFunction());
985 Local<Function> emit = Local<Function>::Cast(emit_v);
987 Local<Value> error = try_catch.Exception();
988 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
990 uncaught_exception_counter++;
991 emit->Call(process, 2, event_argv);
992 // Decrement so we know if the next exception is a recursion or not
993 uncaught_exception_counter--;
997 static ev_async debug_watcher;
998 volatile static bool debugger_msg_pending = false;
1000 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1002 assert(watcher == &debug_watcher);
1003 assert(revents == EV_ASYNC);
1004 Debug::ProcessDebugMessages();
1007 static void DebugMessageDispatch(void) {
1008 // This function is called from V8's debug thread when a debug TCP client
1009 // has sent a message.
1011 // Send a signal to our main thread saying that it should enter V8 to
1012 // handle the message.
1013 debugger_msg_pending = true;
1014 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1017 static Handle<Value> CheckBreak(const Arguments& args) {
1020 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1021 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1022 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1023 // get it to halt until Eclipse connects.
1025 if (!debug_wait_connect)
1028 printf("Waiting for remote debugger connection...\n");
1030 const int halfSecond = 50;
1031 const int tenMs=10000;
1032 debugger_msg_pending = false;
1034 if (debugger_msg_pending) {
1035 Debug::DebugBreak();
1036 Debug::ProcessDebugMessages();
1037 debugger_msg_pending = false;
1039 // wait for 500 msec of silence from remote debugger
1040 int cnt = halfSecond;
1042 debugger_msg_pending = false;
1044 if (debugger_msg_pending) {
1045 debugger_msg_pending = false;
1057 static void Load(int argc, char *argv[]) {
1060 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1061 node::EventEmitter::Initialize(process_template);
1063 process_template->InstanceTemplate()->SetAccessor(String::NewSymbol("now"), NowGetter, NULL);
1065 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1067 // Add a reference to the global object
1068 Local<Object> global = Context::GetCurrent()->Global();
1069 process->Set(String::NewSymbol("global"), global);
1072 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1073 // process.installPrefix
1074 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1077 #define xstr(s) str(s)
1079 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1083 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1084 arguments->Set(Integer::New(0), String::New(argv[0]));
1085 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1086 Local<String> arg = String::New(argv[i]);
1087 arguments->Set(Integer::New(j), arg);
1090 process->Set(String::NewSymbol("ARGV"), arguments);
1091 process->Set(String::NewSymbol("argv"), arguments);
1093 // create process.env
1094 Local<Object> env = Object::New();
1095 for (i = 0; environ[i]; i++) {
1096 // skip entries without a '=' character
1097 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1098 // create the v8 objects
1099 Local<String> field = String::New(environ[i], j);
1100 Local<String> value = Local<String>();
1101 if (environ[i][j] == '=') {
1102 value = String::New(environ[i]+j+1);
1105 env->Set(field, value);
1107 // assign process.ENV
1108 process->Set(String::NewSymbol("ENV"), env);
1109 process->Set(String::NewSymbol("env"), env);
1111 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1113 // define various internal methods
1114 NODE_SET_METHOD(process, "loop", Loop);
1115 NODE_SET_METHOD(process, "unloop", Unloop);
1116 NODE_SET_METHOD(process, "evalcx", EvalCX);
1117 NODE_SET_METHOD(process, "compile", Compile);
1118 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1119 NODE_SET_METHOD(process, "reallyExit", Exit);
1120 NODE_SET_METHOD(process, "chdir", Chdir);
1121 NODE_SET_METHOD(process, "cwd", Cwd);
1122 NODE_SET_METHOD(process, "getuid", GetUid);
1123 NODE_SET_METHOD(process, "setuid", SetUid);
1125 NODE_SET_METHOD(process, "setgid", SetGid);
1126 NODE_SET_METHOD(process, "getgid", GetGid);
1128 NODE_SET_METHOD(process, "umask", Umask);
1129 NODE_SET_METHOD(process, "dlopen", DLOpen);
1130 NODE_SET_METHOD(process, "kill", Kill);
1131 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1132 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1134 // Assign the EventEmitter. It was created in main().
1135 process->Set(String::NewSymbol("EventEmitter"),
1136 EventEmitter::constructor_template->GetFunction());
1138 // Initialize the stats object
1139 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1140 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1141 process->Set(String::NewSymbol("Stats"),
1142 stats_constructor_template->GetFunction());
1145 // Initialize the C++ modules..................filename of module
1146 Buffer::Initialize(process); // buffer.cc
1147 IOWatcher::Initialize(process); // io_watcher.cc
1148 IdleWatcher::Initialize(process); // idle_watcher.cc
1149 Timer::Initialize(process); // timer.cc
1150 Stat::Initialize(process); // stat.cc
1151 SignalHandler::Initialize(process); // signal_handler.cc
1153 InitNet2(process); // net2.cc
1154 InitHttpParser(process); // http_parser.cc
1156 Stdio::Initialize(process); // stdio.cc
1157 ChildProcess::Initialize(process); // child_process.cc
1158 DefineConstants(process); // constants.cc
1160 Local<Object> dns = Object::New();
1161 process->Set(String::NewSymbol("dns"), dns);
1162 DNS::Initialize(dns); // dns.cc
1163 Local<Object> fs = Object::New();
1164 process->Set(String::NewSymbol("fs"), fs);
1165 File::Initialize(fs); // file.cc
1166 // Create node.tcp. Note this separate from lib/tcp.js which is the public
1168 Local<Object> tcp = Object::New();
1169 process->Set(String::New("tcp"), tcp);
1170 Server::Initialize(tcp); // tcp.cc
1171 Connection::Initialize(tcp); // tcp.cc
1172 // Create node.http. Note this separate from lib/http.js which is the
1174 Local<Object> http = Object::New();
1175 process->Set(String::New("http"), http);
1176 HTTPServer::Initialize(http); // http.cc
1177 HTTPConnection::Initialize(http); // http.cc
1181 // Compile, execute the src/node.js file. (Which was included as static C
1182 // string in node_natives.h. 'natve_node' is the string containing that
1185 // The node.js file returns a function 'f'
1191 Local<Value> f_value = ExecuteString(String::New(native_node),
1192 String::New("node.js"));
1194 if (try_catch.HasCaught()) {
1195 ReportException(try_catch);
1199 assert(f_value->IsFunction());
1200 Local<Function> f = Local<Function>::Cast(f_value);
1202 // Now we call 'f' with the 'process' variable that we've built up with
1203 // all our bindings. Inside node.js we'll take care of assigning things to
1206 // We start the process this way in order to be more modular. Developers
1207 // who do not like how 'src/node.js' setups the module system but do like
1208 // Node's I/O bindings may want to replace 'f' with their own function.
1210 Local<Value> args[1] = { Local<Value>::New(process) };
1212 f->Call(global, 1, args);
1215 if (try_catch.HasCaught()) {
1216 ReportException(try_catch);
1222 static void PrintHelp();
1224 static void ParseDebugOpt(const char* arg) {
1227 use_debug_agent = true;
1228 if (!strcmp (arg, "--debug-brk")) {
1229 debug_wait_connect = true;
1231 } else if (!strcmp(arg, "--debug")) {
1233 } else if (strstr(arg, "--debug-brk=") == arg) {
1234 debug_wait_connect = true;
1235 p = 1 + strchr(arg, '=');
1236 debug_port = atoi(p);
1237 } else if (strstr(arg, "--debug=") == arg) {
1238 p = 1 + strchr(arg, '=');
1239 debug_port = atoi(p);
1241 if (p && debug_port > 1024 && debug_port < 65536)
1244 fprintf(stderr, "Bad debug option.\n");
1245 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1251 static void PrintHelp() {
1252 printf("Usage: node [options] script.js [arguments] \n"
1254 " -v, --version print node's version\n"
1255 " --debug[=port] enable remote debugging via given TCP port\n"
1256 " without stopping the execution\n"
1257 " --debug-brk[=port] as above, but break in script.js and\n"
1258 " wait for remote debugger to connect\n"
1259 " --v8-options print v8 command line options\n"
1260 " --vars print various compiled-in variables\n"
1262 "Enviromental variables:\n"
1263 "NODE_PATH ':'-separated list of directories\n"
1264 " prefixed to the module search path,\n"
1266 "NODE_DEBUG Print additional debugging output.\n"
1268 "Documentation can be found at http://nodejs.org/api.html"
1269 " or with 'man node'\n");
1272 // Parse node command line arguments.
1273 static void ParseArgs(int *argc, char **argv) {
1274 // TODO use parse opts
1275 for (int i = 1; i < *argc; i++) {
1276 const char *arg = argv[i];
1277 if (strstr(arg, "--debug") == arg) {
1279 argv[i] = const_cast<char*>("");
1280 option_end_index = i;
1281 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1282 printf("%s\n", NODE_VERSION);
1284 } else if (strcmp(arg, "--vars") == 0) {
1285 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1286 printf("NODE_LIBRARIES_PREFIX: %s/%s\n", NODE_PREFIX, "lib/node/libraries");
1287 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1289 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1292 } else if (strcmp(arg, "--v8-options") == 0) {
1293 argv[i] = const_cast<char*>("--help");
1294 option_end_index = i+1;
1295 } else if (argv[i][0] != '-') {
1296 option_end_index = i-1;
1305 int main(int argc, char *argv[]) {
1306 // Parse a few arguments which are specific to Node.
1307 node::ParseArgs(&argc, argv);
1308 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1309 // in the command line))
1310 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1312 // Error out if we don't have a script argument.
1314 fprintf(stderr, "No script was specified.\n");
1319 // Ignore the SIGPIPE
1320 evcom_ignore_sigpipe();
1322 // Initialize the default ev loop.
1324 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1325 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1326 ev_default_loop(EVBACKEND_SELECT);
1328 ev_default_loop(EVFLAG_AUTO);
1332 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1333 // Set the gc_timer to max priority so that it runs before all other
1334 // watchers. In this way it can check if the 'tick' has other pending
1335 // watchers by using ev_pending_count() - if it ran with lower priority
1336 // then the other watchers might run before it - not giving us good idea
1337 // of loop idleness.
1338 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1339 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1340 ev_unref(EV_DEFAULT_UC);
1343 // Setup the EIO thread pool
1344 { // It requires 3, yes 3, watchers.
1345 ev_idle_init(&node::eio_poller, node::DoPoll);
1347 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1348 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1349 ev_unref(EV_DEFAULT_UC);
1351 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1352 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1353 ev_unref(EV_DEFAULT_UC);
1355 eio_init(node::EIOWantPoll, node::EIODonePoll);
1356 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1357 // race conditions. See test/mjsunit/test-eio-race.js
1358 eio_set_max_poll_reqs(10);
1362 HandleScope handle_scope;
1364 V8::SetFatalErrorHandler(node::OnFatalError);
1366 // If the --debug flag was specified then initialize the debug thread.
1367 if (node::use_debug_agent) {
1368 // Initialize the async watcher for receiving messages from the debug
1369 // thread and marshal it into the main thread. DebugMessageCallback()
1370 // is called from the main thread to execute a random bit of javascript
1371 // - which will give V8 control so it can handle whatever new message
1372 // had been received on the debug thread.
1373 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1374 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1375 // Set the callback DebugMessageDispatch which is called from the debug
1377 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1378 // Start the async watcher.
1379 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1380 // unref it so that we exit the event loop despite it being active.
1381 ev_unref(EV_DEFAULT_UC);
1383 // Start the debug thread and it's associated TCP server on port 5858.
1384 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1386 // Crappy check that everything went well. FIXME
1388 // Print out some information.
1389 printf("debugger listening on port %d\n", node::debug_port);
1392 // Create the one and only Context.
1393 Persistent<Context> context = Context::New();
1394 Context::Scope context_scope(context);
1396 // Create all the objects, load modules, do everything.
1397 // so your next reading stop should be node::Load()!
1398 node::Load(argc, argv);
1400 node::Stdio::Flush();