src: update MakeCallback() function prototype
[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<Value> recv,
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<Object> object, domain;
952   Local<Value> domain_v;
953
954   TryCatch try_catch;
955   try_catch.SetVerbose(true);
956
957   bool has_async_queue = false;
958
959   if (recv->IsObject()) {
960     object = recv.As<Object>();
961     // TODO(trevnorris): This is sucky for performance. Fix it.
962     has_async_queue = object->Has(env->async_queue_string());
963     if (has_async_queue) {
964       env->async_listener_load_function()->Call(process, 1, &recv);
965
966       if (try_catch.HasCaught())
967         return Undefined(node_isolate);
968     }
969   }
970
971   bool has_domain = false;
972
973   if (!object.IsEmpty()) {
974     domain_v = object->Get(env->domain_string());
975     has_domain = domain_v->IsObject();
976     if (has_domain) {
977       domain = domain_v.As<Object>();
978
979       if (domain->Get(env->disposed_string())->IsTrue()) {
980         // domain has been disposed of.
981         return Undefined(node_isolate);
982       }
983
984       Local<Function> enter =
985           domain->Get(env->enter_string()).As<Function>();
986       assert(enter->IsFunction());
987       enter->Call(domain, 0, NULL);
988
989       if (try_catch.HasCaught()) {
990         return Undefined(node_isolate);
991       }
992     }
993   }
994
995   Local<Value> ret = callback->Call(recv, argc, argv);
996
997   if (try_catch.HasCaught()) {
998     return Undefined(node_isolate);
999   }
1000
1001   if (has_domain) {
1002     Local<Function> exit =
1003         domain->Get(env->exit_string()).As<Function>();
1004     assert(exit->IsFunction());
1005     exit->Call(domain, 0, NULL);
1006
1007     if (try_catch.HasCaught()) {
1008       return Undefined(node_isolate);
1009     }
1010   }
1011
1012   if (has_async_queue) {
1013     env->async_listener_unload_function()->Call(process, 1, &recv);
1014
1015     if (try_catch.HasCaught())
1016       return Undefined(node_isolate);
1017   }
1018
1019   Environment::TickInfo* tick_info = env->tick_info();
1020
1021   if (tick_info->last_threw() == 1) {
1022     tick_info->set_last_threw(0);
1023     return ret;
1024   }
1025
1026   if (tick_info->in_tick()) {
1027     return ret;
1028   }
1029
1030   if (tick_info->length() == 0) {
1031     tick_info->set_index(0);
1032     return ret;
1033   }
1034
1035   tick_info->set_in_tick(true);
1036
1037   env->tick_callback_function()->Call(process, 0, NULL);
1038
1039   tick_info->set_in_tick(false);
1040
1041   if (try_catch.HasCaught()) {
1042     tick_info->set_last_threw(true);
1043     return Undefined(node_isolate);
1044   }
1045
1046   return ret;
1047 }
1048
1049
1050 Handle<Value> MakeCallback(Environment* env,
1051                            Handle<Value> recv,
1052                            const Handle<Function> callback,
1053                            int argc,
1054                            Handle<Value> argv[]) {
1055   if (env->using_domains())
1056     return MakeDomainCallback(env, recv, callback, argc, argv);
1057
1058   // If you hit this assertion, you forgot to enter the v8::Context first.
1059   assert(env->context() == env->isolate()->GetCurrentContext());
1060
1061   Local<Object> process = env->process_object();
1062
1063   TryCatch try_catch;
1064   try_catch.SetVerbose(true);
1065
1066   // TODO(trevnorris): This is sucky for performance. Fix it.
1067   bool has_async_queue =
1068       recv->IsObject() && recv.As<Object>()->Has(env->async_queue_string());
1069   if (has_async_queue) {
1070     env->async_listener_load_function()->Call(process, 1, &recv);
1071     if (try_catch.HasCaught())
1072       return Undefined(node_isolate);
1073   }
1074
1075   Local<Value> ret = callback->Call(recv, argc, argv);
1076
1077   if (try_catch.HasCaught()) {
1078     return Undefined(node_isolate);
1079   }
1080
1081   if (has_async_queue) {
1082     env->async_listener_unload_function()->Call(process, 1, &recv);
1083
1084     if (try_catch.HasCaught())
1085       return Undefined(node_isolate);
1086   }
1087
1088   Environment::TickInfo* tick_info = env->tick_info();
1089
1090   if (tick_info->in_tick()) {
1091     return ret;
1092   }
1093
1094   if (tick_info->length() == 0) {
1095     tick_info->set_index(0);
1096     return ret;
1097   }
1098
1099   tick_info->set_in_tick(true);
1100
1101   // process nextTicks after call
1102   env->tick_callback_function()->Call(process, 0, NULL);
1103
1104   tick_info->set_in_tick(false);
1105
1106   if (try_catch.HasCaught()) {
1107     tick_info->set_last_threw(true);
1108     return Undefined(node_isolate);
1109   }
1110
1111   return ret;
1112 }
1113
1114
1115 // Internal only.
1116 Handle<Value> MakeCallback(Environment* env,
1117                            Handle<Object> recv,
1118                            uint32_t index,
1119                            int argc,
1120                            Handle<Value> argv[]) {
1121   Local<Function> callback = recv->Get(index).As<Function>();
1122   assert(callback->IsFunction());
1123
1124   return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1125 }
1126
1127
1128 Handle<Value> MakeCallback(Environment* env,
1129                            Handle<Object> recv,
1130                            Handle<String> symbol,
1131                            int argc,
1132                            Handle<Value> argv[]) {
1133   Local<Function> callback = recv->Get(symbol).As<Function>();
1134   assert(callback->IsFunction());
1135   return MakeCallback(env, recv.As<Value>(), callback, argc, argv);
1136 }
1137
1138
1139 Handle<Value> MakeCallback(Environment* env,
1140                            Handle<Object> recv,
1141                            const char* method,
1142                            int argc,
1143                            Handle<Value> argv[]) {
1144   Local<String> method_string = OneByteString(node_isolate, method);
1145   return MakeCallback(env, recv, method_string, argc, argv);
1146 }
1147
1148
1149 Handle<Value> MakeCallback(Handle<Object> recv,
1150                            const char* method,
1151                            int argc,
1152                            Handle<Value> argv[]) {
1153   Local<Context> context = recv->CreationContext();
1154   Environment* env = Environment::GetCurrent(context);
1155   Context::Scope context_scope(context);
1156   HandleScope handle_scope(env->isolate());
1157   return handle_scope.Close(MakeCallback(env, recv, method, argc, argv));
1158 }
1159
1160
1161 Handle<Value> MakeCallback(Handle<Object> recv,
1162                            Handle<String> symbol,
1163                            int argc,
1164                            Handle<Value> argv[]) {
1165   Local<Context> context = recv->CreationContext();
1166   Environment* env = Environment::GetCurrent(context);
1167   Context::Scope context_scope(context);
1168   HandleScope handle_scope(env->isolate());
1169   return handle_scope.Close(MakeCallback(env, recv, symbol, argc, argv));
1170 }
1171
1172
1173 Handle<Value> MakeCallback(Handle<Object> recv,
1174                            Handle<Function> callback,
1175                            int argc,
1176                            Handle<Value> argv[]) {
1177   Local<Context> context = recv->CreationContext();
1178   Environment* env = Environment::GetCurrent(context);
1179   Context::Scope context_scope(context);
1180   HandleScope handle_scope(env->isolate());
1181   return handle_scope.Close(
1182       MakeCallback(env, recv.As<Value>(), callback, argc, argv));
1183 }
1184
1185
1186 Handle<Value> MakeDomainCallback(Handle<Object> recv,
1187                                  Handle<Function> callback,
1188                                  int argc,
1189                                  Handle<Value> argv[]) {
1190   Local<Context> context = recv->CreationContext();
1191   Environment* env = Environment::GetCurrent(context);
1192   Context::Scope context_scope(context);
1193   HandleScope handle_scope(env->isolate());
1194   return handle_scope.Close(
1195       MakeDomainCallback(env, recv, callback, argc, argv));
1196 }
1197
1198
1199 enum encoding ParseEncoding(Handle<Value> encoding_v, enum encoding _default) {
1200   HandleScope scope(node_isolate);
1201
1202   if (!encoding_v->IsString())
1203     return _default;
1204
1205   String::Utf8Value encoding(encoding_v);
1206
1207   if (strcasecmp(*encoding, "utf8") == 0) {
1208     return UTF8;
1209   } else if (strcasecmp(*encoding, "utf-8") == 0) {
1210     return UTF8;
1211   } else if (strcasecmp(*encoding, "ascii") == 0) {
1212     return ASCII;
1213   } else if (strcasecmp(*encoding, "base64") == 0) {
1214     return BASE64;
1215   } else if (strcasecmp(*encoding, "ucs2") == 0) {
1216     return UCS2;
1217   } else if (strcasecmp(*encoding, "ucs-2") == 0) {
1218     return UCS2;
1219   } else if (strcasecmp(*encoding, "utf16le") == 0) {
1220     return UCS2;
1221   } else if (strcasecmp(*encoding, "utf-16le") == 0) {
1222     return UCS2;
1223   } else if (strcasecmp(*encoding, "binary") == 0) {
1224     return BINARY;
1225   } else if (strcasecmp(*encoding, "buffer") == 0) {
1226     return BUFFER;
1227   } else if (strcasecmp(*encoding, "hex") == 0) {
1228     return HEX;
1229   } else if (strcasecmp(*encoding, "raw") == 0) {
1230     if (!no_deprecation) {
1231       fprintf(stderr, "'raw' (array of integers) has been removed. "
1232                       "Use 'binary'.\n");
1233     }
1234     return BINARY;
1235   } else if (strcasecmp(*encoding, "raws") == 0) {
1236     if (!no_deprecation) {
1237       fprintf(stderr, "'raws' encoding has been renamed to 'binary'. "
1238                       "Please update your code.\n");
1239     }
1240     return BINARY;
1241   } else {
1242     return _default;
1243   }
1244 }
1245
1246 Local<Value> Encode(const void *buf, size_t len, enum encoding encoding) {
1247   return StringBytes::Encode(static_cast<const char*>(buf),
1248                              len,
1249                              encoding);
1250 }
1251
1252 // Returns -1 if the handle was not valid for decoding
1253 ssize_t DecodeBytes(v8::Handle<v8::Value> val, enum encoding encoding) {
1254   HandleScope scope(node_isolate);
1255
1256   if (val->IsArray()) {
1257     fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
1258                     "Use 'binary'.\n");
1259     assert(0);
1260     return -1;
1261   }
1262
1263   return StringBytes::Size(val, encoding);
1264 }
1265
1266 #ifndef MIN
1267 # define MIN(a, b) ((a) < (b) ? (a) : (b))
1268 #endif
1269
1270 // Returns number of bytes written.
1271 ssize_t DecodeWrite(char *buf,
1272                     size_t buflen,
1273                     v8::Handle<v8::Value> val,
1274                     enum encoding encoding) {
1275   return StringBytes::Write(buf, buflen, val, encoding, NULL);
1276 }
1277
1278 void DisplayExceptionLine(Handle<Message> message) {
1279   // Prevent re-entry into this function.  For example, if there is
1280   // a throw from a program in vm.runInThisContext(code, filename, true),
1281   // then we want to show the original failure, not the secondary one.
1282   static bool displayed_error = false;
1283
1284   if (displayed_error)
1285     return;
1286   displayed_error = true;
1287
1288   uv_tty_reset_mode();
1289
1290   fprintf(stderr, "\n");
1291
1292   if (!message.IsEmpty()) {
1293     // Print (filename):(line number): (message).
1294     String::Utf8Value filename(message->GetScriptResourceName());
1295     const char* filename_string = *filename;
1296     int linenum = message->GetLineNumber();
1297     fprintf(stderr, "%s:%i\n", filename_string, linenum);
1298     // Print line of source code.
1299     String::Utf8Value sourceline(message->GetSourceLine());
1300     const char* sourceline_string = *sourceline;
1301
1302     // Because of how node modules work, all scripts are wrapped with a
1303     // "function (module, exports, __filename, ...) {"
1304     // to provide script local variables.
1305     //
1306     // When reporting errors on the first line of a script, this wrapper
1307     // function is leaked to the user. There used to be a hack here to
1308     // truncate off the first 62 characters, but it caused numerous other
1309     // problems when vm.runIn*Context() methods were used for non-module
1310     // code.
1311     //
1312     // If we ever decide to re-instate such a hack, the following steps
1313     // must be taken:
1314     //
1315     // 1. Pass a flag around to say "this code was wrapped"
1316     // 2. Update the stack frame output so that it is also correct.
1317     //
1318     // It would probably be simpler to add a line rather than add some
1319     // number of characters to the first line, since V8 truncates the
1320     // sourceline to 78 characters, and we end up not providing very much
1321     // useful debugging info to the user if we remove 62 characters.
1322
1323     int start = message->GetStartColumn();
1324     int end = message->GetEndColumn();
1325
1326     fprintf(stderr, "%s\n", sourceline_string);
1327     // Print wavy underline (GetUnderline is deprecated).
1328     for (int i = 0; i < start; i++) {
1329       fputc((sourceline_string[i] == '\t') ? '\t' : ' ', stderr);
1330     }
1331     for (int i = start; i < end; i++) {
1332       fputc('^', stderr);
1333     }
1334     fputc('\n', stderr);
1335   }
1336 }
1337
1338
1339 static void ReportException(Handle<Value> er, Handle<Message> message) {
1340   HandleScope scope(node_isolate);
1341
1342   DisplayExceptionLine(message);
1343
1344   Local<Value> trace_value;
1345
1346   if (er->IsUndefined() || er->IsNull()) {
1347     trace_value = Undefined(node_isolate);
1348   } else {
1349     trace_value =
1350         er->ToObject()->Get(FIXED_ONE_BYTE_STRING(node_isolate, "stack"));
1351   }
1352
1353   String::Utf8Value trace(trace_value);
1354
1355   // range errors have a trace member set to undefined
1356   if (trace.length() > 0 && !trace_value->IsUndefined()) {
1357     fprintf(stderr, "%s\n", *trace);
1358   } else {
1359     // this really only happens for RangeErrors, since they're the only
1360     // kind that won't have all this info in the trace, or when non-Error
1361     // objects are thrown manually.
1362     Local<Value> message;
1363     Local<Value> name;
1364
1365     if (er->IsObject()) {
1366       Local<Object> err_obj = er.As<Object>();
1367       message = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "message"));
1368       name = err_obj->Get(FIXED_ONE_BYTE_STRING(node_isolate, "name"));
1369     }
1370
1371     if (message.IsEmpty() ||
1372         message->IsUndefined() ||
1373         name.IsEmpty() ||
1374         name->IsUndefined()) {
1375       // Not an error object. Just print as-is.
1376       String::Utf8Value message(er);
1377       fprintf(stderr, "%s\n", *message);
1378     } else {
1379       String::Utf8Value name_string(name);
1380       String::Utf8Value message_string(message);
1381       fprintf(stderr, "%s: %s\n", *name_string, *message_string);
1382     }
1383   }
1384
1385   fflush(stderr);
1386 }
1387
1388
1389 static void ReportException(const TryCatch& try_catch) {
1390   ReportException(try_catch.Exception(), try_catch.Message());
1391 }
1392
1393
1394 // Executes a str within the current v8 context.
1395 Local<Value> ExecuteString(Handle<String> source, Handle<Value> filename) {
1396   HandleScope scope(node_isolate);
1397   TryCatch try_catch;
1398
1399   // try_catch must be nonverbose to disable FatalException() handler,
1400   // we will handle exceptions ourself.
1401   try_catch.SetVerbose(false);
1402
1403   Local<v8::Script> script = v8::Script::Compile(source, filename);
1404   if (script.IsEmpty()) {
1405     ReportException(try_catch);
1406     exit(3);
1407   }
1408
1409   Local<Value> result = script->Run();
1410   if (result.IsEmpty()) {
1411     ReportException(try_catch);
1412     exit(4);
1413   }
1414
1415   return scope.Close(result);
1416 }
1417
1418
1419 static void GetActiveRequests(const FunctionCallbackInfo<Value>& args) {
1420   HandleScope scope(node_isolate);
1421
1422   Local<Array> ary = Array::New();
1423   QUEUE* q = NULL;
1424   int i = 0;
1425
1426   QUEUE_FOREACH(q, &req_wrap_queue) {
1427     ReqWrap<uv_req_t>* w = CONTAINER_OF(q, ReqWrap<uv_req_t>, req_wrap_queue_);
1428     if (w->persistent().IsEmpty())
1429       continue;
1430     ary->Set(i++, w->object());
1431   }
1432
1433   args.GetReturnValue().Set(ary);
1434 }
1435
1436
1437 // Non-static, friend of HandleWrap. Could have been a HandleWrap method but
1438 // implemented here for consistency with GetActiveRequests().
1439 void GetActiveHandles(const FunctionCallbackInfo<Value>& args) {
1440   HandleScope scope(node_isolate);
1441
1442   Local<Array> ary = Array::New();
1443   QUEUE* q = NULL;
1444   int i = 0;
1445
1446   Local<String> owner_sym = FIXED_ONE_BYTE_STRING(node_isolate, "owner");
1447
1448   QUEUE_FOREACH(q, &handle_wrap_queue) {
1449     HandleWrap* w = CONTAINER_OF(q, HandleWrap, handle_wrap_queue_);
1450     if (w->persistent().IsEmpty() || (w->flags_ & HandleWrap::kUnref))
1451       continue;
1452     Local<Object> object = w->object();
1453     Local<Value> owner = object->Get(owner_sym);
1454     if (owner->IsUndefined())
1455       owner = object;
1456     ary->Set(i++, owner);
1457   }
1458
1459   args.GetReturnValue().Set(ary);
1460 }
1461
1462
1463 static void Abort(const FunctionCallbackInfo<Value>& args) {
1464   abort();
1465 }
1466
1467
1468 static void Chdir(const FunctionCallbackInfo<Value>& args) {
1469   HandleScope scope(node_isolate);
1470
1471   if (args.Length() != 1 || !args[0]->IsString()) {
1472     return ThrowError("Bad argument.");  // FIXME(bnoordhuis) ThrowTypeError?
1473   }
1474
1475   String::Utf8Value path(args[0]);
1476   int err = uv_chdir(*path);
1477   if (err) {
1478     return ThrowUVException(err, "uv_chdir");
1479   }
1480 }
1481
1482
1483 static void Cwd(const FunctionCallbackInfo<Value>& args) {
1484   HandleScope scope(node_isolate);
1485 #ifdef _WIN32
1486   /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */
1487   char buf[MAX_PATH * 4 + 1];
1488 #else
1489   char buf[PATH_MAX + 1];
1490 #endif
1491
1492   int err = uv_cwd(buf, ARRAY_SIZE(buf) - 1);
1493   if (err) {
1494     return ThrowUVException(err, "uv_cwd");
1495   }
1496
1497   buf[ARRAY_SIZE(buf) - 1] = '\0';
1498   Local<String> cwd = String::NewFromUtf8(node_isolate, buf);
1499
1500   args.GetReturnValue().Set(cwd);
1501 }
1502
1503
1504 static void Umask(const FunctionCallbackInfo<Value>& args) {
1505   HandleScope scope(node_isolate);
1506   uint32_t old;
1507
1508   if (args.Length() < 1 || args[0]->IsUndefined()) {
1509     old = umask(0);
1510     umask(static_cast<mode_t>(old));
1511   } else if (!args[0]->IsInt32() && !args[0]->IsString()) {
1512     return ThrowTypeError("argument must be an integer or octal string.");
1513   } else {
1514     int oct;
1515     if (args[0]->IsInt32()) {
1516       oct = args[0]->Uint32Value();
1517     } else {
1518       oct = 0;
1519       String::Utf8Value str(args[0]);
1520
1521       // Parse the octal string.
1522       for (int i = 0; i < str.length(); i++) {
1523         char c = (*str)[i];
1524         if (c > '7' || c < '0') {
1525           return ThrowTypeError("invalid octal string");
1526         }
1527         oct *= 8;
1528         oct += c - '0';
1529       }
1530     }
1531     old = umask(static_cast<mode_t>(oct));
1532   }
1533
1534   args.GetReturnValue().Set(old);
1535 }
1536
1537
1538 #if defined(__POSIX__) && !defined(__ANDROID__)
1539
1540 static const uid_t uid_not_found = static_cast<uid_t>(-1);
1541 static const gid_t gid_not_found = static_cast<gid_t>(-1);
1542
1543
1544 static uid_t uid_by_name(const char* name) {
1545   struct passwd pwd;
1546   struct passwd* pp;
1547   char buf[8192];
1548
1549   errno = 0;
1550   pp = NULL;
1551
1552   if (getpwnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1553     return pp->pw_uid;
1554   }
1555
1556   return uid_not_found;
1557 }
1558
1559
1560 static char* name_by_uid(uid_t uid) {
1561   struct passwd pwd;
1562   struct passwd* pp;
1563   char buf[8192];
1564   int rc;
1565
1566   errno = 0;
1567   pp = NULL;
1568
1569   if ((rc = getpwuid_r(uid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1570     return strdup(pp->pw_name);
1571   }
1572
1573   if (rc == 0) {
1574     errno = ENOENT;
1575   }
1576
1577   return NULL;
1578 }
1579
1580
1581 static gid_t gid_by_name(const char* name) {
1582   struct group pwd;
1583   struct group* pp;
1584   char buf[8192];
1585
1586   errno = 0;
1587   pp = NULL;
1588
1589   if (getgrnam_r(name, &pwd, buf, sizeof(buf), &pp) == 0 && pp != NULL) {
1590     return pp->gr_gid;
1591   }
1592
1593   return gid_not_found;
1594 }
1595
1596
1597 #if 0  // For future use.
1598 static const char* name_by_gid(gid_t gid) {
1599   struct group pwd;
1600   struct group* pp;
1601   char buf[8192];
1602   int rc;
1603
1604   errno = 0;
1605   pp = NULL;
1606
1607   if ((rc = getgrgid_r(gid, &pwd, buf, sizeof(buf), &pp)) == 0 && pp != NULL) {
1608     return strdup(pp->gr_name);
1609   }
1610
1611   if (rc == 0) {
1612     errno = ENOENT;
1613   }
1614
1615   return NULL;
1616 }
1617 #endif
1618
1619
1620 static uid_t uid_by_name(Handle<Value> value) {
1621   if (value->IsUint32()) {
1622     return static_cast<uid_t>(value->Uint32Value());
1623   } else {
1624     String::Utf8Value name(value);
1625     return uid_by_name(*name);
1626   }
1627 }
1628
1629
1630 static gid_t gid_by_name(Handle<Value> value) {
1631   if (value->IsUint32()) {
1632     return static_cast<gid_t>(value->Uint32Value());
1633   } else {
1634     String::Utf8Value name(value);
1635     return gid_by_name(*name);
1636   }
1637 }
1638
1639
1640 static void GetUid(const FunctionCallbackInfo<Value>& args) {
1641   // uid_t is an uint32_t on all supported platforms.
1642   args.GetReturnValue().Set(static_cast<uint32_t>(getuid()));
1643 }
1644
1645
1646 static void GetGid(const FunctionCallbackInfo<Value>& args) {
1647   // gid_t is an uint32_t on all supported platforms.
1648   args.GetReturnValue().Set(static_cast<uint32_t>(getgid()));
1649 }
1650
1651
1652 static void SetGid(const FunctionCallbackInfo<Value>& args) {
1653   HandleScope scope(node_isolate);
1654
1655   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1656     return ThrowTypeError("setgid argument must be a number or a string");
1657   }
1658
1659   gid_t gid = gid_by_name(args[0]);
1660
1661   if (gid == gid_not_found) {
1662     return ThrowError("setgid group id does not exist");
1663   }
1664
1665   if (setgid(gid)) {
1666     return ThrowErrnoException(errno, "setgid");
1667   }
1668 }
1669
1670
1671 static void SetUid(const FunctionCallbackInfo<Value>& args) {
1672   HandleScope scope(node_isolate);
1673
1674   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1675     return ThrowTypeError("setuid argument must be a number or a string");
1676   }
1677
1678   uid_t uid = uid_by_name(args[0]);
1679
1680   if (uid == uid_not_found) {
1681     return ThrowError("setuid user id does not exist");
1682   }
1683
1684   if (setuid(uid)) {
1685     return ThrowErrnoException(errno, "setuid");
1686   }
1687 }
1688
1689
1690 static void GetGroups(const FunctionCallbackInfo<Value>& args) {
1691   HandleScope scope(node_isolate);
1692
1693   int ngroups = getgroups(0, NULL);
1694
1695   if (ngroups == -1) {
1696     return ThrowErrnoException(errno, "getgroups");
1697   }
1698
1699   gid_t* groups = new gid_t[ngroups];
1700
1701   ngroups = getgroups(ngroups, groups);
1702
1703   if (ngroups == -1) {
1704     delete[] groups;
1705     return ThrowErrnoException(errno, "getgroups");
1706   }
1707
1708   Local<Array> groups_list = Array::New(ngroups);
1709   bool seen_egid = false;
1710   gid_t egid = getegid();
1711
1712   for (int i = 0; i < ngroups; i++) {
1713     groups_list->Set(i, Integer::New(groups[i], node_isolate));
1714     if (groups[i] == egid)
1715       seen_egid = true;
1716   }
1717
1718   delete[] groups;
1719
1720   if (seen_egid == false) {
1721     groups_list->Set(ngroups, Integer::New(egid, node_isolate));
1722   }
1723
1724   args.GetReturnValue().Set(groups_list);
1725 }
1726
1727
1728 static void SetGroups(const FunctionCallbackInfo<Value>& args) {
1729   HandleScope scope(node_isolate);
1730
1731   if (!args[0]->IsArray()) {
1732     return ThrowTypeError("argument 1 must be an array");
1733   }
1734
1735   Local<Array> groups_list = args[0].As<Array>();
1736   size_t size = groups_list->Length();
1737   gid_t* groups = new gid_t[size];
1738
1739   for (size_t i = 0; i < size; i++) {
1740     gid_t gid = gid_by_name(groups_list->Get(i));
1741
1742     if (gid == gid_not_found) {
1743       delete[] groups;
1744       return ThrowError("group name not found");
1745     }
1746
1747     groups[i] = gid;
1748   }
1749
1750   int rc = setgroups(size, groups);
1751   delete[] groups;
1752
1753   if (rc == -1) {
1754     return ThrowErrnoException(errno, "setgroups");
1755   }
1756 }
1757
1758
1759 static void InitGroups(const FunctionCallbackInfo<Value>& args) {
1760   HandleScope scope(node_isolate);
1761
1762   if (!args[0]->IsUint32() && !args[0]->IsString()) {
1763     return ThrowTypeError("argument 1 must be a number or a string");
1764   }
1765
1766   if (!args[1]->IsUint32() && !args[1]->IsString()) {
1767     return ThrowTypeError("argument 2 must be a number or a string");
1768   }
1769
1770   String::Utf8Value arg0(args[0]);
1771   gid_t extra_group;
1772   bool must_free;
1773   char* user;
1774
1775   if (args[0]->IsUint32()) {
1776     user = name_by_uid(args[0]->Uint32Value());
1777     must_free = true;
1778   } else {
1779     user = *arg0;
1780     must_free = false;
1781   }
1782
1783   if (user == NULL) {
1784     return ThrowError("initgroups user not found");
1785   }
1786
1787   extra_group = gid_by_name(args[1]);
1788
1789   if (extra_group == gid_not_found) {
1790     if (must_free)
1791       free(user);
1792     return ThrowError("initgroups extra group not found");
1793   }
1794
1795   int rc = initgroups(user, extra_group);
1796
1797   if (must_free) {
1798     free(user);
1799   }
1800
1801   if (rc) {
1802     return ThrowErrnoException(errno, "initgroups");
1803   }
1804 }
1805
1806 #endif  // __POSIX__ && !defined(__ANDROID__)
1807
1808
1809 void Exit(const FunctionCallbackInfo<Value>& args) {
1810   HandleScope scope(node_isolate);
1811   exit(args[0]->IntegerValue());
1812 }
1813
1814
1815 static void Uptime(const FunctionCallbackInfo<Value>& args) {
1816   HandleScope scope(node_isolate);
1817   double uptime;
1818   if (uv_uptime(&uptime))
1819     return;
1820   args.GetReturnValue().Set(uptime - prog_start_time);
1821 }
1822
1823
1824 void MemoryUsage(const FunctionCallbackInfo<Value>& args) {
1825   HandleScope handle_scope(args.GetIsolate());
1826   Environment* env = Environment::GetCurrent(args.GetIsolate());
1827
1828   size_t rss;
1829   int err = uv_resident_set_memory(&rss);
1830   if (err) {
1831     return ThrowUVException(err, "uv_resident_set_memory");
1832   }
1833
1834   // V8 memory usage
1835   HeapStatistics v8_heap_stats;
1836   node_isolate->GetHeapStatistics(&v8_heap_stats);
1837
1838   Local<Integer> heap_total =
1839       Integer::NewFromUnsigned(v8_heap_stats.total_heap_size(), node_isolate);
1840   Local<Integer> heap_used =
1841       Integer::NewFromUnsigned(v8_heap_stats.used_heap_size(), node_isolate);
1842
1843   Local<Object> info = Object::New();
1844   info->Set(env->rss_string(), Number::New(node_isolate, rss));
1845   info->Set(env->heap_total_string(), heap_total);
1846   info->Set(env->heap_used_string(), heap_used);
1847
1848   args.GetReturnValue().Set(info);
1849 }
1850
1851
1852 void Kill(const FunctionCallbackInfo<Value>& args) {
1853   HandleScope scope(node_isolate);
1854
1855   if (args.Length() != 2) {
1856     return ThrowError("Bad argument.");
1857   }
1858
1859   int pid = args[0]->IntegerValue();
1860   int sig = args[1]->Int32Value();
1861   int err = uv_kill(pid, sig);
1862   args.GetReturnValue().Set(err);
1863 }
1864
1865 // used in Hrtime() below
1866 #define NANOS_PER_SEC 1000000000
1867
1868 // Hrtime exposes libuv's uv_hrtime() high-resolution timer.
1869 // The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
1870 // so this function instead returns an Array with 2 entries representing seconds
1871 // and nanoseconds, to avoid any integer overflow possibility.
1872 // Pass in an Array from a previous hrtime() call to instead get a time diff.
1873 void Hrtime(const FunctionCallbackInfo<Value>& args) {
1874   HandleScope scope(node_isolate);
1875
1876   uint64_t t = uv_hrtime();
1877
1878   if (args.Length() > 0) {
1879     // return a time diff tuple
1880     if (!args[0]->IsArray()) {
1881       return ThrowTypeError("process.hrtime() only accepts an Array tuple.");
1882     }
1883     Local<Array> inArray = Local<Array>::Cast(args[0]);
1884     uint64_t seconds = inArray->Get(0)->Uint32Value();
1885     uint64_t nanos = inArray->Get(1)->Uint32Value();
1886     t -= (seconds * NANOS_PER_SEC) + nanos;
1887   }
1888
1889   Local<Array> tuple = Array::New(2);
1890   tuple->Set(0, Integer::NewFromUnsigned(t / NANOS_PER_SEC, node_isolate));
1891   tuple->Set(1, Integer::NewFromUnsigned(t % NANOS_PER_SEC, node_isolate));
1892   args.GetReturnValue().Set(tuple);
1893 }
1894
1895 extern "C" void node_module_register(void* m) {
1896   struct node_module* mp = reinterpret_cast<struct node_module*>(m);
1897
1898   if (mp->nm_flags & NM_F_BUILTIN) {
1899     mp->nm_link = modlist_builtin;
1900     modlist_builtin = mp;
1901   } else {
1902     assert(modpending == NULL);
1903     modpending = mp;
1904   }
1905 }
1906
1907 struct node_module* get_builtin_module(const char* name) {
1908   struct node_module* mp;
1909
1910   for (mp = modlist_builtin; mp != NULL; mp = mp->nm_link) {
1911     if (strcmp(mp->nm_modname, name) == 0)
1912       break;
1913   }
1914
1915   assert(mp == NULL || (mp->nm_flags & NM_F_BUILTIN) != 0);
1916   return (mp);
1917 }
1918
1919 typedef void (UV_DYNAMIC* extInit)(Handle<Object> exports);
1920
1921 // DLOpen is process.dlopen(module, filename).
1922 // Used to load 'module.node' dynamically shared objects.
1923 //
1924 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
1925 // when two contexts try to load the same shared object. Maybe have a shadow
1926 // cache that's a plain C list or hash table that's shared across contexts?
1927 void DLOpen(const FunctionCallbackInfo<Value>& args) {
1928   HandleScope handle_scope(args.GetIsolate());
1929   Environment* env = Environment::GetCurrent(args.GetIsolate());
1930   struct node_module* mp;
1931   uv_lib_t lib;
1932
1933   if (args.Length() < 2) {
1934     ThrowError("process.dlopen takes exactly 2 arguments.");
1935     return;
1936   }
1937
1938   Local<Object> module = args[0]->ToObject();  // Cast
1939   String::Utf8Value filename(args[1]);  // Cast
1940
1941   Local<String> exports_string = env->exports_string();
1942   Local<Object> exports = module->Get(exports_string)->ToObject();
1943
1944   if (uv_dlopen(*filename, &lib)) {
1945     Local<String> errmsg = OneByteString(env->isolate(), uv_dlerror(&lib));
1946 #ifdef _WIN32
1947     // Windows needs to add the filename into the error message
1948     errmsg = String::Concat(errmsg, args[1]->ToString());
1949 #endif  // _WIN32
1950     ThrowException(Exception::Error(errmsg));
1951     return;
1952   }
1953
1954   /*
1955    * Objects containing v14 or later modules will have registered themselves
1956    * on the pending list.  Activate all of them now.  At present, only one
1957    * module per object is supported.
1958    */
1959   mp = modpending;
1960   modpending = NULL;
1961
1962   if (mp == NULL) {
1963     ThrowError("Module did not self-register.");
1964     return;
1965   }
1966   if (mp->nm_version != NODE_MODULE_VERSION) {
1967     char errmsg[1024];
1968     snprintf(errmsg,
1969              sizeof(errmsg),
1970              "Module version mismatch. Expected %d, got %d.",
1971              NODE_MODULE_VERSION, mp->nm_version);
1972     ThrowError(errmsg);
1973     return;
1974   }
1975   if (mp->nm_flags & NM_F_BUILTIN) {
1976     ThrowError("Built-in module self-registered.");
1977     return;
1978   }
1979
1980   mp->nm_dso_handle = lib.handle;
1981   mp->nm_link = modlist_addon;
1982   modlist_addon = mp;
1983
1984   if (mp->nm_context_register_func != NULL) {
1985     mp->nm_context_register_func(exports, module, env->context(), mp->nm_priv);
1986   } else if (mp->nm_register_func != NULL) {
1987     mp->nm_register_func(exports, module, mp->nm_priv);
1988   } else {
1989     ThrowError("Module has no declared entry point.");
1990     return;
1991   }
1992
1993   // Tell coverity that 'handle' should not be freed when we return.
1994   // coverity[leaked_storage]
1995 }
1996
1997
1998 static void OnFatalError(const char* location, const char* message) {
1999   if (location) {
2000     fprintf(stderr, "FATAL ERROR: %s %s\n", location, message);
2001   } else {
2002     fprintf(stderr, "FATAL ERROR: %s\n", message);
2003   }
2004   fflush(stderr);
2005   abort();
2006 }
2007
2008
2009 NO_RETURN void FatalError(const char* location, const char* message) {
2010   OnFatalError(location, message);
2011   // to supress compiler warning
2012   abort();
2013 }
2014
2015
2016 void FatalException(Handle<Value> error, Handle<Message> message) {
2017   HandleScope scope(node_isolate);
2018
2019   Environment* env = Environment::GetCurrent(node_isolate);
2020   Local<Object> process_object = env->process_object();
2021   Local<String> fatal_exception_string = env->fatal_exception_string();
2022   Local<Function> fatal_exception_function =
2023       process_object->Get(fatal_exception_string).As<Function>();
2024
2025   if (!fatal_exception_function->IsFunction()) {
2026     // failed before the process._fatalException function was added!
2027     // this is probably pretty bad.  Nothing to do but report and exit.
2028     ReportException(error, message);
2029     exit(6);
2030   }
2031
2032   TryCatch fatal_try_catch;
2033
2034   // Do not call FatalException when _fatalException handler throws
2035   fatal_try_catch.SetVerbose(false);
2036
2037   // this will return true if the JS layer handled it, false otherwise
2038   Local<Value> caught =
2039       fatal_exception_function->Call(process_object, 1, &error);
2040
2041   if (fatal_try_catch.HasCaught()) {
2042     // the fatal exception function threw, so we must exit
2043     ReportException(fatal_try_catch);
2044     exit(7);
2045   }
2046
2047   if (false == caught->BooleanValue()) {
2048     ReportException(error, message);
2049     exit(1);
2050   }
2051 }
2052
2053
2054 void FatalException(const TryCatch& try_catch) {
2055   HandleScope scope(node_isolate);
2056   // TODO(bajtos) do not call FatalException if try_catch is verbose
2057   // (requires V8 API to expose getter for try_catch.is_verbose_)
2058   FatalException(try_catch.Exception(), try_catch.Message());
2059 }
2060
2061
2062 void OnMessage(Handle<Message> message, Handle<Value> error) {
2063   // The current version of V8 sends messages for errors only
2064   // (thus `error` is always set).
2065   FatalException(error, message);
2066 }
2067
2068
2069 static void Binding(const FunctionCallbackInfo<Value>& args) {
2070   HandleScope handle_scope(args.GetIsolate());
2071   Environment* env = Environment::GetCurrent(args.GetIsolate());
2072
2073   Local<String> module = args[0]->ToString();
2074   String::Utf8Value module_v(module);
2075
2076   Local<Object> cache = env->binding_cache_object();
2077   Local<Object> exports;
2078
2079   if (cache->Has(module)) {
2080     exports = cache->Get(module)->ToObject();
2081     args.GetReturnValue().Set(exports);
2082     return;
2083   }
2084
2085   // Append a string to process.moduleLoadList
2086   char buf[1024];
2087   snprintf(buf, sizeof(buf), "Binding %s", *module_v);
2088
2089   Local<Array> modules = env->module_load_list_array();
2090   uint32_t l = modules->Length();
2091   modules->Set(l, OneByteString(node_isolate, buf));
2092
2093   node_module* mod = get_builtin_module(*module_v);
2094   if (mod != NULL) {
2095     exports = Object::New();
2096     // Internal bindings don't have a "module" object, only exports.
2097     assert(mod->nm_register_func == NULL);
2098     assert(mod->nm_context_register_func != NULL);
2099     Local<Value> unused = Undefined(env->isolate());
2100     mod->nm_context_register_func(exports, unused,
2101       env->context(), mod->nm_priv);
2102     cache->Set(module, exports);
2103   } else if (!strcmp(*module_v, "constants")) {
2104     exports = Object::New();
2105     DefineConstants(exports);
2106     cache->Set(module, exports);
2107   } else if (!strcmp(*module_v, "natives")) {
2108     exports = Object::New();
2109     DefineJavaScript(exports);
2110     cache->Set(module, exports);
2111   } else {
2112     return ThrowError("No such module");
2113   }
2114
2115   args.GetReturnValue().Set(exports);
2116 }
2117
2118
2119 static void ProcessTitleGetter(Local<String> property,
2120                                const PropertyCallbackInfo<Value>& info) {
2121   HandleScope scope(node_isolate);
2122   char buffer[512];
2123   uv_get_process_title(buffer, sizeof(buffer));
2124   info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, buffer));
2125 }
2126
2127
2128 static void ProcessTitleSetter(Local<String> property,
2129                                Local<Value> value,
2130                                const PropertyCallbackInfo<void>& info) {
2131   HandleScope scope(node_isolate);
2132   String::Utf8Value title(value);
2133   // TODO(piscisaureus): protect with a lock
2134   uv_set_process_title(*title);
2135 }
2136
2137
2138 static void EnvGetter(Local<String> property,
2139                       const PropertyCallbackInfo<Value>& info) {
2140   HandleScope scope(node_isolate);
2141 #ifdef __POSIX__
2142   String::Utf8Value key(property);
2143   const char* val = getenv(*key);
2144   if (val) {
2145     return info.GetReturnValue().Set(String::NewFromUtf8(node_isolate, val));
2146   }
2147 #else  // _WIN32
2148   String::Value key(property);
2149   WCHAR buffer[32767];  // The maximum size allowed for environment variables.
2150   DWORD result = GetEnvironmentVariableW(reinterpret_cast<WCHAR*>(*key),
2151                                          buffer,
2152                                          ARRAY_SIZE(buffer));
2153   // If result >= sizeof buffer the buffer was too small. That should never
2154   // happen. If result == 0 and result != ERROR_SUCCESS the variable was not
2155   // not found.
2156   if ((result > 0 || GetLastError() == ERROR_SUCCESS) &&
2157       result < ARRAY_SIZE(buffer)) {
2158     const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(buffer);
2159     Local<String> rc = String::NewFromTwoByte(node_isolate, two_byte_buffer);
2160     return info.GetReturnValue().Set(rc);
2161   }
2162 #endif
2163   // Not found.  Fetch from prototype.
2164   info.GetReturnValue().Set(
2165       info.Data().As<Object>()->Get(property));
2166 }
2167
2168
2169 static void EnvSetter(Local<String> property,
2170                       Local<Value> value,
2171                       const PropertyCallbackInfo<Value>& info) {
2172   HandleScope scope(node_isolate);
2173 #ifdef __POSIX__
2174   String::Utf8Value key(property);
2175   String::Utf8Value val(value);
2176   setenv(*key, *val, 1);
2177 #else  // _WIN32
2178   String::Value key(property);
2179   String::Value val(value);
2180   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2181   // Environment variables that start with '=' are read-only.
2182   if (key_ptr[0] != L'=') {
2183     SetEnvironmentVariableW(key_ptr, reinterpret_cast<WCHAR*>(*val));
2184   }
2185 #endif
2186   // Whether it worked or not, always return rval.
2187   info.GetReturnValue().Set(value);
2188 }
2189
2190
2191 static void EnvQuery(Local<String> property,
2192                      const PropertyCallbackInfo<Integer>& info) {
2193   HandleScope scope(node_isolate);
2194   int32_t rc = -1;  // Not found unless proven otherwise.
2195 #ifdef __POSIX__
2196   String::Utf8Value key(property);
2197   if (getenv(*key))
2198     rc = 0;
2199 #else  // _WIN32
2200   String::Value key(property);
2201   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2202   if (GetEnvironmentVariableW(key_ptr, NULL, 0) > 0 ||
2203       GetLastError() == ERROR_SUCCESS) {
2204     rc = 0;
2205     if (key_ptr[0] == L'=') {
2206       // Environment variables that start with '=' are hidden and read-only.
2207       rc = static_cast<int32_t>(v8::ReadOnly) |
2208            static_cast<int32_t>(v8::DontDelete) |
2209            static_cast<int32_t>(v8::DontEnum);
2210     }
2211   }
2212 #endif
2213   if (rc != -1)
2214     info.GetReturnValue().Set(rc);
2215 }
2216
2217
2218 static void EnvDeleter(Local<String> property,
2219                        const PropertyCallbackInfo<Boolean>& info) {
2220   HandleScope scope(node_isolate);
2221   bool rc = true;
2222 #ifdef __POSIX__
2223   String::Utf8Value key(property);
2224   rc = getenv(*key) != NULL;
2225   if (rc)
2226     unsetenv(*key);
2227 #else
2228   String::Value key(property);
2229   WCHAR* key_ptr = reinterpret_cast<WCHAR*>(*key);
2230   if (key_ptr[0] == L'=' || !SetEnvironmentVariableW(key_ptr, NULL)) {
2231     // Deletion failed. Return true if the key wasn't there in the first place,
2232     // false if it is still there.
2233     rc = GetEnvironmentVariableW(key_ptr, NULL, NULL) == 0 &&
2234          GetLastError() != ERROR_SUCCESS;
2235   }
2236 #endif
2237   info.GetReturnValue().Set(rc);
2238 }
2239
2240
2241 static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
2242   HandleScope scope(node_isolate);
2243 #ifdef __POSIX__
2244   int size = 0;
2245   while (environ[size])
2246     size++;
2247
2248   Local<Array> env = Array::New(size);
2249
2250   for (int i = 0; i < size; ++i) {
2251     const char* var = environ[i];
2252     const char* s = strchr(var, '=');
2253     const int length = s ? s - var : strlen(var);
2254     Local<String> name = String::NewFromUtf8(node_isolate,
2255                                              var,
2256                                              String::kNormalString,
2257                                              length);
2258     env->Set(i, name);
2259   }
2260 #else  // _WIN32
2261   WCHAR* environment = GetEnvironmentStringsW();
2262   if (environment == NULL)
2263     return;  // This should not happen.
2264   Local<Array> env = Array::New();
2265   WCHAR* p = environment;
2266   int i = 0;
2267   while (*p != NULL) {
2268     WCHAR *s;
2269     if (*p == L'=') {
2270       // If the key starts with '=' it is a hidden environment variable.
2271       p += wcslen(p) + 1;
2272       continue;
2273     } else {
2274       s = wcschr(p, L'=');
2275     }
2276     if (!s) {
2277       s = p + wcslen(p);
2278     }
2279     const uint16_t* two_byte_buffer = reinterpret_cast<const uint16_t*>(p);
2280     const size_t two_byte_buffer_len = s - p;
2281     Local<String> value = String::NewFromTwoByte(node_isolate,
2282                                                  two_byte_buffer,
2283                                                  String::kNormalString,
2284                                                  two_byte_buffer_len);
2285     env->Set(i++, value);
2286     p = s + wcslen(s) + 1;
2287   }
2288   FreeEnvironmentStringsW(environment);
2289 #endif
2290
2291   info.GetReturnValue().Set(env);
2292 }
2293
2294
2295 static Handle<Object> GetFeatures() {
2296   HandleScope scope(node_isolate);
2297
2298   Local<Object> obj = Object::New();
2299 #if defined(DEBUG) && DEBUG
2300   Local<Value> debug = True(node_isolate);
2301 #else
2302   Local<Value> debug = False(node_isolate);
2303 #endif  // defined(DEBUG) && DEBUG
2304
2305   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "debug"), debug);
2306
2307   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "uv"), True(node_isolate));
2308   // TODO(bnoordhuis) ping libuv
2309   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "ipv6"), True(node_isolate));
2310
2311 #ifdef OPENSSL_NPN_NEGOTIATED
2312   Local<Boolean> tls_npn = True(node_isolate);
2313 #else
2314   Local<Boolean> tls_npn = False(node_isolate);
2315 #endif
2316   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_npn"), tls_npn);
2317
2318 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
2319   Local<Boolean> tls_sni = True(node_isolate);
2320 #else
2321   Local<Boolean> tls_sni = False(node_isolate);
2322 #endif
2323   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls_sni"), tls_sni);
2324
2325   obj->Set(FIXED_ONE_BYTE_STRING(node_isolate, "tls"),
2326            Boolean::New(get_builtin_module("crypto") != NULL));
2327
2328   return scope.Close(obj);
2329 }
2330
2331
2332 static void DebugPortGetter(Local<String> property,
2333                             const PropertyCallbackInfo<Value>& info) {
2334   HandleScope scope(node_isolate);
2335   info.GetReturnValue().Set(debug_port);
2336 }
2337
2338
2339 static void DebugPortSetter(Local<String> property,
2340                             Local<Value> value,
2341                             const PropertyCallbackInfo<void>& info) {
2342   HandleScope scope(node_isolate);
2343   debug_port = value->NumberValue();
2344 }
2345
2346
2347 static void DebugProcess(const FunctionCallbackInfo<Value>& args);
2348 static void DebugPause(const FunctionCallbackInfo<Value>& args);
2349 static void DebugEnd(const FunctionCallbackInfo<Value>& args);
2350
2351
2352 void NeedImmediateCallbackGetter(Local<String> property,
2353                                  const PropertyCallbackInfo<Value>& info) {
2354   HandleScope handle_scope(info.GetIsolate());
2355   Environment* env = Environment::GetCurrent(info.GetIsolate());
2356   const uv_check_t* immediate_check_handle = env->immediate_check_handle();
2357   bool active = uv_is_active(
2358       reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2359   info.GetReturnValue().Set(active);
2360 }
2361
2362
2363 static void NeedImmediateCallbackSetter(
2364     Local<String> property,
2365     Local<Value> value,
2366     const PropertyCallbackInfo<void>& info) {
2367   HandleScope handle_scope(info.GetIsolate());
2368   Environment* env = Environment::GetCurrent(info.GetIsolate());
2369
2370   uv_check_t* immediate_check_handle = env->immediate_check_handle();
2371   bool active = uv_is_active(
2372       reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
2373
2374   if (active == value->BooleanValue())
2375     return;
2376
2377   uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
2378
2379   if (active) {
2380     uv_check_stop(immediate_check_handle);
2381     uv_idle_stop(immediate_idle_handle);
2382   } else {
2383     uv_check_start(immediate_check_handle, CheckImmediate);
2384     // Idle handle is needed only to stop the event loop from blocking in poll.
2385     uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
2386   }
2387 }
2388
2389
2390 void SetIdle(uv_prepare_t* handle, int) {
2391   Environment* env = Environment::from_idle_prepare_handle(handle);
2392   env->isolate()->GetCpuProfiler()->SetIdle(true);
2393 }
2394
2395
2396 void ClearIdle(uv_check_t* handle, int) {
2397   Environment* env = Environment::from_idle_check_handle(handle);
2398   env->isolate()->GetCpuProfiler()->SetIdle(false);
2399 }
2400
2401
2402 void StartProfilerIdleNotifier(Environment* env) {
2403   uv_prepare_start(env->idle_prepare_handle(), SetIdle);
2404   uv_check_start(env->idle_check_handle(), ClearIdle);
2405 }
2406
2407
2408 void StopProfilerIdleNotifier(Environment* env) {
2409   uv_prepare_stop(env->idle_prepare_handle());
2410   uv_check_stop(env->idle_check_handle());
2411 }
2412
2413
2414 void StartProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2415   HandleScope handle_scope(args.GetIsolate());
2416   Environment* env = Environment::GetCurrent(args.GetIsolate());
2417   StartProfilerIdleNotifier(env);
2418 }
2419
2420
2421 void StopProfilerIdleNotifier(const FunctionCallbackInfo<Value>& args) {
2422   HandleScope handle_scope(args.GetIsolate());
2423   Environment* env = Environment::GetCurrent(args.GetIsolate());
2424   StopProfilerIdleNotifier(env);
2425 }
2426
2427
2428 #define READONLY_PROPERTY(obj, str, var)                                      \
2429   do {                                                                        \
2430     obj->Set(OneByteString(node_isolate, str), var, v8::ReadOnly);            \
2431   } while (0)
2432
2433
2434 void SetupProcessObject(Environment* env,
2435                         int argc,
2436                         const char* const* argv,
2437                         int exec_argc,
2438                         const char* const* exec_argv) {
2439   HandleScope scope(node_isolate);
2440
2441   Local<Object> process = env->process_object();
2442
2443   process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "title"),
2444                        ProcessTitleGetter,
2445                        ProcessTitleSetter);
2446
2447   // process.version
2448   READONLY_PROPERTY(process,
2449                     "version",
2450                     FIXED_ONE_BYTE_STRING(node_isolate, NODE_VERSION));
2451
2452   // process.moduleLoadList
2453   READONLY_PROPERTY(process,
2454                     "moduleLoadList",
2455                     env->module_load_list_array());
2456
2457   // process.versions
2458   Local<Object> versions = Object::New();
2459   READONLY_PROPERTY(process, "versions", versions);
2460
2461   const char http_parser_version[] = NODE_STRINGIFY(HTTP_PARSER_VERSION_MAJOR)
2462                                      "."
2463                                      NODE_STRINGIFY(HTTP_PARSER_VERSION_MINOR);
2464   READONLY_PROPERTY(versions,
2465                     "http_parser",
2466                     FIXED_ONE_BYTE_STRING(node_isolate, http_parser_version));
2467
2468   // +1 to get rid of the leading 'v'
2469   READONLY_PROPERTY(versions,
2470                     "node",
2471                     OneByteString(node_isolate, NODE_VERSION + 1));
2472   READONLY_PROPERTY(versions,
2473                     "v8",
2474                     OneByteString(node_isolate, V8::GetVersion()));
2475   READONLY_PROPERTY(versions,
2476                     "uv",
2477                     OneByteString(node_isolate, uv_version_string()));
2478   READONLY_PROPERTY(versions,
2479                     "zlib",
2480                     FIXED_ONE_BYTE_STRING(node_isolate, ZLIB_VERSION));
2481
2482   const char node_modules_version[] = NODE_STRINGIFY(NODE_MODULE_VERSION);
2483   READONLY_PROPERTY(versions,
2484                     "modules",
2485                     FIXED_ONE_BYTE_STRING(node_isolate, node_modules_version));
2486
2487 #if HAVE_OPENSSL
2488   // Stupid code to slice out the version string.
2489   {  // NOLINT(whitespace/braces)
2490     size_t i, j, k;
2491     int c;
2492     for (i = j = 0, k = sizeof(OPENSSL_VERSION_TEXT) - 1; i < k; ++i) {
2493       c = OPENSSL_VERSION_TEXT[i];
2494       if ('0' <= c && c <= '9') {
2495         for (j = i + 1; j < k; ++j) {
2496           c = OPENSSL_VERSION_TEXT[j];
2497           if (c == ' ')
2498             break;
2499         }
2500         break;
2501       }
2502     }
2503     READONLY_PROPERTY(
2504         versions,
2505         "openssl",
2506         OneByteString(node_isolate, &OPENSSL_VERSION_TEXT[i], j - i));
2507   }
2508 #endif
2509
2510   // process.arch
2511   READONLY_PROPERTY(process, "arch", OneByteString(node_isolate, ARCH));
2512
2513   // process.platform
2514   READONLY_PROPERTY(process,
2515                     "platform",
2516                     OneByteString(node_isolate, PLATFORM));
2517
2518   // process.argv
2519   Local<Array> arguments = Array::New(argc);
2520   for (int i = 0; i < argc; ++i) {
2521     arguments->Set(i, String::NewFromUtf8(node_isolate, argv[i]));
2522   }
2523   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "argv"), arguments);
2524
2525   // process.execArgv
2526   Local<Array> exec_arguments = Array::New(exec_argc);
2527   for (int i = 0; i < exec_argc; ++i) {
2528     exec_arguments->Set(i, String::NewFromUtf8(node_isolate, exec_argv[i]));
2529   }
2530   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execArgv"), exec_arguments);
2531
2532   // create process.env
2533   Local<ObjectTemplate> process_env_template = ObjectTemplate::New();
2534   process_env_template->SetNamedPropertyHandler(EnvGetter,
2535                                                 EnvSetter,
2536                                                 EnvQuery,
2537                                                 EnvDeleter,
2538                                                 EnvEnumerator,
2539                                                 Object::New());
2540   Local<Object> process_env = process_env_template->NewInstance();
2541   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "env"), process_env);
2542
2543   READONLY_PROPERTY(process, "pid", Integer::New(getpid(), node_isolate));
2544   READONLY_PROPERTY(process, "features", GetFeatures());
2545   process->SetAccessor(
2546       FIXED_ONE_BYTE_STRING(node_isolate, "_needImmediateCallback"),
2547       NeedImmediateCallbackGetter,
2548       NeedImmediateCallbackSetter);
2549
2550   // -e, --eval
2551   if (eval_string) {
2552     READONLY_PROPERTY(process,
2553                       "_eval",
2554                       String::NewFromUtf8(node_isolate, eval_string));
2555   }
2556
2557   // -p, --print
2558   if (print_eval) {
2559     READONLY_PROPERTY(process, "_print_eval", True(node_isolate));
2560   }
2561
2562   // -i, --interactive
2563   if (force_repl) {
2564     READONLY_PROPERTY(process, "_forceRepl", True(node_isolate));
2565   }
2566
2567   // --no-deprecation
2568   if (no_deprecation) {
2569     READONLY_PROPERTY(process, "noDeprecation", True(node_isolate));
2570   }
2571
2572   // --throw-deprecation
2573   if (throw_deprecation) {
2574     READONLY_PROPERTY(process, "throwDeprecation", True(node_isolate));
2575   }
2576
2577   // --trace-deprecation
2578   if (trace_deprecation) {
2579     READONLY_PROPERTY(process, "traceDeprecation", True(node_isolate));
2580   }
2581
2582   size_t exec_path_len = 2 * PATH_MAX;
2583   char* exec_path = new char[exec_path_len];
2584   Local<String> exec_path_value;
2585   if (uv_exepath(exec_path, &exec_path_len) == 0) {
2586     exec_path_value = String::NewFromUtf8(node_isolate,
2587                                           exec_path,
2588                                           String::kNormalString,
2589                                           exec_path_len);
2590   } else {
2591     exec_path_value = String::NewFromUtf8(node_isolate, argv[0]);
2592   }
2593   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "execPath"),
2594                exec_path_value);
2595   delete[] exec_path;
2596
2597   process->SetAccessor(FIXED_ONE_BYTE_STRING(node_isolate, "debugPort"),
2598                        DebugPortGetter,
2599                        DebugPortSetter);
2600
2601   // define various internal methods
2602   NODE_SET_METHOD(process,
2603                   "_startProfilerIdleNotifier",
2604                   StartProfilerIdleNotifier);
2605   NODE_SET_METHOD(process,
2606                   "_stopProfilerIdleNotifier",
2607                   StopProfilerIdleNotifier);
2608   NODE_SET_METHOD(process, "_getActiveRequests", GetActiveRequests);
2609   NODE_SET_METHOD(process, "_getActiveHandles", GetActiveHandles);
2610   NODE_SET_METHOD(process, "reallyExit", Exit);
2611   NODE_SET_METHOD(process, "abort", Abort);
2612   NODE_SET_METHOD(process, "chdir", Chdir);
2613   NODE_SET_METHOD(process, "cwd", Cwd);
2614
2615   NODE_SET_METHOD(process, "umask", Umask);
2616
2617 #if defined(__POSIX__) && !defined(__ANDROID__)
2618   NODE_SET_METHOD(process, "getuid", GetUid);
2619   NODE_SET_METHOD(process, "setuid", SetUid);
2620
2621   NODE_SET_METHOD(process, "setgid", SetGid);
2622   NODE_SET_METHOD(process, "getgid", GetGid);
2623
2624   NODE_SET_METHOD(process, "getgroups", GetGroups);
2625   NODE_SET_METHOD(process, "setgroups", SetGroups);
2626   NODE_SET_METHOD(process, "initgroups", InitGroups);
2627 #endif  // __POSIX__ && !defined(__ANDROID__)
2628
2629   NODE_SET_METHOD(process, "_kill", Kill);
2630
2631   NODE_SET_METHOD(process, "_debugProcess", DebugProcess);
2632   NODE_SET_METHOD(process, "_debugPause", DebugPause);
2633   NODE_SET_METHOD(process, "_debugEnd", DebugEnd);
2634
2635   NODE_SET_METHOD(process, "hrtime", Hrtime);
2636
2637   NODE_SET_METHOD(process, "dlopen", DLOpen);
2638
2639   NODE_SET_METHOD(process, "uptime", Uptime);
2640   NODE_SET_METHOD(process, "memoryUsage", MemoryUsage);
2641
2642   NODE_SET_METHOD(process, "binding", Binding);
2643
2644   NODE_SET_METHOD(process, "_setupAsyncListener", SetupAsyncListener);
2645   NODE_SET_METHOD(process, "_setupNextTick", SetupNextTick);
2646   NODE_SET_METHOD(process, "_setupDomainUse", SetupDomainUse);
2647
2648   // values use to cross communicate with processNextTick
2649   Local<Object> tick_info_obj = Object::New();
2650   tick_info_obj->SetIndexedPropertiesToExternalArrayData(
2651       env->tick_info()->fields(),
2652       kExternalUnsignedIntArray,
2653       env->tick_info()->fields_count());
2654   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_tickInfo"), tick_info_obj);
2655
2656   // pre-set _events object for faster emit checks
2657   process->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_events"), Object::New());
2658 }
2659
2660
2661 #undef READONLY_PROPERTY
2662
2663
2664 static void AtExit() {
2665   uv_tty_reset_mode();
2666 }
2667
2668
2669 static void SignalExit(int signal) {
2670   uv_tty_reset_mode();
2671   _exit(128 + signal);
2672 }
2673
2674
2675 // Most of the time, it's best to use `console.error` to write
2676 // to the process.stderr stream.  However, in some cases, such as
2677 // when debugging the stream.Writable class or the process.nextTick
2678 // function, it is useful to bypass JavaScript entirely.
2679 static void RawDebug(const FunctionCallbackInfo<Value>& args) {
2680   HandleScope scope(node_isolate);
2681
2682   assert(args.Length() == 1 && args[0]->IsString() &&
2683          "must be called with a single string");
2684
2685   String::Utf8Value message(args[0]);
2686   fprintf(stderr, "%s\n", *message);
2687   fflush(stderr);
2688 }
2689
2690
2691 void Load(Environment* env) {
2692   HandleScope handle_scope(node_isolate);
2693
2694   // Compile, execute the src/node.js file. (Which was included as static C
2695   // string in node_natives.h. 'natve_node' is the string containing that
2696   // source code.)
2697
2698   // The node.js file returns a function 'f'
2699   atexit(AtExit);
2700
2701   TryCatch try_catch;
2702
2703   // Disable verbose mode to stop FatalException() handler from trying
2704   // to handle the exception. Errors this early in the start-up phase
2705   // are not safe to ignore.
2706   try_catch.SetVerbose(false);
2707
2708   Local<String> script_name = FIXED_ONE_BYTE_STRING(node_isolate, "node.js");
2709   Local<Value> f_value = ExecuteString(MainSource(), script_name);
2710   if (try_catch.HasCaught())  {
2711     ReportException(try_catch);
2712     exit(10);
2713   }
2714   assert(f_value->IsFunction());
2715   Local<Function> f = Local<Function>::Cast(f_value);
2716
2717   // Now we call 'f' with the 'process' variable that we've built up with
2718   // all our bindings. Inside node.js we'll take care of assigning things to
2719   // their places.
2720
2721   // We start the process this way in order to be more modular. Developers
2722   // who do not like how 'src/node.js' setups the module system but do like
2723   // Node's I/O bindings may want to replace 'f' with their own function.
2724
2725   // Add a reference to the global object
2726   Local<Object> global = env->context()->Global();
2727
2728 #if defined HAVE_DTRACE || defined HAVE_ETW
2729   InitDTrace(global);
2730 #endif
2731
2732 #if defined HAVE_PERFCTR
2733   InitPerfCounters(global);
2734 #endif
2735
2736   // Enable handling of uncaught exceptions
2737   // (FatalException(), break on uncaught exception in debugger)
2738   //
2739   // This is not strictly necessary since it's almost impossible
2740   // to attach the debugger fast enought to break on exception
2741   // thrown during process startup.
2742   try_catch.SetVerbose(true);
2743
2744   NODE_SET_METHOD(env->process_object(), "_rawDebug", RawDebug);
2745
2746   Local<Value> arg = env->process_object();
2747   f->Call(global, 1, &arg);
2748 }
2749
2750 static void PrintHelp();
2751
2752 static bool ParseDebugOpt(const char* arg) {
2753   const char* port = NULL;
2754
2755   if (!strcmp(arg, "--debug")) {
2756     use_debug_agent = true;
2757   } else if (!strncmp(arg, "--debug=", sizeof("--debug=") - 1)) {
2758     use_debug_agent = true;
2759     port = arg + sizeof("--debug=") - 1;
2760   } else if (!strcmp(arg, "--debug-brk")) {
2761     use_debug_agent = true;
2762     debug_wait_connect = true;
2763   } else if (!strncmp(arg, "--debug-brk=", sizeof("--debug-brk=") - 1)) {
2764     use_debug_agent = true;
2765     debug_wait_connect = true;
2766     port = arg + sizeof("--debug-brk=") - 1;
2767   } else if (!strncmp(arg, "--debug-port=", sizeof("--debug-port=") - 1)) {
2768     port = arg + sizeof("--debug-port=") - 1;
2769   } else {
2770     return false;
2771   }
2772
2773   if (port != NULL) {
2774     debug_port = atoi(port);
2775     if (debug_port < 1024 || debug_port > 65535) {
2776       fprintf(stderr, "Debug port must be in range 1024 to 65535.\n");
2777       PrintHelp();
2778       exit(12);
2779     }
2780   }
2781
2782   return true;
2783 }
2784
2785 static void PrintHelp() {
2786   printf("Usage: node [options] [ -e script | script.js ] [arguments] \n"
2787          "       node debug script.js [arguments] \n"
2788          "\n"
2789          "Options:\n"
2790          "  -v, --version        print node's version\n"
2791          "  -e, --eval script    evaluate script\n"
2792          "  -p, --print          evaluate script and print result\n"
2793          "  -i, --interactive    always enter the REPL even if stdin\n"
2794          "                       does not appear to be a terminal\n"
2795          "  --no-deprecation     silence deprecation warnings\n"
2796          "  --trace-deprecation  show stack traces on deprecations\n"
2797          "  --v8-options         print v8 command line options\n"
2798          "  --max-stack-size=val set max v8 stack size (bytes)\n"
2799          "\n"
2800          "Environment variables:\n"
2801 #ifdef _WIN32
2802          "NODE_PATH              ';'-separated list of directories\n"
2803 #else
2804          "NODE_PATH              ':'-separated list of directories\n"
2805 #endif
2806          "                       prefixed to the module search path.\n"
2807          "NODE_MODULE_CONTEXTS   Set to 1 to load modules in their own\n"
2808          "                       global contexts.\n"
2809          "NODE_DISABLE_COLORS    Set to 1 to disable colors in the REPL\n"
2810          "\n"
2811          "Documentation can be found at http://nodejs.org/\n");
2812 }
2813
2814
2815 // Parse command line arguments.
2816 //
2817 // argv is modified in place. exec_argv and v8_argv are out arguments that
2818 // ParseArgs() allocates memory for and stores a pointer to the output
2819 // vector in.  The caller should free them with delete[].
2820 //
2821 // On exit:
2822 //
2823 //  * argv contains the arguments with node and V8 options filtered out.
2824 //  * exec_argv contains both node and V8 options and nothing else.
2825 //  * v8_argv contains argv[0] plus any V8 options
2826 static void ParseArgs(int* argc,
2827                       const char** argv,
2828                       int* exec_argc,
2829                       const char*** exec_argv,
2830                       int* v8_argc,
2831                       const char*** v8_argv) {
2832   const unsigned int nargs = static_cast<unsigned int>(*argc);
2833   const char** new_exec_argv = new const char*[nargs];
2834   const char** new_v8_argv = new const char*[nargs];
2835   const char** new_argv = new const char*[nargs];
2836
2837   for (unsigned int i = 0; i < nargs; ++i) {
2838     new_exec_argv[i] = NULL;
2839     new_v8_argv[i] = NULL;
2840     new_argv[i] = NULL;
2841   }
2842
2843   // exec_argv starts with the first option, the other two start with argv[0].
2844   unsigned int new_exec_argc = 0;
2845   unsigned int new_v8_argc = 1;
2846   unsigned int new_argc = 1;
2847   new_v8_argv[0] = argv[0];
2848   new_argv[0] = argv[0];
2849
2850   unsigned int index = 1;
2851   while (index < nargs && argv[index][0] == '-') {
2852     const char* const arg = argv[index];
2853     unsigned int args_consumed = 1;
2854
2855     if (ParseDebugOpt(arg)) {
2856       // Done, consumed by ParseDebugOpt().
2857     } else if (strcmp(arg, "--version") == 0 || strcmp(arg, "-v") == 0) {
2858       printf("%s\n", NODE_VERSION);
2859       exit(0);
2860     } else if (strcmp(arg, "--help") == 0 || strcmp(arg, "-h") == 0) {
2861       PrintHelp();
2862       exit(0);
2863     } else if (strcmp(arg, "--eval") == 0 ||
2864                strcmp(arg, "-e") == 0 ||
2865                strcmp(arg, "--print") == 0 ||
2866                strcmp(arg, "-pe") == 0 ||
2867                strcmp(arg, "-p") == 0) {
2868       bool is_eval = strchr(arg, 'e') != NULL;
2869       bool is_print = strchr(arg, 'p') != NULL;
2870       print_eval = print_eval || is_print;
2871       // --eval, -e and -pe always require an argument.
2872       if (is_eval == true) {
2873         args_consumed += 1;
2874         eval_string = argv[index + 1];
2875         if (eval_string == NULL) {
2876           fprintf(stderr, "%s: %s requires an argument\n", argv[0], arg);
2877           exit(9);
2878         }
2879       } else if ((index + 1 < nargs) &&
2880                  argv[index + 1] != NULL &&
2881                  argv[index + 1][0] != '-') {
2882         args_consumed += 1;
2883         eval_string = argv[index + 1];
2884         if (strncmp(eval_string, "\\-", 2) == 0) {
2885           // Starts with "\\-": escaped expression, drop the backslash.
2886           eval_string += 1;
2887         }
2888       }
2889     } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) {
2890       force_repl = true;
2891     } else if (strcmp(arg, "--no-deprecation") == 0) {
2892       no_deprecation = true;
2893     } else if (strcmp(arg, "--trace-deprecation") == 0) {
2894       trace_deprecation = true;
2895     } else if (strcmp(arg, "--throw-deprecation") == 0) {
2896       throw_deprecation = true;
2897     } else if (strcmp(arg, "--v8-options") == 0) {
2898       new_v8_argv[new_v8_argc] = "--help";
2899       new_v8_argc += 1;
2900     } else {
2901       // V8 option.  Pass through as-is.
2902       new_v8_argv[new_v8_argc] = arg;
2903       new_v8_argc += 1;
2904     }
2905
2906     memcpy(new_exec_argv + new_exec_argc,
2907            argv + index,
2908            args_consumed * sizeof(*argv));
2909
2910     new_exec_argc += args_consumed;
2911     index += args_consumed;
2912   }
2913
2914   // Copy remaining arguments.
2915   const unsigned int args_left = nargs - index;
2916   memcpy(new_argv + new_argc, argv + index, args_left * sizeof(*argv));
2917   new_argc += args_left;
2918
2919   *exec_argc = new_exec_argc;
2920   *exec_argv = new_exec_argv;
2921   *v8_argc = new_v8_argc;
2922   *v8_argv = new_v8_argv;
2923
2924   // Copy new_argv over argv and update argc.
2925   memcpy(argv, new_argv, new_argc * sizeof(*argv));
2926   delete[] new_argv;
2927   *argc = static_cast<int>(new_argc);
2928 }
2929
2930
2931 // Called from V8 Debug Agent TCP thread.
2932 static void DispatchMessagesDebugAgentCallback() {
2933   uv_async_send(&dispatch_debug_messages_async);
2934 }
2935
2936
2937 // Called from the main thread.
2938 static void EnableDebug(bool wait_connect) {
2939   assert(debugger_running == false);
2940   Isolate* isolate = node_isolate;  // TODO(bnoordhuis) Multi-isolate support.
2941   Isolate::Scope isolate_scope(isolate);
2942   HandleScope handle_scope(isolate);
2943   v8::Debug::SetDebugMessageDispatchHandler(DispatchMessagesDebugAgentCallback,
2944                                             false);
2945   debugger_running = v8::Debug::EnableAgent("node " NODE_VERSION,
2946                                             debug_port,
2947                                             wait_connect);
2948   if (debugger_running == false) {
2949     fprintf(stderr, "Starting debugger on port %d failed\n", debug_port);
2950     fflush(stderr);
2951     return;
2952   }
2953   fprintf(stderr, "Debugger listening on port %d\n", debug_port);
2954   fflush(stderr);
2955
2956   Environment* env = Environment::GetCurrentChecked(isolate);
2957   if (env == NULL)
2958     return;  // Still starting up.
2959
2960   Context::Scope context_scope(env->context());
2961   Local<Object> message = Object::New();
2962   message->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "cmd"),
2963                FIXED_ONE_BYTE_STRING(env->isolate(), "NODE_DEBUG_ENABLED"));
2964   Local<Value> argv[] = {
2965     FIXED_ONE_BYTE_STRING(env->isolate(), "internalMessage"),
2966     message
2967   };
2968   MakeCallback(env, env->process_object(), "emit", ARRAY_SIZE(argv), argv);
2969 }
2970
2971
2972 // Called from the main thread.
2973 static void DispatchDebugMessagesAsyncCallback(uv_async_t* handle, int status) {
2974   if (debugger_running == false) {
2975     fprintf(stderr, "Starting debugger agent.\n");
2976     EnableDebug(false);
2977   }
2978   Isolate::Scope isolate_scope(node_isolate);
2979   v8::Debug::ProcessDebugMessages();
2980 }
2981
2982
2983 #ifdef __POSIX__
2984 static volatile sig_atomic_t caught_early_debug_signal;
2985
2986
2987 static void EarlyDebugSignalHandler(int signo) {
2988   caught_early_debug_signal = 1;
2989 }
2990
2991
2992 static void InstallEarlyDebugSignalHandler() {
2993   struct sigaction sa;
2994   memset(&sa, 0, sizeof(sa));
2995   sa.sa_handler = EarlyDebugSignalHandler;
2996   sigaction(SIGUSR1, &sa, NULL);
2997 }
2998
2999
3000 static void EnableDebugSignalHandler(int signo) {
3001   // Call only async signal-safe functions here!
3002   v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3003   uv_async_send(&dispatch_debug_messages_async);
3004 }
3005
3006
3007 static void RegisterSignalHandler(int signal, void (*handler)(int signal)) {
3008   struct sigaction sa;
3009   memset(&sa, 0, sizeof(sa));
3010   sa.sa_handler = handler;
3011   sigfillset(&sa.sa_mask);
3012   sigaction(signal, &sa, NULL);
3013 }
3014
3015
3016 void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3017   HandleScope scope(node_isolate);
3018
3019   if (args.Length() != 1) {
3020     return ThrowError("Invalid number of arguments.");
3021   }
3022
3023   pid_t pid;
3024   int r;
3025
3026   pid = args[0]->IntegerValue();
3027   r = kill(pid, SIGUSR1);
3028   if (r != 0) {
3029     return ThrowErrnoException(errno, "kill");
3030   }
3031 }
3032
3033
3034 static int RegisterDebugSignalHandler() {
3035   // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3036   RegisterSignalHandler(SIGUSR1, EnableDebugSignalHandler);
3037   // If we caught a SIGUSR1 during the bootstrap process, re-raise it
3038   // now that the debugger infrastructure is in place.
3039   if (caught_early_debug_signal)
3040     raise(SIGUSR1);
3041   return 0;
3042 }
3043 #endif  // __POSIX__
3044
3045
3046 #ifdef _WIN32
3047 DWORD WINAPI EnableDebugThreadProc(void* arg) {
3048   v8::Debug::DebugBreak(*static_cast<Isolate* volatile*>(&node_isolate));
3049   uv_async_send(&dispatch_debug_messages_async);
3050   return 0;
3051 }
3052
3053
3054 static int GetDebugSignalHandlerMappingName(DWORD pid, wchar_t* buf,
3055     size_t buf_len) {
3056   return _snwprintf(buf, buf_len, L"node-debug-handler-%u", pid);
3057 }
3058
3059
3060 static int RegisterDebugSignalHandler() {
3061   wchar_t mapping_name[32];
3062   HANDLE mapping_handle;
3063   DWORD pid;
3064   LPTHREAD_START_ROUTINE* handler;
3065
3066   pid = GetCurrentProcessId();
3067
3068   if (GetDebugSignalHandlerMappingName(pid,
3069                                        mapping_name,
3070                                        ARRAY_SIZE(mapping_name)) < 0) {
3071     return -1;
3072   }
3073
3074   mapping_handle = CreateFileMappingW(INVALID_HANDLE_VALUE,
3075                                       NULL,
3076                                       PAGE_READWRITE,
3077                                       0,
3078                                       sizeof *handler,
3079                                       mapping_name);
3080   if (mapping_handle == NULL) {
3081     return -1;
3082   }
3083
3084   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3085       MapViewOfFile(mapping_handle,
3086                     FILE_MAP_ALL_ACCESS,
3087                     0,
3088                     0,
3089                     sizeof *handler));
3090   if (handler == NULL) {
3091     CloseHandle(mapping_handle);
3092     return -1;
3093   }
3094
3095   *handler = EnableDebugThreadProc;
3096
3097   UnmapViewOfFile(static_cast<void*>(handler));
3098
3099   return 0;
3100 }
3101
3102
3103 static void DebugProcess(const FunctionCallbackInfo<Value>& args) {
3104   HandleScope scope(node_isolate);
3105   DWORD pid;
3106   HANDLE process = NULL;
3107   HANDLE thread = NULL;
3108   HANDLE mapping = NULL;
3109   wchar_t mapping_name[32];
3110   LPTHREAD_START_ROUTINE* handler = NULL;
3111
3112   if (args.Length() != 1) {
3113     ThrowError("Invalid number of arguments.");
3114     goto out;
3115   }
3116
3117   pid = (DWORD) args[0]->IntegerValue();
3118
3119   process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
3120                             PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
3121                             PROCESS_VM_READ,
3122                         FALSE,
3123                         pid);
3124   if (process == NULL) {
3125     ThrowException(WinapiErrnoException(GetLastError(), "OpenProcess"));
3126     goto out;
3127   }
3128
3129   if (GetDebugSignalHandlerMappingName(pid,
3130                                        mapping_name,
3131                                        ARRAY_SIZE(mapping_name)) < 0) {
3132     ThrowErrnoException(errno, "sprintf");
3133     goto out;
3134   }
3135
3136   mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name);
3137   if (mapping == NULL) {
3138     ThrowException(WinapiErrnoException(GetLastError(), "OpenFileMappingW"));
3139     goto out;
3140   }
3141
3142   handler = reinterpret_cast<LPTHREAD_START_ROUTINE*>(
3143       MapViewOfFile(mapping,
3144                     FILE_MAP_READ,
3145                     0,
3146                     0,
3147                     sizeof *handler));
3148   if (handler == NULL || *handler == NULL) {
3149     ThrowException(WinapiErrnoException(GetLastError(), "MapViewOfFile"));
3150     goto out;
3151   }
3152
3153   thread = CreateRemoteThread(process,
3154                               NULL,
3155                               0,
3156                               *handler,
3157                               NULL,
3158                               0,
3159                               NULL);
3160   if (thread == NULL) {
3161     ThrowException(WinapiErrnoException(GetLastError(), "CreateRemoteThread"));
3162     goto out;
3163   }
3164
3165   // Wait for the thread to terminate
3166   if (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0) {
3167     ThrowException(WinapiErrnoException(GetLastError(), "WaitForSingleObject"));
3168     goto out;
3169   }
3170
3171  out:
3172   if (process != NULL)
3173     CloseHandle(process);
3174   if (thread != NULL)
3175     CloseHandle(thread);
3176   if (handler != NULL)
3177     UnmapViewOfFile(handler);
3178   if (mapping != NULL)
3179     CloseHandle(mapping);
3180 }
3181 #endif  // _WIN32
3182
3183
3184 static void DebugPause(const FunctionCallbackInfo<Value>& args) {
3185   v8::Debug::DebugBreak(node_isolate);
3186 }
3187
3188
3189 static void DebugEnd(const FunctionCallbackInfo<Value>& args) {
3190   if (debugger_running) {
3191     v8::Debug::DisableAgent();
3192     debugger_running = false;
3193   }
3194 }
3195
3196
3197 void Init(int* argc,
3198           const char** argv,
3199           int* exec_argc,
3200           const char*** exec_argv) {
3201   // Initialize prog_start_time to get relative uptime.
3202   uv_uptime(&prog_start_time);
3203
3204   // Make inherited handles noninheritable.
3205   uv_disable_stdio_inheritance();
3206
3207   // init async debug messages dispatching
3208   // FIXME(bnoordhuis) Should be per-isolate or per-context, not global.
3209   uv_async_init(uv_default_loop(),
3210                 &dispatch_debug_messages_async,
3211                 DispatchDebugMessagesAsyncCallback);
3212   uv_unref(reinterpret_cast<uv_handle_t*>(&dispatch_debug_messages_async));
3213
3214   // Parse a few arguments which are specific to Node.
3215   int v8_argc;
3216   const char** v8_argv;
3217   ParseArgs(argc, argv, exec_argc, exec_argv, &v8_argc, &v8_argv);
3218
3219   // TODO(bnoordhuis) Intercept --prof arguments and start the CPU profiler
3220   // manually?  That would give us a little more control over its runtime
3221   // behavior but it could also interfere with the user's intentions in ways
3222   // we fail to anticipate.  Dillema.
3223   for (int i = 1; i < v8_argc; ++i) {
3224     if (strncmp(v8_argv[i], "--prof", sizeof("--prof") - 1) == 0) {
3225       v8_is_profiling = true;
3226       break;
3227     }
3228   }
3229
3230   // The const_cast doesn't violate conceptual const-ness.  V8 doesn't modify
3231   // the argv array or the elements it points to.
3232   V8::SetFlagsFromCommandLine(&v8_argc, const_cast<char**>(v8_argv), true);
3233
3234   // Anything that's still in v8_argv is not a V8 or a node option.
3235   for (int i = 1; i < v8_argc; i++) {
3236     fprintf(stderr, "%s: bad option: %s\n", argv[0], v8_argv[i]);
3237   }
3238   delete[] v8_argv;
3239   v8_argv = NULL;
3240
3241   if (v8_argc > 1) {
3242     exit(9);
3243   }
3244
3245   if (debug_wait_connect) {
3246     const char expose_debug_as[] = "--expose_debug_as=v8debug";
3247     V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
3248   }
3249
3250   V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton);
3251
3252   // Fetch a reference to the main isolate, so we have a reference to it
3253   // even when we need it to access it from another (debugger) thread.
3254   node_isolate = Isolate::GetCurrent();
3255
3256 #ifdef __POSIX__
3257   // Raise the open file descriptor limit.
3258   {  // NOLINT (whitespace/braces)
3259     struct rlimit lim;
3260     if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
3261       // Do a binary search for the limit.
3262       rlim_t min = lim.rlim_cur;
3263       rlim_t max = 1 << 20;
3264       // But if there's a defined upper bound, don't search, just set it.
3265       if (lim.rlim_max != RLIM_INFINITY) {
3266         min = lim.rlim_max;
3267         max = lim.rlim_max;
3268       }
3269       do {
3270         lim.rlim_cur = min + (max - min) / 2;
3271         if (setrlimit(RLIMIT_NOFILE, &lim)) {
3272           max = lim.rlim_cur;
3273         } else {
3274           min = lim.rlim_cur;
3275         }
3276       } while (min + 1 < max);
3277     }
3278   }
3279   // Ignore SIGPIPE
3280   RegisterSignalHandler(SIGPIPE, SIG_IGN);
3281   RegisterSignalHandler(SIGINT, SignalExit);
3282   RegisterSignalHandler(SIGTERM, SignalExit);
3283 #endif  // __POSIX__
3284
3285   V8::SetFatalErrorHandler(node::OnFatalError);
3286   V8::AddMessageListener(OnMessage);
3287
3288   // If the --debug flag was specified then initialize the debug thread.
3289   if (use_debug_agent) {
3290     EnableDebug(debug_wait_connect);
3291   } else {
3292     RegisterDebugSignalHandler();
3293   }
3294 }
3295
3296
3297 struct AtExitCallback {
3298   AtExitCallback* next_;
3299   void (*cb_)(void* arg);
3300   void* arg_;
3301 };
3302
3303 static AtExitCallback* at_exit_functions_;
3304
3305
3306 // TODO(bnoordhuis) Turn into per-context event.
3307 void RunAtExit(Environment* env) {
3308   AtExitCallback* p = at_exit_functions_;
3309   at_exit_functions_ = NULL;
3310
3311   while (p) {
3312     AtExitCallback* q = p->next_;
3313     p->cb_(p->arg_);
3314     delete p;
3315     p = q;
3316   }
3317 }
3318
3319
3320 void AtExit(void (*cb)(void* arg), void* arg) {
3321   AtExitCallback* p = new AtExitCallback;
3322   p->cb_ = cb;
3323   p->arg_ = arg;
3324   p->next_ = at_exit_functions_;
3325   at_exit_functions_ = p;
3326 }
3327
3328
3329 int EmitExit(Environment* env) {
3330   // process.emit('exit')
3331   HandleScope handle_scope(env->isolate());
3332   Context::Scope context_scope(env->context());
3333   Local<Object> process_object = env->process_object();
3334   process_object->Set(FIXED_ONE_BYTE_STRING(node_isolate, "_exiting"),
3335                       True(node_isolate));
3336
3337   Handle<String> exitCode = FIXED_ONE_BYTE_STRING(node_isolate, "exitCode");
3338   int code = process_object->Get(exitCode)->IntegerValue();
3339
3340   Local<Value> args[] = {
3341     FIXED_ONE_BYTE_STRING(node_isolate, "exit"),
3342     Integer::New(code, node_isolate)
3343   };
3344
3345   MakeCallback(env, process_object, "emit", ARRAY_SIZE(args), args);
3346   return code;
3347 }
3348
3349
3350 Environment* CreateEnvironment(Isolate* isolate,
3351                                int argc,
3352                                const char* const* argv,
3353                                int exec_argc,
3354                                const char* const* exec_argv) {
3355   HandleScope handle_scope(isolate);
3356
3357   Local<Context> context = Context::New(isolate);
3358   Context::Scope context_scope(context);
3359   Environment* env = Environment::New(context);
3360
3361   uv_check_init(env->event_loop(), env->immediate_check_handle());
3362   uv_unref(
3363       reinterpret_cast<uv_handle_t*>(env->immediate_check_handle()));
3364   uv_idle_init(env->event_loop(), env->immediate_idle_handle());
3365
3366   // Inform V8's CPU profiler when we're idle.  The profiler is sampling-based
3367   // but not all samples are created equal; mark the wall clock time spent in
3368   // epoll_wait() and friends so profiling tools can filter it out.  The samples
3369   // still end up in v8.log but with state=IDLE rather than state=EXTERNAL.
3370   // TODO(bnoordhuis) Depends on a libuv implementation detail that we should
3371   // probably fortify in the API contract, namely that the last started prepare
3372   // or check watcher runs first.  It's not 100% foolproof; if an add-on starts
3373   // a prepare or check watcher after us, any samples attributed to its callback
3374   // will be recorded with state=IDLE.
3375   uv_prepare_init(env->event_loop(), env->idle_prepare_handle());
3376   uv_check_init(env->event_loop(), env->idle_check_handle());
3377   uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_prepare_handle()));
3378   uv_unref(reinterpret_cast<uv_handle_t*>(env->idle_check_handle()));
3379
3380   if (v8_is_profiling) {
3381     StartProfilerIdleNotifier(env);
3382   }
3383
3384   Local<FunctionTemplate> process_template = FunctionTemplate::New();
3385   process_template->SetClassName(FIXED_ONE_BYTE_STRING(isolate, "process"));
3386
3387   Local<Object> process_object = process_template->GetFunction()->NewInstance();
3388   env->set_process_object(process_object);
3389
3390   SetupProcessObject(env, argc, argv, exec_argc, exec_argv);
3391   Load(env);
3392
3393   return env;
3394 }
3395
3396
3397 int Start(int argc, char** argv) {
3398 #if !defined(_WIN32)
3399   // Try hard not to lose SIGUSR1 signals during the bootstrap process.
3400   InstallEarlyDebugSignalHandler();
3401 #endif
3402
3403   assert(argc > 0);
3404
3405   // Hack around with the argv pointer. Used for process.title = "blah".
3406   argv = uv_setup_args(argc, argv);
3407
3408   // This needs to run *before* V8::Initialize().  The const_cast is not
3409   // optional, in case you're wondering.
3410   int exec_argc;
3411   const char** exec_argv;
3412   Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
3413
3414 #if HAVE_OPENSSL
3415   // V8 on Windows doesn't have a good source of entropy. Seed it from
3416   // OpenSSL's pool.
3417   V8::SetEntropySource(crypto::EntropySource);
3418 #endif
3419
3420   int code;
3421   V8::Initialize();
3422   {
3423     Locker locker(node_isolate);
3424     Environment* env =
3425         CreateEnvironment(node_isolate, argc, argv, exec_argc, exec_argv);
3426     // This Context::Scope is here so EnableDebug() can look up the current
3427     // environment with Environment::GetCurrentChecked().
3428     // TODO(bnoordhuis) Reorder the debugger initialization logic so it can
3429     // be removed.
3430     Context::Scope context_scope(env->context());
3431     uv_run(env->event_loop(), UV_RUN_DEFAULT);
3432     code = EmitExit(env);
3433     RunAtExit(env);
3434     env->Dispose();
3435     env = NULL;
3436   }
3437
3438 #ifndef NDEBUG
3439   // Clean up. Not strictly necessary.
3440   V8::Dispose();
3441 #endif  // NDEBUG
3442
3443   delete[] exec_argv;
3444   exec_argv = NULL;
3445
3446   return code;
3447 }
3448
3449
3450 }  // namespace node