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