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