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