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