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