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