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:
9 * The above copyright notice and this permission notice shall be included in
10 * all copies or substantial portions of the Software.
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
24 #include <stddef.h> /* NULL */
25 #include <stdio.h> /* printf */
27 #include <string.h> /* strerror */
31 #include <sys/types.h>
33 #include <fcntl.h> /* O_CLOEXEC */
34 #include <sys/ioctl.h>
35 #include <sys/socket.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 */
44 #include <sys/utsname.h>
48 # include <sys/filio.h>
49 # include <sys/types.h>
50 # include <sys/wait.h>
53 #if defined(__APPLE__)
54 # include <sys/filio.h>
55 # endif /* defined(__APPLE__) */
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) */
67 #if defined(__DragonFly__) || \
68 defined(__FreeBSD__) || \
69 defined(__FreeBSD_kernel__) || \
70 defined(__NetBSD__) || \
72 # include <sys/sysctl.h>
73 # include <sys/filio.h>
74 # include <sys/wait.h>
75 # if defined(__FreeBSD__)
76 # define uv__accept4 accept4
78 # if defined(__NetBSD__)
79 # define uv__accept4(a, b, c, d) paccept((a), (b), (c), NULL, (d))
83 #if defined(__FreeBSD__)
84 # include <sys/param.h>
85 # include <sys/cpuset.h>
89 #include <sys/ioctl.h>
92 #if defined(__linux__)
93 # include <sys/syscall.h>
94 # define uv__accept4 accept4
97 #if defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
98 # include <sanitizer/linux_syscall_hooks.h>
101 static int uv__run_pending(uv_loop_t* loop);
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));
113 uint64_t uv_hrtime(void) {
114 return uv__hrtime(UV_CLOCK_PRECISE);
118 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
119 assert(!uv__is_closing(handle));
121 handle->flags |= UV_HANDLE_CLOSING;
122 handle->close_cb = close_cb;
124 switch (handle->type) {
126 uv__pipe_close((uv_pipe_t*)handle);
130 uv__stream_close((uv_stream_t*)handle);
134 uv__tcp_close((uv_tcp_t*)handle);
138 uv__udp_close((uv_udp_t*)handle);
142 uv__prepare_close((uv_prepare_t*)handle);
146 uv__check_close((uv_check_t*)handle);
150 uv__idle_close((uv_idle_t*)handle);
154 uv__async_close((uv_async_t*)handle);
158 uv__timer_close((uv_timer_t*)handle);
162 uv__process_close((uv_process_t*)handle);
166 uv__fs_event_close((uv_fs_event_t*)handle);
170 uv__poll_close((uv_poll_t*)handle);
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. */
180 uv__signal_close((uv_signal_t*) handle);
187 uv__make_close_pending(handle);
190 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
195 if (handle == NULL || value == NULL)
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;
205 len = sizeof(*value);
208 r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
210 r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
213 return UV__ERR(errno);
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;
225 int uv__getiovmax(void) {
228 #elif defined(_SC_IOV_MAX)
229 static int iovmax_cached = -1;
232 iovmax = uv__load_relaxed(&iovmax_cached);
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.
240 iovmax = sysconf(_SC_IOV_MAX);
244 uv__store_relaxed(&iovmax_cached, iovmax);
253 static void uv__finish_close(uv_handle_t* handle) {
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
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.
264 assert(handle->flags & UV_HANDLE_CLOSING);
265 assert(!(handle->flags & UV_HANDLE_CLOSED));
266 handle->flags |= UV_HANDLE_CLOSED;
268 switch (handle->type) {
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.
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. */
297 uv__stream_destroy((uv_stream_t*)handle);
301 uv__udp_finish_close((uv_udp_t*)handle);
309 uv__handle_unref(handle);
310 QUEUE_REMOVE(&handle->handle_queue);
312 if (handle->close_cb) {
313 handle->close_cb(handle);
318 static void uv__run_closing_handles(uv_loop_t* loop) {
322 p = loop->closing_handles;
323 loop->closing_handles = NULL;
333 int uv_is_closing(const uv_handle_t* handle) {
334 return uv__is_closing(handle);
338 int uv_backend_fd(const uv_loop_t* loop) {
339 return loop->backend_fd;
343 int uv_backend_timeout(const uv_loop_t* loop) {
344 if (loop->stop_flag != 0)
347 if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
350 if (!QUEUE_EMPTY(&loop->idle_handles))
353 if (!QUEUE_EMPTY(&loop->pending_queue))
356 if (loop->closing_handles)
359 return uv__next_timeout(loop);
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;
370 int uv_loop_alive(const uv_loop_t* loop) {
371 return uv__loop_alive(loop);
375 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
380 r = uv__loop_alive(loop);
382 uv__update_time(loop);
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);
389 uv__run_prepare(loop);
392 if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
393 timeout = uv_backend_timeout(loop);
395 uv__io_poll(loop, timeout);
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.
402 uv__metrics_update_idle_time(loop);
405 uv__run_closing_handles(loop);
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.
413 * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
416 uv__update_time(loop);
417 uv__run_timers(loop);
420 r = uv__loop_alive(loop);
421 if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
425 /* The if statement lets gcc compile it to a conditional store. Avoids
426 * dirtying a cache line.
428 if (loop->stop_flag != 0)
435 void uv_update_time(uv_loop_t* loop) {
436 uv__update_time(loop);
440 int uv_is_active(const uv_handle_t* handle) {
441 return uv__is_active(handle);
445 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
446 int uv__socket(int domain, int type, int protocol) {
450 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
451 sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
456 return UV__ERR(errno);
459 sockfd = socket(domain, type, protocol);
461 return UV__ERR(errno);
463 err = uv__nonblock(sockfd, 1);
465 err = uv__cloexec(sockfd, 1);
472 #if defined(SO_NOSIGPIPE)
475 setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
482 /* get a file pointer to a file in read-only and close-on-exec mode */
483 FILE* uv__open_file(const char* path) {
487 fd = uv__open_cloexec(path, O_RDONLY);
491 fp = fdopen(fd, "r");
499 int uv__accept(int sockfd) {
508 peerfd = uv__accept4(sockfd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
510 peerfd = accept(sockfd, NULL, NULL);
512 while (peerfd == -1 && errno == EINTR);
515 return UV__ERR(errno);
518 err = uv__cloexec(peerfd, 1);
520 err = uv__nonblock(peerfd, 1);
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.
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.
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);
548 extern int close$NOCANCEL$UNIX2003(int);
549 return close$NOCANCEL$UNIX2003(fd);
551 #pragma GCC diagnostic pop
552 #elif defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
554 __sanitizer_syscall_pre_close(fd);
555 rc = syscall(SYS_close, fd);
556 __sanitizer_syscall_post_close(rc, fd);
558 #elif defined(__linux__) && !defined(__SANITIZE_THREAD__)
559 return syscall(SYS_close, fd);
566 int uv__close_nocheckstdio(int fd) {
570 assert(fd > -1); /* Catch uninitialized io_watcher.fd bugs. */
573 rc = uv__close_nocancel(fd);
576 if (rc == UV_EINTR || rc == UV__ERR(EINPROGRESS))
577 rc = 0; /* The close is in progress, not an error. */
585 int uv__close(int fd) {
586 assert(fd > STDERR_FILENO); /* Catch stdio close bugs. */
588 SAVE_ERRNO(epoll_file_close(fd));
590 return uv__close_nocheckstdio(fd);
593 #if UV__NONBLOCK_IS_IOCTL
594 int uv__nonblock_ioctl(int fd, int set) {
598 r = ioctl(fd, FIONBIO, &set);
599 while (r == -1 && errno == EINTR);
602 return UV__ERR(errno);
608 int uv__cloexec_ioctl(int fd, int set) {
612 r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
613 while (r == -1 && errno == EINTR);
616 return UV__ERR(errno);
623 int uv__nonblock_fcntl(int fd, int set) {
628 r = fcntl(fd, F_GETFL);
629 while (r == -1 && errno == EINTR);
632 return UV__ERR(errno);
634 /* Bail out now if already set/clear. */
635 if (!!(r & O_NONBLOCK) == !!set)
639 flags = r | O_NONBLOCK;
641 flags = r & ~O_NONBLOCK;
644 r = fcntl(fd, F_SETFL, flags);
645 while (r == -1 && errno == EINTR);
648 return UV__ERR(errno);
654 int uv__cloexec_fcntl(int fd, int set) {
659 r = fcntl(fd, F_GETFD);
660 while (r == -1 && errno == EINTR);
663 return UV__ERR(errno);
665 /* Bail out now if already set/clear. */
666 if (!!(r & FD_CLOEXEC) == !!set)
670 flags = r | FD_CLOEXEC;
672 flags = r & ~FD_CLOEXEC;
675 r = fcntl(fd, F_SETFD, flags);
676 while (r == -1 && errno == EINTR);
679 return UV__ERR(errno);
685 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
686 struct cmsghdr* cmsg;
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 */
697 return UV__ERR(errno);
698 rc = recvmsg(fd, msg, flags);
700 return UV__ERR(errno);
701 uv__store_relaxed(&no_msg_cmsg_cloexec, 1);
703 rc = recvmsg(fd, msg, flags);
706 rc = recvmsg(fd, msg, flags);
709 return UV__ERR(errno);
710 if (msg->msg_controllen == 0)
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);
718 uv__cloexec(*pfd, 1);
723 int uv_cwd(char* buffer, size_t* size) {
724 char scratch[1 + UV__PATH_MAX];
726 if (buffer == NULL || size == NULL)
729 /* Try to read directly into the user's buffer first... */
730 if (getcwd(buffer, *size) != NULL)
734 return UV__ERR(errno);
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.
739 if (getcwd(scratch, sizeof(scratch)) == NULL)
740 return UV__ERR(errno);
746 *size = strlen(buffer);
748 if (*size > 1 && buffer[*size - 1] == '/') {
750 buffer[*size] = '\0';
753 if (buffer == scratch) {
762 int uv_chdir(const char* dir) {
764 return UV__ERR(errno);
770 void uv_disable_stdio_inheritance(void) {
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.
777 if (uv__cloexec(fd, 1) && fd > 15)
782 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
785 switch (handle->type) {
789 fd_out = uv__stream_fd((uv_stream_t*) handle);
793 fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
797 fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
804 if (uv__is_closing(handle) || fd_out == -1)
812 static int uv__run_pending(uv_loop_t* loop) {
817 if (QUEUE_EMPTY(&loop->pending_queue))
820 QUEUE_MOVE(&loop->pending_queue, &pq);
822 while (!QUEUE_EMPTY(&pq)) {
826 w = QUEUE_DATA(q, uv__io_t, pending_queue);
827 w->cb(loop, w, POLLOUT);
834 static unsigned int next_power_of_two(unsigned int val) {
845 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
847 void* fake_watcher_list;
848 void* fake_watcher_count;
849 unsigned int nwatchers;
852 if (len <= loop->nwatchers)
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];
860 fake_watcher_list = NULL;
861 fake_watcher_count = NULL;
864 nwatchers = next_power_of_two(len + 2) - 2;
865 watchers = uv__reallocf(loop->watchers,
866 (nwatchers + 2) * sizeof(loop->watchers[0]));
868 if (watchers == NULL)
870 for (i = loop->nwatchers; i < nwatchers; i++)
872 watchers[nwatchers] = fake_watcher_list;
873 watchers[nwatchers + 1] = fake_watcher_count;
875 loop->watchers = watchers;
876 loop->nwatchers = nwatchers;
880 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
883 QUEUE_INIT(&w->pending_queue);
884 QUEUE_INIT(&w->watcher_queue);
890 #if defined(UV_HAVE_KQUEUE)
893 #endif /* defined(UV_HAVE_KQUEUE) */
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)));
901 assert(w->fd < INT_MAX);
903 w->pevents |= events;
904 maybe_resize(loop, w->fd + 1);
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.
911 if (w->events == w->pevents)
915 if (QUEUE_EMPTY(&w->watcher_queue))
916 QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
918 if (loop->watchers[w->fd] == NULL) {
919 loop->watchers[w->fd] = w;
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)));
934 /* Happens when uv__io_stop() is called on a handle that was never started. */
935 if ((unsigned) w->fd >= loop->nwatchers)
938 w->pevents &= ~events;
940 if (w->pevents == 0) {
941 QUEUE_REMOVE(&w->watcher_queue);
942 QUEUE_INIT(&w->watcher_queue);
945 if (w == loop->watchers[w->fd]) {
946 assert(loop->nfds > 0);
947 loop->watchers[w->fd] = NULL;
951 else if (QUEUE_EMPTY(&w->watcher_queue))
952 QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
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);
960 /* Remove stale events for this file descriptor */
962 uv__platform_invalidate_fd(loop, w->fd);
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);
972 int uv__io_active(const uv__io_t* w, unsigned int events) {
973 assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
975 return 0 != (w->pevents & events);
979 int uv__fd_exists(uv_loop_t* loop, int fd) {
980 return (unsigned) fd < loop->nwatchers && loop->watchers[fd] != NULL;
984 int uv_getrusage(uv_rusage_t* rusage) {
987 if (getrusage(RUSAGE_SELF, &usage))
988 return UV__ERR(errno);
990 rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
991 rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
993 rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
994 rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
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;
1017 int uv__open_cloexec(const char* path, int flags) {
1018 #if defined(O_CLOEXEC)
1021 fd = open(path, flags | O_CLOEXEC);
1023 return UV__ERR(errno);
1026 #else /* O_CLOEXEC */
1030 fd = open(path, flags);
1032 return UV__ERR(errno);
1034 err = uv__cloexec(fd, 1);
1041 #endif /* O_CLOEXEC */
1045 int uv__dup2_cloexec(int oldfd, int newfd) {
1046 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__linux__)
1049 r = dup3(oldfd, newfd, O_CLOEXEC);
1051 return UV__ERR(errno);
1058 r = dup2(oldfd, newfd); /* Never retry. */
1060 return UV__ERR(errno);
1062 err = uv__cloexec(newfd, 1);
1073 int uv_os_homedir(char* buffer, size_t* size) {
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
1081 r = uv_os_getenv("HOME", buffer, size);
1086 /* HOME is not set, so call uv__getpwuid_r() */
1087 r = uv__getpwuid_r(&pwd);
1093 len = strlen(pwd.homedir);
1097 uv_os_free_passwd(&pwd);
1101 memcpy(buffer, pwd.homedir, len + 1);
1103 uv_os_free_passwd(&pwd);
1109 int uv_os_tmpdir(char* buffer, size_t* size) {
1113 if (buffer == NULL || size == NULL || *size == 0)
1116 #define CHECK_ENV_VAR(name) \
1118 buf = getenv(name); \
1120 goto return_buffer; \
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");
1130 #undef CHECK_ENV_VAR
1132 /* No temp environment variables defined */
1133 #if defined(__ANDROID__)
1134 buf = "/data/local/tmp";
1147 /* The returned directory should not have a trailing slash. */
1148 if (len > 1 && buf[len - 1] == '/') {
1152 memcpy(buffer, buf, len + 1);
1160 int uv__getpwuid_r(uv_passwd_t* pwd) {
1162 struct passwd* result;
1167 size_t homedir_size;
1175 initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1180 bufsize = (size_t) initsize;
1187 buf = uv__malloc(bufsize);
1193 r = getpwuid_r(uid, &pw, buf, bufsize, &result);
1207 if (result == NULL) {
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);
1218 if (pwd->username == NULL) {
1223 /* Copy the username */
1224 memcpy(pwd->username, pw.pw_name, name_size);
1226 /* Copy the home directory */
1227 pwd->homedir = pwd->username + name_size;
1228 memcpy(pwd->homedir, pw.pw_dir, homedir_size);
1230 /* Copy the shell */
1231 pwd->shell = pwd->homedir + homedir_size;
1232 memcpy(pwd->shell, pw.pw_shell, shell_size);
1234 /* Copy the uid and gid */
1235 pwd->uid = pw.pw_uid;
1236 pwd->gid = pw.pw_gid;
1244 void uv_os_free_passwd(uv_passwd_t* pwd) {
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.
1253 uv__free(pwd->username);
1254 pwd->username = NULL;
1256 pwd->homedir = NULL;
1260 int uv_os_get_passwd(uv_passwd_t* pwd) {
1261 return uv__getpwuid_r(pwd);
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;
1271 int uv_os_environ(uv_env_item_t** envitems, int* count) {
1273 uv_env_item_t* envitem;
1278 for (i = 0; environ[i] != NULL; i++);
1280 *envitems = uv__calloc(i, sizeof(**envitems));
1282 if (*envitems == NULL)
1285 for (j = 0, cnt = 0; j < i; j++) {
1289 if (environ[j] == NULL)
1292 buf = uv__strdup(environ[j]);
1296 ptr = strchr(buf, '=');
1304 envitem = &(*envitems)[cnt];
1305 envitem->name = buf;
1306 envitem->value = ptr + 1;
1315 for (i = 0; i < cnt; i++) {
1316 envitem = &(*envitems)[cnt];
1317 uv__free(envitem->name);
1319 uv__free(*envitems);
1327 int uv_os_getenv(const char* name, char* buffer, size_t* size) {
1331 if (name == NULL || buffer == NULL || size == NULL || *size == 0)
1346 memcpy(buffer, var, len + 1);
1353 int uv_os_setenv(const char* name, const char* value) {
1354 if (name == NULL || value == NULL)
1357 if (setenv(name, value, 1) != 0)
1358 return UV__ERR(errno);
1364 int uv_os_unsetenv(const char* name) {
1368 if (unsetenv(name) != 0)
1369 return UV__ERR(errno);
1375 int uv_os_gethostname(char* buffer, size_t* size) {
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
1382 char buf[UV_MAXHOSTNAMESIZE];
1385 if (buffer == NULL || size == NULL || *size == 0)
1388 if (gethostname(buf, sizeof(buf)) != 0)
1389 return UV__ERR(errno);
1391 buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */
1399 memcpy(buffer, buf, len + 1);
1405 int uv_cpumask_size(void) {
1406 #if defined(__linux__) || defined(__FreeBSD__)
1414 uv_os_fd_t uv_get_osfhandle(int fd) {
1418 int uv_open_osfhandle(uv_os_fd_t os_fd) {
1422 uv_pid_t uv_os_getpid(void) {
1427 uv_pid_t uv_os_getppid(void) {
1432 int uv_os_getpriority(uv_pid_t pid, int* priority) {
1435 if (priority == NULL)
1439 r = getpriority(PRIO_PROCESS, (int) pid);
1441 if (r == -1 && errno != 0)
1442 return UV__ERR(errno);
1449 int uv_os_setpriority(uv_pid_t pid, int priority) {
1450 if (priority < UV_PRIORITY_HIGHEST || priority > UV_PRIORITY_LOW)
1453 if (setpriority(PRIO_PROCESS, (int) pid, priority) != 0)
1454 return UV__ERR(errno);
1460 int uv_os_uname(uv_utsname_t* buffer) {
1467 if (uname(&buf) == -1) {
1472 r = uv__strscpy(buffer->sysname, buf.sysname, sizeof(buffer->sysname));
1477 r = snprintf(buffer->release,
1478 sizeof(buffer->release),
1482 if (r >= sizeof(buffer->release)) {
1487 r = uv__strscpy(buffer->release, buf.release, sizeof(buffer->release));
1492 r = uv__strscpy(buffer->version, buf.version, sizeof(buffer->version));
1496 #if defined(_AIX) || defined(__PASE__)
1497 r = uv__strscpy(buffer->machine, "ppc64", sizeof(buffer->machine));
1499 r = uv__strscpy(buffer->machine, buf.machine, sizeof(buffer->machine));
1508 buffer->sysname[0] = '\0';
1509 buffer->release[0] = '\0';
1510 buffer->version[0] = '\0';
1511 buffer->machine[0] = '\0';
1515 int uv__getsockpeername(const uv_handle_t* handle,
1516 uv__peersockfunc func,
1517 struct sockaddr* name,
1523 r = uv_fileno(handle, &fd);
1527 /* sizeof(socklen_t) != sizeof(int) on some systems. */
1528 socklen = (socklen_t) *namelen;
1530 if (func(fd, name, &socklen))
1531 return UV__ERR(errno);
1533 *namelen = (int) socklen;
1537 int uv_gettimeofday(uv_timeval64_t* tv) {
1538 struct timeval time;
1543 if (gettimeofday(&time, NULL) != 0)
1544 return UV__ERR(errno);
1546 tv->tv_sec = (int64_t) time.tv_sec;
1547 tv->tv_usec = (int32_t) time.tv_usec;
1551 void uv_sleep(unsigned int msec) {
1552 struct timespec timeout;
1555 timeout.tv_sec = msec / 1000;
1556 timeout.tv_nsec = (msec % 1000) * 1000 * 1000;
1559 rc = nanosleep(&timeout, &timeout);
1560 while (rc == -1 && errno == EINTR);
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];
1573 if (buf == NULL || buflen == NULL || *buflen == 0)
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
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);
1589 abspath_size = strlen(abspath);
1592 if (*buflen > abspath_size)
1593 *buflen = abspath_size;
1595 memcpy(buf, abspath, *buflen);
1596 buf[*buflen] = '\0';
1601 /* Case iii). Search PATH environment variable */
1604 path_env = getenv("PATH");
1606 if (path_env == NULL)
1609 cloned_path = uv__strdup(path_env);
1610 if (cloned_path == NULL)
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);
1622 if (*buflen > abspath_size)
1623 *buflen = abspath_size;
1625 memcpy(buf, abspath, *buflen);
1626 buf[*buflen] = '\0';
1628 uv__free(cloned_path);
1632 token = strtok(NULL, ":");
1634 uv__free(cloned_path);
1636 /* Out of tokens (path entries), and no match found */