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