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