src: fix windows build breakage from f674b09
[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   Local<Value> ndt_v =
914       process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_nextDomainTick"));
915   if (!tdc_v->IsFunction()) {
916     fprintf(stderr, "process._tickDomainCallback assigned to non-function\n");
917     abort();
918   }
919   if (!ndt_v->IsFunction()) {
920     fprintf(stderr, "process._nextDomainTick assigned to non-function\n");
921     abort();
922   }
923   Local<Function> tdc = tdc_v.As<Function>();
924   Local<Function> ndt = ndt_v.As<Function>();
925   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"), tdc);
926   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "nextTick"), ndt);
927   process_tickCallback.Reset(node_isolate, tdc);
928 }
929
930
931 Handle<Value>
932 MakeDomainCallback(const Handle<Object> object,
933                    const Handle<Function> callback,
934                    int argc,
935                    Handle<Value> argv[]) {
936   // TODO(trevnorris) Hook for long stack traces to be made here.
937
938   // lazy load domain specific symbols
939   if (enter_symbol.IsEmpty()) {
940     enter_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "enter");
941     exit_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exit");
942     disposed_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "_disposed");
943   }
944
945   Local<Value> domain_v = object->Get(domain_symbol);
946   Local<Object> domain;
947   Local<Function> enter;
948   Local<Function> exit;
949
950   TryCatch try_catch;
951   try_catch.SetVerbose(true);
952
953   bool has_domain = domain_v->IsObject();
954   if (has_domain) {
955     domain = domain_v->ToObject();
956     assert(!domain.IsEmpty());
957     if (domain->Get(disposed_symbol)->IsTrue()) {
958       // domain has been disposed of.
959       return Undefined(node_isolate);
960     }
961     enter = Local<Function>::Cast(domain->Get(enter_symbol));
962     assert(!enter.IsEmpty());
963     enter->Call(domain, 0, NULL);
964
965     if (try_catch.HasCaught()) {
966       return Undefined(node_isolate);
967     }
968   }
969
970   Local<Value> ret = callback->Call(object, argc, argv);
971
972   if (try_catch.HasCaught()) {
973     return Undefined(node_isolate);
974   }
975
976   if (has_domain) {
977     exit = Local<Function>::Cast(domain->Get(exit_symbol));
978     assert(!exit.IsEmpty());
979     exit->Call(domain, 0, NULL);
980
981     if (try_catch.HasCaught()) {
982       return Undefined(node_isolate);
983     }
984   }
985
986   if (tick_infobox.last_threw == 1) {
987     tick_infobox.last_threw = 0;
988     return ret;
989   }
990
991   if (tick_infobox.in_tick == 1) {
992     return ret;
993   }
994
995   if (tick_infobox.length == 0) {
996     tick_infobox.index = 0;
997     return ret;
998   }
999
1000   // process nextTicks after call
1001   Local<Object> process = PersistentToLocal(node_isolate, process_p);
1002   Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1003   fn->Call(process, 0, NULL);
1004
1005   if (try_catch.HasCaught()) {
1006     return Undefined(node_isolate);
1007   }
1008
1009   return ret;
1010 }
1011
1012
1013 Handle<Value>
1014 MakeCallback(const Handle<Object> object,
1015              const Handle<Function> callback,
1016              int argc,
1017              Handle<Value> argv[]) {
1018   // TODO(trevnorris) Hook for long stack traces to be made here.
1019   Local<Object> process = PersistentToLocal(node_isolate, process_p);
1020
1021   if (using_domains)
1022     return MakeDomainCallback(object, callback, argc, argv);
1023
1024   // lazy load no domain next tick callbacks
1025   if (process_tickCallback.IsEmpty()) {
1026     Local<Value> cb_v =
1027         process->Get(FIXED_ONE_BYTE_STRING(node_isolate, "_tickCallback"));
1028     if (!cb_v->IsFunction()) {
1029       fprintf(stderr, "process._tickCallback assigned to non-function\n");
1030       abort();
1031     }
1032     process_tickCallback.Reset(node_isolate, cb_v.As<Function>());
1033   }
1034
1035   TryCatch try_catch;
1036   try_catch.SetVerbose(true);
1037
1038   Local<Value> ret = callback->Call(object, argc, argv);
1039
1040   if (try_catch.HasCaught()) {
1041     return Undefined(node_isolate);
1042   }
1043
1044   if (tick_infobox.in_tick == 1) {
1045     return ret;
1046   }
1047
1048   if (tick_infobox.length == 0) {
1049     tick_infobox.index = 0;
1050     return ret;
1051   }
1052
1053   // process nextTicks after call
1054   Local<Function> fn = PersistentToLocal(node_isolate, process_tickCallback);
1055   fn->Call(process, 0, NULL);
1056
1057   if (try_catch.HasCaught()) {
1058     return Undefined(node_isolate);
1059   }
1060
1061   return ret;
1062 }
1063
1064
1065 Handle<Value>
1066 MakeCallback(const Handle<Object> object,
1067              const Handle<String> symbol,
1068              int argc,
1069              Handle<Value> argv[]) {
1070   HandleScope scope(node_isolate);
1071
1072   Local<Function> callback = object->Get(symbol).As<Function>();
1073   assert(callback->IsFunction());
1074
1075   if (using_domains)
1076     return scope.Close(MakeDomainCallback(object, callback, argc, argv));
1077   return scope.Close(MakeCallback(object, callback, argc, argv));
1078 }
1079
1080
1081 Handle<Value>
1082 MakeCallback(const Handle<Object> object,
1083              const char* method,
1084              int argc,
1085              Handle<Value> argv[]) {
1086   HandleScope scope(node_isolate);
1087
1088   Local<String> method_string = OneByteString(node_isolate, method);
1089   Handle<Value> ret = MakeCallback(object, method_string, argc, argv);
1090
1091   return scope.Close(ret);
1092 }
1093
1094
1095 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1096   HandleScope scope(node_isolate);
1097
1098   if (!encoding_v->IsString()) return _default;
1099
1100   String::Utf8Value encoding(encoding_v);
1101
1102   if (strcasecmp(*encoding, "utf8") == 0) {
1103     return UTF8;
1104   } else if (strcasecmp(*encoding, "utf-8") == 0) {
1105     return UTF8;
1106   } else if (strcasecmp(*encoding, "ascii") == 0) {
1107     return ASCII;
1108   } else if (strcasecmp(*encoding, "base64") == 0) {
1109     return BASE64;
1110   } else if (strcasecmp(*encoding, "ucs2") == 0) {
1111     return UCS2;
1112   } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1113     return UCS2;
1114   } else if (strcasecmp(*encoding, "utf16le") == 0) {
1115     return UCS2;
1116   } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1117     return UCS2;
1118   } else if (strcasecmp(*encoding, "binary") == 0) {
1119     return BINARY;
1120   } else if (strcasecmp(*encoding, "buffer") == 0) {
1121     return BUFFER;
1122   } else if (strcasecmp(*encoding, "hex") == 0) {
1123     return HEX;
1124   } else if (strcasecmp(*encoding, "raw") == 0) {
1125     if (!no_deprecation) {
1126       fprintf(stderr, "'raw' (array of integers) has been removed. "
1127                       "Use 'binary'.\n");
1128     }
1129     return BINARY;
1130   } else if (strcasecmp(*encoding, "raws") == 0) {
1131     if (!no_deprecation) {
1132       fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1133                       "Please update your code.\n");
1134     }
1135     return BINARY;
1136   } else {
1137     return _default;
1138   }
1139 }
1140
1141 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1142   return StringBytes::Encode(static_cast<const char*>(buf),
1143                              len,
1144                              encoding);
1145 }
1146
1147 // Returns -1 if the handle was not valid for decoding
1148 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1149   HandleScope scope(node_isolate);
1150
1151   if (val->IsArray()) {
1152     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1153                     "Use 'binary'.\n");
1154     assert(0);
1155     return -1;
1156   }
1157
1158   return StringBytes::Size(val, encoding);
1159 }
1160
1161 #ifndef MIN
1162 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1163 #endif
1164
1165 // Returns number of bytes written.
1166 ssize_t DecodeWrite(char *buf,
1167                     size_t buflen,
1168                     v8::Handle<v8::Value> val,
1169                     enum encoding encoding) {
1170   return StringBytes::Write(buf, buflen, val, encoding, NULL);
1171 }
1172
1173 void DisplayExceptionLine(Handle<Message> message) {
1174   // Prevent re-entry into this function.  For example, if there is
1175   // a throw from a program in vm.runInThisContext(code, filename, true),
1176   // then we want to show the original failure, not the secondary one.
1177   static bool displayed_error = false;
1178
1179   if (displayed_error) return;
1180   displayed_error = true;
1181
1182   uv_tty_reset_mode();
1183
1184   fprintf(stderr, "\n");
1185
1186   if (!message.IsEmpty()) {
1187     // Print (filename):(line number): (message).
1188     String::Utf8Value filename(message->GetScriptResourceName());
1189     const char* filename_string = *filename;
1190     int linenum = message->GetLineNumber();
1191     fprintf(stderr, "%s:%i\n", filename_string, linenum);
1192     // Print line of source code.
1193     String::Utf8Value sourceline(message->GetSourceLine());
1194     const char* sourceline_string = *sourceline;
1195
1196     // Because of how node modules work, all scripts are wrapped with a
1197     // "function (module, exports, __filename, ...) {"
1198     // to provide script local variables.
1199     //
1200     // When reporting errors on the first line of a script, this wrapper
1201     // function is leaked to the user. There used to be a hack here to
1202     // truncate off the first 62 characters, but it caused numerous other
1203     // problems when vm.runIn*Context() methods were used for non-module
1204     // code.
1205     //
1206     // If we ever decide to re-instate such a hack, the following steps
1207     // must be taken:
1208     //
1209     // 1. Pass a flag around to say "this code was wrapped"
1210     // 2. Update the stack frame output so that it is also correct.
1211     //
1212     // It would probably be simpler to add a line rather than add some
1213     // number of characters to the first line, since V8 truncates the
1214     // sourceline to 78 characters, and we end up not providing very much
1215     // useful debugging info to the user if we remove 62 characters.
1216
1217     int start = message->GetStartColumn();
1218     int end = message->GetEndColumn();
1219
1220     fprintf(stderr, "%s\n", sourceline_string);
1221     // Print wavy underline (GetUnderline is deprecated).
1222     for (int i = 0; i < start; i++) {
1223       fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1224     }
1225     for (int i = start; i < end; i++) {
1226       fputc('^', stderr);
1227     }
1228     fputc('\n', stderr);
1229   }
1230 }
1231
1232
1233 static void ReportException(Handle<Value> er, Handle<Message> message) {
1234   HandleScope scope(node_isolate);
1235
1236   DisplayExceptionLine(message);
1237
1238   Local<Value> trace_value(
1239       er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack")));
1240   String::Utf8Value trace(trace_value);
1241
1242   // range errors have a trace member set to undefined
1243   if (trace.length() > 0 && !trace_value->IsUndefined()) {
1244     fprintf(stderr, "%s\n", *trace);
1245   } else {
1246     // this really only happens for RangeErrors, since they're the only
1247     // kind that won't have all this info in the trace, or when non-Error
1248     // objects are thrown manually.
1249     Local<Value> message;
1250     Local<Value> name;
1251
1252     if (er->IsObject()) {
1253       Local<Object> err_obj = er.As<Object>();
1254       message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1255       name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1256     }
1257
1258     if (message.IsEmpty() ||
1259         message->IsUndefined() ||
1260         name.IsEmpty() ||
1261         name->IsUndefined()) {
1262       // Not an error object. Just print as-is.
1263       String::Utf8Value message(er);
1264       fprintf(stderr, "%s\n", *message);
1265     } else {
1266       String::Utf8Value name_string(name);
1267       String::Utf8Value message_string(message);
1268       fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1269     }
1270   }
1271
1272   fflush(stderr);
1273 }
1274
1275
1276 static void ReportException(const TryCatch& try_catch) {
1277   ReportException(try_catch.Exception(), try_catch.Message());
1278 }
1279
1280
1281 // Executes a str within the current v8 context.
1282 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1283   HandleScope scope(node_isolate);
1284   TryCatch try_catch;
1285
1286   // try_catch must be nonverbose to disable FatalException() handler,
1287   // we will handle exceptions ourself.
1288   try_catch.SetVerbose(false);
1289
1290   Local<v8::Script> script = v8::Script::Compile(source, filename);
1291   if (script.IsEmpty()) {
1292     ReportException(try_catch);
1293     exit(3);
1294   }
1295
1296   Local<Value> result = script->Run();
1297   if (result.IsEmpty()) {
1298     ReportException(try_catch);
1299     exit(4);
1300   }
1301
1302   return scope.Close(result);
1303 }
1304
1305
1306 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1307   HandleScope scope(node_isolate);
1308
1309   Local<Array> ary = Array::New();
1310   QUEUE* q = NULL;
1311   int i = 0;
1312
1313   QUEUE_FOREACH(q, &req_wrap_queue) {
1314     ReqWrap<uv_req_t>* w = container_of(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1315     if (w->persistent().IsEmpty()) continue;
1316     ary->Set(i++, w->object());
1317   }
1318
1319   args.GetReturnValue().Set(ary);
1320 }
1321
1322
1323 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1324 // implemented here for consistency with GetActiveRequests().
1325 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1326   HandleScope scope(node_isolate);
1327
1328   Local<Array> ary = Array::New();
1329   QUEUE* q = NULL;
1330   int i = 0;
1331
1332   Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1333
1334   QUEUE_FOREACH(q, &handle_wrap_queue) {
1335     HandleWrap* w = container_of(q, HandleWrap, handle_wrap_queue_);
1336     if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref)) continue;
1337     Local<Object> object = w->object();
1338     Local<Value> owner = object->Get(owner_sym);
1339     if (owner->IsUndefined()) owner = object;
1340     ary->Set(i++, owner);
1341   }
1342
1343   args.GetReturnValue().Set(ary);
1344 }
1345
1346
1347 static void Abort(const FunctionCallbackInfo<Value>& args) {
1348   abort();
1349 }
1350
1351
1352 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1353   HandleScope scope(node_isolate);
1354
1355   if (args.Length() != 1 || !args[0]->IsString()) {
1356     return ThrowError("Bad argument.");  // FIXME(bnoordhuis) ThrowTypeError?
1357   }
1358
1359   String::Utf8Value path(args[0]);
1360   int err = uv_chdir(*path);
1361   if (err) {
1362     return ThrowUVException(err, "uv_chdir");
1363   }
1364 }
1365
1366
1367 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1368   HandleScope scope(node_isolate);
1369 #ifdef _WIN32
1370   /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1371   char buf[MAX_PATH * 4 + 1];
1372 #else
1373   char buf[PATH_MAX + 1];
1374 #endif
1375
1376   int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1377   if (err) {
1378     return ThrowUVException(err, "uv_cwd");
1379   }
1380
1381   buf[ARRAY_SIZE(buf) - 1] = '\0';
1382   Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1383
1384   args.GetReturnValue().Set(cwd);
1385 }
1386
1387
1388 static void Umask(const FunctionCallbackInfo<Value>& args) {
1389   HandleScope scope(node_isolate);
1390   uint32_t old;
1391
1392   if (args.Length() < 1 || args[0]->IsUndefined()) {
1393     old = umask(0);
1394     umask(static_cast<mode_t>(old));
1395   } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1396     return ThrowTypeError("argument must be an integer or octal string.");
1397   } else {
1398     int oct;
1399     if (args[0]->IsInt32()) {
1400       oct = args[0]->Uint32Value();
1401     } else {
1402       oct = 0;
1403       String::Utf8Value str(args[0]);
1404
1405       // Parse the octal string.
1406       for (int i = 0; i < str.length(); i++) {
1407         char c = (*str)[i];
1408         if (c > '7' || c < '0') {
1409           return ThrowTypeError("invalid octal string");
1410         }
1411         oct *= 8;
1412         oct += c - '0';
1413       }
1414     }
1415     old = umask(static_cast<mode_t>(oct));
1416   }
1417
1418   args.GetReturnValue().Set(old);
1419 }
1420
1421
1422 #if defined(__POSIX__) && !defined(__ANDROID__)
1423
1424 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1425 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1426
1427
1428 static uid_t uid_by_name(const char* name) {
1429   struct passwd pwd;
1430   struct passwd* pp;
1431   char buf[8192];
1432
1433   errno = 0;
1434   pp = NULL;
1435
1436   if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1437     return pp->pw_uid;
1438   }
1439
1440   return uid_not_found;
1441 }
1442
1443
1444 static char* name_by_uid(uid_t uid) {
1445   struct passwd pwd;
1446   struct passwd* pp;
1447   char buf[8192];
1448   int rc;
1449
1450   errno = 0;
1451   pp = NULL;
1452
1453   if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1454     return strdup(pp->pw_name);
1455   }
1456
1457   if (rc == 0) {
1458     errno = ENOENT;
1459   }
1460
1461   return NULL;
1462 }
1463
1464
1465 static gid_t gid_by_name(const char* name) {
1466   struct group pwd;
1467   struct group* pp;
1468   char buf[8192];
1469
1470   errno = 0;
1471   pp = NULL;
1472
1473   if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1474     return pp->gr_gid;
1475   }
1476
1477   return gid_not_found;
1478 }
1479
1480
1481 #if 0  // For future use.
1482 static const char* name_by_gid(gid_t gid) {
1483   struct group pwd;
1484   struct group* pp;
1485   char buf[8192];
1486   int rc;
1487
1488   errno = 0;
1489   pp = NULL;
1490
1491   if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1492     return strdup(pp->gr_name);
1493   }
1494
1495   if (rc == 0) {
1496     errno = ENOENT;
1497   }
1498
1499   return NULL;
1500 }
1501 #endif
1502
1503
1504 static uid_t uid_by_name(Handle<Value> value) {
1505   if (value->IsUint32()) {
1506     return static_cast<uid_t>(value->Uint32Value());
1507   } else {
1508     String::Utf8Value name(value);
1509     return uid_by_name(*name);
1510   }
1511 }
1512
1513
1514 static gid_t gid_by_name(Handle<Value> value) {
1515   if (value->IsUint32()) {
1516     return static_cast<gid_t>(value->Uint32Value());
1517   } else {
1518     String::Utf8Value name(value);
1519     return gid_by_name(*name);
1520   }
1521 }
1522
1523
1524 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1525   args.GetReturnValue().Set(getuid());
1526 }
1527
1528
1529 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1530   args.GetReturnValue().Set(getgid());
1531 }
1532
1533
1534 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1535   HandleScope scope(node_isolate);
1536
1537   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1538     return ThrowTypeError("setgid argument must be a number or a string");
1539   }
1540
1541   gid_t gid = gid_by_name(args[0]);
1542
1543   if (gid == gid_not_found) {
1544     return ThrowError("setgid group id does not exist");
1545   }
1546
1547   if (setgid(gid)) {
1548     return ThrowErrnoException(errno, "setgid");
1549   }
1550 }
1551
1552
1553 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1554   HandleScope scope(node_isolate);
1555
1556   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1557     return ThrowTypeError("setuid argument must be a number or a string");
1558   }
1559
1560   uid_t uid = uid_by_name(args[0]);
1561
1562   if (uid == uid_not_found) {
1563     return ThrowError("setuid user id does not exist");
1564   }
1565
1566   if (setuid(uid)) {
1567     return ThrowErrnoException(errno, "setuid");
1568   }
1569 }
1570
1571
1572 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1573   HandleScope scope(node_isolate);
1574
1575   int ngroups = getgroups(0, NULL);
1576
1577   if (ngroups == -1) {
1578     return ThrowErrnoException(errno, "getgroups");
1579   }
1580
1581   gid_t* groups = new gid_t[ngroups];
1582
1583   ngroups = getgroups(ngroups, groups);
1584
1585   if (ngroups == -1) {
1586     delete[] groups;
1587     return ThrowErrnoException(errno, "getgroups");
1588   }
1589
1590   Local<Array> groups_list = Array::New(ngroups);
1591   bool seen_egid = false;
1592   gid_t egid = getegid();
1593
1594   for (int i = 0; i < ngroups; i++) {
1595     groups_list->Set(i, Integer::New(groups[i], node_isolate));
1596     if (groups[i] == egid) seen_egid = true;
1597   }
1598
1599   delete[] groups;
1600
1601   if (seen_egid == false) {
1602     groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1603   }
1604
1605   args.GetReturnValue().Set(groups_list);
1606 }
1607
1608
1609 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1610   HandleScope scope(node_isolate);
1611
1612   if (!args[0]->IsArray()) {
1613     return ThrowTypeError("argument 1 must be an array");
1614   }
1615
1616   Local<Array> groups_list = args[0].As<Array>();
1617   size_t size = groups_list->Length();
1618   gid_t* groups = new gid_t[size];
1619
1620   for (size_t i = 0; i < size; i++) {
1621     gid_t gid = gid_by_name(groups_list->Get(i));
1622
1623     if (gid == gid_not_found) {
1624       delete[] groups;
1625       return ThrowError("group name not found");
1626     }
1627
1628     groups[i] = gid;
1629   }
1630
1631   int rc = setgroups(size, groups);
1632   delete[] groups;
1633
1634   if (rc == -1) {
1635     return ThrowErrnoException(errno, "setgroups");
1636   }
1637 }
1638
1639
1640 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1641   HandleScope scope(node_isolate);
1642
1643   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1644     return ThrowTypeError("argument 1 must be a number or a string");
1645   }
1646
1647   if (!args[1]->IsUint32() && !args[1]->IsString()) {
1648     return ThrowTypeError("argument 2 must be a number or a string");
1649   }
1650
1651   String::Utf8Value arg0(args[0]);
1652   gid_t extra_group;
1653   bool must_free;
1654   char* user;
1655
1656   if (args[0]->IsUint32()) {
1657     user = name_by_uid(args[0]->Uint32Value());
1658     must_free = true;
1659   } else {
1660     user = *arg0;
1661     must_free = false;
1662   }
1663
1664   if (user == NULL) {
1665     return ThrowError("initgroups user not found");
1666   }
1667
1668   extra_group = gid_by_name(args[1]);
1669
1670   if (extra_group == gid_not_found) {
1671     if (must_free) free(user);
1672     return ThrowError("initgroups extra group not found");
1673   }
1674
1675   int rc = initgroups(user, extra_group);
1676
1677   if (must_free) {
1678     free(user);
1679   }
1680
1681   if (rc) {
1682     return ThrowErrnoException(errno, "initgroups");
1683   }
1684 }
1685
1686 #endif  // __POSIX__ && !defined(__ANDROID__)
1687
1688
1689 void Exit(const FunctionCallbackInfo<Value>& args) {
1690   HandleScope scope(node_isolate);
1691   exit(args[0]->IntegerValue());
1692 }
1693
1694
1695 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1696   HandleScope scope(node_isolate);
1697   double uptime;
1698   if (uv_uptime(&uptime)) return;
1699   args.GetReturnValue().Set(uptime - prog_start_time);
1700 }
1701
1702
1703 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1704   HandleScope scope(node_isolate);
1705
1706   size_t rss;
1707
1708   int err = uv_resident_set_memory(&rss);
1709   if (err) {
1710     return ThrowUVException(err, "uv_resident_set_memory");
1711   }
1712
1713   Local<Object> info = Object::New();
1714
1715   if (rss_symbol.IsEmpty()) {
1716     rss_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "rss");
1717     heap_total_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapTotal");
1718     heap_used_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "heapUsed");
1719   }
1720
1721   info->Set(rss_symbol, Number::New(rss));
1722
1723   // V8 memory usage
1724   HeapStatistics v8_heap_stats;
1725   node_isolate->GetHeapStatistics(&v8_heap_stats);
1726   info->Set(heap_total_symbol,
1727             Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(),
1728                                      node_isolate));
1729   info->Set(heap_used_symbol,
1730             Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(),
1731                                      node_isolate));
1732
1733   args.GetReturnValue().Set(info);
1734 }
1735
1736
1737 void Kill(const FunctionCallbackInfo<Value>& args) {
1738   HandleScope scope(node_isolate);
1739
1740   if (args.Length() != 2) {
1741     return ThrowError("Bad argument.");
1742   }
1743
1744   int pid = args[0]->IntegerValue();
1745   int sig = args[1]->Int32Value();
1746   int err = uv_kill(pid, sig);
1747   args.GetReturnValue().Set(err);
1748 }
1749
1750 // used in Hrtime() below
1751 #define NANOS_PER_SEC 1000000000
1752
1753 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1754 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1755 // so this function instead returns an Array with 2 entries representing seconds
1756 // and nanoseconds, to avoid any integer overflow possibility.
1757 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1758 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1759   HandleScope scope(node_isolate);
1760
1761   uint64_t t = uv_hrtime();
1762
1763   if (args.Length() > 0) {
1764     // return a time diff tuple
1765     if (!args[0]->IsArray()) {
1766       return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1767     }
1768     Local<Array> inArray = Local<Array>::Cast(args[0]);
1769     uint64_t seconds = inArray->Get(0)->Uint32Value();
1770     uint64_t nanos = inArray->Get(1)->Uint32Value();
1771     t -= (seconds * NANOS_PER_SEC) + nanos;
1772   }
1773
1774   Local<Array> tuple = Array::New(2);
1775   tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1776   tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1777   args.GetReturnValue().Set(tuple);
1778 }
1779
1780
1781 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1782
1783 // DLOpen is process.dlopen(module, filename).
1784 // Used to load 'module.node' dynamically shared objects.
1785 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1786   HandleScope scope(node_isolate);
1787   char symbol[1024], *base, *pos;
1788   uv_lib_t lib;
1789   int r;
1790
1791   if (args.Length() < 2) {
1792     return ThrowError("process.dlopen takes exactly 2 arguments.");
1793   }
1794
1795   Local<Object> module = args[0]->ToObject();  // Cast
1796   String::Utf8Value filename(args[1]);  // Cast
1797
1798   if (exports_symbol.IsEmpty()) {
1799     exports_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "exports");
1800   }
1801   Local<Object> exports = module->Get(exports_symbol)->ToObject();
1802
1803   if (uv_dlopen(*filename, &lib)) {
1804     Local<String> errmsg = OneByteString(node_isolate, uv_dlerror(&lib));
1805 #ifdef _WIN32
1806     // Windows needs to add the filename into the error message
1807     errmsg = String::Concat(errmsg, args[1]->ToString());
1808 #endif  // _WIN32
1809     ThrowException(Exception::Error(errmsg));
1810     return;
1811   }
1812
1813   String::Utf8Value path(args[1]);
1814   base = *path;
1815
1816   /* Find the shared library filename within the full path. */
1817 #ifdef __POSIX__
1818   pos = strrchr(base, '/');
1819   if (pos != NULL) {
1820     base = pos + 1;
1821   }
1822 #else  // Windows
1823   for (;;) {
1824     pos = strpbrk(base, "\\/:");
1825     if (pos == NULL) {
1826       break;
1827     }
1828     base = pos + 1;
1829   }
1830 #endif  // __POSIX__
1831
1832   /* Strip the .node extension. */
1833   pos = strrchr(base, '.');
1834   if (pos != NULL) {
1835     *pos = '\0';
1836   }
1837
1838   /* Add the `_module` suffix to the extension name. */
1839   r = snprintf(symbol, sizeof symbol, "%s_module", base);
1840   if (r <= 0 || static_cast<size_t>(r) >= sizeof symbol) {
1841     return ThrowError("Out of memory.");
1842   }
1843
1844   /* Replace dashes with underscores. When loading foo-bar.node,
1845    * look for foo_bar_module, not foo-bar_module.
1846    */
1847   for (pos = symbol; *pos != '\0'; ++pos) {
1848     if (*pos == '-') *pos = '_';
1849   }
1850
1851   node_module_struct *mod;
1852   if (uv_dlsym(&lib, symbol, reinterpret_cast<void**>(&mod))) {
1853     char errmsg[1024];
1854     snprintf(errmsg, sizeof(errmsg), "Symbol %s not found.", symbol);
1855     return ThrowError(errmsg);
1856   }
1857
1858   if (mod->version != NODE_MODULE_VERSION) {
1859     char errmsg[1024];
1860     snprintf(errmsg,
1861              sizeof(errmsg),
1862              "Module version mismatch. Expected %d, got %d.",
1863              NODE_MODULE_VERSION, mod->version);
1864     return ThrowError(errmsg);
1865   }
1866
1867   // Execute the C++ module
1868   mod->register_func(exports, module);
1869
1870   // Tell coverity that 'handle' should not be freed when we return.
1871   // coverity[leaked_storage]
1872 }
1873
1874
1875 static void OnFatalError(const char* location, const char* message) {
1876   if (location) {
1877     fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
1878   } else {
1879     fprintf(stderr, "FATAL ERROR: %s\n", message);
1880   }
1881   fflush(stderr);
1882 #if defined(DEBUG)
1883   abort();
1884 #endif
1885   exit(5);
1886 }
1887
1888
1889 NO_RETURN void FatalError(const char* location, const char* message) {
1890   OnFatalError(location, message);
1891   // to supress compiler warning
1892   abort();
1893 }
1894
1895
1896 void FatalException(Handle<Value> error, Handle<Message> message) {
1897   HandleScope scope(node_isolate);
1898
1899   if (fatal_exception_symbol.IsEmpty()) {
1900     fatal_exception_symbol =
1901         FIXED_ONE_BYTE_STRING(node_isolate, "_fatalException");
1902   }
1903
1904   Local<Object> process = PersistentToLocal(node_isolate, process_p);
1905   Local<Value> fatal_v = process->Get(fatal_exception_symbol);
1906
1907   if (!fatal_v->IsFunction()) {
1908     // failed before the process._fatalException function was added!
1909     // this is probably pretty bad.  Nothing to do but report and exit.
1910     ReportException(error, message);
1911     exit(6);
1912   }
1913
1914   Local<Function> fatal_f = Local<Function>::Cast(fatal_v);
1915
1916   TryCatch fatal_try_catch;
1917
1918   // Do not call FatalException when _fatalException handler throws
1919   fatal_try_catch.SetVerbose(false);
1920
1921   // this will return true if the JS layer handled it, false otherwise
1922   Local<Value> caught = fatal_f->Call(process, 1, &error);
1923
1924   if (fatal_try_catch.HasCaught()) {
1925     // the fatal exception function threw, so we must exit
1926     ReportException(fatal_try_catch);
1927     exit(7);
1928   }
1929
1930   if (false == caught->BooleanValue()) {
1931     ReportException(error, message);
1932     exit(8);
1933   }
1934 }
1935
1936
1937 void FatalException(const TryCatch& try_catch) {
1938   HandleScope scope(node_isolate);
1939   // TODO(bajtos) do not call FatalException if try_catch is verbose
1940   // (requires V8 API to expose getter for try_catch.is_verbose_)
1941   FatalException(try_catch.Exception(), try_catch.Message());
1942 }
1943
1944
1945 void OnMessage(Handle<Message> message, Handle<Value> error) {
1946   // The current version of V8 sends messages for errors only
1947   // (thus `error` is always set).
1948   FatalException(error, message);
1949 }
1950
1951
1952 static void Binding(const FunctionCallbackInfo<Value>& args) {
1953   HandleScope scope(node_isolate);
1954
1955   Local<String> module = args[0]->ToString();
1956   String::Utf8Value module_v(module);
1957   node_module_struct* modp;
1958
1959   Local<Object> cache = PersistentToLocal(node_isolate, binding_cache);
1960   Local<Object> exports;
1961
1962   if (cache->Has(module)) {
1963     exports = cache->Get(module)->ToObject();
1964     args.GetReturnValue().Set(exports);
1965     return;
1966   }
1967
1968   // Append a string to process.moduleLoadList
1969   char buf[1024];
1970   snprintf(buf, sizeof(buf), "Binding %s", *module_v);
1971
1972   Local<Array> modules = PersistentToLocal(node_isolate, module_load_list);
1973   uint32_t l = modules->Length();
1974   modules->Set(l, OneByteString(node_isolate, buf));
1975
1976   if ((modp = get_builtin_module(*module_v)) != NULL) {
1977     exports = Object::New();
1978     // Internal bindings don't have a "module" object,
1979     // only exports.
1980     modp->register_func(exports, Undefined(node_isolate));
1981     cache->Set(module, exports);
1982   } else if (!strcmp(*module_v, "constants")) {
1983     exports = Object::New();
1984     DefineConstants(exports);
1985     cache->Set(module, exports);
1986   } else if (!strcmp(*module_v, "natives")) {
1987     exports = Object::New();
1988     DefineJavaScript(exports);
1989     cache->Set(module, exports);
1990   } else {
1991     return ThrowError("No such module");
1992   }
1993
1994   args.GetReturnValue().Set(exports);
1995 }
1996
1997
1998 static void ProcessTitleGetter(Local<String> property,
1999                                const PropertyCallbackInfo<Value>& info) {
2000   HandleScope scope(node_isolate);
2001   char buffer[512];
2002   uv_get_process_title(buffer, sizeof(buffer));
2003   info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2004 }
2005
2006
2007 static void ProcessTitleSetter(Local<String> property,
2008                                Local<Value> value,
2009                                const PropertyCallbackInfo<void>& info) {
2010   HandleScope scope(node_isolate);
2011   String::Utf8Value title(value);
2012   // TODO(piscisaureus): protect with a lock
2013   uv_set_process_title(*title);
2014 }
2015
2016
2017 static void EnvGetter(Local<String> property,
2018                       const PropertyCallbackInfo<Value>& info) {
2019   HandleScope scope(node_isolate);
2020 #ifdef __POSIX__
2021   String::Utf8Value key(property);
2022   const char* val = getenv(*key);
2023   if (val) {
2024     return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2025   }
2026 #else  // _WIN32
2027   String::Value key(property);
2028   WCHAR buffer[32767];  // The maximum size allowed for environment variables.
2029   DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2030                                          buffer,
2031                                          ARRAY_SIZE(buffer));
2032   // If result >= sizeof buffer the buffer was too small. That should never
2033   // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2034   // not found.
2035   if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2036       result < ARRAY_SIZE(buffer)) {
2037     const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2038     Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2039     return info.GetReturnValue().Set(rc);
2040   }
2041 #endif
2042   // Not found.  Fetch from prototype.
2043   info.GetReturnValue().Set(
2044       info.Data().As<Object>()->Get(property));
2045 }
2046
2047
2048 static void EnvSetter(Local<String> property,
2049                       Local<Value> value,
2050                       const PropertyCallbackInfo<Value>& info) {
2051   HandleScope scope(node_isolate);
2052 #ifdef __POSIX__
2053   String::Utf8Value key(property);
2054   String::Utf8Value val(value);
2055   setenv(*key, *val, 1);
2056 #else  // _WIN32
2057   String::Value key(property);
2058   String::Value val(value);
2059   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2060   // Environment variables that start with '=' are read-only.
2061   if (key_ptr[0] != L'=') {
2062     SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2063   }
2064 #endif
2065   // Whether it worked or not, always return rval.
2066   info.GetReturnValue().Set(value);
2067 }
2068
2069
2070 static void EnvQuery(Local<String> property,
2071                      const PropertyCallbackInfo<Integer>& info) {
2072   HandleScope scope(node_isolate);
2073   int32_t rc = -1;  // Not found unless proven otherwise.
2074 #ifdef __POSIX__
2075   String::Utf8Value key(property);
2076   if (getenv(*key)) rc = 0;
2077 #else  // _WIN32
2078   String::Value key(property);
2079   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2080   if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2081       GetLastError() == ERROR_SUCCESS) {
2082     rc = 0;
2083     if (key_ptr[0] == L'=') {
2084       // Environment variables that start with '=' are hidden and read-only.
2085       rc = static_cast<int32_t>(v8::ReadOnly) |
2086            static_cast<int32_t>(v8::DontDelete) |
2087            static_cast<int32_t>(v8::DontEnum);
2088     }
2089   }
2090 #endif
2091   if (rc != -1) info.GetReturnValue().Set(rc);
2092 }
2093
2094
2095 static void EnvDeleter(Local<String> property,
2096                        const PropertyCallbackInfo<Boolean>& info) {
2097   HandleScope scope(node_isolate);
2098   bool rc = true;
2099 #ifdef __POSIX__
2100   String::Utf8Value key(property);
2101   rc = getenv(*key) != NULL;
2102   if (rc) unsetenv(*key);
2103 #else
2104   String::Value key(property);
2105   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2106   if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2107     // Deletion failed. Return true if the key wasn't there in the first place,
2108     // false if it is still there.
2109     rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2110          GetLastError() != ERROR_SUCCESS;
2111   }
2112 #endif
2113   info.GetReturnValue().Set(rc);
2114 }
2115
2116
2117 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2118   HandleScope scope(node_isolate);
2119 #ifdef __POSIX__
2120   int size = 0;
2121   while (environ[size]) size++;
2122
2123   Local<Array> env = Array::New(size);
2124
2125   for (int i = 0; i < size; ++i) {
2126     const char* var = environ[i];
2127     const char* s = strchr(var, '=');
2128     const int length = s ? s - var : strlen(var);
2129     Local<String> name = String::NewFromUtf8(node_isolate,
2130                                              var,
2131                                              String::kNormalString,
2132                                              length);
2133     env->Set(i, name);
2134   }
2135 #else  // _WIN32
2136   WCHAR* environment = GetEnvironmentStringsW();
2137   if (environment == NULL) return;  // This should not happen.
2138   Local<Array> env = Array::New();
2139   WCHAR* p = environment;
2140   int i = 0;
2141   while (*p != NULL) {
2142     WCHAR *s;
2143     if (*p == L'=') {
2144       // If the key starts with '=' it is a hidden environment variable.
2145       p += wcslen(p) + 1;
2146       continue;
2147     } else {
2148       s = wcschr(p, L'=');
2149     }
2150     if (!s) {
2151       s = p + wcslen(p);
2152     }
2153     const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2154     const size_t two_byte_buffer_len = s - p;
2155     Local<String> value = String::NewFromTwoByte(node_isolate,
2156                                                  two_byte_buffer,
2157                                                  String::kNormalString,
2158                                                  two_byte_buffer_len);
2159     env->Set(i++, value);
2160     p = s + wcslen(s) + 1;
2161   }
2162   FreeEnvironmentStringsW(environment);
2163 #endif
2164
2165   info.GetReturnValue().Set(env);
2166 }
2167
2168
2169 static Handle<Object> GetFeatures() {
2170   HandleScope scope(node_isolate);
2171
2172   Local<Object> obj = Object::New();
2173 #if defined(DEBUG) && DEBUG
2174   Local<Value> debug = True(node_isolate);
2175 #else
2176   Local<Value> debug = False(node_isolate);
2177 #endif  // defined(DEBUG) && DEBUG
2178
2179   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2180
2181   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2182   // TODO(bnoordhuis) ping libuv
2183   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2184
2185   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"),
2186            Boolean::New(use_npn));
2187   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"),
2188            Boolean::New(use_sni));
2189   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2190            Boolean::New(get_builtin_module("crypto") != NULL));
2191
2192   return scope.Close(obj);
2193 }
2194
2195
2196 static void DebugPortGetter(Local<String> property,
2197                             const PropertyCallbackInfo<Value>& info) {
2198   HandleScope scope(node_isolate);
2199   info.GetReturnValue().Set(debug_port);
2200 }
2201
2202
2203 static void DebugPortSetter(Local<String> property,
2204                             Local<Value> value,
2205                             const PropertyCallbackInfo<void>& info) {
2206   HandleScope scope(node_isolate);
2207   debug_port = value->NumberValue();
2208 }
2209
2210
2211 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2212 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2213 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2214
2215
2216 void NeedImmediateCallbackGetter(Local<String> property,
2217                                  const PropertyCallbackInfo<Value>& info) {
2218   info.GetReturnValue().Set(need_immediate_cb);
2219 }
2220
2221
2222 static void NeedImmediateCallbackSetter(Local<String> property,
2223                                         Local<Value> value,
2224                                         const PropertyCallbackInfo<void>&) {
2225   HandleScope scope(node_isolate);
2226
2227   bool bool_value = value->BooleanValue();
2228
2229   if (need_immediate_cb == bool_value) return;
2230
2231   need_immediate_cb = bool_value;
2232
2233   if (need_immediate_cb) {
2234     uv_check_start(&check_immediate_watcher, node::CheckImmediate);
2235     // idle handle is needed only to maintain event loop
2236     uv_idle_start(&idle_immediate_dummy, node::IdleImmediateDummy);
2237   } else {
2238     uv_check_stop(&check_immediate_watcher);
2239     uv_idle_stop(&idle_immediate_dummy);
2240   }
2241 }
2242
2243
2244 #define READONLY_PROPERTY(obj, str, var)                                      \
2245   do {                                                                        \
2246     obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly);            \
2247   } while (0)
2248
2249
2250 Handle<Object> SetupProcessObject(int argc, char *argv[]) {
2251   HandleScope scope(node_isolate);
2252
2253   int i, j;
2254
2255   Local<FunctionTemplate> process_template = FunctionTemplate::New();
2256   process_template->SetClassName(
2257       FIXED_ONE_BYTE_STRING(node_isolate, "process"));
2258
2259   Local<Object> process = process_template->GetFunction()->NewInstance();
2260   assert(process.IsEmpty() == false);
2261   assert(process->IsObject() == true);
2262
2263   process_p.Reset(node_isolate, process);
2264
2265   process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2266                        ProcessTitleGetter,
2267                        ProcessTitleSetter);
2268
2269   // process.version
2270   READONLY_PROPERTY(process,
2271                     "version",
2272                     FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2273
2274   // process.moduleLoadList
2275   Local<Array> modules = Array::New();
2276   module_load_list.Reset(node_isolate, modules);
2277   READONLY_PROPERTY(process, "moduleLoadList", modules);
2278
2279   // process.versions
2280   Local<Object> versions = Object::New();
2281   READONLY_PROPERTY(process, "versions", versions);
2282
2283   const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2284                                      "."
2285                                      NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2286   READONLY_PROPERTY(versions,
2287                     "http_parser",
2288                     FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2289
2290   // +1 to get rid of the leading 'v'
2291   READONLY_PROPERTY(versions,
2292                     "node",
2293                     OneByteString(node_isolate, NODE_VERSION + 1));
2294   READONLY_PROPERTY(versions,
2295                     "v8",
2296                     OneByteString(node_isolate, V8::GetVersion()));
2297   READONLY_PROPERTY(versions,
2298                     "uv",
2299                     OneByteString(node_isolate, uv_version_string()));
2300   READONLY_PROPERTY(versions,
2301                     "zlib",
2302                     FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2303
2304   const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2305   READONLY_PROPERTY(versions,
2306                     "modules",
2307                     FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2308
2309 #if HAVE_OPENSSL
2310   // Stupid code to slice out the version string.
2311   int c, l = strlen(OPENSSL_VERSION_TEXT);
2312   for (i = j = 0; i < l; i++) {
2313     c = OPENSSL_VERSION_TEXT[i];
2314     if ('0' <= c && c <= '9') {
2315       for (j = i + 1; j < l; j++) {
2316         c = OPENSSL_VERSION_TEXT[j];
2317         if (c == ' ') break;
2318       }
2319       break;
2320     }
2321   }
2322   READONLY_PROPERTY(
2323       versions,
2324       "openssl",
2325       OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2326 #endif
2327
2328
2329
2330   // process.arch
2331   READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2332
2333   // process.platform
2334   READONLY_PROPERTY(process,
2335                     "platform",
2336                     OneByteString(node_isolate, PLATFORM));
2337
2338   // process.argv
2339   Local<Array> arguments = Array::New(argc - option_end_index + 1);
2340   arguments->Set(0, String::NewFromUtf8(node_isolate, argv[0]));
2341   for (j = 1, i = option_end_index; i < argc; j++, i++) {
2342     arguments->Set(j, String::NewFromUtf8(node_isolate, argv[i]));
2343   }
2344   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2345
2346   // process.execArgv
2347   Local<Array> exec_argv = Array::New(option_end_index - 1);
2348   for (j = 1, i = 0; j < option_end_index; j++, i++) {
2349     exec_argv->Set(i, String::NewFromUtf8(node_isolate, argv[j]));
2350   }
2351   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_argv);
2352
2353   // create process.env
2354   Local<ObjectTemplate> envTemplate = ObjectTemplate::New();
2355   envTemplate->SetNamedPropertyHandler(EnvGetter,
2356                                        EnvSetter,
2357                                        EnvQuery,
2358                                        EnvDeleter,
2359                                        EnvEnumerator,
2360                                        Object::New());
2361   Local<Object> env = envTemplate->NewInstance();
2362   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), env);
2363
2364   READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2365   READONLY_PROPERTY(process, "features", GetFeatures());
2366   process->SetAccessor(
2367       FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2368       NeedImmediateCallbackGetter,
2369       NeedImmediateCallbackSetter);
2370
2371   // -e, --eval
2372   if (eval_string) {
2373     READONLY_PROPERTY(process,
2374                       "_eval",
2375                       String::NewFromUtf8(node_isolate, eval_string));
2376   }
2377
2378   // -p, --print
2379   if (print_eval) {
2380     READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2381   }
2382
2383   // -i, --interactive
2384   if (force_repl) {
2385     READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2386   }
2387
2388   // --no-deprecation
2389   if (no_deprecation) {
2390     READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2391   }
2392
2393   // --throw-deprecation
2394   if (throw_deprecation) {
2395     READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2396   }
2397
2398   // --trace-deprecation
2399   if (trace_deprecation) {
2400     READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2401   }
2402
2403   size_t exec_path_len = 2 * PATH_MAX;
2404   char* exec_path = new char[exec_path_len];
2405   Local<String> exec_path_value;
2406   if (uv_exepath(exec_path, &exec_path_len) == 0) {
2407     exec_path_value = String::NewFromUtf8(node_isolate,
2408                                           exec_path,
2409                                           String::kNormalString,
2410                                           exec_path_len);
2411   } else {
2412     exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2413   }
2414   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2415                exec_path_value);
2416   delete[] exec_path;
2417
2418   process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2419                        DebugPortGetter,
2420                        DebugPortSetter);
2421
2422   // define various internal methods
2423   NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2424   NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2425   NODE_SET_METHOD(process, "reallyExit", Exit);
2426   NODE_SET_METHOD(process, "abort", Abort);
2427   NODE_SET_METHOD(process, "chdir", Chdir);
2428   NODE_SET_METHOD(process, "cwd", Cwd);
2429
2430   NODE_SET_METHOD(process, "umask", Umask);
2431
2432 #if defined(__POSIX__) && !defined(__ANDROID__)
2433   NODE_SET_METHOD(process, "getuid", GetUid);
2434   NODE_SET_METHOD(process, "setuid", SetUid);
2435
2436   NODE_SET_METHOD(process, "setgid", SetGid);
2437   NODE_SET_METHOD(process, "getgid", GetGid);
2438
2439   NODE_SET_METHOD(process, "getgroups", GetGroups);
2440   NODE_SET_METHOD(process, "setgroups", SetGroups);
2441   NODE_SET_METHOD(process, "initgroups", InitGroups);
2442 #endif  // __POSIX__ && !defined(__ANDROID__)
2443
2444   NODE_SET_METHOD(process, "_kill", Kill);
2445
2446   NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2447   NODE_SET_METHOD(process, "_debugPause", DebugPause);
2448   NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2449
2450   NODE_SET_METHOD(process, "hrtime", Hrtime);
2451
2452   NODE_SET_METHOD(process, "dlopen", DLOpen);
2453
2454   NODE_SET_METHOD(process, "uptime", Uptime);
2455   NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2456
2457   NODE_SET_METHOD(process, "binding", Binding);
2458
2459   NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2460
2461   // values use to cross communicate with processNextTick
2462   Local<Object> info_box = Object::New();
2463   info_box->SetIndexedPropertiesToExternalArrayData(&tick_infobox,
2464                                                     kExternalUnsignedIntArray,
2465                                                     4);
2466   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfoBox"), info_box);
2467
2468   // pre-set _events object for faster emit checks
2469   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2470
2471   return scope.Close(process);
2472 }
2473
2474
2475 #undef READONLY_PROPERTY
2476
2477
2478 static void AtExit() {
2479   uv_tty_reset_mode();
2480 }
2481
2482
2483 static void SignalExit(int signal) {
2484   uv_tty_reset_mode();
2485   _exit(128 + signal);
2486 }
2487
2488
2489 void Load(Handle<Object> process_l) {
2490   HandleScope handle_scope(node_isolate);
2491
2492   process_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "process");
2493   domain_symbol = FIXED_ONE_BYTE_STRING(node_isolate, "domain");
2494
2495   // Compile, execute the src/node.js file. (Which was included as static C
2496   // string in node_natives.h. 'natve_node' is the string containing that
2497   // source code.)
2498
2499   // The node.js file returns a function 'f'
2500   atexit(AtExit);
2501
2502   TryCatch try_catch;
2503
2504   // Disable verbose mode to stop FatalException() handler from trying
2505   // to handle the exception. Errors this early in the start-up phase
2506   // are not safe to ignore.
2507   try_catch.SetVerbose(false);
2508
2509   Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2510   Local<Value> f_value = ExecuteString(MainSource(), script_name);
2511   if (try_catch.HasCaught())  {
2512     ReportException(try_catch);
2513     exit(10);
2514   }
2515   assert(f_value->IsFunction());
2516   Local<Function> f = Local<Function>::Cast(f_value);
2517
2518   // Now we call 'f' with the 'process' variable that we've built up with
2519   // all our bindings. Inside node.js we'll take care of assigning things to
2520   // their places.
2521
2522   // We start the process this way in order to be more modular. Developers
2523   // who do not like how 'src/node.js' setups the module system but do like
2524   // Node's I/O bindings may want to replace 'f' with their own function.
2525
2526   // Add a reference to the global object
2527   Local<Object> global = v8::Context::GetCurrent()->Global();
2528
2529 #if defined HAVE_DTRACE || defined HAVE_ETW || defined HAVE_SYSTEMTAP
2530   InitDTrace(global);
2531 #endif
2532
2533 #if defined HAVE_PERFCTR
2534   InitPerfCounters(global);
2535 #endif
2536
2537   // Enable handling of uncaught exceptions
2538   // (FatalException(), break on uncaught exception in debugger)
2539   //
2540   // This is not strictly necessary since it's almost impossible
2541   // to attach the debugger fast enought to break on exception
2542   // thrown during process startup.
2543   try_catch.SetVerbose(true);
2544
2545   Local<Value> arg = process_l;
2546   f->Call(global, 1, &arg);
2547 }
2548
2549 static void PrintHelp();
2550
2551 static void ParseDebugOpt(const char* arg) {
2552   const char *p = 0;
2553
2554   if (strstr(arg, "--debug-port=") == arg) {
2555     p = 1 + strchr(arg, '=');
2556     debug_port = atoi(p);
2557   } else {
2558     use_debug_agent = true;
2559     if (!strcmp(arg, "--debug-brk")) {
2560       debug_wait_connect = true;
2561       return;
2562     } else if (!strcmp(arg, "--debug")) {
2563       return;
2564     } else if (strstr(arg, "--debug-brk=") == arg) {
2565       debug_wait_connect = true;
2566       p = 1 + strchr(arg, '=');
2567       debug_port = atoi(p);
2568     } else if (strstr(arg, "--debug=") == arg) {
2569       p = 1 + strchr(arg, '=');
2570       debug_port = atoi(p);
2571     }
2572   }
2573   if (p && debug_port > 1024 && debug_port <  65536)
2574       return;
2575
2576   fprintf(stderr, "Bad debug option.\n");
2577   if (p) fprintf(stderr, "Debug port must be in range 1025 to 65535.\n");
2578
2579   PrintHelp();
2580   exit(12);
2581 }
2582
2583 static void PrintHelp() {
2584   printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2585          "       node debug script.js [arguments] \n"
2586          "\n"
2587          "Options:\n"
2588          "  -v, --version        print node's version\n"
2589          "  -e, --eval script    evaluate script\n"
2590          "  -p, --print          evaluate script and print result\n"
2591          "  -i, --interactive    always enter the REPL even if stdin\n"
2592          "                       does not appear to be a terminal\n"
2593          "  --no-deprecation     silence deprecation warnings\n"
2594          "  --trace-deprecation  show stack traces on deprecations\n"
2595          "  --v8-options         print v8 command line options\n"
2596          "  --max-stack-size=val set max v8 stack size (bytes)\n"
2597          "\n"
2598          "Environment variables:\n"
2599 #ifdef _WIN32
2600          "NODE_PATH              ';'-separated list of directories\n"
2601 #else
2602          "NODE_PATH              ':'-separated list of directories\n"
2603 #endif
2604          "                       prefixed to the module search path.\n"
2605          "NODE_MODULE_CONTEXTS   Set to 1 to load modules in their own\n"
2606          "                       global contexts.\n"
2607          "NODE_DISABLE_COLORS    Set to 1 to disable colors in the REPL\n"
2608          "\n"
2609          "Documentation can be found at http://nodejs.org/\n");
2610 }
2611
2612
2613 // Parse node command line arguments.
2614 static void ParseArgs(int argc, char **argv) {
2615   int i;
2616
2617   // TODO(bnoordhuis) use parse opts
2618   for (i = 1; i < argc; i++) {
2619     const char *arg = argv[i];
2620     if (strstr(arg, "--debug") == arg) {
2621       ParseDebugOpt(arg);
2622       argv[i] = const_cast<char*>("");
2623     } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2624       printf("%s\n", NODE_VERSION);
2625       exit(0);
2626     } else if (strstr(arg, "--max-stack-size=") == arg) {
2627       const char *p = 0;
2628       p = 1 + strchr(arg, '=');
2629       max_stack_size = atoi(p);
2630       argv[i] = const_cast<char*>("");
2631     } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2632       PrintHelp();
2633       exit(0);
2634     } else if (strcmp(arg, "--eval") == 0   ||
2635                strcmp(arg, "-e") == 0       ||
2636                strcmp(arg, "--print") == 0  ||
2637                strcmp(arg, "-pe") == 0      ||
2638                strcmp(arg, "-p") == 0) {
2639       bool is_eval = strchr(arg, 'e') != NULL;
2640       bool is_print = strchr(arg, 'p') != NULL;
2641
2642       // argument to -p and --print is optional
2643       if (is_eval == true && i + 1 >= argc) {
2644         fprintf(stderr, "Error: %s requires an argument\n", arg);
2645         exit(13);
2646       }
2647
2648       print_eval = print_eval || is_print;
2649       argv[i] = const_cast<char*>("");
2650
2651       // --eval, -e and -pe always require an argument
2652       if (is_eval == true) {
2653         eval_string = argv[++i];
2654         continue;
2655       }
2656
2657       // next arg is the expression to evaluate unless it starts with:
2658       //  - a dash, then it's another switch
2659       //  - "\\-", then it's an escaped expression, drop the backslash
2660       if (argv[i + 1] == NULL) continue;
2661       if (argv[i + 1][0] == '-') continue;
2662       eval_string = argv[++i];
2663       if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string;
2664     } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2665       force_repl = true;
2666       argv[i] = const_cast<char*>("");
2667     } else if (strcmp(arg, "--v8-options") == 0) {
2668       argv[i] = const_cast<char*>("--help");
2669     } else if (strcmp(arg, "--no-deprecation") == 0) {
2670       argv[i] = const_cast<char*>("");
2671       no_deprecation = true;
2672     } else if (strcmp(arg, "--trace-deprecation") == 0) {
2673       argv[i] = const_cast<char*>("");
2674       trace_deprecation = true;
2675     } else if (strcmp(arg, "--throw-deprecation") == 0) {
2676       argv[i] = const_cast<char*>("");
2677       throw_deprecation = true;
2678     } else if (argv[i][0] != '-') {
2679       break;
2680     }
2681   }
2682
2683   option_end_index = i;
2684 }
2685
2686
2687 // Called from the main thread.
2688 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2689   v8::Debug::ProcessDebugMessages();
2690 }
2691
2692
2693 // Called from V8 Debug Agent TCP thread.
2694 static void DispatchMessagesDebugAgentCallback() {
2695   uv_async_send(&dispatch_debug_messages_async);
2696 }
2697
2698
2699 // Called from the main thread
2700 static void EmitDebugEnabledAsyncCallback(uv_async_t* handle, int status) {
2701   HandleScope handle_scope(node_isolate);
2702   Local<Object> obj = Object::New();
2703   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "cmd"),
2704            FIXED_ONE_BYTE_STRING(node_isolate, "NODE_DEBUG_ENABLED"));
2705   Local<Value> args[] = {
2706     FIXED_ONE_BYTE_STRING(node_isolate, "internalMessage"),
2707     obj
2708   };
2709   MakeCallback(process_p, "emit", ARRAY_SIZE(args), args);
2710 }
2711
2712
2713 // Called from the signal watcher callback
2714 static void EmitDebugEnabled() {
2715   uv_async_send(&emit_debug_enabled_async);
2716 }
2717
2718
2719 static void EnableDebug(bool wait_connect) {
2720   // If we're called from another thread, make sure to enter the right
2721   // v8 isolate.
2722   node_isolate->Enter();
2723
2724   v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2725                                             false);
2726
2727   // Start the debug thread and it's associated TCP server on port 5858.
2728   bool r = v8::Debug::EnableAgent("node " NODE_VERSION,
2729                                   debug_port,
2730                                   wait_connect);
2731
2732   // Crappy check that everything went well. FIXME
2733   assert(r);
2734
2735   // Print out some information.
2736   fprintf(stderr, "debugger listening on port %d\n", debug_port);
2737   fflush(stderr);
2738
2739   debugger_running = true;
2740
2741   // Do not emit NODE_DEBUG_ENABLED when debugger is enabled before starting
2742   // the main process (i.e. when called via `node --debug`)
2743   if (!process_p.IsEmpty())
2744     EmitDebugEnabled();
2745
2746   node_isolate->Exit();
2747 }
2748
2749
2750 #ifdef __POSIX__
2751 static void EnableDebugSignalHandler(uv_signal_t* handle, int) {
2752   // Break once process will return execution to v8
2753   v8::Debug::DebugBreak(node_isolate);
2754
2755   if (!debugger_running) {
2756     fprintf(stderr, "Hit SIGUSR1 - starting debugger agent.\n");
2757     EnableDebug(false);
2758   }
2759 }
2760
2761
2762 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
2763   struct sigaction sa;
2764
2765   memset(&sa, 0, sizeof(sa));
2766   sa.sa_handler = handler;
2767   sigfillset(&sa.sa_mask);
2768   sigaction(signal, &sa, NULL);
2769 }
2770
2771
2772 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2773   HandleScope scope(node_isolate);
2774
2775   if (args.Length() != 1) {
2776     return ThrowError("Invalid number of arguments.");
2777   }
2778
2779   pid_t pid;
2780   int r;
2781
2782   pid = args[0]->IntegerValue();
2783   r = kill(pid, SIGUSR1);
2784   if (r != 0) {
2785     return ThrowErrnoException(errno, "kill");
2786   }
2787 }
2788 #endif  // __POSIX__
2789
2790
2791 #ifdef _WIN32
2792 DWORD WINAPI EnableDebugThreadProc(void* arg) {
2793   // Break once process will return execution to v8
2794   if (!debugger_running) {
2795     for (int i = 0; i < 1; i++) {
2796       fprintf(stderr, "Starting debugger agent.\r\n");
2797       fflush(stderr);
2798       EnableDebug(false);
2799     }
2800   }
2801
2802   v8::Debug::DebugBreak(node_isolate);
2803
2804   return 0;
2805 }
2806
2807
2808 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
2809     size_t buf_len) {
2810   return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
2811 }
2812
2813
2814 static int RegisterDebugSignalHandler() {
2815   wchar_t mapping_name[32];
2816   HANDLE mapping_handle;
2817   DWORD pid;
2818   LPTHREAD_START_ROUTINE* handler;
2819
2820   pid = GetCurrentProcessId();
2821
2822   if (GetDebugSignalHandlerMappingName(pid,
2823                                        mapping_name,
2824                                        ARRAY_SIZE(mapping_name)) < 0) {
2825     return -1;
2826   }
2827
2828   mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
2829                                       NULL,
2830                                       PAGE_READWRITE,
2831                                       0,
2832                                       sizeof *handler,
2833                                       mapping_name);
2834   if (mapping_handle == NULL) {
2835     return -1;
2836   }
2837
2838   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2839       MapViewOfFile(mapping_handle,
2840                     FILE_MAP_ALL_ACCESS,
2841                     0,
2842                     0,
2843                     sizeof *handler));
2844   if (handler == NULL) {
2845     CloseHandle(mapping_handle);
2846     return -1;
2847   }
2848
2849   *handler = EnableDebugThreadProc;
2850
2851   UnmapViewOfFile(static_cast<void*>(handler));
2852
2853   return 0;
2854 }
2855
2856
2857 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
2858   HandleScope scope(node_isolate);
2859   DWORD pid;
2860   HANDLE process = NULL;
2861   HANDLE thread = NULL;
2862   HANDLE mapping = NULL;
2863   wchar_t mapping_name[32];
2864   LPTHREAD_START_ROUTINE* handler = NULL;
2865
2866   if (args.Length() != 1) {
2867     ThrowError("Invalid number of arguments.");
2868     goto out;
2869   }
2870
2871   pid = (DWORD) args[0]->IntegerValue();
2872
2873   process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
2874                             PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
2875                             PROCESS_VM_READ,
2876                         FALSE,
2877                         pid);
2878   if (process == NULL) {
2879     ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
2880     goto out;
2881   }
2882
2883   if (GetDebugSignalHandlerMappingName(pid,
2884                                        mapping_name,
2885                                        ARRAY_SIZE(mapping_name)) < 0) {
2886     ThrowErrnoException(errno, "sprintf");
2887     goto out;
2888   }
2889
2890   mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
2891   if (mapping == NULL) {
2892     ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
2893     goto out;
2894   }
2895
2896   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
2897       MapViewOfFile(mapping,
2898                     FILE_MAP_READ,
2899                     0,
2900                     0,
2901                     sizeof *handler));
2902   if (handler == NULL || *handler == NULL) {
2903     ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
2904     goto out;
2905   }
2906
2907   thread = CreateRemoteThread(process,
2908                               NULL,
2909                               0,
2910                               *handler,
2911                               NULL,
2912                               0,
2913                               NULL);
2914   if (thread == NULL) {
2915     ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
2916     goto out;
2917   }
2918
2919   // Wait for the thread to terminate
2920   if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
2921     ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
2922     goto out;
2923   }
2924
2925  out:
2926   if (process != NULL)
2927     CloseHandle(process);
2928   if (thread != NULL)
2929     CloseHandle(thread);
2930   if (handler != NULL)
2931     UnmapViewOfFile(handler);
2932   if (mapping != NULL)
2933     CloseHandle(mapping);
2934 }
2935 #endif  // _WIN32
2936
2937
2938 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
2939   v8::Debug::DebugBreak(node_isolate);
2940 }
2941
2942
2943 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
2944   if (debugger_running) {
2945     v8::Debug::DisableAgent();
2946     debugger_running = false;
2947   }
2948 }
2949
2950
2951 char** Init(int argc, char *argv[]) {
2952   // Initialize prog_start_time to get relative uptime.
2953   uv_uptime(&prog_start_time);
2954
2955   // Make inherited handles noninheritable.
2956   uv_disable_stdio_inheritance();
2957
2958   // init async debug messages dispatching
2959   uv_async_init(uv_default_loop(),
2960                 &dispatch_debug_messages_async,
2961                 DispatchDebugMessagesAsyncCallback);
2962   uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
2963
2964   // init async NODE_DEBUG_ENABLED emitter
2965   uv_async_init(uv_default_loop(),
2966                 &emit_debug_enabled_async,
2967                 EmitDebugEnabledAsyncCallback);
2968   uv_unref(reinterpret_cast<uv_handle_t*>(&emit_debug_enabled_async));
2969
2970   // Parse a few arguments which are specific to Node.
2971   node::ParseArgs(argc, argv);
2972   // Parse the rest of the args (up to the 'option_end_index' (where '--' was
2973   // in the command line))
2974   int v8argc = option_end_index;
2975   char **v8argv = argv;
2976
2977   if (debug_wait_connect) {
2978     // v8argv is a copy of argv up to the script file argument +2 if --debug-brk
2979     // to expose the v8 debugger js object so that node.js can set
2980     // a breakpoint on the first line of the startup script
2981     v8argc += 2;
2982     v8argv = new char*[v8argc];
2983     memcpy(v8argv, argv, sizeof(*argv) * option_end_index);
2984     v8argv[option_end_index] = const_cast<char*>("--expose_debug_as");
2985     v8argv[option_end_index + 1] = const_cast<char*>("v8debug");
2986   }
2987
2988   // For the normal stack which moves from high to low addresses when frames
2989   // are pushed, we can compute the limit as stack_size bytes below the
2990   // the address of a stack variable (e.g. &stack_var) as an approximation
2991   // of the start of the stack (we're assuming that we haven't pushed a lot
2992   // of frames yet).
2993   if (max_stack_size != 0) {
2994     uint32_t stack_var;
2995     ResourceConstraints constraints;
2996
2997     uint32_t *stack_limit = &stack_var - (max_stack_size / sizeof(uint32_t));
2998     constraints.set_stack_limit(stack_limit);
2999     SetResourceConstraints(&constraints);  // Must be done before V8::Initialize
3000   }
3001   V8::SetFlagsFromCommandLine(&v8argc, v8argv, false);
3002
3003   const char typed_arrays_flag[] = "--harmony_typed_arrays";
3004   V8::SetFlagsFromString(typed_arrays_flag, sizeof(typed_arrays_flag) - 1);
3005   V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3006
3007   // Fetch a reference to the main isolate, so we have a reference to it
3008   // even when we need it to access it from another (debugger) thread.
3009   node_isolate = Isolate::GetCurrent();
3010
3011 #ifdef __POSIX__
3012   // Ignore SIGPIPE
3013   RegisterSignalHandler(SIGPIPE, SIG_IGN);
3014   RegisterSignalHandler(SIGINT, SignalExit);
3015   RegisterSignalHandler(SIGTERM, SignalExit);
3016 #endif  // __POSIX__
3017
3018   uv_check_init(uv_default_loop(), &check_immediate_watcher);
3019   uv_unref(reinterpret_cast<uv_handle_t*>(&check_immediate_watcher));
3020   uv_idle_init(uv_default_loop(), &idle_immediate_dummy);
3021
3022   V8::SetFatalErrorHandler(node::OnFatalError);
3023   V8::AddMessageListener(OnMessage);
3024
3025   // If the --debug flag was specified then initialize the debug thread.
3026   if (use_debug_agent) {
3027     EnableDebug(debug_wait_connect);
3028   } else {
3029 #ifdef _WIN32
3030     RegisterDebugSignalHandler();
3031 #else  // Posix
3032     static uv_signal_t signal_watcher;
3033     uv_signal_init(uv_default_loop(), &signal_watcher);
3034     uv_signal_start(&signal_watcher, EnableDebugSignalHandler, SIGUSR1);
3035     uv_unref(reinterpret_cast<uv_handle_t*>(&signal_watcher));
3036 #endif  // __POSIX__
3037   }
3038
3039   return argv;
3040 }
3041
3042
3043 struct AtExitCallback {
3044   AtExitCallback* next_;
3045   void (*cb_)(void* arg);
3046   void* arg_;
3047 };
3048
3049 static AtExitCallback* at_exit_functions_;
3050
3051
3052 void RunAtExit() {
3053   AtExitCallback* p = at_exit_functions_;
3054   at_exit_functions_ = NULL;
3055
3056   while (p) {
3057     AtExitCallback* q = p->next_;
3058     p->cb_(p->arg_);
3059     delete p;
3060     p = q;
3061   }
3062 }
3063
3064
3065 void AtExit(void (*cb)(void* arg), void* arg) {
3066   AtExitCallback* p = new AtExitCallback;
3067   p->cb_ = cb;
3068   p->arg_ = arg;
3069   p->next_ = at_exit_functions_;
3070   at_exit_functions_ = p;
3071 }
3072
3073
3074 void EmitExit(v8::Handle<v8::Object> process_l) {
3075   // process.emit('exit')
3076   process_l->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3077                  True(node_isolate));
3078   Local<Value> args[] = {
3079     FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3080     Integer::New(0, node_isolate)
3081   };
3082   MakeCallback(process_l, "emit", ARRAY_SIZE(args), args);
3083 }
3084
3085 static char **copy_argv(int argc, char **argv) {
3086   size_t strlen_sum;
3087   char **argv_copy;
3088   char *argv_data;
3089   size_t len;
3090   int i;
3091
3092   strlen_sum = 0;
3093   for (i = 0; i < argc; i++) {
3094     strlen_sum += strlen(argv[i]) + 1;
3095   }
3096
3097   argv_copy = static_cast<char**>(
3098       malloc(sizeof(*argv_copy) * (argc + 1) + strlen_sum));
3099   if (!argv_copy) {
3100     return NULL;
3101   }
3102
3103   argv_data = reinterpret_cast<char*>(argv_copy) +
3104               sizeof(*argv_copy) * (argc + 1);
3105
3106   for (i = 0; i < argc; i++) {
3107     argv_copy[i] = argv_data;
3108     len = strlen(argv[i]) + 1;
3109     memcpy(argv_data, argv[i], len);
3110     argv_data += len;
3111   }
3112
3113   argv_copy[argc] = NULL;
3114
3115   return argv_copy;
3116 }
3117
3118 int Start(int argc, char *argv[]) {
3119   // Hack aroung with the argv pointer. Used for process.title = "blah".
3120   argv = uv_setup_args(argc, argv);
3121
3122   // Logic to duplicate argv as Init() modifies arguments
3123   // that are passed into it.
3124   char **argv_copy = copy_argv(argc, argv);
3125
3126   // This needs to run *before* V8::Initialize()
3127   // Use copy here as to not modify the original argv:
3128   Init(argc, argv_copy);
3129
3130   V8::Initialize();
3131   {
3132     Locker locker(node_isolate);
3133     HandleScope handle_scope(node_isolate);
3134
3135     // Create the one and only Context.
3136     Local<Context> context = Context::New(node_isolate);
3137     Context::Scope context_scope(context);
3138
3139     binding_cache.Reset(node_isolate, Object::New());
3140
3141     // Use original argv, as we're just copying values out of it.
3142     Local<Object> process_l = SetupProcessObject(argc, argv);
3143
3144     // Create all the objects, load modules, do everything.
3145     // so your next reading stop should be node::Load()!
3146     Load(process_l);
3147
3148     // All our arguments are loaded. We've evaluated all of the scripts. We
3149     // might even have created TCP servers. Now we enter the main eventloop. If
3150     // there are no watchers on the loop (except for the ones that were
3151     // uv_unref'd) then this function exits. As long as there are active
3152     // watchers, it blocks.
3153     uv_run(uv_default_loop(), UV_RUN_DEFAULT);
3154
3155     EmitExit(process_l);
3156     RunAtExit();
3157   }
3158
3159 #ifndef NDEBUG
3160   // Clean up. Not strictly necessary.
3161   V8::Dispose();
3162 #endif  // NDEBUG
3163
3164   // Clean up the copy:
3165   free(argv_copy);
3166
3167   return 0;
3168 }
3169
3170
3171 }  // namespace node