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_watcher.h>
28 #include <node_stat_watcher.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>
36 #include <node_crypto.h>
43 extern char **environ;
47 static Persistent<Object> process;
49 static Persistent<String> dev_symbol;
50 static Persistent<String> ino_symbol;
51 static Persistent<String> mode_symbol;
52 static Persistent<String> nlink_symbol;
53 static Persistent<String> uid_symbol;
54 static Persistent<String> gid_symbol;
55 static Persistent<String> rdev_symbol;
56 static Persistent<String> size_symbol;
57 static Persistent<String> blksize_symbol;
58 static Persistent<String> blocks_symbol;
59 static Persistent<String> atime_symbol;
60 static Persistent<String> mtime_symbol;
61 static Persistent<String> ctime_symbol;
63 static Persistent<String> rss_symbol;
64 static Persistent<String> vsize_symbol;
65 static Persistent<String> heap_total_symbol;
66 static Persistent<String> heap_used_symbol;
68 static Persistent<String> listeners_symbol;
69 static Persistent<String> uncaught_exception_symbol;
70 static Persistent<String> emit_symbol;
72 static int option_end_index = 0;
73 static bool use_debug_agent = false;
74 static bool debug_wait_connect = false;
75 static int debug_port=5858;
78 static ev_async eio_want_poll_notifier;
79 static ev_async eio_done_poll_notifier;
80 static ev_idle eio_poller;
82 static ev_timer gc_timer;
83 #define GC_INTERVAL 2.0
86 // Node calls this every GC_INTERVAL seconds in order to try and call the
87 // GC. This watcher is run with maximum priority, so ev_pending_count() == 0
88 // is an effective measure of idleness.
89 static void GCTimeout(EV_P_ ev_timer *watcher, int revents) {
90 assert(watcher == &gc_timer);
91 assert(revents == EV_TIMER);
92 if (ev_pending_count(EV_DEFAULT_UC) == 0) V8::IdleNotification();
96 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
97 assert(watcher == &eio_poller);
98 assert(revents == EV_IDLE);
100 //printf("eio_poller\n");
102 if (eio_poll() != -1) {
103 //printf("eio_poller stop\n");
104 ev_idle_stop(EV_DEFAULT_UC_ watcher);
109 // Called from the main thread.
110 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
111 assert(watcher == &eio_want_poll_notifier);
112 assert(revents == EV_ASYNC);
114 //printf("want poll notifier\n");
116 if (eio_poll() == -1) {
117 //printf("eio_poller start\n");
118 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
123 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
124 assert(watcher == &eio_done_poll_notifier);
125 assert(revents == EV_ASYNC);
127 //printf("done poll notifier\n");
129 if (eio_poll() != -1) {
130 //printf("eio_poller stop\n");
131 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
136 // EIOWantPoll() is called from the EIO thread pool each time an EIO
137 // request (that is, one of the node.fs.* functions) has completed.
138 static void EIOWantPoll(void) {
139 // Signal the main thread that eio_poll need to be processed.
140 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
144 static void EIODonePoll(void) {
145 // Signal the main thread that we should stop calling eio_poll().
146 // from the idle watcher.
147 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
151 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
154 if (!encoding_v->IsString()) return _default;
156 String::Utf8Value encoding(encoding_v->ToString());
158 if (strcasecmp(*encoding, "utf8") == 0) {
160 } else if (strcasecmp(*encoding, "utf-8") == 0) {
162 } else if (strcasecmp(*encoding, "ascii") == 0) {
164 } else if (strcasecmp(*encoding, "binary") == 0) {
166 } else if (strcasecmp(*encoding, "raw") == 0) {
167 fprintf(stderr, "'raw' (array of integers) has been removed. "
170 } else if (strcasecmp(*encoding, "raws") == 0) {
171 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
172 "Please update your code.\n");
179 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
182 if (!len) return scope.Close(String::Empty());
184 if (encoding == BINARY) {
185 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
186 uint16_t * twobytebuf = new uint16_t[len];
187 for (size_t i = 0; i < len; i++) {
188 // XXX is the following line platform independent?
189 twobytebuf[i] = cbuf[i];
191 Local<String> chunk = String::New(twobytebuf, len);
192 delete [] twobytebuf; // TODO use ExternalTwoByteString?
193 return scope.Close(chunk);
196 // utf8 or ascii encoding
197 Local<String> chunk = String::New((const char*)buf, len);
198 return scope.Close(chunk);
201 // Returns -1 if the handle was not valid for decoding
202 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
205 if (val->IsArray()) {
206 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
212 Local<String> str = val->ToString();
214 if (encoding == UTF8) return str->Utf8Length();
216 return str->Length();
220 # define MIN(a, b) ((a) < (b) ? (a) : (b))
223 // Returns number of bytes written.
224 ssize_t DecodeWrite(char *buf, size_t buflen,
225 v8::Handle<v8::Value> val,
226 enum encoding encoding) {
230 // A lot of improvement can be made here. See:
231 // http://code.google.com/p/v8/issues/detail?id=270
232 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
233 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
235 if (val->IsArray()) {
236 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
242 Local<String> str = val->ToString();
244 if (encoding == UTF8) {
245 str->WriteUtf8(buf, buflen);
249 if (encoding == ASCII) {
250 str->WriteAscii(buf, 0, buflen);
254 // THIS IS AWFUL!!! FIXME
256 assert(encoding == BINARY);
258 uint16_t * twobytebuf = new uint16_t[buflen];
260 str->Write(twobytebuf, 0, buflen);
262 for (size_t i = 0; i < buflen; i++) {
263 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
268 delete [] twobytebuf;
273 static Persistent<FunctionTemplate> stats_constructor_template;
275 Local<Object> BuildStatsObject(struct stat * s) {
278 if (dev_symbol.IsEmpty()) {
279 dev_symbol = NODE_PSYMBOL("dev");
280 ino_symbol = NODE_PSYMBOL("ino");
281 mode_symbol = NODE_PSYMBOL("mode");
282 nlink_symbol = NODE_PSYMBOL("nlink");
283 uid_symbol = NODE_PSYMBOL("uid");
284 gid_symbol = NODE_PSYMBOL("gid");
285 rdev_symbol = NODE_PSYMBOL("rdev");
286 size_symbol = NODE_PSYMBOL("size");
287 blksize_symbol = NODE_PSYMBOL("blksize");
288 blocks_symbol = NODE_PSYMBOL("blocks");
289 atime_symbol = NODE_PSYMBOL("atime");
290 mtime_symbol = NODE_PSYMBOL("mtime");
291 ctime_symbol = NODE_PSYMBOL("ctime");
294 Local<Object> stats =
295 stats_constructor_template->GetFunction()->NewInstance();
297 /* ID of device containing file */
298 stats->Set(dev_symbol, Integer::New(s->st_dev));
301 stats->Set(ino_symbol, Integer::New(s->st_ino));
304 stats->Set(mode_symbol, Integer::New(s->st_mode));
306 /* number of hard links */
307 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
309 /* user ID of owner */
310 stats->Set(uid_symbol, Integer::New(s->st_uid));
312 /* group ID of owner */
313 stats->Set(gid_symbol, Integer::New(s->st_gid));
315 /* device ID (if special file) */
316 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
318 /* total size, in bytes */
319 stats->Set(size_symbol, Integer::New(s->st_size));
321 /* blocksize for filesystem I/O */
322 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
324 /* number of blocks allocated */
325 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
327 /* time of last access */
328 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
330 /* time of last modification */
331 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
333 /* time of last status change */
334 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
336 return scope.Close(stats);
340 // Extracts a C str from a V8 Utf8Value.
341 const char* ToCString(const v8::String::Utf8Value& value) {
342 return *value ? *value : "<str conversion failed>";
345 static void ReportException(TryCatch &try_catch, bool show_line = false) {
346 Handle<Message> message = try_catch.Message();
348 Handle<Value> error = try_catch.Exception();
349 Handle<String> stack;
351 if (error->IsObject()) {
352 Handle<Object> obj = Handle<Object>::Cast(error);
353 Handle<Value> raw_stack = obj->Get(String::New("stack"));
354 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
357 if (show_line && !message.IsEmpty()) {
358 // Print (filename):(line number): (message).
359 String::Utf8Value filename(message->GetScriptResourceName());
360 const char* filename_string = ToCString(filename);
361 int linenum = message->GetLineNumber();
362 fprintf(stderr, "%s:%i\n", filename_string, linenum);
363 // Print line of source code.
364 String::Utf8Value sourceline(message->GetSourceLine());
365 const char* sourceline_string = ToCString(sourceline);
366 fprintf(stderr, "%s\n", sourceline_string);
367 // Print wavy underline (GetUnderline is deprecated).
368 int start = message->GetStartColumn();
369 for (int i = 0; i < start; i++) {
370 fprintf(stderr, " ");
372 int end = message->GetEndColumn();
373 for (int i = start; i < end; i++) {
374 fprintf(stderr, "^");
376 fprintf(stderr, "\n");
379 if (stack.IsEmpty()) {
380 message->PrintCurrentStackTrace(stderr);
382 String::Utf8Value trace(stack);
383 fprintf(stderr, "%s\n", *trace);
388 // Executes a str within the current v8 context.
389 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
393 Local<Script> script = Script::Compile(source, filename);
394 if (script.IsEmpty()) {
395 ReportException(try_catch);
399 Local<Value> result = script->Run();
400 if (result.IsEmpty()) {
401 ReportException(try_catch);
405 return scope.Close(result);
408 static Handle<Value> ByteLength(const Arguments& args) {
411 if (args.Length() < 1 || !args[0]->IsString()) {
412 return ThrowException(Exception::Error(String::New("Bad argument.")));
415 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
417 return scope.Close(length);
420 static Handle<Value> Loop(const Arguments& args) {
422 assert(args.Length() == 0);
424 // TODO Probably don't need to start this each time.
425 // Avoids failing on test/mjsunit/test-eio-race3.js though
426 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
428 ev_loop(EV_DEFAULT_UC_ 0);
432 static Handle<Value> Unloop(const Arguments& args) {
433 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
435 int how = EVUNLOOP_ONE;
436 if (args[0]->IsString()) {
437 String::Utf8Value how_s(args[0]->ToString());
438 if (0 == strcmp(*how_s, "all")) {
442 ev_unloop(EV_DEFAULT_ how);
446 static Handle<Value> Chdir(const Arguments& args) {
449 if (args.Length() != 1 || !args[0]->IsString()) {
450 return ThrowException(Exception::Error(String::New("Bad argument.")));
453 String::Utf8Value path(args[0]->ToString());
455 int r = chdir(*path);
458 return ThrowException(Exception::Error(String::New(strerror(errno))));
464 static Handle<Value> Cwd(const Arguments& args) {
466 assert(args.Length() == 0);
468 char output[PATH_MAX];
469 char *r = getcwd(output, PATH_MAX);
471 return ThrowException(Exception::Error(String::New(strerror(errno))));
473 Local<String> cwd = String::New(output);
475 return scope.Close(cwd);
478 static Handle<Value> Umask(const Arguments& args){
481 if(args.Length() < 1) {
485 else if(!args[0]->IsInt32()) {
486 return ThrowException(Exception::TypeError(
487 String::New("argument must be an integer.")));
490 old = umask((mode_t)args[0]->Uint32Value());
492 return scope.Close(Uint32::New(old));
496 static Handle<Value> GetUid(const Arguments& args) {
498 assert(args.Length() == 0);
500 return scope.Close(Integer::New(uid));
503 static Handle<Value> GetGid(const Arguments& args) {
505 assert(args.Length() == 0);
507 return scope.Close(Integer::New(gid));
511 static Handle<Value> SetGid(const Arguments& args) {
514 if (args.Length() < 1) {
515 return ThrowException(Exception::Error(
516 String::New("setgid requires 1 argument")));
519 Local<Integer> given_gid = args[0]->ToInteger();
520 int gid = given_gid->Int32Value();
522 if ((result = setgid(gid)) != 0) {
523 return ThrowException(Exception::Error(String::New(strerror(errno))));
528 static Handle<Value> SetUid(const Arguments& args) {
531 if (args.Length() < 1) {
532 return ThrowException(Exception::Error(
533 String::New("setuid requires 1 argument")));
536 Local<Integer> given_uid = args[0]->ToInteger();
537 int uid = given_uid->Int32Value();
539 if ((result = setuid(uid)) != 0) {
540 return ThrowException(Exception::Error(String::New(strerror(errno))));
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) {
751 assert(args.Length() == 0);
754 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
758 int r = getmem(&rss, &vsize);
761 return ThrowException(Exception::Error(String::New(strerror(errno))));
764 Local<Object> info = Object::New();
766 if (rss_symbol.IsEmpty()) {
767 rss_symbol = NODE_PSYMBOL("rss");
768 vsize_symbol = NODE_PSYMBOL("vsize");
769 heap_total_symbol = NODE_PSYMBOL("heapTotal");
770 heap_used_symbol = NODE_PSYMBOL("heapUsed");
773 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
774 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
777 HeapStatistics v8_heap_stats;
778 V8::GetHeapStatistics(&v8_heap_stats);
779 info->Set(heap_total_symbol,
780 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
781 info->Set(heap_used_symbol,
782 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
784 return scope.Close(info);
789 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
792 if (args.Length() < 1 || !args[0]->IsNumber()) {
793 return ThrowException(Exception::Error(String::New("Bad argument.")));
796 pid_t pid = args[0]->IntegerValue();
800 if (args.Length() >= 2) {
801 if (args[1]->IsNumber()) {
802 sig = args[1]->Int32Value();
803 } else if (args[1]->IsString()) {
804 Local<String> signame = args[1]->ToString();
806 Local<Value> sig_v = process->Get(signame);
807 if (!sig_v->IsNumber()) {
808 return ThrowException(Exception::Error(String::New("Unknown signal")));
810 sig = sig_v->Int32Value();
814 int r = kill(pid, sig);
817 return ThrowException(Exception::Error(String::New(strerror(errno))));
823 typedef void (*extInit)(Handle<Object> exports);
825 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
827 Handle<Value> DLOpen(const v8::Arguments& args) {
830 if (args.Length() < 2) return Undefined();
832 String::Utf8Value filename(args[0]->ToString()); // Cast
833 Local<Object> target = args[1]->ToObject(); // Cast
835 // Actually call dlopen().
836 // FIXME: This is a blocking function and should be called asynchronously!
837 // This function should be moved to file.cc and use libeio to make this
839 void *handle = dlopen(*filename, RTLD_LAZY);
842 if (handle == NULL) {
843 Local<Value> exception = Exception::Error(String::New(dlerror()));
844 return ThrowException(exception);
847 // Get the init() function from the dynamically shared object.
848 void *init_handle = dlsym(handle, "init");
849 // Error out if not found.
850 if (init_handle == NULL) {
851 Local<Value> exception =
852 Exception::Error(String::New("No 'init' symbol found in module."));
853 return ThrowException(exception);
855 extInit init = (extInit)(init_handle); // Cast
857 // Execute the C++ module
863 // evalcx(code, sandbox={})
864 // Executes code in a new context
865 Handle<Value> EvalCX(const Arguments& args) {
868 Local<String> code = args[0]->ToString();
869 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
871 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
872 : String::New("evalcx");
873 // Create the new context
874 Persistent<Context> context = Context::New();
876 // Enter and compile script
879 // Copy objects from global context, to our brand new context
880 Handle<Array> keys = sandbox->GetPropertyNames();
883 for (i = 0; i < keys->Length(); i++) {
884 Handle<String> key = keys->Get(Integer::New(i))->ToString();
885 Handle<Value> value = sandbox->Get(key);
886 context->Global()->Set(key, value);
892 Local<Script> script = Script::Compile(code, filename);
893 Handle<Value> result;
895 if (script.IsEmpty()) {
896 result = ThrowException(try_catch.Exception());
898 result = script->Run();
899 if (result.IsEmpty()) {
900 result = ThrowException(try_catch.Exception());
902 // success! copy changes back onto the sandbox object.
903 keys = context->Global()->GetPropertyNames();
904 for (i = 0; i < keys->Length(); i++) {
905 Handle<String> key = keys->Get(Integer::New(i))->ToString();
906 Handle<Value> value = context->Global()->Get(key);
907 sandbox->Set(key, value);
912 // Clean up, clean up, everybody everywhere!
913 context->DetachGlobal();
917 return scope.Close(result);
920 Handle<Value> Compile(const Arguments& args) {
923 if (args.Length() < 2) {
924 return ThrowException(Exception::TypeError(
925 String::New("needs two arguments.")));
928 Local<String> source = args[0]->ToString();
929 Local<String> filename = args[1]->ToString();
933 Local<Script> script = Script::Compile(source, filename);
934 if (try_catch.HasCaught()) {
935 // Hack because I can't get a proper stacktrace on SyntaxError
936 ReportException(try_catch, true);
940 Local<Value> result = script->Run();
941 if (try_catch.HasCaught()) return try_catch.ReThrow();
943 return scope.Close(result);
946 static void OnFatalError(const char* location, const char* message) {
948 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
950 fprintf(stderr, "FATAL ERROR: %s\n", message);
955 static int uncaught_exception_counter = 0;
957 void FatalException(TryCatch &try_catch) {
960 // Check if uncaught_exception_counter indicates a recursion
961 if (uncaught_exception_counter > 0) {
962 ReportException(try_catch);
966 if (listeners_symbol.IsEmpty()) {
967 listeners_symbol = NODE_PSYMBOL("listeners");
968 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
969 emit_symbol = NODE_PSYMBOL("emit");
972 Local<Value> listeners_v = process->Get(listeners_symbol);
973 assert(listeners_v->IsFunction());
975 Local<Function> listeners = Local<Function>::Cast(listeners_v);
977 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
978 Local<Value> argv[1] = { uncaught_exception_symbol_l };
979 Local<Value> ret = listeners->Call(process, 1, argv);
981 assert(ret->IsArray());
983 Local<Array> listener_array = Local<Array>::Cast(ret);
985 uint32_t length = listener_array->Length();
986 // Report and exit if process has no "uncaughtException" listener
988 ReportException(try_catch);
992 // Otherwise fire the process "uncaughtException" event
993 Local<Value> emit_v = process->Get(emit_symbol);
994 assert(emit_v->IsFunction());
996 Local<Function> emit = Local<Function>::Cast(emit_v);
998 Local<Value> error = try_catch.Exception();
999 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1001 uncaught_exception_counter++;
1002 emit->Call(process, 2, event_argv);
1003 // Decrement so we know if the next exception is a recursion or not
1004 uncaught_exception_counter--;
1008 static ev_async debug_watcher;
1009 volatile static bool debugger_msg_pending = false;
1011 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1013 assert(watcher == &debug_watcher);
1014 assert(revents == EV_ASYNC);
1015 Debug::ProcessDebugMessages();
1018 static void DebugMessageDispatch(void) {
1019 // This function is called from V8's debug thread when a debug TCP client
1020 // has sent a message.
1022 // Send a signal to our main thread saying that it should enter V8 to
1023 // handle the message.
1024 debugger_msg_pending = true;
1025 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1028 static Handle<Value> CheckBreak(const Arguments& args) {
1030 assert(args.Length() == 0);
1032 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1033 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1034 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1035 // get it to halt until Eclipse connects.
1037 if (!debug_wait_connect)
1040 printf("Waiting for remote debugger connection...\n");
1042 const int halfSecond = 50;
1043 const int tenMs=10000;
1044 debugger_msg_pending = false;
1046 if (debugger_msg_pending) {
1047 Debug::DebugBreak();
1048 Debug::ProcessDebugMessages();
1049 debugger_msg_pending = false;
1051 // wait for 500 msec of silence from remote debugger
1052 int cnt = halfSecond;
1054 debugger_msg_pending = false;
1056 if (debugger_msg_pending) {
1057 debugger_msg_pending = false;
1068 Persistent<Object> binding_cache;
1070 static Handle<Value> Binding(const Arguments& args) {
1073 Local<String> module = args[0]->ToString();
1074 String::Utf8Value module_v(module);
1076 if (binding_cache.IsEmpty()) {
1077 binding_cache = Persistent<Object>::New(Object::New());
1080 Local<Object> exports;
1082 // TODO DRY THIS UP!
1084 if (!strcmp(*module_v, "stdio")) {
1085 if (binding_cache->Has(module)) {
1086 exports = binding_cache->Get(module)->ToObject();
1088 exports = Object::New();
1089 Stdio::Initialize(exports);
1090 binding_cache->Set(module, exports);
1093 } else if (!strcmp(*module_v, "http")) {
1094 if (binding_cache->Has(module)) {
1095 exports = binding_cache->Get(module)->ToObject();
1097 // Warning: When calling requireBinding('http') from javascript then
1098 // be sure that you call requireBinding('tcp') before it.
1099 assert(binding_cache->Has(String::New("tcp")));
1100 exports = Object::New();
1101 HTTPServer::Initialize(exports);
1102 HTTPConnection::Initialize(exports);
1103 binding_cache->Set(module, exports);
1106 } else if (!strcmp(*module_v, "tcp")) {
1107 if (binding_cache->Has(module)) {
1108 exports = binding_cache->Get(module)->ToObject();
1110 exports = Object::New();
1111 Server::Initialize(exports);
1112 Connection::Initialize(exports);
1113 binding_cache->Set(module, exports);
1116 } else if (!strcmp(*module_v, "dns")) {
1117 if (binding_cache->Has(module)) {
1118 exports = binding_cache->Get(module)->ToObject();
1120 exports = Object::New();
1121 DNS::Initialize(exports);
1122 binding_cache->Set(module, exports);
1125 } else if (!strcmp(*module_v, "fs")) {
1126 if (binding_cache->Has(module)) {
1127 exports = binding_cache->Get(module)->ToObject();
1129 exports = Object::New();
1131 // Initialize the stats object
1132 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1133 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1134 exports->Set(String::NewSymbol("Stats"),
1135 stats_constructor_template->GetFunction());
1136 StatWatcher::Initialize(exports);
1137 File::Initialize(exports);
1138 binding_cache->Set(module, exports);
1141 } else if (!strcmp(*module_v, "signal_watcher")) {
1142 if (binding_cache->Has(module)) {
1143 exports = binding_cache->Get(module)->ToObject();
1145 exports = Object::New();
1146 SignalWatcher::Initialize(exports);
1147 binding_cache->Set(module, exports);
1150 } else if (!strcmp(*module_v, "net")) {
1151 if (binding_cache->Has(module)) {
1152 exports = binding_cache->Get(module)->ToObject();
1154 exports = Object::New();
1156 binding_cache->Set(module, exports);
1159 } else if (!strcmp(*module_v, "http_parser")) {
1160 if (binding_cache->Has(module)) {
1161 exports = binding_cache->Get(module)->ToObject();
1163 exports = Object::New();
1164 InitHttpParser(exports);
1165 binding_cache->Set(module, exports);
1168 } else if (!strcmp(*module_v, "child_process")) {
1169 if (binding_cache->Has(module)) {
1170 exports = binding_cache->Get(module)->ToObject();
1172 exports = Object::New();
1173 ChildProcess::Initialize(exports);
1174 binding_cache->Set(module, exports);
1177 } else if (!strcmp(*module_v, "buffer")) {
1178 if (binding_cache->Has(module)) {
1179 exports = binding_cache->Get(module)->ToObject();
1181 exports = Object::New();
1182 Buffer::Initialize(exports);
1183 binding_cache->Set(module, exports);
1186 } else if (!strcmp(*module_v, "crypto")) {
1187 if (binding_cache->Has(module)) {
1188 exports = binding_cache->Get(module)->ToObject();
1190 exports = Object::New();
1191 InitCrypto(exports);
1192 binding_cache->Set(module, exports);
1195 } else if (!strcmp(*module_v, "natives")) {
1196 if (binding_cache->Has(module)) {
1197 exports = binding_cache->Get(module)->ToObject();
1199 exports = Object::New();
1200 // Explicitly define native sources.
1201 // TODO DRY/automate this?
1202 exports->Set(String::New("assert"), String::New(native_assert));
1203 exports->Set(String::New("buffer"), String::New(native_buffer));
1204 exports->Set(String::New("child_process"),String::New(native_child_process));
1205 exports->Set(String::New("dns"), String::New(native_dns));
1206 exports->Set(String::New("events"), String::New(native_events));
1207 exports->Set(String::New("file"), String::New(native_file));
1208 exports->Set(String::New("fs"), String::New(native_fs));
1209 exports->Set(String::New("http"), String::New(native_http));
1210 exports->Set(String::New("http_old"), String::New(native_http_old));
1211 exports->Set(String::New("crypto"), String::New(native_crypto));
1212 exports->Set(String::New("ini"), String::New(native_ini));
1213 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1214 exports->Set(String::New("multipart"), String::New(native_multipart));
1215 exports->Set(String::New("net"), String::New(native_net));
1216 exports->Set(String::New("posix"), String::New(native_posix));
1217 exports->Set(String::New("querystring"), String::New(native_querystring));
1218 exports->Set(String::New("repl"), String::New(native_repl));
1219 exports->Set(String::New("sys"), String::New(native_sys));
1220 exports->Set(String::New("tcp"), String::New(native_tcp));
1221 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1222 exports->Set(String::New("uri"), String::New(native_uri));
1223 exports->Set(String::New("url"), String::New(native_url));
1224 exports->Set(String::New("utils"), String::New(native_utils));
1225 binding_cache->Set(module, exports);
1230 return ThrowException(Exception::Error(String::New("No such module")));
1233 return scope.Close(exports);
1237 static void Load(int argc, char *argv[]) {
1240 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1241 node::EventEmitter::Initialize(process_template);
1243 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1245 // Add a reference to the global object
1246 Local<Object> global = Context::GetCurrent()->Global();
1247 process->Set(String::NewSymbol("global"), global);
1250 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1251 // process.installPrefix
1252 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1255 #define xstr(s) str(s)
1257 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1261 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1262 arguments->Set(Integer::New(0), String::New(argv[0]));
1263 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1264 Local<String> arg = String::New(argv[i]);
1265 arguments->Set(Integer::New(j), arg);
1268 process->Set(String::NewSymbol("ARGV"), arguments);
1269 process->Set(String::NewSymbol("argv"), arguments);
1271 // create process.env
1272 Local<Object> env = Object::New();
1273 for (i = 0; environ[i]; i++) {
1274 // skip entries without a '=' character
1275 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1276 // create the v8 objects
1277 Local<String> field = String::New(environ[i], j);
1278 Local<String> value = Local<String>();
1279 if (environ[i][j] == '=') {
1280 value = String::New(environ[i]+j+1);
1283 env->Set(field, value);
1285 // assign process.ENV
1286 process->Set(String::NewSymbol("ENV"), env);
1287 process->Set(String::NewSymbol("env"), env);
1289 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1291 // define various internal methods
1292 NODE_SET_METHOD(process, "loop", Loop);
1293 NODE_SET_METHOD(process, "unloop", Unloop);
1294 NODE_SET_METHOD(process, "evalcx", EvalCX);
1295 NODE_SET_METHOD(process, "compile", Compile);
1296 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1297 NODE_SET_METHOD(process, "reallyExit", Exit);
1298 NODE_SET_METHOD(process, "chdir", Chdir);
1299 NODE_SET_METHOD(process, "cwd", Cwd);
1300 NODE_SET_METHOD(process, "getuid", GetUid);
1301 NODE_SET_METHOD(process, "setuid", SetUid);
1303 NODE_SET_METHOD(process, "setgid", SetGid);
1304 NODE_SET_METHOD(process, "getgid", GetGid);
1306 NODE_SET_METHOD(process, "umask", Umask);
1307 NODE_SET_METHOD(process, "dlopen", DLOpen);
1308 NODE_SET_METHOD(process, "kill", Kill);
1309 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1310 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1312 NODE_SET_METHOD(process, "binding", Binding);
1314 // Assign the EventEmitter. It was created in main().
1315 process->Set(String::NewSymbol("EventEmitter"),
1316 EventEmitter::constructor_template->GetFunction());
1320 // Initialize the C++ modules..................filename of module
1321 IOWatcher::Initialize(process); // io_watcher.cc
1322 IdleWatcher::Initialize(process); // idle_watcher.cc
1323 Timer::Initialize(process); // timer.cc
1324 DefineConstants(process); // constants.cc
1326 // Compile, execute the src/node.js file. (Which was included as static C
1327 // string in node_natives.h. 'natve_node' is the string containing that
1330 // The node.js file returns a function 'f'
1336 Local<Value> f_value = ExecuteString(String::New(native_node),
1337 String::New("node.js"));
1339 if (try_catch.HasCaught()) {
1340 ReportException(try_catch);
1344 assert(f_value->IsFunction());
1345 Local<Function> f = Local<Function>::Cast(f_value);
1347 // Now we call 'f' with the 'process' variable that we've built up with
1348 // all our bindings. Inside node.js we'll take care of assigning things to
1351 // We start the process this way in order to be more modular. Developers
1352 // who do not like how 'src/node.js' setups the module system but do like
1353 // Node's I/O bindings may want to replace 'f' with their own function.
1355 Local<Value> args[1] = { Local<Value>::New(process) };
1357 f->Call(global, 1, args);
1360 if (try_catch.HasCaught()) {
1361 ReportException(try_catch);
1367 static void PrintHelp();
1369 static void ParseDebugOpt(const char* arg) {
1372 use_debug_agent = true;
1373 if (!strcmp (arg, "--debug-brk")) {
1374 debug_wait_connect = true;
1376 } else if (!strcmp(arg, "--debug")) {
1378 } else if (strstr(arg, "--debug-brk=") == arg) {
1379 debug_wait_connect = true;
1380 p = 1 + strchr(arg, '=');
1381 debug_port = atoi(p);
1382 } else if (strstr(arg, "--debug=") == arg) {
1383 p = 1 + strchr(arg, '=');
1384 debug_port = atoi(p);
1386 if (p && debug_port > 1024 && debug_port < 65536)
1389 fprintf(stderr, "Bad debug option.\n");
1390 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1396 static void PrintHelp() {
1397 printf("Usage: node [options] script.js [arguments] \n"
1399 " -v, --version print node's version\n"
1400 " --debug[=port] enable remote debugging via given TCP port\n"
1401 " without stopping the execution\n"
1402 " --debug-brk[=port] as above, but break in script.js and\n"
1403 " wait for remote debugger to connect\n"
1404 " --v8-options print v8 command line options\n"
1405 " --vars print various compiled-in variables\n"
1407 "Enviromental variables:\n"
1408 "NODE_PATH ':'-separated list of directories\n"
1409 " prefixed to the module search path,\n"
1411 "NODE_DEBUG Print additional debugging output.\n"
1413 "Documentation can be found at http://nodejs.org/api.html"
1414 " or with 'man node'\n");
1417 // Parse node command line arguments.
1418 static void ParseArgs(int *argc, char **argv) {
1419 // TODO use parse opts
1420 for (int i = 1; i < *argc; i++) {
1421 const char *arg = argv[i];
1422 if (strstr(arg, "--debug") == arg) {
1424 argv[i] = const_cast<char*>("");
1425 option_end_index = i;
1426 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1427 printf("%s\n", NODE_VERSION);
1429 } else if (strcmp(arg, "--vars") == 0) {
1430 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1431 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1433 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1436 } else if (strcmp(arg, "--v8-options") == 0) {
1437 argv[i] = const_cast<char*>("--help");
1438 option_end_index = i+1;
1439 } else if (argv[i][0] != '-') {
1440 option_end_index = i-1;
1449 int main(int argc, char *argv[]) {
1450 // Parse a few arguments which are specific to Node.
1451 node::ParseArgs(&argc, argv);
1452 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1453 // in the command line))
1454 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1456 // Error out if we don't have a script argument.
1458 fprintf(stderr, "No script was specified.\n");
1463 // Ignore the SIGPIPE
1464 evcom_ignore_sigpipe();
1466 // Initialize the default ev loop.
1468 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1469 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1470 ev_default_loop(EVBACKEND_SELECT);
1472 ev_default_loop(EVFLAG_AUTO);
1476 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1477 // Set the gc_timer to max priority so that it runs before all other
1478 // watchers. In this way it can check if the 'tick' has other pending
1479 // watchers by using ev_pending_count() - if it ran with lower priority
1480 // then the other watchers might run before it - not giving us good idea
1481 // of loop idleness.
1482 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1483 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1484 ev_unref(EV_DEFAULT_UC);
1487 // Setup the EIO thread pool
1488 { // It requires 3, yes 3, watchers.
1489 ev_idle_init(&node::eio_poller, node::DoPoll);
1491 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1492 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1493 ev_unref(EV_DEFAULT_UC);
1495 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1496 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1497 ev_unref(EV_DEFAULT_UC);
1499 eio_init(node::EIOWantPoll, node::EIODonePoll);
1500 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1501 // race conditions. See test/mjsunit/test-eio-race.js
1502 eio_set_max_poll_reqs(10);
1506 HandleScope handle_scope;
1508 V8::SetFatalErrorHandler(node::OnFatalError);
1510 // If the --debug flag was specified then initialize the debug thread.
1511 if (node::use_debug_agent) {
1512 // Initialize the async watcher for receiving messages from the debug
1513 // thread and marshal it into the main thread. DebugMessageCallback()
1514 // is called from the main thread to execute a random bit of javascript
1515 // - which will give V8 control so it can handle whatever new message
1516 // had been received on the debug thread.
1517 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1518 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1519 // Set the callback DebugMessageDispatch which is called from the debug
1521 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1522 // Start the async watcher.
1523 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1524 // unref it so that we exit the event loop despite it being active.
1525 ev_unref(EV_DEFAULT_UC);
1527 // Start the debug thread and it's associated TCP server on port 5858.
1528 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1530 // Crappy check that everything went well. FIXME
1532 // Print out some information.
1533 printf("debugger listening on port %d\n", node::debug_port);
1536 // Create the one and only Context.
1537 Persistent<Context> context = Context::New();
1538 Context::Scope context_scope(context);
1540 // Create all the objects, load modules, do everything.
1541 // so your next reading stop should be node::Load()!
1542 node::Load(argc, argv);
1544 node::Stdio::Flush();