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, 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) {
419 assert(args.Length() == 0);
421 // TODO Probably don't need to start this each time.
422 // Avoids failing on test/mjsunit/test-eio-race3.js though
423 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
425 ev_loop(EV_DEFAULT_UC_ 0);
429 static Handle<Value> Unloop(const Arguments& args) {
430 fprintf(stderr, "Deprecation: Don't use process.unloop(). It will be removed soon.\n");
432 int how = EVUNLOOP_ONE;
433 if (args[0]->IsString()) {
434 String::Utf8Value how_s(args[0]->ToString());
435 if (0 == strcmp(*how_s, "all")) {
439 ev_unloop(EV_DEFAULT_ how);
443 static Handle<Value> Chdir(const Arguments& args) {
446 if (args.Length() != 1 || !args[0]->IsString()) {
447 return ThrowException(Exception::Error(String::New("Bad argument.")));
450 String::Utf8Value path(args[0]->ToString());
452 int r = chdir(*path);
455 return ThrowException(Exception::Error(String::New(strerror(errno))));
461 static Handle<Value> Cwd(const Arguments& args) {
463 assert(args.Length() == 0);
465 char output[PATH_MAX];
466 char *r = getcwd(output, PATH_MAX);
468 return ThrowException(Exception::Error(String::New(strerror(errno))));
470 Local<String> cwd = String::New(output);
472 return scope.Close(cwd);
475 static Handle<Value> Umask(const Arguments& args){
478 if(args.Length() < 1) {
482 else if(!args[0]->IsInt32()) {
483 return ThrowException(Exception::TypeError(
484 String::New("argument must be an integer.")));
487 old = umask((mode_t)args[0]->Uint32Value());
489 return scope.Close(Uint32::New(old));
493 static Handle<Value> GetUid(const Arguments& args) {
495 assert(args.Length() == 0);
497 return scope.Close(Integer::New(uid));
500 static Handle<Value> GetGid(const Arguments& args) {
502 assert(args.Length() == 0);
504 return scope.Close(Integer::New(gid));
508 static Handle<Value> SetGid(const Arguments& args) {
511 if (args.Length() < 1) {
512 return ThrowException(Exception::Error(
513 String::New("setgid requires 1 argument")));
516 Local<Integer> given_gid = args[0]->ToInteger();
517 int gid = given_gid->Int32Value();
519 if ((result = setgid(gid)) != 0) {
520 return ThrowException(Exception::Error(String::New(strerror(errno))));
525 static Handle<Value> SetUid(const Arguments& args) {
528 if (args.Length() < 1) {
529 return ThrowException(Exception::Error(
530 String::New("setuid requires 1 argument")));
533 Local<Integer> given_uid = args[0]->ToInteger();
534 int uid = given_uid->Int32Value();
536 if ((result = setuid(uid)) != 0) {
537 return ThrowException(Exception::Error(String::New(strerror(errno))));
543 NowGetter (Local<String> property, const AccessorInfo& info)
546 return scope.Close(Integer::New(ev_now(EV_DEFAULT_UC)));
550 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
554 exit(args[0]->IntegerValue());
559 #define HAVE_GETMEM 1
560 #include <unistd.h> /* getpagesize() */
562 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
563 #define PROCFS_FILE_OFFSET_BITS_HACK 1
564 #undef _FILE_OFFSET_BITS
566 #define PROCFS_FILE_OFFSET_BITS_HACK 0
571 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
572 #define _FILE_OFFSET_BITS 64
575 int getmem(size_t *rss, size_t *vsize) {
576 pid_t pid = getpid();
578 size_t page_size = getpagesize();
580 sprintf(pidpath, "/proc/%d/psinfo", pid);
583 FILE *f = fopen(pidpath, "r");
586 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
593 *vsize = (size_t) psinfo.pr_size * page_size;
594 *rss = (size_t) psinfo.pr_rssize * 1024;
604 #define HAVE_GETMEM 1
606 #include <sys/param.h>
607 #include <sys/sysctl.h>
608 #include <sys/user.h>
612 int getmem(size_t *rss, size_t *vsize) {
614 struct kinfo_proc *kinfo = NULL;
617 size_t page_size = getpagesize();
621 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
622 if (kd == NULL) goto error;
624 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
625 if (kinfo == NULL) goto error;
627 *rss = kinfo->ki_rssize * page_size;
628 *vsize = kinfo->ki_size;
635 if (kd) kvm_close(kd);
638 #endif // __FreeBSD__
642 #define HAVE_GETMEM 1
643 /* Researched by Tim Becker and Michael Knight
644 * http://blog.kuriositaet.de/?p=257
647 #include <mach/task.h>
648 #include <mach/mach_init.h>
650 int getmem(size_t *rss, size_t *vsize) {
651 struct task_basic_info t_info;
652 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
654 int r = task_info(mach_task_self(),
656 (task_info_t)&t_info,
659 if (r != KERN_SUCCESS) return -1;
661 *rss = t_info.resident_size;
662 *vsize = t_info.virtual_size;
669 # define HAVE_GETMEM 1
670 # include <sys/param.h> /* for MAXPATHLEN */
672 int getmem(size_t *rss, size_t *vsize) {
673 FILE *f = fopen("/proc/self/stat", "r");
678 char buffer[MAXPATHLEN];
679 size_t page_size = getpagesize();
682 if (fscanf(f, "%d ", &itmp) == 0) goto error;
684 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
686 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
688 if (fscanf (f, "%d ", &itmp) == 0) goto error;
690 if (fscanf (f, "%d ", &itmp) == 0) goto error;
692 if (fscanf (f, "%d ", &itmp) == 0) goto error;
694 if (fscanf (f, "%d ", &itmp) == 0) goto error;
695 /* TTY owner process group */
696 if (fscanf (f, "%d ", &itmp) == 0) goto error;
698 if (fscanf (f, "%u ", &itmp) == 0) goto error;
699 /* Minor faults (no memory page) */
700 if (fscanf (f, "%u ", &itmp) == 0) goto error;
701 /* Minor faults, children */
702 if (fscanf (f, "%u ", &itmp) == 0) goto error;
703 /* Major faults (memory page faults) */
704 if (fscanf (f, "%u ", &itmp) == 0) goto error;
705 /* Major faults, children */
706 if (fscanf (f, "%u ", &itmp) == 0) goto error;
708 if (fscanf (f, "%d ", &itmp) == 0) goto error;
710 if (fscanf (f, "%d ", &itmp) == 0) goto error;
711 /* utime, children */
712 if (fscanf (f, "%d ", &itmp) == 0) goto error;
713 /* stime, children */
714 if (fscanf (f, "%d ", &itmp) == 0) goto error;
715 /* jiffies remaining in current time slice */
716 if (fscanf (f, "%d ", &itmp) == 0) goto error;
718 if (fscanf (f, "%d ", &itmp) == 0) goto error;
719 /* jiffies until next timeout */
720 if (fscanf (f, "%u ", &itmp) == 0) goto error;
721 /* jiffies until next SIGALRM */
722 if (fscanf (f, "%u ", &itmp) == 0) goto error;
723 /* start time (jiffies since system boot) */
724 if (fscanf (f, "%d ", &itmp) == 0) goto error;
726 /* Virtual memory size */
727 if (fscanf (f, "%u ", &itmp) == 0) goto error;
728 *vsize = (size_t) itmp;
730 /* Resident set size */
731 if (fscanf (f, "%u ", &itmp) == 0) goto error;
732 *rss = (size_t) itmp * page_size;
735 if (fscanf (f, "%u ", &itmp) == 0) goto error;
737 if (fscanf (f, "%u ", &itmp) == 0) goto error;
739 if (fscanf (f, "%u ", &itmp) == 0) goto error;
741 if (fscanf (f, "%u ", &itmp) == 0) goto error;
753 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
755 assert(args.Length() == 0);
758 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
762 int r = getmem(&rss, &vsize);
765 return ThrowException(Exception::Error(String::New(strerror(errno))));
768 Local<Object> info = Object::New();
770 if (rss_symbol.IsEmpty()) {
771 rss_symbol = NODE_PSYMBOL("rss");
772 vsize_symbol = NODE_PSYMBOL("vsize");
773 heap_total_symbol = NODE_PSYMBOL("heapTotal");
774 heap_used_symbol = NODE_PSYMBOL("heapUsed");
777 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
778 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
781 HeapStatistics v8_heap_stats;
782 V8::GetHeapStatistics(&v8_heap_stats);
783 info->Set(heap_total_symbol,
784 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
785 info->Set(heap_used_symbol,
786 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
788 return scope.Close(info);
793 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
796 if (args.Length() < 1 || !args[0]->IsNumber()) {
797 return ThrowException(Exception::Error(String::New("Bad argument.")));
800 pid_t pid = args[0]->IntegerValue();
804 if (args.Length() >= 2) {
805 if (args[1]->IsNumber()) {
806 sig = args[1]->Int32Value();
807 } else if (args[1]->IsString()) {
808 Local<String> signame = args[1]->ToString();
810 Local<Value> sig_v = process->Get(signame);
811 if (!sig_v->IsNumber()) {
812 return ThrowException(Exception::Error(String::New("Unknown signal")));
814 sig = sig_v->Int32Value();
818 int r = kill(pid, sig);
821 return ThrowException(Exception::Error(String::New(strerror(errno))));
827 typedef void (*extInit)(Handle<Object> exports);
829 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
831 Handle<Value> DLOpen(const v8::Arguments& args) {
834 if (args.Length() < 2) return Undefined();
836 String::Utf8Value filename(args[0]->ToString()); // Cast
837 Local<Object> target = args[1]->ToObject(); // Cast
839 // Actually call dlopen().
840 // FIXME: This is a blocking function and should be called asynchronously!
841 // This function should be moved to file.cc and use libeio to make this
843 void *handle = dlopen(*filename, RTLD_LAZY);
846 if (handle == NULL) {
847 Local<Value> exception = Exception::Error(String::New(dlerror()));
848 return ThrowException(exception);
851 // Get the init() function from the dynamically shared object.
852 void *init_handle = dlsym(handle, "init");
853 // Error out if not found.
854 if (init_handle == NULL) {
855 Local<Value> exception =
856 Exception::Error(String::New("No 'init' symbol found in module."));
857 return ThrowException(exception);
859 extInit init = (extInit)(init_handle); // Cast
861 // Execute the C++ module
867 // evalcx(code, sandbox={})
868 // Executes code in a new context
869 Handle<Value> EvalCX(const Arguments& args) {
872 Local<String> code = args[0]->ToString();
873 Local<Object> sandbox = args.Length() > 1 ? args[1]->ToObject()
875 // Create the new context
876 Persistent<Context> context = Context::New();
878 // Enter and compile script
881 // Copy objects from global context, to our brand new context
882 Handle<Array> keys = sandbox->GetPropertyNames();
885 for (i = 0; i < keys->Length(); i++) {
886 Handle<String> key = keys->Get(Integer::New(i))->ToString();
887 Handle<Value> value = sandbox->Get(key);
888 context->Global()->Set(key, value);
894 Local<Script> script = Script::Compile(code, String::New("evalcx"));
895 Handle<Value> result;
897 if (script.IsEmpty()) {
898 result = ThrowException(try_catch.Exception());
900 result = script->Run();
901 if (result.IsEmpty()) {
902 result = ThrowException(try_catch.Exception());
904 // success! copy changes back onto the sandbox object.
905 keys = context->Global()->GetPropertyNames();
906 for (i = 0; i < keys->Length(); i++) {
907 Handle<String> key = keys->Get(Integer::New(i))->ToString();
908 Handle<Value> value = context->Global()->Get(key);
909 sandbox->Set(key, value);
914 // Clean up, clean up, everybody everywhere!
915 context->DetachGlobal();
919 return scope.Close(result);
922 Handle<Value> Compile(const Arguments& args) {
925 if (args.Length() < 2) {
926 return ThrowException(Exception::TypeError(
927 String::New("needs two arguments.")));
930 Local<String> source = args[0]->ToString();
931 Local<String> filename = args[1]->ToString();
935 Local<Script> script = Script::Compile(source, filename);
936 if (try_catch.HasCaught()) {
937 // Hack because I can't get a proper stacktrace on SyntaxError
938 ReportException(try_catch, true);
942 Local<Value> result = script->Run();
943 if (try_catch.HasCaught()) return try_catch.ReThrow();
945 return scope.Close(result);
948 static void OnFatalError(const char* location, const char* message) {
950 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
952 fprintf(stderr, "FATAL ERROR: %s\n", message);
957 static int uncaught_exception_counter = 0;
959 void FatalException(TryCatch &try_catch) {
962 // Check if uncaught_exception_counter indicates a recursion
963 if (uncaught_exception_counter > 0) {
964 ReportException(try_catch);
968 if (listeners_symbol.IsEmpty()) {
969 listeners_symbol = NODE_PSYMBOL("listeners");
970 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
971 emit_symbol = NODE_PSYMBOL("emit");
974 Local<Value> listeners_v = process->Get(listeners_symbol);
975 assert(listeners_v->IsFunction());
977 Local<Function> listeners = Local<Function>::Cast(listeners_v);
979 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
980 Local<Value> argv[1] = { uncaught_exception_symbol_l };
981 Local<Value> ret = listeners->Call(process, 1, argv);
983 assert(ret->IsArray());
985 Local<Array> listener_array = Local<Array>::Cast(ret);
987 uint32_t length = listener_array->Length();
988 // Report and exit if process has no "uncaughtException" listener
990 ReportException(try_catch);
994 // Otherwise fire the process "uncaughtException" event
995 Local<Value> emit_v = process->Get(emit_symbol);
996 assert(emit_v->IsFunction());
998 Local<Function> emit = Local<Function>::Cast(emit_v);
1000 Local<Value> error = try_catch.Exception();
1001 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
1003 uncaught_exception_counter++;
1004 emit->Call(process, 2, event_argv);
1005 // Decrement so we know if the next exception is a recursion or not
1006 uncaught_exception_counter--;
1010 static ev_async debug_watcher;
1011 volatile static bool debugger_msg_pending = false;
1013 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
1015 assert(watcher == &debug_watcher);
1016 assert(revents == EV_ASYNC);
1017 Debug::ProcessDebugMessages();
1020 static void DebugMessageDispatch(void) {
1021 // This function is called from V8's debug thread when a debug TCP client
1022 // has sent a message.
1024 // Send a signal to our main thread saying that it should enter V8 to
1025 // handle the message.
1026 debugger_msg_pending = true;
1027 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
1030 static Handle<Value> CheckBreak(const Arguments& args) {
1032 assert(args.Length() == 0);
1034 // TODO FIXME This function is a hack to wait until V8 is ready to accept
1035 // commands. There seems to be a bug in EnableAgent( _ , _ , true) which
1036 // makes it unusable here. Ideally we'd be able to bind EnableAgent and
1037 // get it to halt until Eclipse connects.
1039 if (!debug_wait_connect)
1042 printf("Waiting for remote debugger connection...\n");
1044 const int halfSecond = 50;
1045 const int tenMs=10000;
1046 debugger_msg_pending = false;
1048 if (debugger_msg_pending) {
1049 Debug::DebugBreak();
1050 Debug::ProcessDebugMessages();
1051 debugger_msg_pending = false;
1053 // wait for 500 msec of silence from remote debugger
1054 int cnt = halfSecond;
1056 debugger_msg_pending = false;
1058 if (debugger_msg_pending) {
1059 debugger_msg_pending = false;
1070 Persistent<Object> binding_cache;
1072 static Handle<Value> Binding(const Arguments& args) {
1075 Local<String> module = args[0]->ToString();
1076 String::Utf8Value module_v(module);
1078 if (binding_cache.IsEmpty()) {
1079 binding_cache = Persistent<Object>::New(Object::New());
1082 Local<Object> exports;
1084 // TODO DRY THIS UP!
1086 if (!strcmp(*module_v, "stdio")) {
1087 if (binding_cache->Has(module)) {
1088 exports = binding_cache->Get(module)->ToObject();
1090 exports = Object::New();
1091 Stdio::Initialize(exports);
1092 binding_cache->Set(module, exports);
1095 } else if (!strcmp(*module_v, "http")) {
1096 if (binding_cache->Has(module)) {
1097 exports = binding_cache->Get(module)->ToObject();
1099 // Warning: When calling requireBinding('http') from javascript then
1100 // be sure that you call requireBinding('tcp') before it.
1101 assert(binding_cache->Has(String::New("tcp")));
1102 exports = Object::New();
1103 HTTPServer::Initialize(exports);
1104 HTTPConnection::Initialize(exports);
1105 binding_cache->Set(module, exports);
1108 } else if (!strcmp(*module_v, "tcp")) {
1109 if (binding_cache->Has(module)) {
1110 exports = binding_cache->Get(module)->ToObject();
1112 exports = Object::New();
1113 Server::Initialize(exports);
1114 Connection::Initialize(exports);
1115 binding_cache->Set(module, exports);
1118 } else if (!strcmp(*module_v, "dns")) {
1119 if (binding_cache->Has(module)) {
1120 exports = binding_cache->Get(module)->ToObject();
1122 exports = Object::New();
1123 DNS::Initialize(exports);
1124 binding_cache->Set(module, exports);
1127 } else if (!strcmp(*module_v, "fs")) {
1128 if (binding_cache->Has(module)) {
1129 exports = binding_cache->Get(module)->ToObject();
1131 exports = Object::New();
1133 // Initialize the stats object
1134 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
1135 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
1136 exports->Set(String::NewSymbol("Stats"),
1137 stats_constructor_template->GetFunction());
1138 StatWatcher::Initialize(exports);
1139 File::Initialize(exports);
1140 binding_cache->Set(module, exports);
1143 } else if (!strcmp(*module_v, "signal_watcher")) {
1144 if (binding_cache->Has(module)) {
1145 exports = binding_cache->Get(module)->ToObject();
1147 exports = Object::New();
1148 SignalWatcher::Initialize(exports);
1149 binding_cache->Set(module, exports);
1152 } else if (!strcmp(*module_v, "net")) {
1153 if (binding_cache->Has(module)) {
1154 exports = binding_cache->Get(module)->ToObject();
1156 exports = Object::New();
1158 binding_cache->Set(module, exports);
1161 } else if (!strcmp(*module_v, "http_parser")) {
1162 if (binding_cache->Has(module)) {
1163 exports = binding_cache->Get(module)->ToObject();
1165 exports = Object::New();
1166 InitHttpParser(exports);
1167 binding_cache->Set(module, exports);
1170 } else if (!strcmp(*module_v, "child_process")) {
1171 if (binding_cache->Has(module)) {
1172 exports = binding_cache->Get(module)->ToObject();
1174 exports = Object::New();
1175 ChildProcess::Initialize(exports);
1176 binding_cache->Set(module, exports);
1179 } else if (!strcmp(*module_v, "natives")) {
1180 if (binding_cache->Has(module)) {
1181 exports = binding_cache->Get(module)->ToObject();
1183 exports = Object::New();
1184 // Explicitly define native sources.
1185 // TODO DRY/automate this?
1186 exports->Set(String::New("assert"), String::New(native_assert));
1187 exports->Set(String::New("child_process"),String::New(native_child_process));
1188 exports->Set(String::New("dns"), String::New(native_dns));
1189 exports->Set(String::New("events"), String::New(native_events));
1190 exports->Set(String::New("file"), String::New(native_file));
1191 exports->Set(String::New("fs"), String::New(native_fs));
1192 exports->Set(String::New("http"), String::New(native_http));
1193 exports->Set(String::New("http_old"), String::New(native_http_old));
1194 exports->Set(String::New("ini"), String::New(native_ini));
1195 exports->Set(String::New("mjsunit"), String::New(native_mjsunit));
1196 exports->Set(String::New("multipart"), String::New(native_multipart));
1197 exports->Set(String::New("net"), String::New(native_net));
1198 exports->Set(String::New("posix"), String::New(native_posix));
1199 exports->Set(String::New("querystring"), String::New(native_querystring));
1200 exports->Set(String::New("repl"), String::New(native_repl));
1201 exports->Set(String::New("sys"), String::New(native_sys));
1202 exports->Set(String::New("tcp"), String::New(native_tcp));
1203 exports->Set(String::New("uri"), String::New(native_uri));
1204 exports->Set(String::New("url"), String::New(native_url));
1205 exports->Set(String::New("utils"), String::New(native_utils));
1206 binding_cache->Set(module, exports);
1211 return ThrowException(Exception::Error(String::New("No such module")));
1214 return scope.Close(exports);
1218 static void Load(int argc, char *argv[]) {
1221 Local<FunctionTemplate> process_template = FunctionTemplate::New();
1222 node::EventEmitter::Initialize(process_template);
1224 process_template->InstanceTemplate()->SetAccessor(String::NewSymbol("now"), NowGetter, NULL);
1226 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
1228 // Add a reference to the global object
1229 Local<Object> global = Context::GetCurrent()->Global();
1230 process->Set(String::NewSymbol("global"), global);
1233 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
1234 // process.installPrefix
1235 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
1238 #define xstr(s) str(s)
1240 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
1244 Local<Array> arguments = Array::New(argc - option_end_index + 1);
1245 arguments->Set(Integer::New(0), String::New(argv[0]));
1246 for (j = 1, i = option_end_index + 1; i < argc; j++, i++) {
1247 Local<String> arg = String::New(argv[i]);
1248 arguments->Set(Integer::New(j), arg);
1251 process->Set(String::NewSymbol("ARGV"), arguments);
1252 process->Set(String::NewSymbol("argv"), arguments);
1254 // create process.env
1255 Local<Object> env = Object::New();
1256 for (i = 0; environ[i]; i++) {
1257 // skip entries without a '=' character
1258 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
1259 // create the v8 objects
1260 Local<String> field = String::New(environ[i], j);
1261 Local<String> value = Local<String>();
1262 if (environ[i][j] == '=') {
1263 value = String::New(environ[i]+j+1);
1266 env->Set(field, value);
1268 // assign process.ENV
1269 process->Set(String::NewSymbol("ENV"), env);
1270 process->Set(String::NewSymbol("env"), env);
1272 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
1274 // define various internal methods
1275 NODE_SET_METHOD(process, "loop", Loop);
1276 NODE_SET_METHOD(process, "unloop", Unloop);
1277 NODE_SET_METHOD(process, "evalcx", EvalCX);
1278 NODE_SET_METHOD(process, "compile", Compile);
1279 NODE_SET_METHOD(process, "_byteLength", ByteLength);
1280 NODE_SET_METHOD(process, "reallyExit", Exit);
1281 NODE_SET_METHOD(process, "chdir", Chdir);
1282 NODE_SET_METHOD(process, "cwd", Cwd);
1283 NODE_SET_METHOD(process, "getuid", GetUid);
1284 NODE_SET_METHOD(process, "setuid", SetUid);
1286 NODE_SET_METHOD(process, "setgid", SetGid);
1287 NODE_SET_METHOD(process, "getgid", GetGid);
1289 NODE_SET_METHOD(process, "umask", Umask);
1290 NODE_SET_METHOD(process, "dlopen", DLOpen);
1291 NODE_SET_METHOD(process, "kill", Kill);
1292 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
1293 NODE_SET_METHOD(process, "checkBreak", CheckBreak);
1295 NODE_SET_METHOD(process, "binding", Binding);
1297 // Assign the EventEmitter. It was created in main().
1298 process->Set(String::NewSymbol("EventEmitter"),
1299 EventEmitter::constructor_template->GetFunction());
1303 // Initialize the C++ modules..................filename of module
1304 Buffer::Initialize(process); // buffer.cc
1305 IOWatcher::Initialize(process); // io_watcher.cc
1306 IdleWatcher::Initialize(process); // idle_watcher.cc
1307 Timer::Initialize(process); // timer.cc
1308 DefineConstants(process); // constants.cc
1310 // Compile, execute the src/node.js file. (Which was included as static C
1311 // string in node_natives.h. 'natve_node' is the string containing that
1314 // The node.js file returns a function 'f'
1320 Local<Value> f_value = ExecuteString(String::New(native_node),
1321 String::New("node.js"));
1323 if (try_catch.HasCaught()) {
1324 ReportException(try_catch);
1328 assert(f_value->IsFunction());
1329 Local<Function> f = Local<Function>::Cast(f_value);
1331 // Now we call 'f' with the 'process' variable that we've built up with
1332 // all our bindings. Inside node.js we'll take care of assigning things to
1335 // We start the process this way in order to be more modular. Developers
1336 // who do not like how 'src/node.js' setups the module system but do like
1337 // Node's I/O bindings may want to replace 'f' with their own function.
1339 Local<Value> args[1] = { Local<Value>::New(process) };
1341 f->Call(global, 1, args);
1344 if (try_catch.HasCaught()) {
1345 ReportException(try_catch);
1351 static void PrintHelp();
1353 static void ParseDebugOpt(const char* arg) {
1356 use_debug_agent = true;
1357 if (!strcmp (arg, "--debug-brk")) {
1358 debug_wait_connect = true;
1360 } else if (!strcmp(arg, "--debug")) {
1362 } else if (strstr(arg, "--debug-brk=") == arg) {
1363 debug_wait_connect = true;
1364 p = 1 + strchr(arg, '=');
1365 debug_port = atoi(p);
1366 } else if (strstr(arg, "--debug=") == arg) {
1367 p = 1 + strchr(arg, '=');
1368 debug_port = atoi(p);
1370 if (p && debug_port > 1024 && debug_port < 65536)
1373 fprintf(stderr, "Bad debug option.\n");
1374 if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
1380 static void PrintHelp() {
1381 printf("Usage: node [options] script.js [arguments] \n"
1383 " -v, --version print node's version\n"
1384 " --debug[=port] enable remote debugging via given TCP port\n"
1385 " without stopping the execution\n"
1386 " --debug-brk[=port] as above, but break in script.js and\n"
1387 " wait for remote debugger to connect\n"
1388 " --v8-options print v8 command line options\n"
1389 " --vars print various compiled-in variables\n"
1391 "Enviromental variables:\n"
1392 "NODE_PATH ':'-separated list of directories\n"
1393 " prefixed to the module search path,\n"
1395 "NODE_DEBUG Print additional debugging output.\n"
1397 "Documentation can be found at http://nodejs.org/api.html"
1398 " or with 'man node'\n");
1401 // Parse node command line arguments.
1402 static void ParseArgs(int *argc, char **argv) {
1403 // TODO use parse opts
1404 for (int i = 1; i < *argc; i++) {
1405 const char *arg = argv[i];
1406 if (strstr(arg, "--debug") == arg) {
1408 argv[i] = const_cast<char*>("");
1409 option_end_index = i;
1410 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1411 printf("%s\n", NODE_VERSION);
1413 } else if (strcmp(arg, "--vars") == 0) {
1414 printf("NODE_PREFIX: %s\n", NODE_PREFIX);
1415 printf("NODE_CFLAGS: %s\n", NODE_CFLAGS);
1417 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1420 } else if (strcmp(arg, "--v8-options") == 0) {
1421 argv[i] = const_cast<char*>("--help");
1422 option_end_index = i+1;
1423 } else if (argv[i][0] != '-') {
1424 option_end_index = i-1;
1433 int main(int argc, char *argv[]) {
1434 // Parse a few arguments which are specific to Node.
1435 node::ParseArgs(&argc, argv);
1436 // Parse the rest of the args (up to the 'option_end_index' (where '--' was
1437 // in the command line))
1438 V8::SetFlagsFromCommandLine(&node::option_end_index, argv, false);
1440 // Error out if we don't have a script argument.
1442 fprintf(stderr, "No script was specified.\n");
1447 // Ignore the SIGPIPE
1448 evcom_ignore_sigpipe();
1450 // Initialize the default ev loop.
1452 // TODO(Ryan) I'm experiencing abnormally high load using Solaris's
1453 // EVBACKEND_PORT. Temporarally forcing select() until I debug.
1454 ev_default_loop(EVBACKEND_SELECT);
1456 ev_default_loop(EVFLAG_AUTO);
1460 ev_timer_init(&node::gc_timer, node::GCTimeout, GC_INTERVAL, GC_INTERVAL);
1461 // Set the gc_timer to max priority so that it runs before all other
1462 // watchers. In this way it can check if the 'tick' has other pending
1463 // watchers by using ev_pending_count() - if it ran with lower priority
1464 // then the other watchers might run before it - not giving us good idea
1465 // of loop idleness.
1466 ev_set_priority(&node::gc_timer, EV_MAXPRI);
1467 ev_timer_start(EV_DEFAULT_UC_ &node::gc_timer);
1468 ev_unref(EV_DEFAULT_UC);
1471 // Setup the EIO thread pool
1472 { // It requires 3, yes 3, watchers.
1473 ev_idle_init(&node::eio_poller, node::DoPoll);
1475 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1476 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1477 ev_unref(EV_DEFAULT_UC);
1479 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1480 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1481 ev_unref(EV_DEFAULT_UC);
1483 eio_init(node::EIOWantPoll, node::EIODonePoll);
1484 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1485 // race conditions. See test/mjsunit/test-eio-race.js
1486 eio_set_max_poll_reqs(10);
1490 HandleScope handle_scope;
1492 V8::SetFatalErrorHandler(node::OnFatalError);
1494 // If the --debug flag was specified then initialize the debug thread.
1495 if (node::use_debug_agent) {
1496 // Initialize the async watcher for receiving messages from the debug
1497 // thread and marshal it into the main thread. DebugMessageCallback()
1498 // is called from the main thread to execute a random bit of javascript
1499 // - which will give V8 control so it can handle whatever new message
1500 // had been received on the debug thread.
1501 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1502 ev_set_priority(&node::debug_watcher, EV_MAXPRI);
1503 // Set the callback DebugMessageDispatch which is called from the debug
1505 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1506 // Start the async watcher.
1507 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1508 // unref it so that we exit the event loop despite it being active.
1509 ev_unref(EV_DEFAULT_UC);
1511 // Start the debug thread and it's associated TCP server on port 5858.
1512 bool r = Debug::EnableAgent("node " NODE_VERSION, node::debug_port);
1514 // Crappy check that everything went well. FIXME
1516 // Print out some information.
1517 printf("debugger listening on port %d\n", node::debug_port);
1520 // Create the one and only Context.
1521 Persistent<Context> context = Context::New();
1522 Context::Scope context_scope(context);
1524 // Create all the objects, load modules, do everything.
1525 // so your next reading stop should be node::Load()!
1526 node::Load(argc, argv);
1528 node::Stdio::Flush();