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