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