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>
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,
223 v8::Handle<v8::Value> val,
224 enum encoding encoding) {
228 // A lot of improvement can be made here. See:
229 // http://code.google.com/p/v8/issues/detail?id=270
230 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
231 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
233 if (val->IsArray()) {
234 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
240 Local<String> str = val->ToString();
242 if (encoding == UTF8) {
243 str->WriteUtf8(buf, buflen);
247 if (encoding == ASCII) {
248 str->WriteAscii(buf, 0, buflen);
252 // THIS IS AWFUL!!! FIXME
254 assert(encoding == BINARY);
256 uint16_t * twobytebuf = new uint16_t[buflen];
258 str->Write(twobytebuf, 0, buflen);
260 for (size_t i = 0; i < buflen; i++) {
261 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
266 delete [] twobytebuf;
271 static Persistent<FunctionTemplate> stats_constructor_template;
273 Local<Object> BuildStatsObject(struct stat * s) {
276 if (dev_symbol.IsEmpty()) {
277 dev_symbol = NODE_PSYMBOL("dev");
278 ino_symbol = NODE_PSYMBOL("ino");
279 mode_symbol = NODE_PSYMBOL("mode");
280 nlink_symbol = NODE_PSYMBOL("nlink");
281 uid_symbol = NODE_PSYMBOL("uid");
282 gid_symbol = NODE_PSYMBOL("gid");
283 rdev_symbol = NODE_PSYMBOL("rdev");
284 size_symbol = NODE_PSYMBOL("size");
285 blksize_symbol = NODE_PSYMBOL("blksize");
286 blocks_symbol = NODE_PSYMBOL("blocks");
287 atime_symbol = NODE_PSYMBOL("atime");
288 mtime_symbol = NODE_PSYMBOL("mtime");
289 ctime_symbol = NODE_PSYMBOL("ctime");
292 Local<Object> stats =
293 stats_constructor_template->GetFunction()->NewInstance();
295 /* ID of device containing file */
296 stats->Set(dev_symbol, Integer::New(s->st_dev));
299 stats->Set(ino_symbol, Integer::New(s->st_ino));
302 stats->Set(mode_symbol, Integer::New(s->st_mode));
304 /* number of hard links */
305 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
307 /* user ID of owner */
308 stats->Set(uid_symbol, Integer::New(s->st_uid));
310 /* group ID of owner */
311 stats->Set(gid_symbol, Integer::New(s->st_gid));
313 /* device ID (if special file) */
314 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
316 /* total size, in bytes */
317 stats->Set(size_symbol, Integer::New(s->st_size));
319 /* blocksize for filesystem I/O */
320 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
322 /* number of blocks allocated */
323 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
325 /* time of last access */
326 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
328 /* time of last modification */
329 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
331 /* time of last status change */
332 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
334 return scope.Close(stats);
338 // Extracts a C str from a V8 Utf8Value.
339 const char* ToCString(const v8::String::Utf8Value& value) {
340 return *value ? *value : "<str conversion failed>";
343 static void ReportException(TryCatch &try_catch, bool show_line = false) {
344 Handle<Message> message = try_catch.Message();
346 Handle<Value> error = try_catch.Exception();
347 Handle<String> stack;
349 if (error->IsObject()) {
350 Handle<Object> obj = Handle<Object>::Cast(error);
351 Handle<Value> raw_stack = obj->Get(String::New("stack"));
352 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
355 if (show_line && !message.IsEmpty()) {
356 // Print (filename):(line number): (message).
357 String::Utf8Value filename(message->GetScriptResourceName());
358 const char* filename_string = ToCString(filename);
359 int linenum = message->GetLineNumber();
360 fprintf(stderr, "%s:%i\n", filename_string, linenum);
361 // Print line of source code.
362 String::Utf8Value sourceline(message->GetSourceLine());
363 const char* sourceline_string = ToCString(sourceline);
364 fprintf(stderr, "%s\n", sourceline_string);
365 // Print wavy underline (GetUnderline is deprecated).
366 int start = message->GetStartColumn();
367 for (int i = 0; i < start; i++) {
368 fprintf(stderr, " ");
370 int end = message->GetEndColumn();
371 for (int i = start; i < end; i++) {
372 fprintf(stderr, "^");
374 fprintf(stderr, "\n");
377 if (stack.IsEmpty()) {
378 message->PrintCurrentStackTrace(stderr);
380 String::Utf8Value trace(stack);
381 fprintf(stderr, "%s\n", *trace);
386 // Executes a str within the current v8 context.
387 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
391 Local<Script> script = Script::Compile(source, filename);
392 if (script.IsEmpty()) {
393 ReportException(try_catch);
397 Local<Value> result = script->Run();
398 if (result.IsEmpty()) {
399 ReportException(try_catch);
403 return scope.Close(result);
406 static Handle<Value> ByteLength(const Arguments& args) {
409 if (args.Length() < 1 || !args[0]->IsString()) {
410 return ThrowException(Exception::Error(String::New("Bad argument.")));
413 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
415 return scope.Close(length);
418 static Handle<Value> Loop(const Arguments& args) {
420 assert(args.Length() == 0);
422 // TODO Probably don't need to start this each time.
423 // Avoids failing on test/mjsunit/test-eio-race3.js though
424 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
426 ev_loop(EV_DEFAULT_UC_ 0);
430 static Handle<Value> Unloop(const Arguments& args) {
431 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
433 int how = EVUNLOOP_ONE;
434 if (args[0]->IsString()) {
435 String::Utf8Value how_s(args[0]->ToString());
436 if (0 == strcmp(*how_s, "all")) {
440 ev_unloop(EV_DEFAULT_ how);
444 static Handle<Value> Chdir(const Arguments& args) {
447 if (args.Length() != 1 || !args[0]->IsString()) {
448 return ThrowException(Exception::Error(String::New("Bad argument.")));
451 String::Utf8Value path(args[0]->ToString());
453 int r = chdir(*path);
456 return ThrowException(Exception::Error(String::New(strerror(errno))));
462 static Handle<Value> Cwd(const Arguments& args) {
464 assert(args.Length() == 0);
466 char output[PATH_MAX];
467 char *r = getcwd(output, PATH_MAX);
469 return ThrowException(Exception::Error(String::New(strerror(errno))));
471 Local<String> cwd = String::New(output);
473 return scope.Close(cwd);
476 static Handle<Value> Umask(const Arguments& args){
479 if(args.Length() < 1) {
483 else if(!args[0]->IsInt32()) {
484 return ThrowException(Exception::TypeError(
485 String::New("argument must be an integer.")));
488 old = umask((mode_t)args[0]->Uint32Value());
490 return scope.Close(Uint32::New(old));
494 static Handle<Value> GetUid(const Arguments& args) {
496 assert(args.Length() == 0);
498 return scope.Close(Integer::New(uid));
501 static Handle<Value> GetGid(const Arguments& args) {
503 assert(args.Length() == 0);
505 return scope.Close(Integer::New(gid));
509 static Handle<Value> SetGid(const Arguments& args) {
512 if (args.Length() < 1) {
513 return ThrowException(Exception::Error(
514 String::New("setgid requires 1 argument")));
517 Local<Integer> given_gid = args[0]->ToInteger();
518 int gid = given_gid->Int32Value();
520 if ((result = setgid(gid)) != 0) {
521 return ThrowException(Exception::Error(String::New(strerror(errno))));
526 static Handle<Value> SetUid(const Arguments& args) {
529 if (args.Length() < 1) {
530 return ThrowException(Exception::Error(
531 String::New("setuid requires 1 argument")));
534 Local<Integer> given_uid = args[0]->ToInteger();
535 int uid = given_uid->Int32Value();
537 if ((result = setuid(uid)) != 0) {
538 return ThrowException(Exception::Error(String::New(strerror(errno))));
544 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
548 exit(args[0]->IntegerValue());
553 #define HAVE_GETMEM 1
554 #include <unistd.h> /* getpagesize() */
556 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
557 #define PROCFS_FILE_OFFSET_BITS_HACK 1
558 #undef _FILE_OFFSET_BITS
560 #define PROCFS_FILE_OFFSET_BITS_HACK 0
565 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
566 #define _FILE_OFFSET_BITS 64
569 int getmem(size_t *rss, size_t *vsize) {
570 pid_t pid = getpid();
572 size_t page_size = getpagesize();
574 sprintf(pidpath, "/proc/%d/psinfo", pid);
577 FILE *f = fopen(pidpath, "r");
580 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
587 *vsize = (size_t) psinfo.pr_size * page_size;
588 *rss = (size_t) psinfo.pr_rssize * 1024;
598 #define HAVE_GETMEM 1
600 #include <sys/param.h>
601 #include <sys/sysctl.h>
602 #include <sys/user.h>
606 int getmem(size_t *rss, size_t *vsize) {
608 struct kinfo_proc *kinfo = NULL;
611 size_t page_size = getpagesize();
615 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
616 if (kd == NULL) goto error;
618 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
619 if (kinfo == NULL) goto error;
621 *rss = kinfo->ki_rssize * page_size;
622 *vsize = kinfo->ki_size;
629 if (kd) kvm_close(kd);
632 #endif // __FreeBSD__
636 #define HAVE_GETMEM 1
637 /* Researched by Tim Becker and Michael Knight
638 * http://blog.kuriositaet.de/?p=257
641 #include <mach/task.h>
642 #include <mach/mach_init.h>
644 int getmem(size_t *rss, size_t *vsize) {
645 struct task_basic_info t_info;
646 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
648 int r = task_info(mach_task_self(),
650 (task_info_t)&t_info,
653 if (r != KERN_SUCCESS) return -1;
655 *rss = t_info.resident_size;
656 *vsize = t_info.virtual_size;
663 # define HAVE_GETMEM 1
664 # include <sys/param.h> /* for MAXPATHLEN */
666 int getmem(size_t *rss, size_t *vsize) {
667 FILE *f = fopen("/proc/self/stat", "r");
672 char buffer[MAXPATHLEN];
673 size_t page_size = getpagesize();
676 if (fscanf(f, "%d ", &itmp) == 0) goto error;
678 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
680 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
682 if (fscanf (f, "%d ", &itmp) == 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;
689 /* TTY owner process group */
690 if (fscanf (f, "%d ", &itmp) == 0) goto error;
692 if (fscanf (f, "%u ", &itmp) == 0) goto error;
693 /* Minor faults (no memory page) */
694 if (fscanf (f, "%u ", &itmp) == 0) goto error;
695 /* Minor faults, children */
696 if (fscanf (f, "%u ", &itmp) == 0) goto error;
697 /* Major faults (memory page faults) */
698 if (fscanf (f, "%u ", &itmp) == 0) goto error;
699 /* Major faults, children */
700 if (fscanf (f, "%u ", &itmp) == 0) goto error;
702 if (fscanf (f, "%d ", &itmp) == 0) goto error;
704 if (fscanf (f, "%d ", &itmp) == 0) goto error;
705 /* utime, children */
706 if (fscanf (f, "%d ", &itmp) == 0) goto error;
707 /* stime, children */
708 if (fscanf (f, "%d ", &itmp) == 0) goto error;
709 /* jiffies remaining in current time slice */
710 if (fscanf (f, "%d ", &itmp) == 0) goto error;
712 if (fscanf (f, "%d ", &itmp) == 0) goto error;
713 /* jiffies until next timeout */
714 if (fscanf (f, "%u ", &itmp) == 0) goto error;
715 /* jiffies until next SIGALRM */
716 if (fscanf (f, "%u ", &itmp) == 0) goto error;
717 /* start time (jiffies since system boot) */
718 if (fscanf (f, "%d ", &itmp) == 0) goto error;
720 /* Virtual memory size */
721 if (fscanf (f, "%u ", &itmp) == 0) goto error;
722 *vsize = (size_t) itmp;
724 /* Resident set size */
725 if (fscanf (f, "%u ", &itmp) == 0) goto error;
726 *rss = (size_t) itmp * page_size;
729 if (fscanf (f, "%u ", &itmp) == 0) goto error;
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;
747 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
749 assert(args.Length() == 0);
752 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
756 int r = getmem(&rss, &vsize);
759 return ThrowException(Exception::Error(String::New(strerror(errno))));
762 Local<Object> info = Object::New();
764 if (rss_symbol.IsEmpty()) {
765 rss_symbol = NODE_PSYMBOL("rss");
766 vsize_symbol = NODE_PSYMBOL("vsize");
767 heap_total_symbol = NODE_PSYMBOL("heapTotal");
768 heap_used_symbol = NODE_PSYMBOL("heapUsed");
771 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
772 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
775 HeapStatistics v8_heap_stats;
776 V8::GetHeapStatistics(&v8_heap_stats);
777 info->Set(heap_total_symbol,
778 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
779 info->Set(heap_used_symbol,
780 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
782 return scope.Close(info);
787 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
790 if (args.Length() < 1 || !args[0]->IsNumber()) {
791 return ThrowException(Exception::Error(String::New("Bad argument.")));
794 pid_t pid = args[0]->IntegerValue();
798 if (args.Length() >= 2) {
799 if (args[1]->IsNumber()) {
800 sig = args[1]->Int32Value();
801 } else if (args[1]->IsString()) {
802 Local<String> signame = args[1]->ToString();
804 Local<Value> sig_v = process->Get(signame);
805 if (!sig_v->IsNumber()) {
806 return ThrowException(Exception::Error(String::New("Unknown signal")));
808 sig = sig_v->Int32Value();
812 int r = kill(pid, sig);
815 return ThrowException(Exception::Error(String::New(strerror(errno))));
821 typedef void (*extInit)(Handle<Object> exports);
823 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
825 Handle<Value> DLOpen(const v8::Arguments& args) {
828 if (args.Length() < 2) return Undefined();
830 String::Utf8Value filename(args[0]->ToString()); // Cast
831 Local<Object> target = args[1]->ToObject(); // Cast
833 // Actually call dlopen().
834 // FIXME: This is a blocking function and should be called asynchronously!
835 // This function should be moved to file.cc and use libeio to make this
837 void *handle = dlopen(*filename, RTLD_LAZY);
840 if (handle == NULL) {
841 Local<Value> exception = Exception::Error(String::New(dlerror()));
842 return ThrowException(exception);
845 // Get the init() function from the dynamically shared object.
846 void *init_handle = dlsym(handle, "init");
847 // Error out if not found.
848 if (init_handle == NULL) {
849 Local<Value> exception =
850 Exception::Error(String::New("No 'init' symbol found in module."));
851 return ThrowException(exception);
853 extInit init = (extInit)(init_handle); // Cast
855 // Execute the C++ module
861 // evalcx(code, sandbox={})
862 // Executes code in a new context
863 Handle<Value> EvalCX(const Arguments& args) {
866 Local<String> code = args[0]->ToString();
867 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
869 Local<String> filename = args.Length() > 2 ? args[2]->ToString()
870 : String::New("evalcx");
871 // Create the new context
872 Persistent<Context> context = Context::New();
874 // Enter and compile script
877 // Copy objects from global context, to our brand new context
878 Handle<Array> keys = sandbox->GetPropertyNames();
881 for (i = 0; i < keys->Length(); i++) {
882 Handle<String> key = keys->Get(Integer::New(i))->ToString();
883 Handle<Value> value = sandbox->Get(key);
884 context->Global()->Set(key, value);
890 Local<Script> script = Script::Compile(code, filename);
891 Handle<Value> result;
893 if (script.IsEmpty()) {
894 result = ThrowException(try_catch.Exception());
896 result = script->Run();
897 if (result.IsEmpty()) {
898 result = ThrowException(try_catch.Exception());
900 // success! copy changes back onto the sandbox object.
901 keys = context->Global()->GetPropertyNames();
902 for (i = 0; i < keys->Length(); i++) {
903 Handle<String> key = keys->Get(Integer::New(i))->ToString();
904 Handle<Value> value = context->Global()->Get(key);
905 sandbox->Set(key, value);
910 // Clean up, clean up, everybody everywhere!
911 context->DetachGlobal();
915 return scope.Close(result);
918 Handle<Value> Compile(const Arguments& args) {
921 if (args.Length() < 2) {
922 return ThrowException(Exception::TypeError(
923 String::New("needs two arguments.")));
926 Local<String> source = args[0]->ToString();
927 Local<String> filename = args[1]->ToString();
931 Local<Script> script = Script::Compile(source, filename);
932 if (try_catch.HasCaught()) {
933 // Hack because I can't get a proper stacktrace on SyntaxError
934 ReportException(try_catch, true);
938 Local<Value> result = script->Run();
939 if (try_catch.HasCaught()) return try_catch.ReThrow();
941 return scope.Close(result);
944 static void OnFatalError(const char* location, const char* message) {
946 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
948 fprintf(stderr, "FATAL ERROR: %s\n", message);
953 static int uncaught_exception_counter = 0;
955 void FatalException(TryCatch &try_catch) {
958 // Check if uncaught_exception_counter indicates a recursion
959 if (uncaught_exception_counter > 0) {
960 ReportException(try_catch);
964 if (listeners_symbol.IsEmpty()) {
965 listeners_symbol = NODE_PSYMBOL("listeners");
966 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
967 emit_symbol = NODE_PSYMBOL("emit");
970 Local<Value> listeners_v = process->Get(listeners_symbol);
971 assert(listeners_v->IsFunction());
973 Local<Function> listeners = Local<Function>::Cast(listeners_v);
975 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
976 Local<Value> argv[1] = { uncaught_exception_symbol_l };
977 Local<Value> ret = listeners->Call(process, 1, argv);
979 assert(ret->IsArray());
981 Local<Array> listener_array = Local<Array>::Cast(ret);
983 uint32_t length = listener_array->Length();
984 // Report and exit if process has no "uncaughtException" listener
986 ReportException(try_catch);
990 // Otherwise fire the process "uncaughtException" event
991 Local<Value> emit_v = process->Get(emit_symbol);
992 assert(emit_v->IsFunction());
994 Local<Function> emit = Local<Function>::Cast(emit_v);
996 Local<Value> error = try_catch.Exception();
997 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
999 uncaught_exception_counter++;
1000 emit->Call(process, 2, event_argv);
1001 // Decrement so we know if the next exception is a recursion or not
1002 uncaught_exception_counter--;
1006 static ev_async debug_watcher;
1007 volatile static bool debugger_msg_pending = false;
1009 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1011 assert(watcher == &debug_watcher);
1012 assert(revents == EV_ASYNC);
1013 Debug::ProcessDebugMessages();
1016 static void DebugMessageDispatch(void) {
1017 // This function is called from V8's debug thread when a debug TCP client
1018 // has sent a message.
1020 // Send a signal to our main thread saying that it should enter V8 to
1021 // handle the message.
1022 debugger_msg_pending = true;
1023 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1026 static Handle<Value> CheckBreak(const Arguments& args) {
1028 assert(args.Length() == 0);
1030 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1031 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1032 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1033 // get it to halt until Eclipse connects.
1035 if (!debug_wait_connect)
1038 printf("Waiting for remote debugger connection...\n");
1040 const int halfSecond = 50;
1041 const int tenMs=10000;
1042 debugger_msg_pending = false;
1044 if (debugger_msg_pending) {
1045 Debug::DebugBreak();
1046 Debug::ProcessDebugMessages();
1047 debugger_msg_pending = false;
1049 // wait for 500 msec of silence from remote debugger
1050 int cnt = halfSecond;
1052 debugger_msg_pending = false;
1054 if (debugger_msg_pending) {
1055 debugger_msg_pending = false;
1066 Persistent<Object> binding_cache;
1068 static Handle<Value> Binding(const Arguments& args) {
1071 Local<String> module = args[0]->ToString();
1072 String::Utf8Value module_v(module);
1074 if (binding_cache.IsEmpty()) {
1075 binding_cache = Persistent<Object>::New(Object::New());
1078 Local<Object> exports;
1080 // TODO DRY THIS UP!
1082 if (!strcmp(*module_v, "stdio")) {
1083 if (binding_cache->Has(module)) {
1084 exports = binding_cache->Get(module)->ToObject();
1086 exports = Object::New();
1087 Stdio::Initialize(exports);
1088 binding_cache->Set(module, exports);
1091 } else if (!strcmp(*module_v, "http")) {
1092 if (binding_cache->Has(module)) {
1093 exports = binding_cache->Get(module)->ToObject();
1095 // Warning: When calling requireBinding('http') from javascript then
1096 // be sure that you call requireBinding('tcp') before it.
1097 assert(binding_cache->Has(String::New("tcp")));
1098 exports = Object::New();
1099 HTTPServer::Initialize(exports);
1100 HTTPConnection::Initialize(exports);
1101 binding_cache->Set(module, exports);
1104 } else if (!strcmp(*module_v, "tcp")) {
1105 if (binding_cache->Has(module)) {
1106 exports = binding_cache->Get(module)->ToObject();
1108 exports = Object::New();
1109 Server::Initialize(exports);
1110 Connection::Initialize(exports);
1111 binding_cache->Set(module, exports);
1114 } else if (!strcmp(*module_v, "dns")) {
1115 if (binding_cache->Has(module)) {
1116 exports = binding_cache->Get(module)->ToObject();
1118 exports = Object::New();
1119 DNS::Initialize(exports);
1120 binding_cache->Set(module, exports);
1123 } else if (!strcmp(*module_v, "fs")) {
1124 if (binding_cache->Has(module)) {
1125 exports = binding_cache->Get(module)->ToObject();
1127 exports = Object::New();
1129 // Initialize the stats object
1130 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1131 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1132 exports->Set(String::NewSymbol("Stats"),
1133 stats_constructor_template->GetFunction());
1134 StatWatcher::Initialize(exports);
1135 File::Initialize(exports);
1136 binding_cache->Set(module, exports);
1139 } else if (!strcmp(*module_v, "signal_watcher")) {
1140 if (binding_cache->Has(module)) {
1141 exports = binding_cache->Get(module)->ToObject();
1143 exports = Object::New();
1144 SignalWatcher::Initialize(exports);
1145 binding_cache->Set(module, exports);
1148 } else if (!strcmp(*module_v, "net")) {
1149 if (binding_cache->Has(module)) {
1150 exports = binding_cache->Get(module)->ToObject();
1152 exports = Object::New();
1154 binding_cache->Set(module, exports);
1157 } else if (!strcmp(*module_v, "http_parser")) {
1158 if (binding_cache->Has(module)) {
1159 exports = binding_cache->Get(module)->ToObject();
1161 exports = Object::New();
1162 InitHttpParser(exports);
1163 binding_cache->Set(module, exports);
1166 } else if (!strcmp(*module_v, "child_process")) {
1167 if (binding_cache->Has(module)) {
1168 exports = binding_cache->Get(module)->ToObject();
1170 exports = Object::New();
1171 ChildProcess::Initialize(exports);
1172 binding_cache->Set(module, exports);
1175 } else if (!strcmp(*module_v, "buffer")) {
1176 if (binding_cache->Has(module)) {
1177 exports = binding_cache->Get(module)->ToObject();
1179 exports = Object::New();
1180 Buffer::Initialize(exports);
1181 binding_cache->Set(module, exports);
1184 } else if (!strcmp(*module_v, "natives")) {
1185 if (binding_cache->Has(module)) {
1186 exports = binding_cache->Get(module)->ToObject();
1188 exports = Object::New();
1189 // Explicitly define native sources.
1190 // TODO DRY/automate this?
1191 exports->Set(String::New("assert"), String::New(native_assert));
1192 exports->Set(String::New("buffer"), String::New(native_buffer));
1193 exports->Set(String::New("child_process"),String::New(native_child_process));
1194 exports->Set(String::New("dns"), String::New(native_dns));
1195 exports->Set(String::New("events"), String::New(native_events));
1196 exports->Set(String::New("file"), String::New(native_file));
1197 exports->Set(String::New("fs"), String::New(native_fs));
1198 exports->Set(String::New("http"), String::New(native_http));
1199 exports->Set(String::New("http_old"), String::New(native_http_old));
1200 exports->Set(String::New("ini"), String::New(native_ini));
1201 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1202 exports->Set(String::New("net"), String::New(native_net));
1203 exports->Set(String::New("posix"), String::New(native_posix));
1204 exports->Set(String::New("querystring"), String::New(native_querystring));
1205 exports->Set(String::New("repl"), String::New(native_repl));
1206 exports->Set(String::New("sys"), String::New(native_sys));
1207 exports->Set(String::New("tcp"), String::New(native_tcp));
1208 exports->Set(String::New("tcp_old"), String::New(native_tcp_old));
1209 exports->Set(String::New("uri"), String::New(native_uri));
1210 exports->Set(String::New("url"), String::New(native_url));
1211 exports->Set(String::New("utils"), String::New(native_utils));
1212 binding_cache->Set(module, exports);
1217 return ThrowException(Exception::Error(String::New("No such module")));
1220 return scope.Close(exports);
1224 static void Load(int argc, char *argv[]) {
1227 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1228 node::EventEmitter::Initialize(process_template);
1230 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1232 // Add a reference to the global object
1233 Local<Object> global = Context::GetCurrent()->Global();
1234 process->Set(String::NewSymbol("global"), global);
1237 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1238 // process.installPrefix
1239 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1242 #define xstr(s) str(s)
1244 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1248 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1249 arguments->Set(Integer::New(0), String::New(argv[0]));
1250 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1251 Local<String> arg = String::New(argv[i]);
1252 arguments->Set(Integer::New(j), arg);
1255 process->Set(String::NewSymbol("ARGV"), arguments);
1256 process->Set(String::NewSymbol("argv"), arguments);
1258 // create process.env
1259 Local<Object> env = Object::New();
1260 for (i = 0; environ[i]; i++) {
1261 // skip entries without a '=' character
1262 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1263 // create the v8 objects
1264 Local<String> field = String::New(environ[i], j);
1265 Local<String> value = Local<String>();
1266 if (environ[i][j] == '=') {
1267 value = String::New(environ[i]+j+1);
1270 env->Set(field, value);
1272 // assign process.ENV
1273 process->Set(String::NewSymbol("ENV"), env);
1274 process->Set(String::NewSymbol("env"), env);
1276 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1278 // define various internal methods
1279 NODE_SET_METHOD(process, "loop", Loop);
1280 NODE_SET_METHOD(process, "unloop", Unloop);
1281 NODE_SET_METHOD(process, "evalcx", EvalCX);
1282 NODE_SET_METHOD(process, "compile", Compile);
1283 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1284 NODE_SET_METHOD(process, "reallyExit", Exit);
1285 NODE_SET_METHOD(process, "chdir", Chdir);
1286 NODE_SET_METHOD(process, "cwd", Cwd);
1287 NODE_SET_METHOD(process, "getuid", GetUid);
1288 NODE_SET_METHOD(process, "setuid", SetUid);
1290 NODE_SET_METHOD(process, "setgid", SetGid);
1291 NODE_SET_METHOD(process, "getgid", GetGid);
1293 NODE_SET_METHOD(process, "umask", Umask);
1294 NODE_SET_METHOD(process, "dlopen", DLOpen);
1295 NODE_SET_METHOD(process, "kill", Kill);
1296 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1297 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1299 NODE_SET_METHOD(process, "binding", Binding);
1301 // Assign the EventEmitter. It was created in main().
1302 process->Set(String::NewSymbol("EventEmitter"),
1303 EventEmitter::constructor_template->GetFunction());
1307 // Initialize the C++ modules..................filename of module
1308 IOWatcher::Initialize(process); // io_watcher.cc
1309 IdleWatcher::Initialize(process); // idle_watcher.cc
1310 Timer::Initialize(process); // timer.cc
1311 DefineConstants(process); // constants.cc
1313 // Compile, execute the src/node.js file. (Which was included as static C
1314 // string in node_natives.h. 'natve_node' is the string containing that
1317 // The node.js file returns a function 'f'
1323 Local<Value> f_value = ExecuteString(String::New(native_node),
1324 String::New("node.js"));
1326 if (try_catch.HasCaught()) {
1327 ReportException(try_catch);
1331 assert(f_value->IsFunction());
1332 Local<Function> f = Local<Function>::Cast(f_value);
1334 // Now we call 'f' with the 'process' variable that we've built up with
1335 // all our bindings. Inside node.js we'll take care of assigning things to
1338 // We start the process this way in order to be more modular. Developers
1339 // who do not like how 'src/node.js' setups the module system but do like
1340 // Node's I/O bindings may want to replace 'f' with their own function.
1342 Local<Value> args[1] = { Local<Value>::New(process) };
1344 f->Call(global, 1, args);
1347 if (try_catch.HasCaught()) {
1348 ReportException(try_catch);
1354 static void PrintHelp();
1356 static void ParseDebugOpt(const char* arg) {
1359 use_debug_agent = true;
1360 if (!strcmp (arg, "--debug-brk")) {
1361 debug_wait_connect = true;
1363 } else if (!strcmp(arg, "--debug")) {
1365 } else if (strstr(arg, "--debug-brk=") == arg) {
1366 debug_wait_connect = true;
1367 p = 1 + strchr(arg, '=');
1368 debug_port = atoi(p);
1369 } else if (strstr(arg, "--debug=") == arg) {
1370 p = 1 + strchr(arg, '=');
1371 debug_port = atoi(p);
1373 if (p && debug_port > 1024 && debug_port < 65536)
1376 fprintf(stderr, "Bad debug option.\n");
1377 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1383 static void PrintHelp() {
1384 printf("Usage: node [options] script.js [arguments] \n"
1386 " -v, --version print node's version\n"
1387 " --debug[=port] enable remote debugging via given TCP port\n"
1388 " without stopping the execution\n"
1389 " --debug-brk[=port] as above, but break in script.js and\n"
1390 " wait for remote debugger to connect\n"
1391 " --v8-options print v8 command line options\n"
1392 " --vars print various compiled-in variables\n"
1394 "Enviromental variables:\n"
1395 "NODE_PATH ':'-separated list of directories\n"
1396 " prefixed to the module search path,\n"
1398 "NODE_DEBUG Print additional debugging output.\n"
1400 "Documentation can be found at http://nodejs.org/api.html"
1401 " or with 'man node'\n");
1404 // Parse node command line arguments.
1405 static void ParseArgs(int *argc, char **argv) {
1406 // TODO use parse opts
1407 for (int i = 1; i < *argc; i++) {
1408 const char *arg = argv[i];
1409 if (strstr(arg, "--debug") == arg) {
1411 argv[i] = const_cast<char*>("");
1412 option_end_index = i;
1413 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1414 printf("%s\n", NODE_VERSION);
1416 } else if (strcmp(arg, "--vars") == 0) {
1417 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1418 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1420 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1423 } else if (strcmp(arg, "--v8-options") == 0) {
1424 argv[i] = const_cast<char*>("--help");
1425 option_end_index = i+1;
1426 } else if (argv[i][0] != '-') {
1427 option_end_index = i-1;
1436 int main(int argc, char *argv[]) {
1437 // Parse a few arguments which are specific to Node.
1438 node::ParseArgs(&argc, argv);
1439 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1440 // in the command line))
1441 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1443 // Error out if we don't have a script argument.
1445 fprintf(stderr, "No script was specified.\n");
1450 // Ignore the SIGPIPE
1451 evcom_ignore_sigpipe();
1453 // Initialize the default ev loop.
1455 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1456 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1457 ev_default_loop(EVBACKEND_SELECT);
1459 ev_default_loop(EVFLAG_AUTO);
1463 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1464 // Set the gc_timer to max priority so that it runs before all other
1465 // watchers. In this way it can check if the 'tick' has other pending
1466 // watchers by using ev_pending_count() - if it ran with lower priority
1467 // then the other watchers might run before it - not giving us good idea
1468 // of loop idleness.
1469 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1470 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1471 ev_unref(EV_DEFAULT_UC);
1474 // Setup the EIO thread pool
1475 { // It requires 3, yes 3, watchers.
1476 ev_idle_init(&node::eio_poller, node::DoPoll);
1478 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1479 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1480 ev_unref(EV_DEFAULT_UC);
1482 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1483 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1484 ev_unref(EV_DEFAULT_UC);
1486 eio_init(node::EIOWantPoll, node::EIODonePoll);
1487 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1488 // race conditions. See test/mjsunit/test-eio-race.js
1489 eio_set_max_poll_reqs(10);
1493 HandleScope handle_scope;
1495 V8::SetFatalErrorHandler(node::OnFatalError);
1497 // If the --debug flag was specified then initialize the debug thread.
1498 if (node::use_debug_agent) {
1499 // Initialize the async watcher for receiving messages from the debug
1500 // thread and marshal it into the main thread. DebugMessageCallback()
1501 // is called from the main thread to execute a random bit of javascript
1502 // - which will give V8 control so it can handle whatever new message
1503 // had been received on the debug thread.
1504 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1505 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1506 // Set the callback DebugMessageDispatch which is called from the debug
1508 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1509 // Start the async watcher.
1510 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1511 // unref it so that we exit the event loop despite it being active.
1512 ev_unref(EV_DEFAULT_UC);
1514 // Start the debug thread and it's associated TCP server on port 5858.
1515 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1517 // Crappy check that everything went well. FIXME
1519 // Print out some information.
1520 printf("debugger listening on port %d\n", node::debug_port);
1523 // Create the one and only Context.
1524 Persistent<Context> context = Context::New();
1525 Context::Scope context_scope(context);
1527 // Create all the objects, load modules, do everything.
1528 // so your next reading stop should be node::Load()!
1529 node::Load(argc, argv);
1531 node::Stdio::Flush();