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