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