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