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