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