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