1 // Copyright 2009 Ryan Dahl <ry@tinyclouds.org>
7 #include <limits.h> /* PATH_MAX */
11 #include <dlfcn.h> /* dlopen(), dlsym() */
12 #include <sys/types.h>
13 #include <unistd.h> /* setuid, getuid */
15 #include <node_events.h>
18 #include <node_file.h>
19 #include <node_idle_watcher.h>
20 #include <node_http.h>
21 #include <node_signal_handler.h>
22 #include <node_stat.h>
23 #include <node_timer.h>
24 #include <node_child_process.h>
25 #include <node_constants.h>
26 #include <node_stdio.h>
27 #include <node_natives.h>
28 #include <node_version.h>
34 extern char **environ;
38 static Persistent<Object> process;
40 static Persistent<String> dev_symbol;
41 static Persistent<String> ino_symbol;
42 static Persistent<String> mode_symbol;
43 static Persistent<String> nlink_symbol;
44 static Persistent<String> uid_symbol;
45 static Persistent<String> gid_symbol;
46 static Persistent<String> rdev_symbol;
47 static Persistent<String> size_symbol;
48 static Persistent<String> blksize_symbol;
49 static Persistent<String> blocks_symbol;
50 static Persistent<String> atime_symbol;
51 static Persistent<String> mtime_symbol;
52 static Persistent<String> ctime_symbol;
54 static Persistent<String> rss_symbol;
55 static Persistent<String> vsize_symbol;
56 static Persistent<String> heap_total_symbol;
57 static Persistent<String> heap_used_symbol;
59 static Persistent<String> listeners_symbol;
60 static Persistent<String> uncaught_exception_symbol;
61 static Persistent<String> emit_symbol;
63 static int dash_dash_index = 0;
64 static bool use_debug_agent = false;
67 static ev_async eio_want_poll_notifier;
68 static ev_async eio_done_poll_notifier;
69 static ev_idle eio_poller;
72 static void DoPoll(EV_P_ ev_idle *watcher, int revents) {
73 assert(watcher == &eio_poller);
74 assert(revents == EV_IDLE);
76 //printf("eio_poller\n");
78 if (eio_poll() != -1) {
79 //printf("eio_poller stop\n");
80 ev_idle_stop(EV_DEFAULT_UC_ watcher);
85 // Called from the main thread.
86 static void WantPollNotifier(EV_P_ ev_async *watcher, int revents) {
87 assert(watcher == &eio_want_poll_notifier);
88 assert(revents == EV_ASYNC);
90 //printf("want poll notifier\n");
92 if (eio_poll() == -1) {
93 //printf("eio_poller start\n");
94 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
99 static void DonePollNotifier(EV_P_ ev_async *watcher, int revents) {
100 assert(watcher == &eio_done_poll_notifier);
101 assert(revents == EV_ASYNC);
103 //printf("done poll notifier\n");
105 if (eio_poll() != -1) {
106 //printf("eio_poller stop\n");
107 ev_idle_stop(EV_DEFAULT_UC_ &eio_poller);
112 // EIOWantPoll() is called from the EIO thread pool each time an EIO
113 // request (that is, one of the node.fs.* functions) has completed.
114 static void EIOWantPoll(void) {
115 // Signal the main thread that eio_poll need to be processed.
116 ev_async_send(EV_DEFAULT_UC_ &eio_want_poll_notifier);
120 static void EIODonePoll(void) {
121 // Signal the main thread that we should stop calling eio_poll().
122 // from the idle watcher.
123 ev_async_send(EV_DEFAULT_UC_ &eio_done_poll_notifier);
127 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
130 if (!encoding_v->IsString()) return _default;
132 String::Utf8Value encoding(encoding_v->ToString());
134 if (strcasecmp(*encoding, "utf8") == 0) {
136 } else if (strcasecmp(*encoding, "utf-8") == 0) {
138 } else if (strcasecmp(*encoding, "ascii") == 0) {
140 } else if (strcasecmp(*encoding, "binary") == 0) {
142 } else if (strcasecmp(*encoding, "raw") == 0) {
143 fprintf(stderr, "'raw' (array of integers) has been removed. "
146 } else if (strcasecmp(*encoding, "raws") == 0) {
147 fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
148 "Please update your code.\n");
155 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
158 if (!len) return scope.Close(Null());
160 if (encoding == BINARY) {
161 const unsigned char *cbuf = static_cast<const unsigned char*>(buf);
162 uint16_t * twobytebuf = new uint16_t[len];
163 for (size_t i = 0; i < len; i++) {
164 // XXX is the following line platform independent?
165 twobytebuf[i] = cbuf[i];
167 Local<String> chunk = String::New(twobytebuf, len);
168 delete [] twobytebuf; // TODO use ExternalTwoByteString?
169 return scope.Close(chunk);
172 // utf8 or ascii encoding
173 Local<String> chunk = String::New((const char*)buf, len);
174 return scope.Close(chunk);
177 // Returns -1 if the handle was not valid for decoding
178 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
181 if (val->IsArray()) {
182 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
188 Local<String> str = val->ToString();
190 if (encoding == UTF8) return str->Utf8Length();
192 return str->Length();
196 # define MIN(a, b) ((a) < (b) ? (a) : (b))
199 // Returns number of bytes written.
200 ssize_t DecodeWrite(char *buf, size_t buflen,
201 v8::Handle<v8::Value> val,
202 enum encoding encoding) {
206 // A lot of improvement can be made here. See:
207 // http://code.google.com/p/v8/issues/detail?id=270
208 // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
209 // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611
211 if (val->IsArray()) {
212 fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
218 Local<String> str = val->ToString();
220 if (encoding == UTF8) {
221 str->WriteUtf8(buf, buflen);
225 if (encoding == ASCII) {
226 str->WriteAscii(buf, 0, buflen);
230 // THIS IS AWFUL!!! FIXME
232 assert(encoding == BINARY);
234 uint16_t * twobytebuf = new uint16_t[buflen];
236 str->Write(twobytebuf, 0, buflen);
238 for (size_t i = 0; i < buflen; i++) {
239 unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
244 delete [] twobytebuf;
249 static Persistent<FunctionTemplate> stats_constructor_template;
251 Local<Object> BuildStatsObject(struct stat * s) {
254 if (dev_symbol.IsEmpty()) {
255 dev_symbol = NODE_PSYMBOL("dev");
256 ino_symbol = NODE_PSYMBOL("ino");
257 mode_symbol = NODE_PSYMBOL("mode");
258 nlink_symbol = NODE_PSYMBOL("nlink");
259 uid_symbol = NODE_PSYMBOL("uid");
260 gid_symbol = NODE_PSYMBOL("gid");
261 rdev_symbol = NODE_PSYMBOL("rdev");
262 size_symbol = NODE_PSYMBOL("size");
263 blksize_symbol = NODE_PSYMBOL("blksize");
264 blocks_symbol = NODE_PSYMBOL("blocks");
265 atime_symbol = NODE_PSYMBOL("atime");
266 mtime_symbol = NODE_PSYMBOL("mtime");
267 ctime_symbol = NODE_PSYMBOL("ctime");
270 Local<Object> stats =
271 stats_constructor_template->GetFunction()->NewInstance();
273 /* ID of device containing file */
274 stats->Set(dev_symbol, Integer::New(s->st_dev));
277 stats->Set(ino_symbol, Integer::New(s->st_ino));
280 stats->Set(mode_symbol, Integer::New(s->st_mode));
282 /* number of hard links */
283 stats->Set(nlink_symbol, Integer::New(s->st_nlink));
285 /* user ID of owner */
286 stats->Set(uid_symbol, Integer::New(s->st_uid));
288 /* group ID of owner */
289 stats->Set(gid_symbol, Integer::New(s->st_gid));
291 /* device ID (if special file) */
292 stats->Set(rdev_symbol, Integer::New(s->st_rdev));
294 /* total size, in bytes */
295 stats->Set(size_symbol, Integer::New(s->st_size));
297 /* blocksize for filesystem I/O */
298 stats->Set(blksize_symbol, Integer::New(s->st_blksize));
300 /* number of blocks allocated */
301 stats->Set(blocks_symbol, Integer::New(s->st_blocks));
303 /* time of last access */
304 stats->Set(atime_symbol, NODE_UNIXTIME_V8(s->st_atime));
306 /* time of last modification */
307 stats->Set(mtime_symbol, NODE_UNIXTIME_V8(s->st_mtime));
309 /* time of last status change */
310 stats->Set(ctime_symbol, NODE_UNIXTIME_V8(s->st_ctime));
312 return scope.Close(stats);
316 // Extracts a C str from a V8 Utf8Value.
317 const char* ToCString(const v8::String::Utf8Value& value) {
318 return *value ? *value : "<str conversion failed>";
321 static void ReportException(TryCatch &try_catch, bool show_line = false) {
322 Handle<Message> message = try_catch.Message();
323 if (message.IsEmpty()) {
324 fprintf(stderr, "Error: (no message)\n");
329 Handle<Value> error = try_catch.Exception();
330 Handle<String> stack;
332 if (error->IsObject()) {
333 Handle<Object> obj = Handle<Object>::Cast(error);
334 Handle<Value> raw_stack = obj->Get(String::New("stack"));
335 if (raw_stack->IsString()) stack = Handle<String>::Cast(raw_stack);
339 // Print (filename):(line number): (message).
340 String::Utf8Value filename(message->GetScriptResourceName());
341 const char* filename_string = ToCString(filename);
342 int linenum = message->GetLineNumber();
343 fprintf(stderr, "%s:%i\n", filename_string, linenum);
344 // Print line of source code.
345 String::Utf8Value sourceline(message->GetSourceLine());
346 const char* sourceline_string = ToCString(sourceline);
347 fprintf(stderr, "%s\n", sourceline_string);
348 // Print wavy underline (GetUnderline is deprecated).
349 int start = message->GetStartColumn();
350 for (int i = 0; i < start; i++) {
351 fprintf(stderr, " ");
353 int end = message->GetEndColumn();
354 for (int i = start; i < end; i++) {
355 fprintf(stderr, "^");
357 fprintf(stderr, "\n");
360 if (stack.IsEmpty()) {
361 message->PrintCurrentStackTrace(stderr);
363 String::Utf8Value trace(stack);
364 fprintf(stderr, "%s\n", *trace);
369 // Executes a str within the current v8 context.
370 Local<Value> ExecuteString(Local<String> source, Local<Value> filename) {
374 Local<Script> script = Script::Compile(source, filename);
375 if (script.IsEmpty()) {
376 ReportException(try_catch);
380 Local<Value> result = script->Run();
381 if (result.IsEmpty()) {
382 ReportException(try_catch);
386 return scope.Close(result);
389 static Handle<Value> ByteLength(const Arguments& args) {
392 if (args.Length() < 1 || !args[0]->IsString()) {
393 return ThrowException(Exception::Error(String::New("Bad argument.")));
396 Local<Integer> length = Integer::New(DecodeBytes(args[0], ParseEncoding(args[1], UTF8)));
398 return scope.Close(length);
401 static Handle<Value> Loop(const Arguments& args) {
404 // TODO Probably don't need to start this each time.
405 // Avoids failing on test/mjsunit/test-eio-race3.js though
406 ev_idle_start(EV_DEFAULT_UC_ &eio_poller);
408 ev_loop(EV_DEFAULT_UC_ 0);
412 static Handle<Value> Unloop(const Arguments& args) {
414 int how = EVUNLOOP_ONE;
415 if (args[0]->IsString()) {
416 String::Utf8Value how_s(args[0]->ToString());
417 if (0 == strcmp(*how_s, "all")) {
421 ev_unloop(EV_DEFAULT_ how);
425 static Handle<Value> Chdir(const Arguments& args) {
428 if (args.Length() != 1 || !args[0]->IsString()) {
429 return ThrowException(Exception::Error(String::New("Bad argument.")));
432 String::Utf8Value path(args[0]->ToString());
434 int r = chdir(*path);
437 return ThrowException(Exception::Error(String::New(strerror(errno))));
443 static Handle<Value> Cwd(const Arguments& args) {
446 char output[PATH_MAX];
447 char *r = getcwd(output, PATH_MAX);
449 return ThrowException(Exception::Error(String::New(strerror(errno))));
451 Local<String> cwd = String::New(output);
453 return scope.Close(cwd);
456 static Handle<Value> Umask(const Arguments& args){
459 if(args.Length() < 1 || !args[0]->IsInt32()) {
460 return ThrowException(Exception::TypeError(
461 String::New("argument must be an integer.")));
463 unsigned int mask = args[0]->Uint32Value();
464 unsigned int old = umask((mode_t)mask);
466 return scope.Close(Uint32::New(old));
470 static Handle<Value> GetUid(const Arguments& args) {
473 return scope.Close(Integer::New(uid));
477 static Handle<Value> SetUid(const Arguments& args) {
480 if (args.Length() < 1) {
481 return ThrowException(Exception::Error(
482 String::New("setuid requires 1 argument")));
485 Local<Integer> given_uid = args[0]->ToInteger();
486 int uid = given_uid->Int32Value();
488 if ((result = setuid(uid)) != 0) {
489 return ThrowException(Exception::Error(String::New(strerror(errno))));
495 v8::Handle<v8::Value> Exit(const v8::Arguments& args) {
499 exit(args[0]->IntegerValue());
504 #define HAVE_GETMEM 1
505 #include <unistd.h> /* getpagesize() */
507 #if (!defined(_LP64)) && (_FILE_OFFSET_BITS - 0 == 64)
508 #define PROCFS_FILE_OFFSET_BITS_HACK 1
509 #undef _FILE_OFFSET_BITS
511 #define PROCFS_FILE_OFFSET_BITS_HACK 0
516 #if (PROCFS_FILE_OFFSET_BITS_HACK - 0 == 1)
517 #define _FILE_OFFSET_BITS 64
520 int getmem(size_t *rss, size_t *vsize) {
521 pid_t pid = getpid();
523 size_t page_size = getpagesize();
525 sprintf(pidpath, "/proc/%d/psinfo", pid);
528 FILE *f = fopen(pidpath, "r");
531 if (fread(&psinfo, sizeof(psinfo_t), 1, f) != 1) {
538 *vsize = (size_t) psinfo.pr_size * page_size;
539 *rss = (size_t) psinfo.pr_rssize * 1024;
549 #define HAVE_GETMEM 1
551 #include <sys/param.h>
552 #include <sys/sysctl.h>
553 #include <sys/user.h>
557 int getmem(size_t *rss, size_t *vsize) {
559 struct kinfo_proc *kinfo = NULL;
565 kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open");
566 if (kd == NULL) goto error;
568 kinfo = kvm_getprocs(kd, KERN_PROC_PID, pid, &nprocs);
569 if (kinfo == NULL) goto error;
571 *rss = kinfo->ki_rssize * PAGE_SIZE;
572 *vsize = kinfo->ki_size;
579 if (kd) kvm_close(kd);
582 #endif // __FreeBSD__
586 #define HAVE_GETMEM 1
587 /* Researched by Tim Becker and Michael Knight
588 * http://blog.kuriositaet.de/?p=257
591 #include <mach/task.h>
592 #include <mach/mach_init.h>
594 int getmem(size_t *rss, size_t *vsize) {
595 struct task_basic_info t_info;
596 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
598 int r = task_info(mach_task_self(),
600 (task_info_t)&t_info,
603 if (r != KERN_SUCCESS) return -1;
605 *rss = t_info.resident_size;
606 *vsize = t_info.virtual_size;
613 # define HAVE_GETMEM 1
614 # include <sys/param.h> /* for MAXPATHLEN */
616 int getmem(size_t *rss, size_t *vsize) {
617 FILE *f = fopen("/proc/self/stat", "r");
622 char buffer[MAXPATHLEN];
623 size_t page_size = getpagesize();
626 if (fscanf(f, "%d ", &itmp) == 0) goto error;
628 if (fscanf (f, "%s ", &buffer[0]) == 0) goto error;
630 if (fscanf (f, "%c ", &ctmp) == 0) goto error;
632 if (fscanf (f, "%d ", &itmp) == 0) goto error;
634 if (fscanf (f, "%d ", &itmp) == 0) goto error;
636 if (fscanf (f, "%d ", &itmp) == 0) goto error;
638 if (fscanf (f, "%d ", &itmp) == 0) goto error;
639 /* TTY owner process group */
640 if (fscanf (f, "%d ", &itmp) == 0) goto error;
642 if (fscanf (f, "%u ", &itmp) == 0) goto error;
643 /* Minor faults (no memory page) */
644 if (fscanf (f, "%u ", &itmp) == 0) goto error;
645 /* Minor faults, children */
646 if (fscanf (f, "%u ", &itmp) == 0) goto error;
647 /* Major faults (memory page faults) */
648 if (fscanf (f, "%u ", &itmp) == 0) goto error;
649 /* Major faults, children */
650 if (fscanf (f, "%u ", &itmp) == 0) goto error;
652 if (fscanf (f, "%d ", &itmp) == 0) goto error;
654 if (fscanf (f, "%d ", &itmp) == 0) goto error;
655 /* utime, children */
656 if (fscanf (f, "%d ", &itmp) == 0) goto error;
657 /* stime, children */
658 if (fscanf (f, "%d ", &itmp) == 0) goto error;
659 /* jiffies remaining in current time slice */
660 if (fscanf (f, "%d ", &itmp) == 0) goto error;
662 if (fscanf (f, "%d ", &itmp) == 0) goto error;
663 /* jiffies until next timeout */
664 if (fscanf (f, "%u ", &itmp) == 0) goto error;
665 /* jiffies until next SIGALRM */
666 if (fscanf (f, "%u ", &itmp) == 0) goto error;
667 /* start time (jiffies since system boot) */
668 if (fscanf (f, "%d ", &itmp) == 0) goto error;
670 /* Virtual memory size */
671 if (fscanf (f, "%u ", &itmp) == 0) goto error;
672 *vsize = (size_t) itmp;
674 /* Resident set size */
675 if (fscanf (f, "%u ", &itmp) == 0) goto error;
676 *rss = (size_t) itmp * page_size;
679 if (fscanf (f, "%u ", &itmp) == 0) goto error;
681 if (fscanf (f, "%u ", &itmp) == 0) goto error;
683 if (fscanf (f, "%u ", &itmp) == 0) goto error;
685 if (fscanf (f, "%u ", &itmp) == 0) goto error;
697 v8::Handle<v8::Value> MemoryUsage(const v8::Arguments& args) {
701 return ThrowException(Exception::Error(String::New("Not support on your platform. (Talk to Ryan.)")));
705 int r = getmem(&rss, &vsize);
708 return ThrowException(Exception::Error(String::New(strerror(errno))));
711 Local<Object> info = Object::New();
713 if (rss_symbol.IsEmpty()) {
714 rss_symbol = NODE_PSYMBOL("rss");
715 vsize_symbol = NODE_PSYMBOL("vsize");
716 heap_total_symbol = NODE_PSYMBOL("heapTotal");
717 heap_used_symbol = NODE_PSYMBOL("heapUsed");
720 info->Set(rss_symbol, Integer::NewFromUnsigned(rss));
721 info->Set(vsize_symbol, Integer::NewFromUnsigned(vsize));
724 HeapStatistics v8_heap_stats;
725 V8::GetHeapStatistics(&v8_heap_stats);
726 info->Set(heap_total_symbol,
727 Integer::NewFromUnsigned(v8_heap_stats.total_heap_size()));
728 info->Set(heap_used_symbol,
729 Integer::NewFromUnsigned(v8_heap_stats.used_heap_size()));
731 return scope.Close(info);
736 v8::Handle<v8::Value> Kill(const v8::Arguments& args) {
739 if (args.Length() < 1 || !args[0]->IsNumber()) {
740 return ThrowException(Exception::Error(String::New("Bad argument.")));
743 pid_t pid = args[0]->IntegerValue();
747 if (args.Length() >= 2) {
748 if (args[1]->IsNumber()) {
749 sig = args[1]->Int32Value();
750 } else if (args[1]->IsString()) {
751 Local<String> signame = args[1]->ToString();
753 Local<Value> sig_v = process->Get(signame);
754 if (!sig_v->IsNumber()) {
755 return ThrowException(Exception::Error(String::New("Unknown signal")));
757 sig = sig_v->Int32Value();
761 int r = kill(pid, sig);
764 return ThrowException(Exception::Error(String::New(strerror(errno))));
770 typedef void (*extInit)(Handle<Object> exports);
772 // DLOpen is node.dlopen(). Used to load 'module.node' dynamically shared
774 Handle<Value> DLOpen(const v8::Arguments& args) {
777 if (args.Length() < 2) return Undefined();
779 String::Utf8Value filename(args[0]->ToString()); // Cast
780 Local<Object> target = args[1]->ToObject(); // Cast
782 // Actually call dlopen().
783 // FIXME: This is a blocking function and should be called asynchronously!
784 // This function should be moved to file.cc and use libeio to make this
786 void *handle = dlopen(*filename, RTLD_LAZY);
789 if (handle == NULL) {
790 Local<Value> exception = Exception::Error(String::New(dlerror()));
791 return ThrowException(exception);
794 // Get the init() function from the dynamically shared object.
795 void *init_handle = dlsym(handle, "init");
796 // Error out if not found.
797 if (init_handle == NULL) {
798 Local<Value> exception =
799 Exception::Error(String::New("No 'init' symbol found in module."));
800 return ThrowException(exception);
802 extInit init = (extInit)(init_handle); // Cast
804 // Execute the C++ module
810 Handle<Value> Compile(const Arguments& args) {
813 if (args.Length() < 2) {
814 return ThrowException(Exception::TypeError(
815 String::New("needs two arguments.")));
818 Local<String> source = args[0]->ToString();
819 Local<String> filename = args[1]->ToString();
823 Local<Script> script = Script::Compile(source, filename);
824 if (try_catch.HasCaught()) {
825 // Hack because I can't get a proper stacktrace on SyntaxError
826 ReportException(try_catch, true);
830 Local<Value> result = script->Run();
831 if (try_catch.HasCaught()) return try_catch.ReThrow();
833 return scope.Close(result);
836 static void OnFatalError(const char* location, const char* message) {
838 fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
840 fprintf(stderr, "FATAL ERROR: %s\n", message);
845 static int uncaught_exception_counter = 0;
847 void FatalException(TryCatch &try_catch) {
850 // Check if uncaught_exception_counter indicates a recursion
851 if (uncaught_exception_counter > 0) {
852 ReportException(try_catch);
856 if (listeners_symbol.IsEmpty()) {
857 listeners_symbol = NODE_PSYMBOL("listeners");
858 uncaught_exception_symbol = NODE_PSYMBOL("uncaughtException");
859 emit_symbol = NODE_PSYMBOL("emit");
862 Local<Value> listeners_v = process->Get(listeners_symbol);
863 assert(listeners_v->IsFunction());
865 Local<Function> listeners = Local<Function>::Cast(listeners_v);
867 Local<String> uncaught_exception_symbol_l = Local<String>::New(uncaught_exception_symbol);
868 Local<Value> argv[1] = { uncaught_exception_symbol_l };
869 Local<Value> ret = listeners->Call(process, 1, argv);
871 assert(ret->IsArray());
873 Local<Array> listener_array = Local<Array>::Cast(ret);
875 uint32_t length = listener_array->Length();
876 // Report and exit if process has no "uncaughtException" listener
878 ReportException(try_catch);
882 // Otherwise fire the process "uncaughtException" event
883 Local<Value> emit_v = process->Get(emit_symbol);
884 assert(emit_v->IsFunction());
886 Local<Function> emit = Local<Function>::Cast(emit_v);
888 Local<Value> error = try_catch.Exception();
889 Local<Value> event_argv[2] = { uncaught_exception_symbol_l, error };
891 uncaught_exception_counter++;
892 emit->Call(process, 2, event_argv);
893 // Decrement so we know if the next exception is a recursion or not
894 uncaught_exception_counter--;
898 static ev_async debug_watcher;
900 static void DebugMessageCallback(EV_P_ ev_async *watcher, int revents) {
902 assert(watcher == &debug_watcher);
903 assert(revents == EV_ASYNC);
904 ExecuteString(String::New("1+1;"), String::New("debug_poll"));
907 static void DebugMessageDispatch(void) {
908 // This function is called from V8's debug thread when a debug TCP client
909 // has sent a message.
911 // Send a signal to our main thread saying that it should enter V8 to
912 // handle the message.
913 ev_async_send(EV_DEFAULT_UC_ &debug_watcher);
917 static void Load(int argc, char *argv[]) {
920 Local<FunctionTemplate> process_template = FunctionTemplate::New();
921 node::EventEmitter::Initialize(process_template);
923 process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
925 // Add a reference to the global object
926 Local<Object> global = Context::GetCurrent()->Global();
927 process->Set(String::NewSymbol("global"), global);
930 process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
931 // process.installPrefix
932 process->Set(String::NewSymbol("installPrefix"), String::New(NODE_PREFIX));
935 #define xstr(s) str(s)
937 process->Set(String::NewSymbol("platform"), String::New(xstr(PLATFORM)));
941 Local<Array> arguments = Array::New(argc - dash_dash_index + 1);
942 arguments->Set(Integer::New(0), String::New(argv[0]));
943 for (j = 1, i = dash_dash_index + 1; i < argc; j++, i++) {
944 Local<String> arg = String::New(argv[i]);
945 arguments->Set(Integer::New(j), arg);
948 process->Set(String::NewSymbol("ARGV"), arguments);
949 process->Set(String::NewSymbol("argv"), arguments);
951 // create process.env
952 Local<Object> env = Object::New();
953 for (i = 0; environ[i]; i++) {
954 // skip entries without a '=' character
955 for (j = 0; environ[i][j] && environ[i][j] != '='; j++) { ; }
956 // create the v8 objects
957 Local<String> field = String::New(environ[i], j);
958 Local<String> value = Local<String>();
959 if (environ[i][j] == '=') {
960 value = String::New(environ[i]+j+1);
963 env->Set(field, value);
965 // assign process.ENV
966 process->Set(String::NewSymbol("ENV"), env);
967 process->Set(String::NewSymbol("env"), env);
969 process->Set(String::NewSymbol("pid"), Integer::New(getpid()));
971 // define various internal methods
972 NODE_SET_METHOD(process, "loop", Loop);
973 NODE_SET_METHOD(process, "unloop", Unloop);
974 NODE_SET_METHOD(process, "compile", Compile);
975 NODE_SET_METHOD(process, "_byteLength", ByteLength);
976 NODE_SET_METHOD(process, "reallyExit", Exit);
977 NODE_SET_METHOD(process, "chdir", Chdir);
978 NODE_SET_METHOD(process, "cwd", Cwd);
979 NODE_SET_METHOD(process, "getuid", GetUid);
980 NODE_SET_METHOD(process, "setuid", SetUid);
981 NODE_SET_METHOD(process, "umask", Umask);
982 NODE_SET_METHOD(process, "dlopen", DLOpen);
983 NODE_SET_METHOD(process, "kill", Kill);
984 NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
986 // Assign the EventEmitter. It was created in main().
987 process->Set(String::NewSymbol("EventEmitter"),
988 EventEmitter::constructor_template->GetFunction());
990 // Initialize the stats object
991 Local<FunctionTemplate> stat_templ = FunctionTemplate::New();
992 stats_constructor_template = Persistent<FunctionTemplate>::New(stat_templ);
993 process->Set(String::NewSymbol("Stats"),
994 stats_constructor_template->GetFunction());
997 // Initialize the C++ modules..................filename of module
998 IdleWatcher::Initialize(process); // idle_watcher.cc
999 Stdio::Initialize(process); // stdio.cc
1000 Timer::Initialize(process); // timer.cc
1001 SignalHandler::Initialize(process); // signal_handler.cc
1002 Stat::Initialize(process); // stat.cc
1003 ChildProcess::Initialize(process); // child_process.cc
1004 DefineConstants(process); // constants.cc
1006 Local<Object> dns = Object::New();
1007 process->Set(String::NewSymbol("dns"), dns);
1008 DNS::Initialize(dns); // dns.cc
1009 Local<Object> fs = Object::New();
1010 process->Set(String::NewSymbol("fs"), fs);
1011 File::Initialize(fs); // file.cc
1012 // Create node.tcp. Note this separate from lib/tcp.js which is the public
1014 Local<Object> tcp = Object::New();
1015 process->Set(String::New("tcp"), tcp);
1016 Server::Initialize(tcp); // tcp.cc
1017 Connection::Initialize(tcp); // tcp.cc
1018 // Create node.http. Note this separate from lib/http.js which is the
1020 Local<Object> http = Object::New();
1021 process->Set(String::New("http"), http);
1022 HTTPServer::Initialize(http); // http.cc
1023 HTTPConnection::Initialize(http); // http.cc
1027 // Compile, execute the src/node.js file. (Which was included as static C
1028 // string in node_natives.h. 'natve_node' is the string containing that
1031 // The node.js file returns a function 'f'
1037 Local<Value> f_value = ExecuteString(String::New(native_node),
1038 String::New("node.js"));
1040 if (try_catch.HasCaught()) {
1041 ReportException(try_catch);
1045 assert(f_value->IsFunction());
1046 Local<Function> f = Local<Function>::Cast(f_value);
1048 // Now we call 'f' with the 'process' variable that we've built up with
1049 // all our bindings. Inside node.js we'll take care of assigning things to
1052 // We start the process this way in order to be more modular. Developers
1053 // who do not like how 'src/node.js' setups the module system but do like
1054 // Node's I/O bindings may want to replace 'f' with their own function.
1056 Local<Value> args[1] = { Local<Value>::New(process) };
1057 f->Call(global, 1, args);
1060 if (try_catch.HasCaught()) {
1061 ReportException(try_catch);
1067 static void PrintHelp() {
1068 printf("Usage: node [options] [--] script.js [arguments] \n"
1069 " -v, --version print node's version\n"
1070 " --debug enable remote debugging\n" // TODO specify port
1071 " --cflags print pre-processor and compiler flags\n"
1072 " --v8-options print v8 command line options\n\n"
1073 "Documentation can be found at http://nodejs.org/api.html"
1074 " or with 'man node'\n");
1077 // Parse node command line arguments.
1078 static void ParseArgs(int *argc, char **argv) {
1079 // TODO use parse opts
1080 for (int i = 1; i < *argc; i++) {
1081 const char *arg = argv[i];
1082 if (strcmp(arg, "--") == 0) {
1083 dash_dash_index = i;
1085 } else if (strcmp(arg, "--debug") == 0) {
1086 argv[i] = reinterpret_cast<const char*>("");
1087 use_debug_agent = true;
1088 dash_dash_index = i;
1089 } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
1090 printf("%s\n", NODE_VERSION);
1092 } else if (strcmp(arg, "--cflags") == 0) {
1093 printf("%s\n", NODE_CFLAGS);
1095 } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
1098 } else if (strcmp(arg, "--v8-options") == 0) {
1099 argv[i] = reinterpret_cast<const char*>("--help");
1100 dash_dash_index = i+1;
1108 int main(int argc, char *argv[]) {
1109 // Parse a few arguments which are specific to Node.
1110 node::ParseArgs(&argc, argv);
1111 // Parse the rest of the args (up to the 'dash_dash_index' (where '--' was
1112 // in the command line))
1113 V8::SetFlagsFromCommandLine(&node::dash_dash_index, argv, false);
1115 // Error out if we don't have a script argument.
1117 fprintf(stderr, "No script was specified.\n");
1122 // Ignore the SIGPIPE
1123 evcom_ignore_sigpipe();
1125 // Initialize the default ev loop.
1126 ev_default_loop(EVFLAG_AUTO);
1128 // Setup the EIO thread pool
1129 { // It requires 3, yes 3, watchers.
1130 ev_idle_init(&node::eio_poller, node::DoPoll);
1132 ev_async_init(&node::eio_want_poll_notifier, node::WantPollNotifier);
1133 ev_async_start(EV_DEFAULT_UC_ &node::eio_want_poll_notifier);
1134 ev_unref(EV_DEFAULT_UC);
1136 ev_async_init(&node::eio_done_poll_notifier, node::DonePollNotifier);
1137 ev_async_start(EV_DEFAULT_UC_ &node::eio_done_poll_notifier);
1138 ev_unref(EV_DEFAULT_UC);
1140 eio_init(node::EIOWantPoll, node::EIODonePoll);
1141 // Don't handle more than 10 reqs on each eio_poll(). This is to avoid
1142 // race conditions. See test/mjsunit/test-eio-race.js
1143 eio_set_max_poll_reqs(10);
1147 HandleScope handle_scope;
1149 V8::SetFatalErrorHandler(node::OnFatalError);
1151 #define AUTO_BREAK_FLAG "--debugger_auto_break"
1152 // If the --debug flag was specified then initialize the debug thread.
1153 if (node::use_debug_agent) {
1154 // First apply --debugger_auto_break setting to V8. This is so we can
1155 // enter V8 by just executing any bit of javascript
1156 V8::SetFlagsFromString(AUTO_BREAK_FLAG, sizeof(AUTO_BREAK_FLAG));
1157 // Initialize the async watcher for receiving messages from the debug
1158 // thread and marshal it into the main thread. DebugMessageCallback()
1159 // is called from the main thread to execute a random bit of javascript
1160 // - which will give V8 control so it can handle whatever new message
1161 // had been received on the debug thread.
1162 ev_async_init(&node::debug_watcher, node::DebugMessageCallback);
1163 // Set the callback DebugMessageDispatch which is called from the debug
1165 Debug::SetDebugMessageDispatchHandler(node::DebugMessageDispatch);
1166 // Start the async watcher.
1167 ev_async_start(EV_DEFAULT_UC_ &node::debug_watcher);
1168 // unref it so that we exit the event loop despite it being active.
1169 ev_unref(EV_DEFAULT_UC);
1171 // Start the debug thread and it's associated TCP server on port 5858.
1172 bool r = Debug::EnableAgent("node " NODE_VERSION, 5858);
1173 // Crappy check that everything went well. FIXME
1175 // Print out some information. REMOVEME
1176 printf("debugger listening on port 5858\n"
1177 "Use 'd8 --remote_debugger' to access it.\n");
1180 // Create the one and only Context.
1181 Persistent<Context> context = Context::New();
1182 Context::Scope context_scope(context);
1184 // Create all the objects, load modules, do everything.
1185 // so your next reading stop should be node::Load()!
1186 node::Load(argc, argv);
1188 node::Stdio::Flush();