0793922472ec12b18229157a3d9b6e2fe2ac8e25
[platform/upstream/cmake.git] / Utilities / cmlibuv / src / unix / core.c
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  * Permission is hereby granted, free of charge, to any person obtaining a copy
3  * of this software and associated documentation files (the "Software"), to
4  * deal in the Software without restriction, including without limitation the
5  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6  * sell copies of the Software, and to permit persons to whom the Software is
7  * furnished to do so, subject to the following conditions:
8  *
9  * The above copyright notice and this permission notice shall be included in
10  * all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18  * IN THE SOFTWARE.
19  */
20
21 #include "uv.h"
22 #include "internal.h"
23
24 #include <stddef.h> /* NULL */
25 #include <stdio.h> /* printf */
26 #include <stdlib.h>
27 #include <string.h> /* strerror */
28 #include <errno.h>
29 #include <assert.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>  /* O_CLOEXEC */
34 #include <sys/ioctl.h>
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
40 #include <sys/uio.h> /* writev */
41 #include <sys/resource.h> /* getrusage */
42 #include <pwd.h>
43 #include <sched.h>
44 #include <sys/utsname.h>
45 #include <sys/time.h>
46
47 #ifdef __sun
48 # include <sys/filio.h>
49 # include <sys/types.h>
50 # include <sys/wait.h>
51 #endif
52
53 #if defined(__APPLE__)
54 # include <sys/filio.h>
55 # endif /* defined(__APPLE__) */
56
57
58 #if defined(__APPLE__) && !TARGET_OS_IPHONE
59 # include <crt_externs.h>
60 # include <mach-o/dyld.h> /* _NSGetExecutablePath */
61 # define environ (*_NSGetEnviron())
62 #else /* defined(__APPLE__) && !TARGET_OS_IPHONE */
63 extern char** environ;
64 #endif /* !(defined(__APPLE__) && !TARGET_OS_IPHONE) */
65
66
67 #if defined(__DragonFly__)      || \
68     defined(__FreeBSD__)        || \
69     defined(__FreeBSD_kernel__) || \
70     defined(__NetBSD__)         || \
71     defined(__OpenBSD__)
72 # include <sys/sysctl.h>
73 # include <sys/filio.h>
74 # include <sys/wait.h>
75 # if defined(__FreeBSD__)
76 #  define uv__accept4 accept4
77 # endif
78 # if defined(__NetBSD__)
79 #  define uv__accept4(a, b, c, d) paccept((a), (b), (c), NULL, (d))
80 # endif
81 #endif
82
83 #if defined(__FreeBSD__)
84 # include <sys/param.h>
85 # include <sys/cpuset.h>
86 #endif
87
88 #if defined(__MVS__)
89 #include <sys/ioctl.h>
90 #endif
91
92 #if defined(__linux__)
93 # include <sys/syscall.h>
94 # define uv__accept4 accept4
95 #endif
96
97 #if defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
98 # include <sanitizer/linux_syscall_hooks.h>
99 #endif
100
101 static int uv__run_pending(uv_loop_t* loop);
102
103 /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
104 STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
105 STATIC_ASSERT(sizeof(((uv_buf_t*) 0)->base) ==
106               sizeof(((struct iovec*) 0)->iov_base));
107 STATIC_ASSERT(sizeof(((uv_buf_t*) 0)->len) ==
108               sizeof(((struct iovec*) 0)->iov_len));
109 STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
110 STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
111
112
113 uint64_t uv_hrtime(void) {
114   return uv__hrtime(UV_CLOCK_PRECISE);
115 }
116
117
118 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
119   assert(!uv__is_closing(handle));
120
121   handle->flags |= UV_HANDLE_CLOSING;
122   handle->close_cb = close_cb;
123
124   switch (handle->type) {
125   case UV_NAMED_PIPE:
126     uv__pipe_close((uv_pipe_t*)handle);
127     break;
128
129   case UV_TTY:
130     uv__stream_close((uv_stream_t*)handle);
131     break;
132
133   case UV_TCP:
134     uv__tcp_close((uv_tcp_t*)handle);
135     break;
136
137   case UV_UDP:
138     uv__udp_close((uv_udp_t*)handle);
139     break;
140
141   case UV_PREPARE:
142     uv__prepare_close((uv_prepare_t*)handle);
143     break;
144
145   case UV_CHECK:
146     uv__check_close((uv_check_t*)handle);
147     break;
148
149   case UV_IDLE:
150     uv__idle_close((uv_idle_t*)handle);
151     break;
152
153   case UV_ASYNC:
154     uv__async_close((uv_async_t*)handle);
155     break;
156
157   case UV_TIMER:
158     uv__timer_close((uv_timer_t*)handle);
159     break;
160
161   case UV_PROCESS:
162     uv__process_close((uv_process_t*)handle);
163     break;
164
165   case UV_FS_EVENT:
166     uv__fs_event_close((uv_fs_event_t*)handle);
167     break;
168
169   case UV_POLL:
170     uv__poll_close((uv_poll_t*)handle);
171     break;
172
173   case UV_FS_POLL:
174     uv__fs_poll_close((uv_fs_poll_t*)handle);
175     /* Poll handles use file system requests, and one of them may still be
176      * running. The poll code will call uv__make_close_pending() for us. */
177     return;
178
179   case UV_SIGNAL:
180     uv__signal_close((uv_signal_t*) handle);
181     break;
182
183   default:
184     assert(0);
185   }
186
187   uv__make_close_pending(handle);
188 }
189
190 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
191   int r;
192   int fd;
193   socklen_t len;
194
195   if (handle == NULL || value == NULL)
196     return UV_EINVAL;
197
198   if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
199     fd = uv__stream_fd((uv_stream_t*) handle);
200   else if (handle->type == UV_UDP)
201     fd = ((uv_udp_t *) handle)->io_watcher.fd;
202   else
203     return UV_ENOTSUP;
204
205   len = sizeof(*value);
206
207   if (*value == 0)
208     r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
209   else
210     r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
211
212   if (r < 0)
213     return UV__ERR(errno);
214
215   return 0;
216 }
217
218 void uv__make_close_pending(uv_handle_t* handle) {
219   assert(handle->flags & UV_HANDLE_CLOSING);
220   assert(!(handle->flags & UV_HANDLE_CLOSED));
221   handle->next_closing = handle->loop->closing_handles;
222   handle->loop->closing_handles = handle;
223 }
224
225 int uv__getiovmax(void) {
226 #if defined(IOV_MAX)
227   return IOV_MAX;
228 #elif defined(_SC_IOV_MAX)
229   static int iovmax_cached = -1;
230   int iovmax;
231
232   iovmax = uv__load_relaxed(&iovmax_cached);
233   if (iovmax != -1)
234     return iovmax;
235
236   /* On some embedded devices (arm-linux-uclibc based ip camera),
237    * sysconf(_SC_IOV_MAX) can not get the correct value. The return
238    * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
239    */
240   iovmax = sysconf(_SC_IOV_MAX);
241   if (iovmax == -1)
242     iovmax = 1;
243
244   uv__store_relaxed(&iovmax_cached, iovmax);
245
246   return iovmax;
247 #else
248   return 1024;
249 #endif
250 }
251
252
253 static void uv__finish_close(uv_handle_t* handle) {
254   uv_signal_t* sh;
255
256   /* Note: while the handle is in the UV_HANDLE_CLOSING state now, it's still
257    * possible for it to be active in the sense that uv__is_active() returns
258    * true.
259    *
260    * A good example is when the user calls uv_shutdown(), immediately followed
261    * by uv_close(). The handle is considered active at this point because the
262    * completion of the shutdown req is still pending.
263    */
264   assert(handle->flags & UV_HANDLE_CLOSING);
265   assert(!(handle->flags & UV_HANDLE_CLOSED));
266   handle->flags |= UV_HANDLE_CLOSED;
267
268   switch (handle->type) {
269     case UV_PREPARE:
270     case UV_CHECK:
271     case UV_IDLE:
272     case UV_ASYNC:
273     case UV_TIMER:
274     case UV_PROCESS:
275     case UV_FS_EVENT:
276     case UV_FS_POLL:
277     case UV_POLL:
278       break;
279
280     case UV_SIGNAL:
281       /* If there are any caught signals "trapped" in the signal pipe,
282        * we can't call the close callback yet. Reinserting the handle
283        * into the closing queue makes the event loop spin but that's
284        * okay because we only need to deliver the pending events.
285        */
286       sh = (uv_signal_t*) handle;
287       if (sh->caught_signals > sh->dispatched_signals) {
288         handle->flags ^= UV_HANDLE_CLOSED;
289         uv__make_close_pending(handle);  /* Back into the queue. */
290         return;
291       }
292       break;
293
294     case UV_NAMED_PIPE:
295     case UV_TCP:
296     case UV_TTY:
297       uv__stream_destroy((uv_stream_t*)handle);
298       break;
299
300     case UV_UDP:
301       uv__udp_finish_close((uv_udp_t*)handle);
302       break;
303
304     default:
305       assert(0);
306       break;
307   }
308
309   uv__handle_unref(handle);
310   QUEUE_REMOVE(&handle->handle_queue);
311
312   if (handle->close_cb) {
313     handle->close_cb(handle);
314   }
315 }
316
317
318 static void uv__run_closing_handles(uv_loop_t* loop) {
319   uv_handle_t* p;
320   uv_handle_t* q;
321
322   p = loop->closing_handles;
323   loop->closing_handles = NULL;
324
325   while (p) {
326     q = p->next_closing;
327     uv__finish_close(p);
328     p = q;
329   }
330 }
331
332
333 int uv_is_closing(const uv_handle_t* handle) {
334   return uv__is_closing(handle);
335 }
336
337
338 int uv_backend_fd(const uv_loop_t* loop) {
339   return loop->backend_fd;
340 }
341
342
343 int uv_backend_timeout(const uv_loop_t* loop) {
344   if (loop->stop_flag != 0)
345     return 0;
346
347   if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
348     return 0;
349
350   if (!QUEUE_EMPTY(&loop->idle_handles))
351     return 0;
352
353   if (!QUEUE_EMPTY(&loop->pending_queue))
354     return 0;
355
356   if (loop->closing_handles)
357     return 0;
358
359   return uv__next_timeout(loop);
360 }
361
362
363 static int uv__loop_alive(const uv_loop_t* loop) {
364   return uv__has_active_handles(loop) ||
365          uv__has_active_reqs(loop) ||
366          loop->closing_handles != NULL;
367 }
368
369
370 int uv_loop_alive(const uv_loop_t* loop) {
371     return uv__loop_alive(loop);
372 }
373
374
375 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
376   int timeout;
377   int r;
378   int ran_pending;
379
380   r = uv__loop_alive(loop);
381   if (!r)
382     uv__update_time(loop);
383
384   while (r != 0 && loop->stop_flag == 0) {
385     uv__update_time(loop);
386     uv__run_timers(loop);
387     ran_pending = uv__run_pending(loop);
388     uv__run_idle(loop);
389     uv__run_prepare(loop);
390
391     timeout = 0;
392     if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
393       timeout = uv_backend_timeout(loop);
394
395     uv__io_poll(loop, timeout);
396
397     /* Run one final update on the provider_idle_time in case uv__io_poll
398      * returned because the timeout expired, but no events were received. This
399      * call will be ignored if the provider_entry_time was either never set (if
400      * the timeout == 0) or was already updated b/c an event was received.
401      */
402     uv__metrics_update_idle_time(loop);
403
404     uv__run_check(loop);
405     uv__run_closing_handles(loop);
406
407     if (mode == UV_RUN_ONCE) {
408       /* UV_RUN_ONCE implies forward progress: at least one callback must have
409        * been invoked when it returns. uv__io_poll() can return without doing
410        * I/O (meaning: no callbacks) when its timeout expires - which means we
411        * have pending timers that satisfy the forward progress constraint.
412        *
413        * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
414        * the check.
415        */
416       uv__update_time(loop);
417       uv__run_timers(loop);
418     }
419
420     r = uv__loop_alive(loop);
421     if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
422       break;
423   }
424
425   /* The if statement lets gcc compile it to a conditional store. Avoids
426    * dirtying a cache line.
427    */
428   if (loop->stop_flag != 0)
429     loop->stop_flag = 0;
430
431   return r;
432 }
433
434
435 void uv_update_time(uv_loop_t* loop) {
436   uv__update_time(loop);
437 }
438
439
440 int uv_is_active(const uv_handle_t* handle) {
441   return uv__is_active(handle);
442 }
443
444
445 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
446 int uv__socket(int domain, int type, int protocol) {
447   int sockfd;
448   int err;
449
450 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
451   sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
452   if (sockfd != -1)
453     return sockfd;
454
455   if (errno != EINVAL)
456     return UV__ERR(errno);
457 #endif
458
459   sockfd = socket(domain, type, protocol);
460   if (sockfd == -1)
461     return UV__ERR(errno);
462
463   err = uv__nonblock(sockfd, 1);
464   if (err == 0)
465     err = uv__cloexec(sockfd, 1);
466
467   if (err) {
468     uv__close(sockfd);
469     return err;
470   }
471
472 #if defined(SO_NOSIGPIPE)
473   {
474     int on = 1;
475     setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
476   }
477 #endif
478
479   return sockfd;
480 }
481
482 /* get a file pointer to a file in read-only and close-on-exec mode */
483 FILE* uv__open_file(const char* path) {
484   int fd;
485   FILE* fp;
486
487   fd = uv__open_cloexec(path, O_RDONLY);
488   if (fd < 0)
489     return NULL;
490
491    fp = fdopen(fd, "r");
492    if (fp == NULL)
493      uv__close(fd);
494
495    return fp;
496 }
497
498
499 int uv__accept(int sockfd) {
500   int peerfd;
501   int err;
502
503   (void) &err;
504   assert(sockfd >= 0);
505
506   do
507 #ifdef uv__accept4
508     peerfd = uv__accept4(sockfd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
509 #else
510     peerfd = accept(sockfd, NULL, NULL);
511 #endif
512   while (peerfd == -1 && errno == EINTR);
513
514   if (peerfd == -1)
515     return UV__ERR(errno);
516
517 #ifndef uv__accept4
518   err = uv__cloexec(peerfd, 1);
519   if (err == 0)
520     err = uv__nonblock(peerfd, 1);
521
522   if (err != 0) {
523     uv__close(peerfd);
524     return err;
525   }
526 #endif
527
528   return peerfd;
529 }
530
531
532 /* close() on macos has the "interesting" quirk that it fails with EINTR
533  * without closing the file descriptor when a thread is in the cancel state.
534  * That's why libuv calls close$NOCANCEL() instead.
535  *
536  * glibc on linux has a similar issue: close() is a cancellation point and
537  * will unwind the thread when it's in the cancel state. Work around that
538  * by making the system call directly. Musl libc is unaffected.
539  */
540 int uv__close_nocancel(int fd) {
541 #if defined(__APPLE__)
542 #pragma GCC diagnostic push
543 #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension"
544 #if defined(__LP64__) || TARGET_OS_IPHONE
545   extern int close$NOCANCEL(int);
546   return close$NOCANCEL(fd);
547 #else
548   extern int close$NOCANCEL$UNIX2003(int);
549   return close$NOCANCEL$UNIX2003(fd);
550 #endif
551 #pragma GCC diagnostic pop
552 #elif defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
553   long rc;
554   __sanitizer_syscall_pre_close(fd);
555   rc = syscall(SYS_close, fd);
556   __sanitizer_syscall_post_close(rc, fd);
557   return rc;
558 #elif defined(__linux__) && !defined(__SANITIZE_THREAD__)
559   return syscall(SYS_close, fd);
560 #else
561   return close(fd);
562 #endif
563 }
564
565
566 int uv__close_nocheckstdio(int fd) {
567   int saved_errno;
568   int rc;
569
570   assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
571
572   saved_errno = errno;
573   rc = uv__close_nocancel(fd);
574   if (rc == -1) {
575     rc = UV__ERR(errno);
576     if (rc == UV_EINTR || rc == UV__ERR(EINPROGRESS))
577       rc = 0;    /* The close is in progress, not an error. */
578     errno = saved_errno;
579   }
580
581   return rc;
582 }
583
584
585 int uv__close(int fd) {
586   assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
587 #if defined(__MVS__)
588   SAVE_ERRNO(epoll_file_close(fd));
589 #endif
590   return uv__close_nocheckstdio(fd);
591 }
592
593 #if UV__NONBLOCK_IS_IOCTL
594 int uv__nonblock_ioctl(int fd, int set) {
595   int r;
596
597   do
598     r = ioctl(fd, FIONBIO, &set);
599   while (r == -1 && errno == EINTR);
600
601   if (r)
602     return UV__ERR(errno);
603
604   return 0;
605 }
606
607
608 int uv__cloexec_ioctl(int fd, int set) {
609   int r;
610
611   do
612     r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
613   while (r == -1 && errno == EINTR);
614
615   if (r)
616     return UV__ERR(errno);
617
618   return 0;
619 }
620 #endif
621
622
623 int uv__nonblock_fcntl(int fd, int set) {
624   int flags;
625   int r;
626
627   do
628     r = fcntl(fd, F_GETFL);
629   while (r == -1 && errno == EINTR);
630
631   if (r == -1)
632     return UV__ERR(errno);
633
634   /* Bail out now if already set/clear. */
635   if (!!(r & O_NONBLOCK) == !!set)
636     return 0;
637
638   if (set)
639     flags = r | O_NONBLOCK;
640   else
641     flags = r & ~O_NONBLOCK;
642
643   do
644     r = fcntl(fd, F_SETFL, flags);
645   while (r == -1 && errno == EINTR);
646
647   if (r)
648     return UV__ERR(errno);
649
650   return 0;
651 }
652
653
654 int uv__cloexec_fcntl(int fd, int set) {
655   int flags;
656   int r;
657
658   do
659     r = fcntl(fd, F_GETFD);
660   while (r == -1 && errno == EINTR);
661
662   if (r == -1)
663     return UV__ERR(errno);
664
665   /* Bail out now if already set/clear. */
666   if (!!(r & FD_CLOEXEC) == !!set)
667     return 0;
668
669   if (set)
670     flags = r | FD_CLOEXEC;
671   else
672     flags = r & ~FD_CLOEXEC;
673
674   do
675     r = fcntl(fd, F_SETFD, flags);
676   while (r == -1 && errno == EINTR);
677
678   if (r)
679     return UV__ERR(errno);
680
681   return 0;
682 }
683
684
685 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
686   struct cmsghdr* cmsg;
687   ssize_t rc;
688   int* pfd;
689   int* end;
690 #if defined(__linux__)
691   static int no_msg_cmsg_cloexec;
692   if (0 == uv__load_relaxed(&no_msg_cmsg_cloexec)) {
693     rc = recvmsg(fd, msg, flags | 0x40000000);  /* MSG_CMSG_CLOEXEC */
694     if (rc != -1)
695       return rc;
696     if (errno != EINVAL)
697       return UV__ERR(errno);
698     rc = recvmsg(fd, msg, flags);
699     if (rc == -1)
700       return UV__ERR(errno);
701     uv__store_relaxed(&no_msg_cmsg_cloexec, 1);
702   } else {
703     rc = recvmsg(fd, msg, flags);
704   }
705 #else
706   rc = recvmsg(fd, msg, flags);
707 #endif
708   if (rc == -1)
709     return UV__ERR(errno);
710   if (msg->msg_controllen == 0)
711     return rc;
712   for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
713     if (cmsg->cmsg_type == SCM_RIGHTS)
714       for (pfd = (int*) CMSG_DATA(cmsg),
715            end = (int*) ((char*) cmsg + cmsg->cmsg_len);
716            pfd < end;
717            pfd += 1)
718         uv__cloexec(*pfd, 1);
719   return rc;
720 }
721
722
723 int uv_cwd(char* buffer, size_t* size) {
724   char scratch[1 + UV__PATH_MAX];
725
726   if (buffer == NULL || size == NULL)
727     return UV_EINVAL;
728
729   /* Try to read directly into the user's buffer first... */
730   if (getcwd(buffer, *size) != NULL)
731     goto fixup;
732
733   if (errno != ERANGE)
734     return UV__ERR(errno);
735
736   /* ...or into scratch space if the user's buffer is too small
737    * so we can report how much space to provide on the next try.
738    */
739   if (getcwd(scratch, sizeof(scratch)) == NULL)
740     return UV__ERR(errno);
741
742   buffer = scratch;
743
744 fixup:
745
746   *size = strlen(buffer);
747
748   if (*size > 1 && buffer[*size - 1] == '/') {
749     *size -= 1;
750     buffer[*size] = '\0';
751   }
752
753   if (buffer == scratch) {
754     *size += 1;
755     return UV_ENOBUFS;
756   }
757
758   return 0;
759 }
760
761
762 int uv_chdir(const char* dir) {
763   if (chdir(dir))
764     return UV__ERR(errno);
765
766   return 0;
767 }
768
769
770 void uv_disable_stdio_inheritance(void) {
771   int fd;
772
773   /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
774    * first 16 file descriptors. After that, bail out after the first error.
775    */
776   for (fd = 0; ; fd++)
777     if (uv__cloexec(fd, 1) && fd > 15)
778       break;
779 }
780
781
782 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
783   int fd_out;
784
785   switch (handle->type) {
786   case UV_TCP:
787   case UV_NAMED_PIPE:
788   case UV_TTY:
789     fd_out = uv__stream_fd((uv_stream_t*) handle);
790     break;
791
792   case UV_UDP:
793     fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
794     break;
795
796   case UV_POLL:
797     fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
798     break;
799
800   default:
801     return UV_EINVAL;
802   }
803
804   if (uv__is_closing(handle) || fd_out == -1)
805     return UV_EBADF;
806
807   *fd = fd_out;
808   return 0;
809 }
810
811
812 static int uv__run_pending(uv_loop_t* loop) {
813   QUEUE* q;
814   QUEUE pq;
815   uv__io_t* w;
816
817   if (QUEUE_EMPTY(&loop->pending_queue))
818     return 0;
819
820   QUEUE_MOVE(&loop->pending_queue, &pq);
821
822   while (!QUEUE_EMPTY(&pq)) {
823     q = QUEUE_HEAD(&pq);
824     QUEUE_REMOVE(q);
825     QUEUE_INIT(q);
826     w = QUEUE_DATA(q, uv__io_t, pending_queue);
827     w->cb(loop, w, POLLOUT);
828   }
829
830   return 1;
831 }
832
833
834 static unsigned int next_power_of_two(unsigned int val) {
835   val -= 1;
836   val |= val >> 1;
837   val |= val >> 2;
838   val |= val >> 4;
839   val |= val >> 8;
840   val |= val >> 16;
841   val += 1;
842   return val;
843 }
844
845 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
846   uv__io_t** watchers;
847   void* fake_watcher_list;
848   void* fake_watcher_count;
849   unsigned int nwatchers;
850   unsigned int i;
851
852   if (len <= loop->nwatchers)
853     return;
854
855   /* Preserve fake watcher list and count at the end of the watchers */
856   if (loop->watchers != NULL) {
857     fake_watcher_list = loop->watchers[loop->nwatchers];
858     fake_watcher_count = loop->watchers[loop->nwatchers + 1];
859   } else {
860     fake_watcher_list = NULL;
861     fake_watcher_count = NULL;
862   }
863
864   nwatchers = next_power_of_two(len + 2) - 2;
865   watchers = uv__reallocf(loop->watchers,
866                           (nwatchers + 2) * sizeof(loop->watchers[0]));
867
868   if (watchers == NULL)
869     abort();
870   for (i = loop->nwatchers; i < nwatchers; i++)
871     watchers[i] = NULL;
872   watchers[nwatchers] = fake_watcher_list;
873   watchers[nwatchers + 1] = fake_watcher_count;
874
875   loop->watchers = watchers;
876   loop->nwatchers = nwatchers;
877 }
878
879
880 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
881   assert(cb != NULL);
882   assert(fd >= -1);
883   QUEUE_INIT(&w->pending_queue);
884   QUEUE_INIT(&w->watcher_queue);
885   w->cb = cb;
886   w->fd = fd;
887   w->events = 0;
888   w->pevents = 0;
889
890 #if defined(UV_HAVE_KQUEUE)
891   w->rcount = 0;
892   w->wcount = 0;
893 #endif /* defined(UV_HAVE_KQUEUE) */
894 }
895
896
897 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
898   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
899   assert(0 != events);
900   assert(w->fd >= 0);
901   assert(w->fd < INT_MAX);
902
903   w->pevents |= events;
904   maybe_resize(loop, w->fd + 1);
905
906 #if !defined(__sun)
907   /* The event ports backend needs to rearm all file descriptors on each and
908    * every tick of the event loop but the other backends allow us to
909    * short-circuit here if the event mask is unchanged.
910    */
911   if (w->events == w->pevents)
912     return;
913 #endif
914
915   if (QUEUE_EMPTY(&w->watcher_queue))
916     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
917
918   if (loop->watchers[w->fd] == NULL) {
919     loop->watchers[w->fd] = w;
920     loop->nfds++;
921   }
922 }
923
924
925 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
926   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
927   assert(0 != events);
928
929   if (w->fd == -1)
930     return;
931
932   assert(w->fd >= 0);
933
934   /* Happens when uv__io_stop() is called on a handle that was never started. */
935   if ((unsigned) w->fd >= loop->nwatchers)
936     return;
937
938   w->pevents &= ~events;
939
940   if (w->pevents == 0) {
941     QUEUE_REMOVE(&w->watcher_queue);
942     QUEUE_INIT(&w->watcher_queue);
943     w->events = 0;
944
945     if (w == loop->watchers[w->fd]) {
946       assert(loop->nfds > 0);
947       loop->watchers[w->fd] = NULL;
948       loop->nfds--;
949     }
950   }
951   else if (QUEUE_EMPTY(&w->watcher_queue))
952     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
953 }
954
955
956 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
957   uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI);
958   QUEUE_REMOVE(&w->pending_queue);
959
960   /* Remove stale events for this file descriptor */
961   if (w->fd != -1)
962     uv__platform_invalidate_fd(loop, w->fd);
963 }
964
965
966 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
967   if (QUEUE_EMPTY(&w->pending_queue))
968     QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
969 }
970
971
972 int uv__io_active(const uv__io_t* w, unsigned int events) {
973   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
974   assert(0 != events);
975   return 0 != (w->pevents & events);
976 }
977
978
979 int uv__fd_exists(uv_loop_t* loop, int fd) {
980   return (unsigned) fd < loop->nwatchers && loop->watchers[fd] != NULL;
981 }
982
983
984 int uv_getrusage(uv_rusage_t* rusage) {
985   struct rusage usage;
986
987   if (getrusage(RUSAGE_SELF, &usage))
988     return UV__ERR(errno);
989
990   rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
991   rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
992
993   rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
994   rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
995
996 #if !defined(__MVS__) && !defined(__HAIKU__)
997   rusage->ru_maxrss = usage.ru_maxrss;
998   rusage->ru_ixrss = usage.ru_ixrss;
999   rusage->ru_idrss = usage.ru_idrss;
1000   rusage->ru_isrss = usage.ru_isrss;
1001   rusage->ru_minflt = usage.ru_minflt;
1002   rusage->ru_majflt = usage.ru_majflt;
1003   rusage->ru_nswap = usage.ru_nswap;
1004   rusage->ru_inblock = usage.ru_inblock;
1005   rusage->ru_oublock = usage.ru_oublock;
1006   rusage->ru_msgsnd = usage.ru_msgsnd;
1007   rusage->ru_msgrcv = usage.ru_msgrcv;
1008   rusage->ru_nsignals = usage.ru_nsignals;
1009   rusage->ru_nvcsw = usage.ru_nvcsw;
1010   rusage->ru_nivcsw = usage.ru_nivcsw;
1011 #endif
1012
1013   return 0;
1014 }
1015
1016
1017 int uv__open_cloexec(const char* path, int flags) {
1018 #if defined(O_CLOEXEC)
1019   int fd;
1020
1021   fd = open(path, flags | O_CLOEXEC);
1022   if (fd == -1)
1023     return UV__ERR(errno);
1024
1025   return fd;
1026 #else  /* O_CLOEXEC */
1027   int err;
1028   int fd;
1029
1030   fd = open(path, flags);
1031   if (fd == -1)
1032     return UV__ERR(errno);
1033
1034   err = uv__cloexec(fd, 1);
1035   if (err) {
1036     uv__close(fd);
1037     return err;
1038   }
1039
1040   return fd;
1041 #endif  /* O_CLOEXEC */
1042 }
1043
1044
1045 int uv__dup2_cloexec(int oldfd, int newfd) {
1046 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__linux__)
1047   int r;
1048
1049   r = dup3(oldfd, newfd, O_CLOEXEC);
1050   if (r == -1)
1051     return UV__ERR(errno);
1052
1053   return r;
1054 #else
1055   int err;
1056   int r;
1057
1058   r = dup2(oldfd, newfd);  /* Never retry. */
1059   if (r == -1)
1060     return UV__ERR(errno);
1061
1062   err = uv__cloexec(newfd, 1);
1063   if (err != 0) {
1064     uv__close(newfd);
1065     return err;
1066   }
1067
1068   return r;
1069 #endif
1070 }
1071
1072
1073 int uv_os_homedir(char* buffer, size_t* size) {
1074   uv_passwd_t pwd;
1075   size_t len;
1076   int r;
1077
1078   /* Check if the HOME environment variable is set first. The task of
1079      performing input validation on buffer and size is taken care of by
1080      uv_os_getenv(). */
1081   r = uv_os_getenv("HOME", buffer, size);
1082
1083   if (r != UV_ENOENT)
1084     return r;
1085
1086   /* HOME is not set, so call uv__getpwuid_r() */
1087   r = uv__getpwuid_r(&pwd);
1088
1089   if (r != 0) {
1090     return r;
1091   }
1092
1093   len = strlen(pwd.homedir);
1094
1095   if (len >= *size) {
1096     *size = len + 1;
1097     uv_os_free_passwd(&pwd);
1098     return UV_ENOBUFS;
1099   }
1100
1101   memcpy(buffer, pwd.homedir, len + 1);
1102   *size = len;
1103   uv_os_free_passwd(&pwd);
1104
1105   return 0;
1106 }
1107
1108
1109 int uv_os_tmpdir(char* buffer, size_t* size) {
1110   const char* buf;
1111   size_t len;
1112
1113   if (buffer == NULL || size == NULL || *size == 0)
1114     return UV_EINVAL;
1115
1116 #define CHECK_ENV_VAR(name)                                                   \
1117   do {                                                                        \
1118     buf = getenv(name);                                                       \
1119     if (buf != NULL)                                                          \
1120       goto return_buffer;                                                     \
1121   }                                                                           \
1122   while (0)
1123
1124   /* Check the TMPDIR, TMP, TEMP, and TEMPDIR environment variables in order */
1125   CHECK_ENV_VAR("TMPDIR");
1126   CHECK_ENV_VAR("TMP");
1127   CHECK_ENV_VAR("TEMP");
1128   CHECK_ENV_VAR("TEMPDIR");
1129
1130 #undef CHECK_ENV_VAR
1131
1132   /* No temp environment variables defined */
1133   #if defined(__ANDROID__)
1134     buf = "/data/local/tmp";
1135   #else
1136     buf = "/tmp";
1137   #endif
1138
1139 return_buffer:
1140   len = strlen(buf);
1141
1142   if (len >= *size) {
1143     *size = len + 1;
1144     return UV_ENOBUFS;
1145   }
1146
1147   /* The returned directory should not have a trailing slash. */
1148   if (len > 1 && buf[len - 1] == '/') {
1149     len--;
1150   }
1151
1152   memcpy(buffer, buf, len + 1);
1153   buffer[len] = '\0';
1154   *size = len;
1155
1156   return 0;
1157 }
1158
1159
1160 int uv__getpwuid_r(uv_passwd_t* pwd) {
1161   struct passwd pw;
1162   struct passwd* result;
1163   char* buf;
1164   uid_t uid;
1165   size_t bufsize;
1166   size_t name_size;
1167   size_t homedir_size;
1168   size_t shell_size;
1169   long initsize;
1170   int r;
1171
1172   if (pwd == NULL)
1173     return UV_EINVAL;
1174
1175   initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1176
1177   if (initsize <= 0)
1178     bufsize = 4096;
1179   else
1180     bufsize = (size_t) initsize;
1181
1182   uid = geteuid();
1183   buf = NULL;
1184
1185   for (;;) {
1186     uv__free(buf);
1187     buf = uv__malloc(bufsize);
1188
1189     if (buf == NULL)
1190       return UV_ENOMEM;
1191
1192     do
1193       r = getpwuid_r(uid, &pw, buf, bufsize, &result);
1194     while (r == EINTR);
1195
1196     if (r != ERANGE)
1197       break;
1198
1199     bufsize *= 2;
1200   }
1201
1202   if (r != 0) {
1203     uv__free(buf);
1204     return UV__ERR(r);
1205   }
1206
1207   if (result == NULL) {
1208     uv__free(buf);
1209     return UV_ENOENT;
1210   }
1211
1212   /* Allocate memory for the username, shell, and home directory */
1213   name_size = strlen(pw.pw_name) + 1;
1214   homedir_size = strlen(pw.pw_dir) + 1;
1215   shell_size = strlen(pw.pw_shell) + 1;
1216   pwd->username = uv__malloc(name_size + homedir_size + shell_size);
1217
1218   if (pwd->username == NULL) {
1219     uv__free(buf);
1220     return UV_ENOMEM;
1221   }
1222
1223   /* Copy the username */
1224   memcpy(pwd->username, pw.pw_name, name_size);
1225
1226   /* Copy the home directory */
1227   pwd->homedir = pwd->username + name_size;
1228   memcpy(pwd->homedir, pw.pw_dir, homedir_size);
1229
1230   /* Copy the shell */
1231   pwd->shell = pwd->homedir + homedir_size;
1232   memcpy(pwd->shell, pw.pw_shell, shell_size);
1233
1234   /* Copy the uid and gid */
1235   pwd->uid = pw.pw_uid;
1236   pwd->gid = pw.pw_gid;
1237
1238   uv__free(buf);
1239
1240   return 0;
1241 }
1242
1243
1244 void uv_os_free_passwd(uv_passwd_t* pwd) {
1245   if (pwd == NULL)
1246     return;
1247
1248   /*
1249     The memory for name, shell, and homedir are allocated in a single
1250     uv__malloc() call. The base of the pointer is stored in pwd->username, so
1251     that is the field that needs to be freed.
1252   */
1253   uv__free(pwd->username);
1254   pwd->username = NULL;
1255   pwd->shell = NULL;
1256   pwd->homedir = NULL;
1257 }
1258
1259
1260 int uv_os_get_passwd(uv_passwd_t* pwd) {
1261   return uv__getpwuid_r(pwd);
1262 }
1263
1264
1265 int uv_translate_sys_error(int sys_errno) {
1266   /* If < 0 then it's already a libuv error. */
1267   return sys_errno <= 0 ? sys_errno : -sys_errno;
1268 }
1269
1270
1271 int uv_os_environ(uv_env_item_t** envitems, int* count) {
1272   int i, j, cnt;
1273   uv_env_item_t* envitem;
1274
1275   *envitems = NULL;
1276   *count = 0;
1277
1278   for (i = 0; environ[i] != NULL; i++);
1279
1280   *envitems = uv__calloc(i, sizeof(**envitems));
1281
1282   if (*envitems == NULL)
1283     return UV_ENOMEM;
1284
1285   for (j = 0, cnt = 0; j < i; j++) {
1286     char* buf;
1287     char* ptr;
1288
1289     if (environ[j] == NULL)
1290       break;
1291
1292     buf = uv__strdup(environ[j]);
1293     if (buf == NULL)
1294       goto fail;
1295
1296     ptr = strchr(buf, '=');
1297     if (ptr == NULL) {
1298       uv__free(buf);
1299       continue;
1300     }
1301
1302     *ptr = '\0';
1303
1304     envitem = &(*envitems)[cnt];
1305     envitem->name = buf;
1306     envitem->value = ptr + 1;
1307
1308     cnt++;
1309   }
1310
1311   *count = cnt;
1312   return 0;
1313
1314 fail:
1315   for (i = 0; i < cnt; i++) {
1316     envitem = &(*envitems)[cnt];
1317     uv__free(envitem->name);
1318   }
1319   uv__free(*envitems);
1320
1321   *envitems = NULL;
1322   *count = 0;
1323   return UV_ENOMEM;
1324 }
1325
1326
1327 int uv_os_getenv(const char* name, char* buffer, size_t* size) {
1328   char* var;
1329   size_t len;
1330
1331   if (name == NULL || buffer == NULL || size == NULL || *size == 0)
1332     return UV_EINVAL;
1333
1334   var = getenv(name);
1335
1336   if (var == NULL)
1337     return UV_ENOENT;
1338
1339   len = strlen(var);
1340
1341   if (len >= *size) {
1342     *size = len + 1;
1343     return UV_ENOBUFS;
1344   }
1345
1346   memcpy(buffer, var, len + 1);
1347   *size = len;
1348
1349   return 0;
1350 }
1351
1352
1353 int uv_os_setenv(const char* name, const char* value) {
1354   if (name == NULL || value == NULL)
1355     return UV_EINVAL;
1356
1357   if (setenv(name, value, 1) != 0)
1358     return UV__ERR(errno);
1359
1360   return 0;
1361 }
1362
1363
1364 int uv_os_unsetenv(const char* name) {
1365   if (name == NULL)
1366     return UV_EINVAL;
1367
1368   if (unsetenv(name) != 0)
1369     return UV__ERR(errno);
1370
1371   return 0;
1372 }
1373
1374
1375 int uv_os_gethostname(char* buffer, size_t* size) {
1376   /*
1377     On some platforms, if the input buffer is not large enough, gethostname()
1378     succeeds, but truncates the result. libuv can detect this and return ENOBUFS
1379     instead by creating a large enough buffer and comparing the hostname length
1380     to the size input.
1381   */
1382   char buf[UV_MAXHOSTNAMESIZE];
1383   size_t len;
1384
1385   if (buffer == NULL || size == NULL || *size == 0)
1386     return UV_EINVAL;
1387
1388   if (gethostname(buf, sizeof(buf)) != 0)
1389     return UV__ERR(errno);
1390
1391   buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */
1392   len = strlen(buf);
1393
1394   if (len >= *size) {
1395     *size = len + 1;
1396     return UV_ENOBUFS;
1397   }
1398
1399   memcpy(buffer, buf, len + 1);
1400   *size = len;
1401   return 0;
1402 }
1403
1404
1405 int uv_cpumask_size(void) {
1406 #if defined(__linux__) || defined(__FreeBSD__)
1407   return CPU_SETSIZE;
1408 #else
1409   return UV_ENOTSUP;
1410 #endif
1411 }
1412
1413
1414 uv_os_fd_t uv_get_osfhandle(int fd) {
1415   return fd;
1416 }
1417
1418 int uv_open_osfhandle(uv_os_fd_t os_fd) {
1419   return os_fd;
1420 }
1421
1422 uv_pid_t uv_os_getpid(void) {
1423   return getpid();
1424 }
1425
1426
1427 uv_pid_t uv_os_getppid(void) {
1428   return getppid();
1429 }
1430
1431
1432 int uv_os_getpriority(uv_pid_t pid, int* priority) {
1433   int r;
1434
1435   if (priority == NULL)
1436     return UV_EINVAL;
1437
1438   errno = 0;
1439   r = getpriority(PRIO_PROCESS, (int) pid);
1440
1441   if (r == -1 && errno != 0)
1442     return UV__ERR(errno);
1443
1444   *priority = r;
1445   return 0;
1446 }
1447
1448
1449 int uv_os_setpriority(uv_pid_t pid, int priority) {
1450   if (priority < UV_PRIORITY_HIGHEST || priority > UV_PRIORITY_LOW)
1451     return UV_EINVAL;
1452
1453   if (setpriority(PRIO_PROCESS, (int) pid, priority) != 0)
1454     return UV__ERR(errno);
1455
1456   return 0;
1457 }
1458
1459
1460 int uv_os_uname(uv_utsname_t* buffer) {
1461   struct utsname buf;
1462   int r;
1463
1464   if (buffer == NULL)
1465     return UV_EINVAL;
1466
1467   if (uname(&buf) == -1) {
1468     r = UV__ERR(errno);
1469     goto error;
1470   }
1471
1472   r = uv__strscpy(buffer->sysname, buf.sysname, sizeof(buffer->sysname));
1473   if (r == UV_E2BIG)
1474     goto error;
1475
1476 #ifdef _AIX
1477   r = snprintf(buffer->release,
1478                sizeof(buffer->release),
1479                "%s.%s",
1480                buf.version,
1481                buf.release);
1482   if (r >= sizeof(buffer->release)) {
1483     r = UV_E2BIG;
1484     goto error;
1485   }
1486 #else
1487   r = uv__strscpy(buffer->release, buf.release, sizeof(buffer->release));
1488   if (r == UV_E2BIG)
1489     goto error;
1490 #endif
1491
1492   r = uv__strscpy(buffer->version, buf.version, sizeof(buffer->version));
1493   if (r == UV_E2BIG)
1494     goto error;
1495
1496 #if defined(_AIX) || defined(__PASE__)
1497   r = uv__strscpy(buffer->machine, "ppc64", sizeof(buffer->machine));
1498 #else
1499   r = uv__strscpy(buffer->machine, buf.machine, sizeof(buffer->machine));
1500 #endif
1501
1502   if (r == UV_E2BIG)
1503     goto error;
1504
1505   return 0;
1506
1507 error:
1508   buffer->sysname[0] = '\0';
1509   buffer->release[0] = '\0';
1510   buffer->version[0] = '\0';
1511   buffer->machine[0] = '\0';
1512   return r;
1513 }
1514
1515 int uv__getsockpeername(const uv_handle_t* handle,
1516                         uv__peersockfunc func,
1517                         struct sockaddr* name,
1518                         int* namelen) {
1519   socklen_t socklen;
1520   uv_os_fd_t fd;
1521   int r;
1522
1523   r = uv_fileno(handle, &fd);
1524   if (r < 0)
1525     return r;
1526
1527   /* sizeof(socklen_t) != sizeof(int) on some systems. */
1528   socklen = (socklen_t) *namelen;
1529
1530   if (func(fd, name, &socklen))
1531     return UV__ERR(errno);
1532
1533   *namelen = (int) socklen;
1534   return 0;
1535 }
1536
1537 int uv_gettimeofday(uv_timeval64_t* tv) {
1538   struct timeval time;
1539
1540   if (tv == NULL)
1541     return UV_EINVAL;
1542
1543   if (gettimeofday(&time, NULL) != 0)
1544     return UV__ERR(errno);
1545
1546   tv->tv_sec = (int64_t) time.tv_sec;
1547   tv->tv_usec = (int32_t) time.tv_usec;
1548   return 0;
1549 }
1550
1551 void uv_sleep(unsigned int msec) {
1552   struct timespec timeout;
1553   int rc;
1554
1555   timeout.tv_sec = msec / 1000;
1556   timeout.tv_nsec = (msec % 1000) * 1000 * 1000;
1557
1558   do
1559     rc = nanosleep(&timeout, &timeout);
1560   while (rc == -1 && errno == EINTR);
1561
1562   assert(rc == 0);
1563 }
1564
1565 int uv__search_path(const char* prog, char* buf, size_t* buflen) {
1566   char abspath[UV__PATH_MAX];
1567   size_t abspath_size;
1568   char trypath[UV__PATH_MAX];
1569   char* cloned_path;
1570   char* path_env;
1571   char* token;
1572
1573   if (buf == NULL || buflen == NULL || *buflen == 0)
1574     return UV_EINVAL;
1575
1576   /*
1577    * Possibilities for prog:
1578    * i) an absolute path such as: /home/user/myprojects/nodejs/node
1579    * ii) a relative path such as: ./node or ../myprojects/nodejs/node
1580    * iii) a bare filename such as "node", after exporting PATH variable
1581    *     to its location.
1582    */
1583
1584   /* Case i) and ii) absolute or relative paths */
1585   if (strchr(prog, '/') != NULL) {
1586     if (realpath(prog, abspath) != abspath)
1587       return UV__ERR(errno);
1588
1589     abspath_size = strlen(abspath);
1590
1591     *buflen -= 1;
1592     if (*buflen > abspath_size)
1593       *buflen = abspath_size;
1594
1595     memcpy(buf, abspath, *buflen);
1596     buf[*buflen] = '\0';
1597
1598     return 0;
1599   }
1600
1601   /* Case iii). Search PATH environment variable */
1602   cloned_path = NULL;
1603   token = NULL;
1604   path_env = getenv("PATH");
1605
1606   if (path_env == NULL)
1607     return UV_EINVAL;
1608
1609   cloned_path = uv__strdup(path_env);
1610   if (cloned_path == NULL)
1611     return UV_ENOMEM;
1612
1613   token = strtok(cloned_path, ":");
1614   while (token != NULL) {
1615     snprintf(trypath, sizeof(trypath) - 1, "%s/%s", token, prog);
1616     if (realpath(trypath, abspath) == abspath) {
1617       /* Check the match is executable */
1618       if (access(abspath, X_OK) == 0) {
1619         abspath_size = strlen(abspath);
1620
1621         *buflen -= 1;
1622         if (*buflen > abspath_size)
1623           *buflen = abspath_size;
1624
1625         memcpy(buf, abspath, *buflen);
1626         buf[*buflen] = '\0';
1627
1628         uv__free(cloned_path);
1629         return 0;
1630       }
1631     }
1632     token = strtok(NULL, ":");
1633   }
1634   uv__free(cloned_path);
1635
1636   /* Out of tokens (path entries), and no match found */
1637   return UV_EINVAL;
1638 }