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