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