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