node: add inTick and lastThrew to infoBox
[platform/upstream/nodejs.git] / src / node.cc
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 #include "node.h"
23 #include "req_wrap.h"
24 #include "handle_wrap.h"
25 #include "string_bytes.h"
26
27 #include "ares.h"
28 #include "uv.h"
29
30 #include "v8-debug.h"
31 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
32 # include "node_dtrace.h"
33 #endif
34 #if defined HAVE_PERFCTR
35 # include "node_counters.h"
36 #endif
37
38 #include <locale.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #if !defined(_MSC_VER)
44 #include <strings.h>
45 #else
46 #define strcasecmp _stricmp
47 #endif
48 #include <limits.h> /* PATH_MAX */
49 #include <assert.h>
50 #if !defined(_MSC_VER)
51 #include <unistd.h> /* setuid, getuid */
52 #else
53 #include <direct.h>
54 #include <process.h>
55 #define getpid _getpid
56 #include <io.h>
57 #define umask _umask
58 typedef int mode_t;
59 #endif
60 #include <errno.h>
61 #include <sys/types.h>
62 #include "zlib.h"
63
64 #if defined(__POSIX__) && !defined(__ANDROID__)
65 # include <pwd.h> /* getpwnam() */
66 # include <grp.h> /* getgrnam() */
67 #endif
68
69 #include "node_buffer.h"
70 #include "node_file.h"
71 #include "node_http_parser.h"
72 #include "node_constants.h"
73 #include "node_javascript.h"
74 #include "node_version.h"
75 #if HAVE_OPENSSL
76 # include "node_crypto.h"
77 #endif
78 #if HAVE_SYSTEMTAP
79 #include "node_provider.h"
80 #endif
81 #include "node_script.h"
82
83 # ifdef __APPLE__
84 # include <crt_externs.h>
85 # define environ (*_NSGetEnviron())
86 # elif !defined(_MSC_VER)
87 extern char **environ;
88 # endif
89
90 namespace node {
91
92 using v8::Array;
93 using v8::ArrayBuffer;
94 using v8::Boolean;
95 using v8::Context;
96 using v8::Exception;
97 using v8::Function;
98 using v8::FunctionCallbackInfo;
99 using v8::FunctionTemplate;
100 using v8::Handle;
101 using v8::HandleScope;
102 using v8::HeapStatistics;
103 using v8::Integer;
104 using v8::Isolate;
105 using v8::Local;
106 using v8::Locker;
107 using v8::Message;
108 using v8::Number;
109 using v8::Object;
110 using v8::ObjectTemplate;
111 using v8::Persistent;
112 using v8::PropertyCallbackInfo;
113 using v8::ResourceConstraints;
114 using v8::SetResourceConstraints;
115 using v8::String;
116 using v8::ThrowException;
117 using v8::TryCatch;
118 using v8::Uint32;
119 using v8::V8;
120 using v8::Value;
121 using v8::kExternalUnsignedIntArray;
122
123 QUEUE handle_wrap_queue = { &handle_wrap_queue, &handle_wrap_queue };
124 QUEUE req_wrap_queue = { &req_wrap_queue, &req_wrap_queue };
125
126 // declared in req_wrap.h
127 Cached<String> process_symbol;
128 Cached<String> domain_symbol;
129
130 // declared in node_internals.h
131 Persistent<Object> process_p;
132
133 static Persistent<Function> process_tickCallback;
134 static Persistent<Object> binding_cache;
135 static Persistent<Array> module_load_list;
136
137 static Cached<String> exports_symbol;
138
139 static Cached<String> errno_symbol;
140 static Cached<String> syscall_symbol;
141 static Cached<String> errpath_symbol;
142 static Cached<String> code_symbol;
143
144 static Cached<String> rss_symbol;
145 static Cached<String> heap_total_symbol;
146 static Cached<String> heap_used_symbol;
147
148 static Cached<String> fatal_exception_symbol;
149
150 static Cached<String> enter_symbol;
151 static Cached<String> exit_symbol;
152 static Cached<String> disposed_symbol;
153
154 // Essential for node_wrap.h
155 Persistent<FunctionTemplate> pipeConstructorTmpl;
156 Persistent<FunctionTemplate> tcpConstructorTmpl;
157 Persistent<FunctionTemplate> ttyConstructorTmpl;
158
159 static bool print_eval = false;
160 static bool force_repl = false;
161 static bool trace_deprecation = false;
162 static bool throw_deprecation = false;
163 static char *eval_string = NULL;
164 static int option_end_index = 0;
165 static bool use_debug_agent = false;
166 static bool debug_wait_connect = false;
167 static int debug_port=5858;
168 static int max_stack_size = 0;
169 bool using_domains = false;
170
171 // used by C++ modules as well
172 bool no_deprecation = false;
173
174 static uv_check_t check_immediate_watcher;
175 static uv_idle_t idle_immediate_dummy;
176 static bool need_immediate_cb;
177 static Cached<String> immediate_callback_sym;
178
179 // for quick ref to tickCallback values
180 static struct {
181   uint32_t length;
182   uint32_t index;
183   uint32_t in_tick;
184   uint32_t last_threw;
185 } tick_infobox;
186
187 #ifdef OPENSSL_NPN_NEGOTIATED
188 static bool use_npn = true;
189 #else
190 static bool use_npn = false;
191 #endif
192
193 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
194 static bool use_sni = true;
195 #else
196 static bool use_sni = false;
197 #endif
198
199 // process-relative uptime base, initialized at start-up
200 static double prog_start_time;
201
202 static volatile bool debugger_running = false;
203 static uv_async_t dispatch_debug_messages_async;
204 static uv_async_t emit_debug_enabled_async;
205
206 // Declared in node_internals.h
207 Isolate* node_isolate = NULL;
208
209
210 class ArrayBufferAllocator : public ArrayBuffer::Allocator {
211 public:
212   // Impose an upper limit to avoid out of memory errors that bring down
213   // the process.
214   static const size_t kMaxLength = 0x3fffffff;
215   static ArrayBufferAllocator the_singleton;
216   virtual ~ArrayBufferAllocator() {}
217   virtual void* Allocate(size_t length);
218   virtual void Free(void* data);
219 private:
220   ArrayBufferAllocator() {}
221   ArrayBufferAllocator(const ArrayBufferAllocator&);
222   void operator=(const ArrayBufferAllocator&);
223 };
224
225 ArrayBufferAllocator ArrayBufferAllocator::the_singleton;
226
227
228 void* ArrayBufferAllocator::Allocate(size_t length) {
229   if (length > kMaxLength) return NULL;
230   return new char[length];
231 }
232
233
234 void ArrayBufferAllocator::Free(void* data) {
235   delete[] static_cast<char*>(data);
236 }
237
238
239 static void CheckImmediate(uv_check_t* handle, int status) {
240   assert(handle == &check_immediate_watcher);
241   assert(status == 0);
242
243   HandleScope scope(node_isolate);
244
245   if (immediate_callback_sym.IsEmpty()) {
246     immediate_callback_sym = String::New("_immediateCallback");
247   }
248
249   MakeCallback(process_p, immediate_callback_sym, 0, NULL);
250 }
251
252
253 static void IdleImmediateDummy(uv_idle_t* handle, int status) {
254   // Do nothing. Only for maintaining event loop
255   assert(handle == &idle_immediate_dummy);
256   assert(status == 0);
257 }
258
259
260 static inline const char *errno_string(int errorno) {
261 #define ERRNO_CASE(e)  case e: return #e;
262   switch (errorno) {
263
264 #ifdef EACCES
265   ERRNO_CASE(EACCES);
266 #endif
267
268 #ifdef EADDRINUSE
269   ERRNO_CASE(EADDRINUSE);
270 #endif
271
272 #ifdef EADDRNOTAVAIL
273   ERRNO_CASE(EADDRNOTAVAIL);
274 #endif
275
276 #ifdef EAFNOSUPPORT
277   ERRNO_CASE(EAFNOSUPPORT);
278 #endif
279
280 #ifdef EAGAIN
281   ERRNO_CASE(EAGAIN);
282 #endif
283
284 #ifdef EWOULDBLOCK
285 # if EAGAIN != EWOULDBLOCK
286   ERRNO_CASE(EWOULDBLOCK);
287 # endif
288 #endif
289
290 #ifdef EALREADY
291   ERRNO_CASE(EALREADY);
292 #endif
293
294 #ifdef EBADF
295   ERRNO_CASE(EBADF);
296 #endif
297
298 #ifdef EBADMSG
299   ERRNO_CASE(EBADMSG);
300 #endif
301
302 #ifdef EBUSY
303   ERRNO_CASE(EBUSY);
304 #endif
305
306 #ifdef ECANCELED
307   ERRNO_CASE(ECANCELED);
308 #endif
309
310 #ifdef ECHILD
311   ERRNO_CASE(ECHILD);
312 #endif
313
314 #ifdef ECONNABORTED
315   ERRNO_CASE(ECONNABORTED);
316 #endif
317
318 #ifdef ECONNREFUSED
319   ERRNO_CASE(ECONNREFUSED);
320 #endif
321
322 #ifdef ECONNRESET
323   ERRNO_CASE(ECONNRESET);
324 #endif
325
326 #ifdef EDEADLK
327   ERRNO_CASE(EDEADLK);
328 #endif
329
330 #ifdef EDESTADDRREQ
331   ERRNO_CASE(EDESTADDRREQ);
332 #endif
333
334 #ifdef EDOM
335   ERRNO_CASE(EDOM);
336 #endif
337
338 #ifdef EDQUOT
339   ERRNO_CASE(EDQUOT);
340 #endif
341
342 #ifdef EEXIST
343   ERRNO_CASE(EEXIST);
344 #endif
345
346 #ifdef EFAULT
347   ERRNO_CASE(EFAULT);
348 #endif
349
350 #ifdef EFBIG
351   ERRNO_CASE(EFBIG);
352 #endif
353
354 #ifdef EHOSTUNREACH
355   ERRNO_CASE(EHOSTUNREACH);
356 #endif
357
358 #ifdef EIDRM
359   ERRNO_CASE(EIDRM);
360 #endif
361
362 #ifdef EILSEQ
363   ERRNO_CASE(EILSEQ);
364 #endif
365
366 #ifdef EINPROGRESS
367   ERRNO_CASE(EINPROGRESS);
368 #endif
369
370 #ifdef EINTR
371   ERRNO_CASE(EINTR);
372 #endif
373
374 #ifdef EINVAL
375   ERRNO_CASE(EINVAL);
376 #endif
377
378 #ifdef EIO
379   ERRNO_CASE(EIO);
380 #endif
381
382 #ifdef EISCONN
383   ERRNO_CASE(EISCONN);
384 #endif
385
386 #ifdef EISDIR
387   ERRNO_CASE(EISDIR);
388 #endif
389
390 #ifdef ELOOP
391   ERRNO_CASE(ELOOP);
392 #endif
393
394 #ifdef EMFILE
395   ERRNO_CASE(EMFILE);
396 #endif
397
398 #ifdef EMLINK
399   ERRNO_CASE(EMLINK);
400 #endif
401
402 #ifdef EMSGSIZE
403   ERRNO_CASE(EMSGSIZE);
404 #endif
405
406 #ifdef EMULTIHOP
407   ERRNO_CASE(EMULTIHOP);
408 #endif
409
410 #ifdef ENAMETOOLONG
411   ERRNO_CASE(ENAMETOOLONG);
412 #endif
413
414 #ifdef ENETDOWN
415   ERRNO_CASE(ENETDOWN);
416 #endif
417
418 #ifdef ENETRESET
419   ERRNO_CASE(ENETRESET);
420 #endif
421
422 #ifdef ENETUNREACH
423   ERRNO_CASE(ENETUNREACH);
424 #endif
425
426 #ifdef ENFILE
427   ERRNO_CASE(ENFILE);
428 #endif
429
430 #ifdef ENOBUFS
431   ERRNO_CASE(ENOBUFS);
432 #endif
433
434 #ifdef ENODATA
435   ERRNO_CASE(ENODATA);
436 #endif
437
438 #ifdef ENODEV
439   ERRNO_CASE(ENODEV);
440 #endif
441
442 #ifdef ENOENT
443   ERRNO_CASE(ENOENT);
444 #endif
445
446 #ifdef ENOEXEC
447   ERRNO_CASE(ENOEXEC);
448 #endif
449
450 #ifdef ENOLINK
451   ERRNO_CASE(ENOLINK);
452 #endif
453
454 #ifdef ENOLCK
455 # if ENOLINK != ENOLCK
456   ERRNO_CASE(ENOLCK);
457 # endif
458 #endif
459
460 #ifdef ENOMEM
461   ERRNO_CASE(ENOMEM);
462 #endif
463
464 #ifdef ENOMSG
465   ERRNO_CASE(ENOMSG);
466 #endif
467
468 #ifdef ENOPROTOOPT
469   ERRNO_CASE(ENOPROTOOPT);
470 #endif
471
472 #ifdef ENOSPC
473   ERRNO_CASE(ENOSPC);
474 #endif
475
476 #ifdef ENOSR
477   ERRNO_CASE(ENOSR);
478 #endif
479
480 #ifdef ENOSTR
481   ERRNO_CASE(ENOSTR);
482 #endif
483
484 #ifdef ENOSYS
485   ERRNO_CASE(ENOSYS);
486 #endif
487
488 #ifdef ENOTCONN
489   ERRNO_CASE(ENOTCONN);
490 #endif
491
492 #ifdef ENOTDIR
493   ERRNO_CASE(ENOTDIR);
494 #endif
495
496 #ifdef ENOTEMPTY
497   ERRNO_CASE(ENOTEMPTY);
498 #endif
499
500 #ifdef ENOTSOCK
501   ERRNO_CASE(ENOTSOCK);
502 #endif
503
504 #ifdef ENOTSUP
505   ERRNO_CASE(ENOTSUP);
506 #else
507 # ifdef EOPNOTSUPP
508   ERRNO_CASE(EOPNOTSUPP);
509 # endif
510 #endif
511
512 #ifdef ENOTTY
513   ERRNO_CASE(ENOTTY);
514 #endif
515
516 #ifdef ENXIO
517   ERRNO_CASE(ENXIO);
518 #endif
519
520
521 #ifdef EOVERFLOW
522   ERRNO_CASE(EOVERFLOW);
523 #endif
524
525 #ifdef EPERM
526   ERRNO_CASE(EPERM);
527 #endif
528
529 #ifdef EPIPE
530   ERRNO_CASE(EPIPE);
531 #endif
532
533 #ifdef EPROTO
534   ERRNO_CASE(EPROTO);
535 #endif
536
537 #ifdef EPROTONOSUPPORT
538   ERRNO_CASE(EPROTONOSUPPORT);
539 #endif
540
541 #ifdef EPROTOTYPE
542   ERRNO_CASE(EPROTOTYPE);
543 #endif
544
545 #ifdef ERANGE
546   ERRNO_CASE(ERANGE);
547 #endif
548
549 #ifdef EROFS
550   ERRNO_CASE(EROFS);
551 #endif
552
553 #ifdef ESPIPE
554   ERRNO_CASE(ESPIPE);
555 #endif
556
557 #ifdef ESRCH
558   ERRNO_CASE(ESRCH);
559 #endif
560
561 #ifdef ESTALE
562   ERRNO_CASE(ESTALE);
563 #endif
564
565 #ifdef ETIME
566   ERRNO_CASE(ETIME);
567 #endif
568
569 #ifdef ETIMEDOUT
570   ERRNO_CASE(ETIMEDOUT);
571 #endif
572
573 #ifdef ETXTBSY
574   ERRNO_CASE(ETXTBSY);
575 #endif
576
577 #ifdef EXDEV
578   ERRNO_CASE(EXDEV);
579 #endif
580
581   default: return "";
582   }
583 }
584
585 const char *signo_string(int signo) {
586 #define SIGNO_CASE(e)  case e: return #e;
587   switch (signo) {
588
589 #ifdef SIGHUP
590   SIGNO_CASE(SIGHUP);
591 #endif
592
593 #ifdef SIGINT
594   SIGNO_CASE(SIGINT);
595 #endif
596
597 #ifdef SIGQUIT
598   SIGNO_CASE(SIGQUIT);
599 #endif
600
601 #ifdef SIGILL
602   SIGNO_CASE(SIGILL);
603 #endif
604
605 #ifdef SIGTRAP
606   SIGNO_CASE(SIGTRAP);
607 #endif
608
609 #ifdef SIGABRT
610   SIGNO_CASE(SIGABRT);
611 #endif
612
613 #ifdef SIGIOT
614 # if SIGABRT != SIGIOT
615   SIGNO_CASE(SIGIOT);
616 # endif
617 #endif
618
619 #ifdef SIGBUS
620   SIGNO_CASE(SIGBUS);
621 #endif
622
623 #ifdef SIGFPE
624   SIGNO_CASE(SIGFPE);
625 #endif
626
627 #ifdef SIGKILL
628   SIGNO_CASE(SIGKILL);
629 #endif
630
631 #ifdef SIGUSR1
632   SIGNO_CASE(SIGUSR1);
633 #endif
634
635 #ifdef SIGSEGV
636   SIGNO_CASE(SIGSEGV);
637 #endif
638
639 #ifdef SIGUSR2
640   SIGNO_CASE(SIGUSR2);
641 #endif
642
643 #ifdef SIGPIPE
644   SIGNO_CASE(SIGPIPE);
645 #endif
646
647 #ifdef SIGALRM
648   SIGNO_CASE(SIGALRM);
649 #endif
650
651   SIGNO_CASE(SIGTERM);
652
653 #ifdef SIGCHLD
654   SIGNO_CASE(SIGCHLD);
655 #endif
656
657 #ifdef SIGSTKFLT
658   SIGNO_CASE(SIGSTKFLT);
659 #endif
660
661
662 #ifdef SIGCONT
663   SIGNO_CASE(SIGCONT);
664 #endif
665
666 #ifdef SIGSTOP
667   SIGNO_CASE(SIGSTOP);
668 #endif
669
670 #ifdef SIGTSTP
671   SIGNO_CASE(SIGTSTP);
672 #endif
673
674 #ifdef SIGBREAK
675   SIGNO_CASE(SIGBREAK);
676 #endif
677
678 #ifdef SIGTTIN
679   SIGNO_CASE(SIGTTIN);
680 #endif
681
682 #ifdef SIGTTOU
683   SIGNO_CASE(SIGTTOU);
684 #endif
685
686 #ifdef SIGURG
687   SIGNO_CASE(SIGURG);
688 #endif
689
690 #ifdef SIGXCPU
691   SIGNO_CASE(SIGXCPU);
692 #endif
693
694 #ifdef SIGXFSZ
695   SIGNO_CASE(SIGXFSZ);
696 #endif
697
698 #ifdef SIGVTALRM
699   SIGNO_CASE(SIGVTALRM);
700 #endif
701
702 #ifdef SIGPROF
703   SIGNO_CASE(SIGPROF);
704 #endif
705
706 #ifdef SIGWINCH
707   SIGNO_CASE(SIGWINCH);
708 #endif
709
710 #ifdef SIGIO
711   SIGNO_CASE(SIGIO);
712 #endif
713
714 #ifdef SIGPOLL
715 # if SIGPOLL != SIGIO
716   SIGNO_CASE(SIGPOLL);
717 # endif
718 #endif
719
720 #ifdef SIGLOST
721   SIGNO_CASE(SIGLOST);
722 #endif
723
724 #ifdef SIGPWR
725 # if SIGPWR != SIGLOST
726   SIGNO_CASE(SIGPWR);
727 # endif
728 #endif
729
730 #ifdef SIGSYS
731   SIGNO_CASE(SIGSYS);
732 #endif
733
734   default: return "";
735   }
736 }
737
738
739 Local<Value> ErrnoException(int errorno,
740                             const char *syscall,
741                             const char *msg,
742                             const char *path) {
743   Local<Value> e;
744   Local<String> estring = String::NewSymbol(errno_string(errorno));
745   if (msg == NULL || msg[0] == '\0') {
746     msg = strerror(errorno);
747   }
748   Local<String> message = String::NewSymbol(msg);
749
750   Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
751   Local<String> cons2 = String::Concat(cons1, message);
752
753   if (syscall_symbol.IsEmpty()) {
754     syscall_symbol = String::New("syscall");
755     errno_symbol = String::New("errno");
756     errpath_symbol = String::New("path");
757     code_symbol = String::New("code");
758   }
759
760   if (path) {
761     Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
762     Local<String> cons4 = String::Concat(cons3, String::New(path));
763     Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
764     e = Exception::Error(cons5);
765   } else {
766     e = Exception::Error(cons2);
767   }
768
769   Local<Object> obj = e->ToObject();
770
771   obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
772   obj->Set(code_symbol, estring);
773   if (path) obj->Set(errpath_symbol, String::New(path));
774   if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
775   return e;
776 }
777
778
779 // hack alert! copy of ErrnoException, tuned for uv errors
780 Local<Value> UVException(int errorno,
781                          const char *syscall,
782                          const char *msg,
783                          const char *path) {
784   if (syscall_symbol.IsEmpty()) {
785     syscall_symbol = String::New("syscall");
786     errno_symbol = String::New("errno");
787     errpath_symbol = String::New("path");
788     code_symbol = String::New("code");
789   }
790
791   if (!msg || !msg[0])
792     msg = uv_strerror(errorno);
793
794   Local<String> estring = String::NewSymbol(uv_err_name(errorno));
795   Local<String> message = String::NewSymbol(msg);
796   Local<String> cons1 = String::Concat(estring, String::NewSymbol(", "));
797   Local<String> cons2 = String::Concat(cons1, message);
798
799   Local<Value> e;
800
801   Local<String> path_str;
802
803   if (path) {
804 #ifdef _WIN32
805     if (strncmp(path, "\\\\?\\UNC\\", 8) == 0) {
806       path_str = String::Concat(String::New("\\\\"), String::New(path + 8));
807     } else if (strncmp(path, "\\\\?\\", 4) == 0) {
808       path_str = String::New(path + 4);
809     } else {
810       path_str = String::New(path);
811     }
812 #else
813     path_str = String::New(path);
814 #endif
815
816     Local<String> cons3 = String::Concat(cons2, String::NewSymbol(" '"));
817     Local<String> cons4 = String::Concat(cons3, path_str);
818     Local<String> cons5 = String::Concat(cons4, String::NewSymbol("'"));
819     e = Exception::Error(cons5);
820   } else {
821     e = Exception::Error(cons2);
822   }
823
824   Local<Object> obj = e->ToObject();
825
826   // TODO errno should probably go
827   obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
828   obj->Set(code_symbol, estring);
829   if (path) obj->Set(errpath_symbol, path_str);
830   if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
831   return e;
832 }
833
834
835 #ifdef _WIN32
836 // Does about the same as strerror(),
837 // but supports all windows error messages
838 static const char *winapi_strerror(const int errorno) {
839   char *errmsg = NULL;
840
841   FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
842       FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorno,
843       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errmsg, 0, NULL);
844
845   if (errmsg) {
846     // Remove trailing newlines
847     for (int i = strlen(errmsg) - 1;
848         i >= 0 && (errmsg[i] == '\n' || errmsg[i] == '\r'); i--) {
849       errmsg[i] = '\0';
850     }
851
852     return errmsg;
853   } else {
854     // FormatMessage failed
855     return "Unknown error";
856   }
857 }
858
859
860 Local<Value> WinapiErrnoException(int errorno,
861                                   const char* syscall,
862                                   const char* msg,
863                                   const char* path) {
864   Local<Value> e;
865   if (!msg || !msg[0]) {
866     msg = winapi_strerror(errorno);
867   }
868   Local<String> message = String::NewSymbol(msg);
869
870   if (syscall_symbol.IsEmpty()) {
871     syscall_symbol = String::New("syscall");
872     errno_symbol = String::New("errno");
873     errpath_symbol = String::New("path");
874     code_symbol = String::New("code");
875   }
876
877   if (path) {
878     Local<String> cons1 = String::Concat(message, String::NewSymbol(" '"));
879     Local<String> cons2 = String::Concat(cons1, String::New(path));
880     Local<String> cons3 = String::Concat(cons2, String::NewSymbol("'"));
881     e = Exception::Error(cons3);
882   } else {
883     e = Exception::Error(message);
884   }
885
886   Local<Object> obj = e->ToObject();
887
888   obj->Set(errno_symbol, Integer::New(errorno, node_isolate));
889   if (path) obj->Set(errpath_symbol, String::New(path));
890   if (syscall) obj->Set(syscall_symbol, String::NewSymbol(syscall));
891   return e;
892 }
893 #endif
894
895
896 void SetupDomainUse(const FunctionCallbackInfo<Value>& args) {
897   if (using_domains) return;
898   HandleScope scope(node_isolate);
899   using_domains = true;
900   Local<Object> process = PersistentToLocal(process_p);
901   Local<Value> tdc_v = process->Get(String::New("_tickDomainCallback"));
902   Local<Value> ndt_v = process->Get(String::New("_nextDomainTick"));
903   if (!tdc_v->IsFunction()) {
904     fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
905     abort();
906   }
907   if (!ndt_v->IsFunction()) {
908     fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
909     abort();
910   }
911   Local<Function> tdc = tdc_v.As<Function>();
912   Local<Function> ndt = ndt_v.As<Function>();
913   process->Set(String::New("_tickCallback"), tdc);
914   process->Set(String::New("nextTick"), ndt);
915   process_tickCallback.Reset(node_isolate, tdc);
916 }
917
918
919 Handle<Value>
920 MakeDomainCallback(const Handle<Object> object,
921                    const Handle<Function> callback,
922                    int argc,
923                    Handle<Value> argv[]) {
924   // TODO Hook for long stack traces to be made here.
925
926   // lazy load domain specific symbols
927   if (enter_symbol.IsEmpty()) {
928     enter_symbol = String::New("enter");
929     exit_symbol = String::New("exit");
930     disposed_symbol = String::New("_disposed");
931   }
932
933   Local<Value> domain_v = object->Get(domain_symbol);
934   Local<Object> domain;
935   Local<Function> enter;
936   Local<Function> exit;
937
938   TryCatch try_catch;
939   try_catch.SetVerbose(true);
940
941   bool has_domain = domain_v->IsObject();
942   if (has_domain) {
943     domain = domain_v->ToObject();
944     assert(!domain.IsEmpty());
945     if (domain->Get(disposed_symbol)->IsTrue()) {
946       // domain has been disposed of.
947       return Undefined(node_isolate);
948     }
949     enter = Local<Function>::Cast(domain->Get(enter_symbol));
950     assert(!enter.IsEmpty());
951     enter->Call(domain, 0, NULL);
952
953     if (try_catch.HasCaught()) {
954       return Undefined(node_isolate);
955     }
956   }
957
958   Local<Value> ret = callback->Call(object, argc, argv);
959
960   if (try_catch.HasCaught()) {
961     return Undefined(node_isolate);
962   }
963
964   if (has_domain) {
965     exit = Local<Function>::Cast(domain->Get(exit_symbol));
966     assert(!exit.IsEmpty());
967     exit->Call(domain, 0, NULL);
968
969     if (try_catch.HasCaught()) {
970       return Undefined(node_isolate);
971     }
972   }
973
974   if (tick_infobox.last_threw == 1) {
975     tick_infobox.last_threw = 0;
976     return ret;
977   }
978
979   if (tick_infobox.in_tick == 1) {
980     return ret;
981   }
982
983   if (tick_infobox.length == 0) {
984     tick_infobox.index = 0;
985     return ret;
986   }
987
988   // process nextTicks after call
989   Local<Object> process = PersistentToLocal(process_p);
990   Local<Function> fn = PersistentToLocal(process_tickCallback);
991   fn->Call(process, 0, NULL);
992
993   if (try_catch.HasCaught()) {
994     return Undefined(node_isolate);
995   }
996
997   return ret;
998 }
999
1000
1001 Handle<Value>
1002 MakeCallback(const Handle<Object> object,
1003              const Handle<Function> callback,
1004              int argc,
1005              Handle<Value> argv[]) {
1006   // TODO Hook for long stack traces to be made here.
1007   Local<Object> process = PersistentToLocal(process_p);
1008
1009   if (using_domains)
1010     return MakeDomainCallback(object, callback, argc, argv);
1011
1012   // lazy load no domain next tick callbacks
1013   if (process_tickCallback.IsEmpty()) {
1014     Local<Value> cb_v = process->Get(String::New("_tickCallback"));
1015     if (!cb_v->IsFunction()) {
1016       fprintf(stderr, "process._tickCallback assigned to non-function\n");
1017       abort();
1018     }
1019     process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1020   }
1021
1022   TryCatch try_catch;
1023   try_catch.SetVerbose(true);
1024
1025   Local<Value> ret = callback->Call(object, argc, argv);
1026
1027   if (try_catch.HasCaught()) {
1028     return Undefined(node_isolate);
1029   }
1030
1031   if (tick_infobox.in_tick == 1) {
1032     return ret;
1033   }
1034
1035   if (tick_infobox.length == 0) {
1036     tick_infobox.index = 0;
1037     return ret;
1038   }
1039
1040   // process nextTicks after call
1041   Local<Function> fn = PersistentToLocal(process_tickCallback);
1042   fn->Call(process, 0, NULL);
1043
1044   if (try_catch.HasCaught()) {
1045     return Undefined(node_isolate);
1046   }
1047
1048   return ret;
1049 }
1050
1051
1052 Handle<Value>
1053 MakeCallback(const Handle<Object> object,
1054              const Handle<String> symbol,
1055              int argc,
1056              Handle<Value> argv[]) {
1057   HandleScope scope(node_isolate);
1058
1059   Local<Function> callback = object->Get(symbol).As<Function>();
1060   assert(callback->IsFunction());
1061
1062   if (using_domains)
1063     return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1064   return scope.Close(MakeCallback(object, callback, argc, argv));
1065 }
1066
1067
1068 Handle<Value>
1069 MakeCallback(const Handle<Object> object,
1070              const char* method,
1071              int argc,
1072              Handle<Value> argv[]) {
1073   HandleScope scope(node_isolate);
1074
1075   Handle<Value> ret =
1076     MakeCallback(object, String::NewSymbol(method), argc, argv);
1077
1078   return scope.Close(ret);
1079 }
1080
1081
1082 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1083   HandleScope scope(node_isolate);
1084
1085   if (!encoding_v->IsString()) return _default;
1086
1087   String::Utf8Value encoding(encoding_v);
1088
1089   if (strcasecmp(*encoding, "utf8") == 0) {
1090     return UTF8;
1091   } else if (strcasecmp(*encoding, "utf-8") == 0) {
1092     return UTF8;
1093   } else if (strcasecmp(*encoding, "ascii") == 0) {
1094     return ASCII;
1095   } else if (strcasecmp(*encoding, "base64") == 0) {
1096     return BASE64;
1097   } else if (strcasecmp(*encoding, "ucs2") == 0) {
1098     return UCS2;
1099   } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1100     return UCS2;
1101   } else if (strcasecmp(*encoding, "utf16le") == 0) {
1102     return UCS2;
1103   } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1104     return UCS2;
1105   } else if (strcasecmp(*encoding, "binary") == 0) {
1106     return BINARY;
1107   } else if (strcasecmp(*encoding, "buffer") == 0) {
1108     return BUFFER;
1109   } else if (strcasecmp(*encoding, "hex") == 0) {
1110     return HEX;
1111   } else if (strcasecmp(*encoding, "raw") == 0) {
1112     if (!no_deprecation) {
1113       fprintf(stderr, "'raw' (array of integers) has been removed. "
1114                       "Use 'binary'.\n");
1115     }
1116     return BINARY;
1117   } else if (strcasecmp(*encoding, "raws") == 0) {
1118     if (!no_deprecation) {
1119       fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1120                       "Please update your code.\n");
1121     }
1122     return BINARY;
1123   } else {
1124     return _default;
1125   }
1126 }
1127
1128 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1129   return StringBytes::Encode(static_cast<const char*>(buf),
1130                              len,
1131                              encoding);
1132 }
1133
1134 // Returns -1 if the handle was not valid for decoding
1135 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1136   HandleScope scope(node_isolate);
1137
1138   if (val->IsArray()) {
1139     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1140                     "Use 'binary'.\n");
1141     assert(0);
1142     return -1;
1143   }
1144
1145   return StringBytes::Size(val, encoding);
1146 }
1147
1148 #ifndef MIN
1149 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1150 #endif
1151
1152 // Returns number of bytes written.
1153 ssize_t DecodeWrite(char *buf,
1154                     size_t buflen,
1155                     v8::Handle<v8::Value> val,
1156                     enum encoding encoding) {
1157   return StringBytes::Write(buf, buflen, val, encoding, NULL);
1158 }
1159
1160 void DisplayExceptionLine(Handle<Message> message) {
1161   // Prevent re-entry into this function.  For example, if there is
1162   // a throw from a program in vm.runInThisContext(code, filename, true),
1163   // then we want to show the original failure, not the secondary one.
1164   static bool displayed_error = false;
1165
1166   if (displayed_error) return;
1167   displayed_error = true;
1168
1169   uv_tty_reset_mode();
1170
1171   fprintf(stderr, "\n");
1172
1173   if (!message.IsEmpty()) {
1174     // Print (filename):(line number): (message).
1175     String::Utf8Value filename(message->GetScriptResourceName());
1176     const char* filename_string = *filename;
1177     int linenum = message->GetLineNumber();
1178     fprintf(stderr, "%s:%i\n", filename_string, linenum);
1179     // Print line of source code.
1180     String::Utf8Value sourceline(message->GetSourceLine());
1181     const char* sourceline_string = *sourceline;
1182
1183     // Because of how node modules work, all scripts are wrapped with a
1184     // "function (module, exports, __filename, ...) {"
1185     // to provide script local variables.
1186     //
1187     // When reporting errors on the first line of a script, this wrapper
1188     // function is leaked to the user. There used to be a hack here to
1189     // truncate off the first 62 characters, but it caused numerous other
1190     // problems when vm.runIn*Context() methods were used for non-module
1191     // code.
1192     //
1193     // If we ever decide to re-instate such a hack, the following steps
1194     // must be taken:
1195     //
1196     // 1. Pass a flag around to say "this code was wrapped"
1197     // 2. Update the stack frame output so that it is also correct.
1198     //
1199     // It would probably be simpler to add a line rather than add some
1200     // number of characters to the first line, since V8 truncates the
1201     // sourceline to 78 characters, and we end up not providing very much
1202     // useful debugging info to the user if we remove 62 characters.
1203
1204     int start = message->GetStartColumn();
1205     int end = message->GetEndColumn();
1206
1207     // fprintf(stderr, "---\nsourceline:%s\noffset:%d\nstart:%d\nend:%d\n---\n", sourceline_string, start, end);
1208
1209     fprintf(stderr, "%s\n", sourceline_string);
1210     // Print wavy underline (GetUnderline is deprecated).
1211     for (int i = 0; i < start; i++) {
1212       fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1213     }
1214     for (int i = start; i < end; i++) {
1215       fputc('^', stderr);
1216     }
1217     fputc('\n', stderr);
1218   }
1219 }
1220
1221
1222 static void ReportException(Handle<Value> er, Handle<Message> message) {
1223   HandleScope scope(node_isolate);
1224
1225   DisplayExceptionLine(message);
1226
1227   Local<Value> trace_value(er->ToObject()->Get(String::New("stack")));
1228   String::Utf8Value trace(trace_value);
1229
1230   // range errors have a trace member set to undefined
1231   if (trace.length() > 0 && !trace_value->IsUndefined()) {
1232     fprintf(stderr, "%s\n", *trace);
1233   } else {
1234     // this really only happens for RangeErrors, since they're the only
1235     // kind that won't have all this info in the trace, or when non-Error
1236     // objects are thrown manually.
1237     bool isErrorObject = er->IsObject() &&
1238       !(er->ToObject()->Get(String::New("message"))->IsUndefined()) &&
1239       !(er->ToObject()->Get(String::New("name"))->IsUndefined());
1240
1241     if (isErrorObject) {
1242       String::Utf8Value name(er->ToObject()->Get(String::New("name")));
1243       fprintf(stderr, "%s: ", *name);
1244     }
1245
1246     String::Utf8Value msg(!isErrorObject ? er
1247                          : er->ToObject()->Get(String::New("message")));
1248     fprintf(stderr, "%s\n", *msg);
1249   }
1250
1251   fflush(stderr);
1252 }
1253
1254
1255 static void ReportException(TryCatch& try_catch) {
1256   ReportException(try_catch.Exception(), try_catch.Message());
1257 }
1258
1259
1260 // Executes a str within the current v8 context.
1261 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1262   HandleScope scope(node_isolate);
1263   TryCatch try_catch;
1264
1265   // try_catch must be nonverbose to disable FatalException() handler,
1266   // we will handle exceptions ourself.
1267   try_catch.SetVerbose(false);
1268
1269   Local<v8::Script> script = v8::Script::Compile(source, filename);
1270   if (script.IsEmpty()) {
1271     ReportException(try_catch);
1272     exit(3);
1273   }
1274
1275   Local<Value> result = script->Run();
1276   if (result.IsEmpty()) {
1277     ReportException(try_catch);
1278     exit(4);
1279   }
1280
1281   return scope.Close(result);
1282 }
1283
1284
1285 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1286   HandleScope scope(node_isolate);
1287
1288   Local<Array> ary = Array::New();
1289   QUEUE* q = NULL;
1290   int i = 0;
1291
1292   QUEUE_FOREACH(q, &req_wrap_queue) {
1293     ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1294     if (w->persistent().IsEmpty()) continue;
1295     ary->Set(i++, w->object());
1296   }
1297
1298   args.GetReturnValue().Set(ary);
1299 }
1300
1301
1302 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1303 // implemented here for consistency with GetActiveRequests().
1304 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1305   HandleScope scope(node_isolate);
1306
1307   Local<Array> ary = Array::New();
1308   QUEUE* q = NULL;
1309   int i = 0;
1310
1311   Local<String> owner_sym = String::New("owner");
1312
1313   QUEUE_FOREACH(q, &handle_wrap_queue) {
1314     HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1315     if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1316     Local<Object> object = w->object();
1317     Local<Value> owner = object->Get(owner_sym);
1318     if (owner->IsUndefined()) owner = object;
1319     ary->Set(i++, owner);
1320   }
1321
1322   args.GetReturnValue().Set(ary);
1323 }
1324
1325
1326 static void Abort(const FunctionCallbackInfo<Value>& args) {
1327   abort();
1328 }
1329
1330
1331 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1332   HandleScope scope(node_isolate);
1333
1334   if (args.Length() != 1 || !args[0]->IsString()) {
1335     return ThrowError("Bad argument.");  // FIXME(bnoordhuis) ThrowTypeError?
1336   }
1337
1338   String::Utf8Value path(args[0]);
1339   int err = uv_chdir(*path);
1340   if (err) {
1341     return ThrowUVException(err, "uv_chdir");
1342   }
1343 }
1344
1345
1346 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1347   HandleScope scope(node_isolate);
1348 #ifdef _WIN32
1349   /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1350   char buf[MAX_PATH * 4 + 1];
1351 #else
1352   char buf[PATH_MAX + 1];
1353 #endif
1354
1355   int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1356   if (err) {
1357     return ThrowUVException(err, "uv_cwd");
1358   }
1359
1360   buf[ARRAY_SIZE(buf) - 1] = '\0';
1361   Local<String> cwd = String::New(buf);
1362
1363   args.GetReturnValue().Set(cwd);
1364 }
1365
1366
1367 static void Umask(const FunctionCallbackInfo<Value>& args) {
1368   HandleScope scope(node_isolate);
1369   uint32_t old;
1370
1371   if (args.Length() < 1 || args[0]->IsUndefined()) {
1372     old = umask(0);
1373     umask(static_cast<mode_t>(old));
1374
1375   } else if(!args[0]->IsInt32() && !args[0]->IsString()) {
1376     return ThrowTypeError("argument must be an integer or octal string.");
1377
1378   } else {
1379     int oct;
1380     if(args[0]->IsInt32()) {
1381       oct = args[0]->Uint32Value();
1382     } else {
1383       oct = 0;
1384       String::Utf8Value str(args[0]);
1385
1386       // Parse the octal string.
1387       for (int i = 0; i < str.length(); i++) {
1388         char c = (*str)[i];
1389         if (c > '7' || c < '0') {
1390           return ThrowTypeError("invalid octal string");
1391         }
1392         oct *= 8;
1393         oct += c - '0';
1394       }
1395     }
1396     old = umask(static_cast<mode_t>(oct));
1397   }
1398
1399   args.GetReturnValue().Set(old);
1400 }
1401
1402
1403 #if defined(__POSIX__) && !defined(__ANDROID__)
1404
1405 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1406 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1407
1408
1409 static uid_t uid_by_name(const char* name) {
1410   struct passwd pwd;
1411   struct passwd* pp;
1412   char buf[8192];
1413
1414   errno = 0;
1415   pp = NULL;
1416
1417   if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1418     return pp->pw_uid;
1419   }
1420
1421   return uid_not_found;
1422 }
1423
1424
1425 static char* name_by_uid(uid_t uid) {
1426   struct passwd pwd;
1427   struct passwd* pp;
1428   char buf[8192];
1429   int rc;
1430
1431   errno = 0;
1432   pp = NULL;
1433
1434   if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1435     return strdup(pp->pw_name);
1436   }
1437
1438   if (rc == 0) {
1439     errno = ENOENT;
1440   }
1441
1442   return NULL;
1443 }
1444
1445
1446 static gid_t gid_by_name(const char* name) {
1447   struct group pwd;
1448   struct group* pp;
1449   char buf[8192];
1450
1451   errno = 0;
1452   pp = NULL;
1453
1454   if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1455     return pp->gr_gid;
1456   }
1457
1458   return gid_not_found;
1459 }
1460
1461
1462 #if 0  // For future use.
1463 static const char* name_by_gid(gid_t gid) {
1464   struct group pwd;
1465   struct group* pp;
1466   char buf[8192];
1467   int rc;
1468
1469   errno = 0;
1470   pp = NULL;
1471
1472   if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1473     return strdup(pp->gr_name);
1474   }
1475
1476   if (rc == 0) {
1477     errno = ENOENT;
1478   }
1479
1480   return NULL;
1481 }
1482 #endif
1483
1484
1485 static uid_t uid_by_name(Handle<Value> value) {
1486   if (value->IsUint32()) {
1487     return static_cast<uid_t>(value->Uint32Value());
1488   } else {
1489     String::Utf8Value name(value);
1490     return uid_by_name(*name);
1491   }
1492 }
1493
1494
1495 static gid_t gid_by_name(Handle<Value> value) {
1496   if (value->IsUint32()) {
1497     return static_cast<gid_t>(value->Uint32Value());
1498   } else {
1499     String::Utf8Value name(value);
1500     return gid_by_name(*name);
1501   }
1502 }
1503
1504
1505 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1506   args.GetReturnValue().Set(getuid());
1507 }
1508
1509
1510 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1511   args.GetReturnValue().Set(getgid());
1512 }
1513
1514
1515 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1516   HandleScope scope(node_isolate);
1517
1518   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1519     return ThrowTypeError("setgid argument must be a number or a string");
1520   }
1521
1522   gid_t gid = gid_by_name(args[0]);
1523
1524   if (gid == gid_not_found) {
1525     return ThrowError("setgid group id does not exist");
1526   }
1527
1528   if (setgid(gid)) {
1529     return ThrowErrnoException(errno, "setgid");
1530   }
1531 }
1532
1533
1534 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1535   HandleScope scope(node_isolate);
1536
1537   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1538     return ThrowTypeError("setuid argument must be a number or a string");
1539   }
1540
1541   uid_t uid = uid_by_name(args[0]);
1542
1543   if (uid == uid_not_found) {
1544     return ThrowError("setuid user id does not exist");
1545   }
1546
1547   if (setuid(uid)) {
1548     return ThrowErrnoException(errno, "setuid");
1549   }
1550 }
1551
1552
1553 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1554   HandleScope scope(node_isolate);
1555
1556   int ngroups = getgroups(0, NULL);
1557
1558   if (ngroups == -1) {
1559     return ThrowErrnoException(errno, "getgroups");
1560   }
1561
1562   gid_t* groups = new gid_t[ngroups];
1563
1564   ngroups = getgroups(ngroups, groups);
1565
1566   if (ngroups == -1) {
1567     delete[] groups;
1568     return ThrowErrnoException(errno, "getgroups");
1569   }
1570
1571   Local<Array> groups_list = Array::New(ngroups);
1572   bool seen_egid = false;
1573   gid_t egid = getegid();
1574
1575   for (int i = 0; i < ngroups; i++) {
1576     groups_list->Set(i, Integer::New(groups[i], node_isolate));
1577     if (groups[i] == egid) seen_egid = true;
1578   }
1579
1580   delete[] groups;
1581
1582   if (seen_egid == false) {
1583     groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1584   }
1585
1586   args.GetReturnValue().Set(groups_list);
1587 }
1588
1589
1590 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1591   HandleScope scope(node_isolate);
1592
1593   if (!args[0]->IsArray()) {
1594     return ThrowTypeError("argument 1 must be an array");
1595   }
1596
1597   Local<Array> groups_list = args[0].As<Array>();
1598   size_t size = groups_list->Length();
1599   gid_t* groups = new gid_t[size];
1600
1601   for (size_t i = 0; i < size; i++) {
1602     gid_t gid = gid_by_name(groups_list->Get(i));
1603
1604     if (gid == gid_not_found) {
1605       delete[] groups;
1606       return ThrowError("group name not found");
1607     }
1608
1609     groups[i] = gid;
1610   }
1611
1612   int rc = setgroups(size, groups);
1613   delete[] groups;
1614
1615   if (rc == -1) {
1616     return ThrowErrnoException(errno, "setgroups");
1617   }
1618 }
1619
1620
1621 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1622   HandleScope scope(node_isolate);
1623
1624   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1625     return ThrowTypeError("argument 1 must be a number or a string");
1626   }
1627
1628   if (!args[1]->IsUint32() && !args[1]->IsString()) {
1629     return ThrowTypeError("argument 2 must be a number or a string");
1630   }
1631
1632   String::Utf8Value arg0(args[0]);
1633   gid_t extra_group;
1634   bool must_free;
1635   char* user;
1636
1637   if (args[0]->IsUint32()) {
1638     user = name_by_uid(args[0]->Uint32Value());
1639     must_free = true;
1640   } else {
1641     user = *arg0;
1642     must_free = false;
1643   }
1644
1645   if (user == NULL) {
1646     return ThrowError("initgroups user not found");
1647   }
1648
1649   extra_group = gid_by_name(args[1]);
1650
1651   if (extra_group == gid_not_found) {
1652     if (must_free) free(user);
1653     return ThrowError("initgroups extra group not found");
1654   }
1655
1656   int rc = initgroups(user, extra_group);
1657
1658   if (must_free) {
1659     free(user);
1660   }
1661
1662   if (rc) {
1663     return ThrowErrnoException(errno, "initgroups");
1664   }
1665 }
1666
1667 #endif // __POSIX__ && !defined(__ANDROID__)
1668
1669
1670 void Exit(const FunctionCallbackInfo<Value>& args) {
1671   HandleScope scope(node_isolate);
1672   exit(args[0]->IntegerValue());
1673 }
1674
1675
1676 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1677   HandleScope scope(node_isolate);
1678   double uptime;
1679   if (uv_uptime(&uptime)) return;
1680   args.GetReturnValue().Set(uptime - prog_start_time);
1681 }
1682
1683
1684 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1685   HandleScope scope(node_isolate);
1686
1687   size_t rss;
1688
1689   int err = uv_resident_set_memory(&rss);
1690   if (err) {
1691     return ThrowUVException(err, "uv_resident_set_memory");
1692   }
1693
1694   Local<Object> info = Object::New();
1695
1696   if (rss_symbol.IsEmpty()) {
1697     rss_symbol = String::New("rss");
1698     heap_total_symbol = String::New("heapTotal");
1699     heap_used_symbol = String::New("heapUsed");
1700   }
1701
1702   info->Set(rss_symbol, Number::New(rss));
1703
1704   // V8 memory usage
1705   HeapStatistics v8_heap_stats;
1706   node_isolate->GetHeapStatistics(&v8_heap_stats);
1707   info->Set(heap_total_symbol,
1708             Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1709                                      node_isolate));
1710   info->Set(heap_used_symbol,
1711             Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1712                                      node_isolate));
1713
1714   args.GetReturnValue().Set(info);
1715 }
1716
1717
1718 void Kill(const FunctionCallbackInfo<Value>& args) {
1719   HandleScope scope(node_isolate);
1720
1721   if (args.Length() != 2) {
1722     return ThrowError("Bad argument.");
1723   }
1724
1725   int pid = args[0]->IntegerValue();
1726   int sig = args[1]->Int32Value();
1727   int err = uv_kill(pid, sig);
1728   args.GetReturnValue().Set(err);
1729 }
1730
1731 // used in Hrtime() below
1732 #define NANOS_PER_SEC 1000000000
1733
1734 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1735 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1736 // so this function instead returns an Array with 2 entries representing seconds
1737 // and nanoseconds, to avoid any integer overflow possibility.
1738 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1739 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1740   HandleScope scope(node_isolate);
1741
1742   uint64_t t = uv_hrtime();
1743
1744   if (args.Length() > 0) {
1745     // return a time diff tuple
1746     if (!args[0]->IsArray()) {
1747       return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1748     }
1749     Local<Array> inArray = Local<Array>::Cast(args[0]);
1750     uint64_t seconds = inArray->Get(0)->Uint32Value();
1751     uint64_t nanos = inArray->Get(1)->Uint32Value();
1752     t -= (seconds * NANOS_PER_SEC) + nanos;
1753   }
1754
1755   Local<Array> tuple = Array::New(2);
1756   tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1757   tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1758   args.GetReturnValue().Set(tuple);
1759 }
1760
1761
1762 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1763
1764 // DLOpen is process.dlopen(module, filename).
1765 // Used to load 'module.node' dynamically shared objects.
1766 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1767   HandleScope scope(node_isolate);
1768   char symbol[1024], *base, *pos;
1769   uv_lib_t lib;
1770   int r;
1771
1772   if (args.Length() < 2) {
1773     return ThrowError("process.dlopen takes exactly 2 arguments.");
1774   }
1775
1776   Local<Object> module = args[0]->ToObject(); // Cast
1777   String::Utf8Value filename(args[1]); // Cast
1778
1779   if (exports_symbol.IsEmpty()) {
1780     exports_symbol = String::New("exports");
1781   }
1782   Local<Object> exports = module->Get(exports_symbol)->ToObject();
1783
1784   if (uv_dlopen(*filename, &lib)) {
1785     Local<String> errmsg = String::New(uv_dlerror(&lib));
1786 #ifdef _WIN32
1787     // Windows needs to add the filename into the error message
1788     errmsg = String::Concat(errmsg, args[1]->ToString());
1789 #endif
1790     ThrowException(Exception::Error(errmsg));
1791     return;
1792   }
1793
1794   String::Utf8Value path(args[1]);
1795   base = *path;
1796
1797   /* Find the shared library filename within the full path. */
1798 #ifdef __POSIX__
1799   pos = strrchr(base, '/');
1800   if (pos != NULL) {
1801     base = pos + 1;
1802   }
1803 #else // Windows
1804   for (;;) {
1805     pos = strpbrk(base, "\\/:");
1806     if (pos == NULL) {
1807       break;
1808     }
1809     base = pos + 1;
1810   }
1811 #endif
1812
1813   /* Strip the .node extension. */
1814   pos = strrchr(base, '.');
1815   if (pos != NULL) {
1816     *pos = '\0';
1817   }
1818
1819   /* Add the `_module` suffix to the extension name. */
1820   r = snprintf(symbol, sizeof symbol, "%s_module", base);
1821   if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1822     return ThrowError("Out of memory.");
1823   }
1824
1825   /* Replace dashes with underscores. When loading foo-bar.node,
1826    * look for foo_bar_module, not foo-bar_module.
1827    */
1828   for (pos = symbol; *pos != '\0'; ++pos) {
1829     if (*pos == '-') *pos = '_';
1830   }
1831
1832   node_module_struct *mod;
1833   if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1834     char errmsg[1024];
1835     snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1836     return ThrowError(errmsg);
1837   }
1838
1839   if (mod->version != NODE_MODULE_VERSION) {
1840     char errmsg[1024];
1841     snprintf(errmsg,
1842              sizeof(errmsg),
1843              "Module version mismatch. Expected %d, got %d.",
1844              NODE_MODULE_VERSION, mod->version);
1845     return ThrowError(errmsg);
1846   }
1847
1848   // Execute the C++ module
1849   mod->register_func(exports, module);
1850
1851   // Tell coverity that 'handle' should not be freed when we return.
1852   // coverity[leaked_storage]
1853 }
1854
1855
1856 static void OnFatalError(const char* location, const char* message) {
1857   if (location) {
1858     fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1859   } else {
1860     fprintf(stderr, "FATAL ERROR: %s\n", message);
1861   }
1862   fflush(stderr);
1863 #if defined(DEBUG)
1864   abort();
1865 #endif
1866   exit(5);
1867 }
1868
1869
1870 NO_RETURN void FatalError(const char* location, const char* message) {
1871   OnFatalError(location, message);
1872   // to supress compiler warning
1873   abort();
1874 }
1875
1876
1877 void FatalException(Handle<Value> error, Handle<Message> message) {
1878   HandleScope scope(node_isolate);
1879
1880   if (fatal_exception_symbol.IsEmpty())
1881     fatal_exception_symbol = String::New("_fatalException");
1882
1883   Local<Object> process = PersistentToLocal(process_p);
1884   Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1885
1886   if (!fatal_v->IsFunction()) {
1887     // failed before the process._fatalException function was added!
1888     // this is probably pretty bad.  Nothing to do but report and exit.
1889     ReportException(error, message);
1890     exit(6);
1891   }
1892
1893   Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1894
1895   TryCatch fatal_try_catch;
1896
1897   // Do not call FatalException when _fatalException handler throws
1898   fatal_try_catch.SetVerbose(false);
1899
1900   // this will return true if the JS layer handled it, false otherwise
1901   Local<Value> caught = fatal_f->Call(process, 1, &error);
1902
1903   if (fatal_try_catch.HasCaught()) {
1904     // the fatal exception function threw, so we must exit
1905     ReportException(fatal_try_catch);
1906     exit(7);
1907   }
1908
1909   if (false == caught->BooleanValue()) {
1910     ReportException(error, message);
1911     exit(8);
1912   }
1913 }
1914
1915
1916 void FatalException(TryCatch& try_catch) {
1917   HandleScope scope(node_isolate);
1918   // TODO do not call FatalException if try_catch is verbose
1919   // (requires V8 API to expose getter for try_catch.is_verbose_)
1920   FatalException(try_catch.Exception(), try_catch.Message());
1921 }
1922
1923
1924 void OnMessage(Handle<Message> message, Handle<Value> error) {
1925   // The current version of V8 sends messages for errors only
1926   // (thus `error` is always set).
1927   FatalException(error, message);
1928 }
1929
1930
1931 static void Binding(const FunctionCallbackInfo<Value>& args) {
1932   HandleScope scope(node_isolate);
1933
1934   Local<String> module = args[0]->ToString();
1935   String::Utf8Value module_v(module);
1936   node_module_struct* modp;
1937
1938   Local<Object> cache = PersistentToLocal(binding_cache);
1939   Local<Object> exports;
1940
1941   if (cache->Has(module)) {
1942     exports = cache->Get(module)->ToObject();
1943     args.GetReturnValue().Set(exports);
1944     return;
1945   }
1946
1947   // Append a string to process.moduleLoadList
1948   char buf[1024];
1949   snprintf(buf, 1024, "Binding %s", *module_v);
1950
1951   Local<Array> modules = PersistentToLocal(module_load_list);
1952   uint32_t l = modules->Length();
1953   modules->Set(l, String::New(buf));
1954
1955   if ((modp = get_builtin_module(*module_v)) != NULL) {
1956     exports = Object::New();
1957     // Internal bindings don't have a "module" object,
1958     // only exports.
1959     modp->register_func(exports, Undefined(node_isolate));
1960     cache->Set(module, exports);
1961
1962   } else if (!strcmp(*module_v, "constants")) {
1963     exports = Object::New();
1964     DefineConstants(exports);
1965     cache->Set(module, exports);
1966
1967   } else if (!strcmp(*module_v, "natives")) {
1968     exports = Object::New();
1969     DefineJavaScript(exports);
1970     cache->Set(module, exports);
1971
1972   } else {
1973
1974     return ThrowError("No such module");
1975   }
1976
1977   args.GetReturnValue().Set(exports);
1978 }
1979
1980
1981 static void ProcessTitleGetter(Local<String> property,
1982                                const PropertyCallbackInfo<Value>& info) {
1983   HandleScope scope(node_isolate);
1984   char buffer[512];
1985   uv_get_process_title(buffer, sizeof(buffer));
1986   info.GetReturnValue().Set(String::New(buffer));
1987 }
1988
1989
1990 static void ProcessTitleSetter(Local<String> property,
1991                                Local<Value> value,
1992                                const PropertyCallbackInfo<void>& info) {
1993   HandleScope scope(node_isolate);
1994   String::Utf8Value title(value);
1995   // TODO: protect with a lock
1996   uv_set_process_title(*title);
1997 }
1998
1999
2000 static void EnvGetter(Local<String> property,
2001                       const PropertyCallbackInfo<Value>& info) {
2002   HandleScope scope(node_isolate);
2003 #ifdef __POSIX__
2004   String::Utf8Value key(property);
2005   const char* val = getenv(*key);
2006   if (val) {
2007     return info.GetReturnValue().Set(String::New(val));
2008   }
2009 #else  // _WIN32
2010   String::Value key(property);
2011   WCHAR buffer[32767]; // The maximum size allowed for environment variables.
2012   DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2013                                          buffer,
2014                                          ARRAY_SIZE(buffer));
2015   // If result >= sizeof buffer the buffer was too small. That should never
2016   // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2017   // not found.
2018   if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2019       result < ARRAY_SIZE(buffer)) {
2020     return info.GetReturnValue().Set(
2021         String::New(reinterpret_cast<uint16_t*>(buffer), result));
2022   }
2023 #endif
2024   // Not found.  Fetch from prototype.
2025   info.GetReturnValue().Set(
2026       info.Data().As<Object>()->Get(property));
2027 }
2028
2029
2030 static void EnvSetter(Local<String> property,
2031                       Local<Value> value,
2032                       const PropertyCallbackInfo<Value>& info) {
2033   HandleScope scope(node_isolate);
2034 #ifdef __POSIX__
2035   String::Utf8Value key(property);
2036   String::Utf8Value val(value);
2037   setenv(*key, *val, 1);
2038 #else  // _WIN32
2039   String::Value key(property);
2040   String::Value val(value);
2041   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2042   // Environment variables that start with '=' are read-only.
2043   if (key_ptr[0] != L'=') {
2044     SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2045   }
2046 #endif
2047   // Whether it worked or not, always return rval.
2048   info.GetReturnValue().Set(value);
2049 }
2050
2051
2052 static void EnvQuery(Local<String> property,
2053                      const PropertyCallbackInfo<Integer>& info) {
2054   HandleScope scope(node_isolate);
2055   int32_t rc = -1;  // Not found unless proven otherwise.
2056 #ifdef __POSIX__
2057   String::Utf8Value key(property);
2058   if (getenv(*key)) rc = 0;
2059 #else  // _WIN32
2060   String::Value key(property);
2061   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2062   if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2063       GetLastError() == ERROR_SUCCESS) {
2064     rc = 0;
2065     if (key_ptr[0] == L'=') {
2066       // Environment variables that start with '=' are hidden and read-only.
2067       rc = static_cast<int32_t>(v8::ReadOnly) |
2068            static_cast<int32_t>(v8::DontDelete) |
2069            static_cast<int32_t>(v8::DontEnum);
2070     }
2071   }
2072 #endif
2073   if (rc != -1) info.GetReturnValue().Set(rc);
2074 }
2075
2076
2077 static void EnvDeleter(Local<String> property,
2078                        const PropertyCallbackInfo<Boolean>& info) {
2079   HandleScope scope(node_isolate);
2080   bool rc = true;
2081 #ifdef __POSIX__
2082   String::Utf8Value key(property);
2083   rc = getenv(*key) != NULL;
2084   if (rc) unsetenv(*key);
2085 #else
2086   String::Value key(property);
2087   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2088   if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2089     // Deletion failed. Return true if the key wasn't there in the first place,
2090     // false if it is still there.
2091     rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2092          GetLastError() != ERROR_SUCCESS;
2093   }
2094 #endif
2095   info.GetReturnValue().Set(rc);
2096 }
2097
2098
2099 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2100   HandleScope scope(node_isolate);
2101 #ifdef __POSIX__
2102   int size = 0;
2103   while (environ[size]) size++;
2104
2105   Local<Array> env = Array::New(size);
2106
2107   for (int i = 0; i < size; ++i) {
2108     const char* var = environ[i];
2109     const char* s = strchr(var, '=');
2110     const int length = s ? s - var : strlen(var);
2111     env->Set(i, String::New(var, length));
2112   }
2113 #else  // _WIN32
2114   WCHAR* environment = GetEnvironmentStringsW();
2115   if (environment == NULL) return;  // This should not happen.
2116   Local<Array> env = Array::New();
2117   WCHAR* p = environment;
2118   int i = 0;
2119   while (*p != NULL) {
2120     WCHAR *s;
2121     if (*p == L'=') {
2122       // If the key starts with '=' it is a hidden environment variable.
2123       p += wcslen(p) + 1;
2124       continue;
2125     } else {
2126       s = wcschr(p, L'=');
2127     }
2128     if (!s) {
2129       s = p + wcslen(p);
2130     }
2131     env->Set(i++, String::New(reinterpret_cast<uint16_t*>(p), s - p));
2132     p = s + wcslen(s) + 1;
2133   }
2134   FreeEnvironmentStringsW(environment);
2135 #endif
2136
2137   info.GetReturnValue().Set(env);
2138 }
2139
2140
2141 static Handle<Object> GetFeatures() {
2142   HandleScope scope(node_isolate);
2143
2144   Local<Object> obj = Object::New();
2145   obj->Set(String::NewSymbol("debug"),
2146 #if defined(DEBUG) && DEBUG
2147     True(node_isolate)
2148 #else
2149     False(node_isolate)
2150 #endif
2151   );
2152
2153   obj->Set(String::NewSymbol("uv"), True(node_isolate));
2154   obj->Set(String::NewSymbol("ipv6"), True(node_isolate)); // TODO ping libuv
2155   obj->Set(String::NewSymbol("tls_npn"), Boolean::New(use_npn));
2156   obj->Set(String::NewSymbol("tls_sni"), Boolean::New(use_sni));
2157   obj->Set(String::NewSymbol("tls"),
2158       Boolean::New(get_builtin_module("crypto") != NULL));
2159
2160   return scope.Close(obj);
2161 }
2162
2163
2164 static void DebugPortGetter(Local<String> property,
2165                             const PropertyCallbackInfo<Value>& info) {
2166   HandleScope scope(node_isolate);
2167   info.GetReturnValue().Set(debug_port);
2168 }
2169
2170
2171 static void DebugPortSetter(Local<String> property,
2172                             Local<Value> value,
2173                             const PropertyCallbackInfo<void>& info) {
2174   HandleScope scope(node_isolate);
2175   debug_port = value->NumberValue();
2176 }
2177
2178
2179 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2180 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2181 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2182
2183
2184 void NeedImmediateCallbackGetter(Local<String> property,
2185                                  const PropertyCallbackInfo<Value>& info) {
2186   info.GetReturnValue().Set(need_immediate_cb);
2187 }
2188
2189
2190 static void NeedImmediateCallbackSetter(Local<String> property,
2191                                         Local<Value> value,
2192                                         const PropertyCallbackInfo<void>&) {
2193   HandleScope scope(node_isolate);
2194
2195   bool bool_value = value->BooleanValue();
2196
2197   if (need_immediate_cb == bool_value) return;
2198
2199   need_immediate_cb = bool_value;
2200
2201   if (need_immediate_cb) {
2202     uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2203     // idle handle is needed only to maintain event loop
2204     uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2205   } else {
2206     uv_check_stop(&check_immediate_watcher);
2207     uv_idle_stop(&idle_immediate_dummy);
2208   }
2209 }
2210
2211
2212 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2213   HandleScope scope(node_isolate);
2214
2215   int i, j;
2216
2217   Local<FunctionTemplate> process_template = FunctionTemplate::New();
2218   process_template->SetClassName(String::New("process"));
2219
2220   Local<Object> process = process_template->GetFunction()->NewInstance();
2221   assert(process.IsEmpty() == false);
2222   assert(process->IsObject() == true);
2223
2224   process_p.Reset(node_isolate, process);
2225
2226   process->SetAccessor(String::New("title"),
2227                        ProcessTitleGetter,
2228                        ProcessTitleSetter);
2229
2230   // process.version
2231   process->Set(String::NewSymbol("version"), String::New(NODE_VERSION));
2232
2233   // process.moduleLoadList
2234   Local<Array> modules = Array::New();
2235   module_load_list.Reset(node_isolate, modules);
2236   process->Set(String::NewSymbol("moduleLoadList"), modules);
2237
2238   // process.versions
2239   Local<Object> versions = Object::New();
2240   process->Set(String::NewSymbol("versions"), versions);
2241   versions->Set(String::NewSymbol("http_parser"), String::New(
2242                NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR) "."
2243                NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR)));
2244   // +1 to get rid of the leading 'v'
2245   versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
2246   versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
2247   versions->Set(String::NewSymbol("ares"), String::New(ARES_VERSION_STR));
2248   versions->Set(String::NewSymbol("uv"), String::New(uv_version_string()));
2249   versions->Set(String::NewSymbol("zlib"), String::New(ZLIB_VERSION));
2250   versions->Set(String::NewSymbol("modules"),
2251                 String::New(NODE_STRINGIFY(NODE_MODULE_VERSION)));
2252 #if HAVE_OPENSSL
2253   // Stupid code to slice out the version string.
2254   int c, l = strlen(OPENSSL_VERSION_TEXT);
2255   for (i = j = 0; i < l; i++) {
2256     c = OPENSSL_VERSION_TEXT[i];
2257     if ('0' <= c && c <= '9') {
2258       for (j = i + 1; j < l; j++) {
2259         c = OPENSSL_VERSION_TEXT[j];
2260         if (c == ' ') break;
2261       }
2262       break;
2263     }
2264   }
2265   versions->Set(String::NewSymbol("openssl"),
2266                 String::New(&OPENSSL_VERSION_TEXT[i], j - i));
2267 #endif
2268
2269
2270
2271   // process.arch
2272   process->Set(String::NewSymbol("arch"), String::New(ARCH));
2273
2274   // process.platform
2275   process->Set(String::NewSymbol("platform"), String::New(PLATFORM));
2276
2277   // process.argv
2278   Local<Array> arguments = Array::New(argc - option_end_index + 1);
2279   arguments->Set(Integer::New(0, node_isolate), String::New(argv[0]));
2280   for (j = 1, i = option_end_index; i < argc; j++, i++) {
2281     Local<String> arg = String::New(argv[i]);
2282     arguments->Set(Integer::New(j, node_isolate), arg);
2283   }
2284   // assign it
2285   process->Set(String::NewSymbol("argv"), arguments);
2286
2287   // process.execArgv
2288   Local<Array> execArgv = Array::New(option_end_index - 1);
2289   for (j = 1, i = 0; j < option_end_index; j++, i++) {
2290     execArgv->Set(Integer::New(i, node_isolate), String::New(argv[j]));
2291   }
2292   // assign it
2293   process->Set(String::NewSymbol("execArgv"), execArgv);
2294
2295
2296   // create process.env
2297   Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2298   envTemplate->SetNamedPropertyHandler(EnvGetter,
2299                                        EnvSetter,
2300                                        EnvQuery,
2301                                        EnvDeleter,
2302                                        EnvEnumerator,
2303                                        Object::New());
2304   Local<Object> env = envTemplate->NewInstance();
2305   process->Set(String::NewSymbol("env"), env);
2306
2307   process->Set(String::NewSymbol("pid"), Integer::New(getpid(), node_isolate));
2308   process->Set(String::NewSymbol("features"), GetFeatures());
2309   process->SetAccessor(String::New("_needImmediateCallback"),
2310                        NeedImmediateCallbackGetter,
2311                        NeedImmediateCallbackSetter);
2312
2313   // -e, --eval
2314   if (eval_string) {
2315     process->Set(String::NewSymbol("_eval"), String::New(eval_string));
2316   }
2317
2318   // -p, --print
2319   if (print_eval) {
2320     process->Set(String::NewSymbol("_print_eval"), True(node_isolate));
2321   }
2322
2323   // -i, --interactive
2324   if (force_repl) {
2325     process->Set(String::NewSymbol("_forceRepl"), True(node_isolate));
2326   }
2327
2328   // --no-deprecation
2329   if (no_deprecation) {
2330     process->Set(String::NewSymbol("noDeprecation"), True(node_isolate));
2331   }
2332
2333   // --throw-deprecation
2334   if (throw_deprecation) {
2335     process->Set(String::NewSymbol("throwDeprecation"), True(node_isolate));
2336   }
2337
2338   // --trace-deprecation
2339   if (trace_deprecation) {
2340     process->Set(String::NewSymbol("traceDeprecation"), True(node_isolate));
2341   }
2342
2343   size_t size = 2*PATH_MAX;
2344   char* execPath = new char[size];
2345   if (uv_exepath(execPath, &size) != 0) {
2346     // as a last ditch effort, fallback on argv[0] ?
2347     process->Set(String::NewSymbol("execPath"), String::New(argv[0]));
2348   } else {
2349     process->Set(String::NewSymbol("execPath"), String::New(execPath, size));
2350   }
2351   delete [] execPath;
2352
2353   process->SetAccessor(String::New("debugPort"),
2354                        DebugPortGetter,
2355                        DebugPortSetter);
2356
2357
2358   // define various internal methods
2359   NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2360   NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2361   NODE_SET_METHOD(process, "reallyExit", Exit);
2362   NODE_SET_METHOD(process, "abort", Abort);
2363   NODE_SET_METHOD(process, "chdir", Chdir);
2364   NODE_SET_METHOD(process, "cwd", Cwd);
2365
2366   NODE_SET_METHOD(process, "umask", Umask);
2367
2368 #if defined(__POSIX__) && !defined(__ANDROID__)
2369   NODE_SET_METHOD(process, "getuid", GetUid);
2370   NODE_SET_METHOD(process, "setuid", SetUid);
2371
2372   NODE_SET_METHOD(process, "setgid", SetGid);
2373   NODE_SET_METHOD(process, "getgid", GetGid);
2374
2375   NODE_SET_METHOD(process, "getgroups", GetGroups);
2376   NODE_SET_METHOD(process, "setgroups", SetGroups);
2377   NODE_SET_METHOD(process, "initgroups", InitGroups);
2378 #endif // __POSIX__ && !defined(__ANDROID__)
2379
2380   NODE_SET_METHOD(process, "_kill", Kill);
2381
2382   NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2383   NODE_SET_METHOD(process, "_debugPause", DebugPause);
2384   NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2385
2386   NODE_SET_METHOD(process, "hrtime", Hrtime);
2387
2388   NODE_SET_METHOD(process, "dlopen", DLOpen);
2389
2390   NODE_SET_METHOD(process, "uptime", Uptime);
2391   NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2392
2393   NODE_SET_METHOD(process, "binding", Binding);
2394
2395   NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2396
2397   // values use to cross communicate with processNextTick
2398   Local<Object> info_box = Object::New();
2399   info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2400                                                     kExternalUnsignedIntArray,
2401                                                     4);
2402   process->Set(String::NewSymbol("_tickInfoBox"), info_box);
2403
2404   // pre-set _events object for faster emit checks
2405   process->Set(String::NewSymbol("_events"), Object::New());
2406
2407   return scope.Close(process);
2408 }
2409
2410
2411 static void AtExit() {
2412   uv_tty_reset_mode();
2413 }
2414
2415
2416 static void SignalExit(int signal) {
2417   uv_tty_reset_mode();
2418   _exit(128 + signal);
2419 }
2420
2421
2422 void Load(Handle<Object> process_l) {
2423   HandleScope handle_scope(node_isolate);
2424
2425   process_symbol = String::New("process");
2426   domain_symbol = String::New("domain");
2427
2428   // Compile, execute the src/node.js file. (Which was included as static C
2429   // string in node_natives.h. 'natve_node' is the string containing that
2430   // source code.)
2431
2432   // The node.js file returns a function 'f'
2433   atexit(AtExit);
2434
2435   TryCatch try_catch;
2436
2437   // Disable verbose mode to stop FatalException() handler from trying
2438   // to handle the exception. Errors this early in the start-up phase
2439   // are not safe to ignore.
2440   try_catch.SetVerbose(false);
2441
2442   Local<Value> f_value = ExecuteString(MainSource(), String::New("node.js"));
2443   if (try_catch.HasCaught())  {
2444     ReportException(try_catch);
2445     exit(10);
2446   }
2447   assert(f_value->IsFunction());
2448   Local<Function> f = Local<Function>::Cast(f_value);
2449
2450   // Now we call 'f' with the 'process' variable that we've built up with
2451   // all our bindings. Inside node.js we'll take care of assigning things to
2452   // their places.
2453
2454   // We start the process this way in order to be more modular. Developers
2455   // who do not like how 'src/node.js' setups the module system but do like
2456   // Node's I/O bindings may want to replace 'f' with their own function.
2457
2458   // Add a reference to the global object
2459   Local<Object> global = v8::Context::GetCurrent()->Global();
2460
2461 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2462   InitDTrace(global);
2463 #endif
2464
2465 #if defined HAVE_PERFCTR
2466   InitPerfCounters(global);
2467 #endif
2468
2469   // Enable handling of uncaught exceptions
2470   // (FatalException(), break on uncaught exception in debugger)
2471   //
2472   // This is not strictly necessary since it's almost impossible
2473   // to attach the debugger fast enought to break on exception
2474   // thrown during process startup.
2475   try_catch.SetVerbose(true);
2476
2477   Local<Value> arg = process_l;
2478   f->Call(global, 1, &arg);
2479 }
2480
2481 static void PrintHelp();
2482
2483 static void ParseDebugOpt(const char* arg) {
2484   const char *p = 0;
2485
2486   if (strstr(arg, "--debug-port=") == arg) {
2487     p = 1 + strchr(arg, '=');
2488     debug_port = atoi(p);
2489   } else {
2490     use_debug_agent = true;
2491     if (!strcmp (arg, "--debug-brk")) {
2492       debug_wait_connect = true;
2493       return;
2494     } else if (!strcmp(arg, "--debug")) {
2495       return;
2496     } else if (strstr(arg, "--debug-brk=") == arg) {
2497       debug_wait_connect = true;
2498       p = 1 + strchr(arg, '=');
2499       debug_port = atoi(p);
2500     } else if (strstr(arg, "--debug=") == arg) {
2501       p = 1 + strchr(arg, '=');
2502       debug_port = atoi(p);
2503     }
2504   }
2505   if (p && debug_port > 1024 && debug_port <  65536)
2506       return;
2507
2508   fprintf(stderr, "Bad debug option.\n");
2509   if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2510
2511   PrintHelp();
2512   exit(12);
2513 }
2514
2515 static void PrintHelp() {
2516   printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2517          "       node debug script.js [arguments] \n"
2518          "\n"
2519          "Options:\n"
2520          "  -v, --version        print node's version\n"
2521          "  -e, --eval script    evaluate script\n"
2522          "  -p, --print          evaluate script and print result\n"
2523          "  -i, --interactive    always enter the REPL even if stdin\n"
2524          "                       does not appear to be a terminal\n"
2525          "  --no-deprecation     silence deprecation warnings\n"
2526          "  --trace-deprecation  show stack traces on deprecations\n"
2527          "  --v8-options         print v8 command line options\n"
2528          "  --max-stack-size=val set max v8 stack size (bytes)\n"
2529          "\n"
2530          "Environment variables:\n"
2531 #ifdef _WIN32
2532          "NODE_PATH              ';'-separated list of directories\n"
2533 #else
2534          "NODE_PATH              ':'-separated list of directories\n"
2535 #endif
2536          "                       prefixed to the module search path.\n"
2537          "NODE_MODULE_CONTEXTS   Set to 1 to load modules in their own\n"
2538          "                       global contexts.\n"
2539          "NODE_DISABLE_COLORS    Set to 1 to disable colors in the REPL\n"
2540          "\n"
2541          "Documentation can be found at http://nodejs.org/\n");
2542 }
2543
2544
2545 // Parse node command line arguments.
2546 static void ParseArgs(int argc, char **argv) {
2547   int i;
2548
2549   // TODO use parse opts
2550   for (i = 1; i < argc; i++) {
2551     const char *arg = argv[i];
2552     if (strstr(arg, "--debug") == arg) {
2553       ParseDebugOpt(arg);
2554       argv[i] = const_cast<char*>("");
2555     } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2556       printf("%s\n", NODE_VERSION);
2557       exit(0);
2558     } else if (strstr(arg, "--max-stack-size=") == arg) {
2559       const char *p = 0;
2560       p = 1 + strchr(arg, '=');
2561       max_stack_size = atoi(p);
2562       argv[i] = const_cast<char*>("");
2563     } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2564       PrintHelp();
2565       exit(0);
2566     } else if (strcmp(arg, "--eval") == 0   ||
2567                strcmp(arg, "-e") == 0       ||
2568                strcmp(arg, "--print") == 0  ||
2569                strcmp(arg, "-pe") == 0      ||
2570                strcmp(arg, "-p") == 0) {
2571       bool is_eval = strchr(arg, 'e') != NULL;
2572       bool is_print = strchr(arg, 'p') != NULL;
2573
2574       // argument to -p and --print is optional
2575       if (is_eval == true && i + 1 >= argc) {
2576         fprintf(stderr, "Error: %s requires an argument\n", arg);
2577         exit(13);
2578       }
2579
2580       print_eval = print_eval || is_print;
2581       argv[i] = const_cast<char*>("");
2582
2583       // --eval, -e and -pe always require an argument
2584       if (is_eval == true) {
2585         eval_string = argv[++i];
2586         continue;
2587       }
2588
2589       // next arg is the expression to evaluate unless it starts with:
2590       //  - a dash, then it's another switch
2591       //  - "\\-", then it's an escaped expression, drop the backslash
2592       if (argv[i + 1] == NULL) continue;
2593       if (argv[i + 1][0] == '-') continue;
2594       eval_string = argv[++i];
2595       if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2596     } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2597       force_repl = true;
2598       argv[i] = const_cast<char*>("");
2599     } else if (strcmp(arg, "--v8-options") == 0) {
2600       argv[i] = const_cast<char*>("--help");
2601     } else if (strcmp(arg, "--no-deprecation") == 0) {
2602       argv[i] = const_cast<char*>("");
2603       no_deprecation = true;
2604     } else if (strcmp(arg, "--trace-deprecation") == 0) {
2605       argv[i] = const_cast<char*>("");
2606       trace_deprecation = true;
2607     } else if (strcmp(arg, "--throw-deprecation") == 0) {
2608       argv[i] = const_cast<char*>("");
2609       throw_deprecation = true;
2610     } else if (argv[i][0] != '-') {
2611       break;
2612     }
2613   }
2614
2615   option_end_index = i;
2616 }
2617
2618
2619 // Called from the main thread.
2620 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2621   v8::Debug::ProcessDebugMessages();
2622 }
2623
2624
2625 // Called from V8 Debug Agent TCP thread.
2626 static void DispatchMessagesDebugAgentCallback() {
2627   uv_async_send(&dispatch_debug_messages_async);
2628 }
2629
2630
2631 // Called from the main thread
2632 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2633   HandleScope handle_scope(node_isolate);
2634   Local<Object> obj = Object::New();
2635   obj->Set(String::New("cmd"), String::New("NODE_DEBUG_ENABLED"));
2636   Local<Value> args[] = { String::New("internalMessage"), obj };
2637   MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2638 }
2639
2640
2641 // Called from the signal watcher callback
2642 static void EmitDebugEnabled() {
2643   uv_async_send(&emit_debug_enabled_async);
2644 }
2645
2646
2647 static void EnableDebug(bool wait_connect) {
2648   // If we're called from another thread, make sure to enter the right
2649   // v8 isolate.
2650   node_isolate->Enter();
2651
2652   v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2653                                             false);
2654
2655   // Start the debug thread and it's associated TCP server on port 5858.
2656   bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2657                                   debug_port,
2658                                   wait_connect);
2659
2660   // Crappy check that everything went well. FIXME
2661   assert(r);
2662
2663   // Print out some information.
2664   fprintf(stderr, "debugger listening on port %d\n", debug_port);
2665   fflush(stderr);
2666
2667   debugger_running = true;
2668
2669   // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2670   // the main process (i.e. when called via `node --debug`)
2671   if (!process_p.IsEmpty())
2672     EmitDebugEnabled();
2673
2674   node_isolate->Exit();
2675 }
2676
2677
2678 #ifdef __POSIX__
2679 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2680   // Break once process will return execution to v8
2681   v8::Debug::DebugBreak(node_isolate);
2682
2683   if (!debugger_running) {
2684     fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2685     EnableDebug(false);
2686   }
2687 }
2688
2689
2690 static void RegisterSignalHandler(int signal, void (*handler)(int)) {
2691   struct sigaction sa;
2692
2693   memset(&sa, 0, sizeof(sa));
2694   sa.sa_handler = handler;
2695   sigfillset(&sa.sa_mask);
2696   sigaction(signal, &sa, NULL);
2697 }
2698
2699
2700 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2701   HandleScope scope(node_isolate);
2702
2703   if (args.Length() != 1) {
2704     return ThrowError("Invalid number of arguments.");
2705   }
2706
2707   pid_t pid;
2708   int r;
2709
2710   pid = args[0]->IntegerValue();
2711   r = kill(pid, SIGUSR1);
2712   if (r != 0) {
2713     return ThrowErrnoException(errno, "kill");
2714   }
2715 }
2716 #endif // __POSIX__
2717
2718
2719 #ifdef _WIN32
2720 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2721   // Break once process will return execution to v8
2722   if (!debugger_running) {
2723     for (int i = 0; i < 1; i++) {
2724       fprintf(stderr, "Starting debugger agent.\r\n");
2725       fflush(stderr);
2726       EnableDebug(false);
2727     }
2728   }
2729
2730   v8::Debug::DebugBreak(node_isolate);
2731
2732   return 0;
2733 }
2734
2735
2736 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2737     size_t buf_len) {
2738   return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2739 }
2740
2741
2742 static int RegisterDebugSignalHandler() {
2743   wchar_t mapping_name[32];
2744   HANDLE mapping_handle;
2745   DWORD pid;
2746   LPTHREAD_START_ROUTINE* handler;
2747
2748   pid = GetCurrentProcessId();
2749
2750   if (GetDebugSignalHandlerMappingName(pid,
2751                                        mapping_name,
2752                                        ARRAY_SIZE(mapping_name)) < 0) {
2753     return -1;
2754   }
2755
2756   mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2757                                       NULL,
2758                                       PAGE_READWRITE,
2759                                       0,
2760                                       sizeof *handler,
2761                                       mapping_name);
2762   if (mapping_handle == NULL) {
2763     return -1;
2764   }
2765
2766   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2767       MapViewOfFile(mapping_handle,
2768                     FILE_MAP_ALL_ACCESS,
2769                     0,
2770                     0,
2771                     sizeof *handler));
2772   if (handler == NULL) {
2773     CloseHandle(mapping_handle);
2774     return -1;
2775   }
2776
2777   *handler = EnableDebugThreadProc;
2778
2779   UnmapViewOfFile((void*) handler);
2780
2781   return 0;
2782 }
2783
2784
2785 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2786   HandleScope scope(node_isolate);
2787   DWORD pid;
2788   HANDLE process = NULL;
2789   HANDLE thread = NULL;
2790   HANDLE mapping = NULL;
2791   wchar_t mapping_name[32];
2792   LPTHREAD_START_ROUTINE* handler = NULL;
2793
2794   if (args.Length() != 1) {
2795     ThrowError("Invalid number of arguments.");
2796     goto out;
2797   }
2798
2799   pid = (DWORD) args[0]->IntegerValue();
2800
2801   process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2802                             PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2803                             PROCESS_VM_READ,
2804                         FALSE,
2805                         pid);
2806   if (process == NULL) {
2807     ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2808     goto out;
2809   }
2810
2811   if (GetDebugSignalHandlerMappingName(pid,
2812                                        mapping_name,
2813                                        ARRAY_SIZE(mapping_name)) < 0) {
2814     ThrowErrnoException(errno, "sprintf");
2815     goto out;
2816   }
2817
2818   mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2819   if (mapping == NULL) {
2820     ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2821     goto out;
2822   }
2823
2824   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2825       MapViewOfFile(mapping,
2826                     FILE_MAP_READ,
2827                     0,
2828                     0,
2829                     sizeof *handler));
2830   if (handler == NULL || *handler == NULL) {
2831     ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2832     goto out;
2833   }
2834
2835   thread = CreateRemoteThread(process,
2836                               NULL,
2837                               0,
2838                               *handler,
2839                               NULL,
2840                               0,
2841                               NULL);
2842   if (thread == NULL) {
2843     ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2844     goto out;
2845   }
2846
2847   // Wait for the thread to terminate
2848   if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2849     ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2850     goto out;
2851   }
2852
2853  out:
2854   if (process != NULL) {
2855    CloseHandle(process);
2856   }
2857   if (thread != NULL) {
2858     CloseHandle(thread);
2859   }
2860   if (handler != NULL) {
2861     UnmapViewOfFile(handler);
2862   }
2863   if (mapping != NULL) {
2864     CloseHandle(mapping);
2865   }
2866 }
2867 #endif // _WIN32
2868
2869
2870 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2871   v8::Debug::DebugBreak(node_isolate);
2872 }
2873
2874
2875 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2876   if (debugger_running) {
2877     v8::Debug::DisableAgent();
2878     debugger_running = false;
2879   }
2880 }
2881
2882
2883 char** Init(int argc, char *argv[]) {
2884   // Initialize prog_start_time to get relative uptime.
2885   uv_uptime(&prog_start_time);
2886
2887   // Make inherited handles noninheritable.
2888   uv_disable_stdio_inheritance();
2889
2890   // init async debug messages dispatching
2891   uv_async_init(uv_default_loop(),
2892                 &dispatch_debug_messages_async,
2893                 DispatchDebugMessagesAsyncCallback);
2894   uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2895
2896   // init async NODE_DEBUG_ENABLED emitter
2897   uv_async_init(uv_default_loop(),
2898                 &emit_debug_enabled_async,
2899                 EmitDebugEnabledAsyncCallback);
2900   uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2901
2902   // Parse a few arguments which are specific to Node.
2903   node::ParseArgs(argc, argv);
2904   // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2905   // in the command line))
2906   int v8argc = option_end_index;
2907   char **v8argv = argv;
2908
2909   if (debug_wait_connect) {
2910     // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2911     // to expose the v8 debugger js object so that node.js can set
2912     // a breakpoint on the first line of the startup script
2913     v8argc += 2;
2914     v8argv = new char*[v8argc];
2915     memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2916     v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2917     v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2918   }
2919
2920   // For the normal stack which moves from high to low addresses when frames
2921   // are pushed, we can compute the limit as stack_size bytes below the
2922   // the address of a stack variable (e.g. &stack_var) as an approximation
2923   // of the start of the stack (we're assuming that we haven't pushed a lot
2924   // of frames yet).
2925   if (max_stack_size != 0) {
2926     uint32_t stack_var;
2927     ResourceConstraints constraints;
2928
2929     uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2930     constraints.set_stack_limit(stack_limit);
2931     SetResourceConstraints(&constraints); // Must be done before V8::Initialize
2932   }
2933   V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
2934
2935   const char typed_arrays_flag[] = "--harmony_typed_arrays";
2936   V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
2937   V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
2938
2939   // Fetch a reference to the main isolate, so we have a reference to it
2940   // even when we need it to access it from another (debugger) thread.
2941   node_isolate = Isolate::GetCurrent();
2942
2943 #ifdef __POSIX__
2944   // Ignore SIGPIPE
2945   RegisterSignalHandler(SIGPIPE, SIG_IGN);
2946   RegisterSignalHandler(SIGINT, SignalExit);
2947   RegisterSignalHandler(SIGTERM, SignalExit);
2948 #endif // __POSIX__
2949
2950   uv_check_init(uv_default_loop(), &check_immediate_watcher);
2951   uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
2952   uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
2953
2954   V8::SetFatalErrorHandler(node::OnFatalError);
2955   V8::AddMessageListener(OnMessage);
2956
2957   // If the --debug flag was specified then initialize the debug thread.
2958   if (use_debug_agent) {
2959     EnableDebug(debug_wait_connect);
2960   } else {
2961 #ifdef _WIN32
2962     RegisterDebugSignalHandler();
2963 #else // Posix
2964     static uv_signal_t signal_watcher;
2965     uv_signal_init(uv_default_loop(), &signal_watcher);
2966     uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
2967     uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
2968 #endif // __POSIX__
2969   }
2970
2971   return argv;
2972 }
2973
2974
2975 struct AtExitCallback {
2976   AtExitCallback* next_;
2977   void (*cb_)(void* arg);
2978   void* arg_;
2979 };
2980
2981 static AtExitCallback* at_exit_functions_;
2982
2983
2984 void RunAtExit() {
2985   AtExitCallback* p = at_exit_functions_;
2986   at_exit_functions_ = NULL;
2987
2988   while (p) {
2989     AtExitCallback* q = p->next_;
2990     p->cb_(p->arg_);
2991     delete p;
2992     p = q;
2993   }
2994 }
2995
2996
2997 void AtExit(void (*cb)(void* arg), void* arg) {
2998   AtExitCallback* p = new AtExitCallback;
2999   p->cb_ = cb;
3000   p->arg_ = arg;
3001   p->next_ = at_exit_functions_;
3002   at_exit_functions_ = p;
3003 }
3004
3005
3006 void EmitExit(v8::Handle<v8::Object> process_l) {
3007   // process.emit('exit')
3008   process_l->Set(String::NewSymbol("_exiting"), True(node_isolate));
3009   Local<Value> args[] = { String::New("exit"), Integer::New(0, node_isolate) };
3010   MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3011 }
3012
3013 static char **copy_argv(int argc, char **argv) {
3014   size_t strlen_sum;
3015   char **argv_copy;
3016   char *argv_data;
3017   size_t len;
3018   int i;
3019
3020   strlen_sum = 0;
3021   for(i = 0; i < argc; i++) {
3022     strlen_sum += strlen(argv[i]) + 1;
3023   }
3024
3025   argv_copy = (char **) malloc(sizeof(char *) * (argc + 1) + strlen_sum);
3026   if (!argv_copy) {
3027     return NULL;
3028   }
3029
3030   argv_data = (char *) argv_copy + sizeof(char *) * (argc + 1);
3031
3032   for(i = 0; i < argc; i++) {
3033     argv_copy[i] = argv_data;
3034     len = strlen(argv[i]) + 1;
3035     memcpy(argv_data, argv[i], len);
3036     argv_data += len;
3037   }
3038
3039   argv_copy[argc] = NULL;
3040
3041   return argv_copy;
3042 }
3043
3044 int Start(int argc, char *argv[]) {
3045   // Hack aroung with the argv pointer. Used for process.title = "blah".
3046   argv = uv_setup_args(argc, argv);
3047
3048   // Logic to duplicate argv as Init() modifies arguments
3049   // that are passed into it.
3050   char **argv_copy = copy_argv(argc, argv);
3051
3052   // This needs to run *before* V8::Initialize()
3053   // Use copy here as to not modify the original argv:
3054   Init(argc, argv_copy);
3055
3056   V8::Initialize();
3057   {
3058     Locker locker(node_isolate);
3059     HandleScope handle_scope(node_isolate);
3060
3061     // Create the one and only Context.
3062     Local<Context> context = Context::New(node_isolate);
3063     Context::Scope context_scope(context);
3064
3065     binding_cache.Reset(node_isolate, Object::New());
3066
3067     // Use original argv, as we're just copying values out of it.
3068     Local<Object> process_l = SetupProcessObject(argc, argv);
3069
3070     // Create all the objects, load modules, do everything.
3071     // so your next reading stop should be node::Load()!
3072     Load(process_l);
3073
3074     // All our arguments are loaded. We've evaluated all of the scripts. We
3075     // might even have created TCP servers. Now we enter the main eventloop. If
3076     // there are no watchers on the loop (except for the ones that were
3077     // uv_unref'd) then this function exits. As long as there are active
3078     // watchers, it blocks.
3079     uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3080
3081     EmitExit(process_l);
3082     RunAtExit();
3083   }
3084
3085 #ifndef NDEBUG
3086   // Clean up. Not strictly necessary.
3087   V8::Dispose();
3088 #endif  // NDEBUG
3089
3090   // Clean up the copy:
3091   free(argv_copy);
3092
3093   return 0;
3094 }
3095
3096
3097 }  // namespace node