• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "uv_log.h"
23 #include "internal.h"
24 #include "strtok.h"
25 
26 #include <stddef.h> /* NULL */
27 #include <stdio.h> /* printf */
28 #include <stdlib.h>
29 #include <string.h> /* strerror */
30 #include <errno.h>
31 #include <assert.h>
32 #include <unistd.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>  /* O_CLOEXEC */
36 #include <sys/ioctl.h>
37 #include <sys/socket.h>
38 #include <sys/un.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
42 #include <sys/uio.h> /* writev */
43 #include <sys/resource.h> /* getrusage */
44 #include <pwd.h>
45 #include <grp.h>
46 #include <sys/utsname.h>
47 #include <sys/time.h>
48 #include <time.h> /* clock_gettime */
49 
50 #ifdef __sun
51 # include <sys/filio.h>
52 # include <sys/wait.h>
53 #endif
54 
55 #if defined(__APPLE__)
56 # include <sys/filio.h>
57 # endif /* defined(__APPLE__) */
58 
59 
60 #if defined(__APPLE__) && !TARGET_OS_IPHONE
61 # include <crt_externs.h>
62 # include <mach-o/dyld.h> /* _NSGetExecutablePath */
63 # define environ (*_NSGetEnviron())
64 #else /* defined(__APPLE__) && !TARGET_OS_IPHONE */
65 extern char** environ;
66 #endif /* !(defined(__APPLE__) && !TARGET_OS_IPHONE) */
67 
68 
69 #if defined(__DragonFly__)      || \
70     defined(__FreeBSD__)        || \
71     defined(__NetBSD__)         || \
72     defined(__OpenBSD__)
73 # include <sys/sysctl.h>
74 # include <sys/filio.h>
75 # include <sys/wait.h>
76 # include <sys/param.h>
77 # if defined(__FreeBSD__)
78 #  include <sys/cpuset.h>
79 #  define uv__accept4 accept4
80 # endif
81 # if defined(__NetBSD__)
82 #  define uv__accept4(a, b, c, d) paccept((a), (b), (c), NULL, (d))
83 # endif
84 #endif
85 
86 #if defined(__MVS__)
87 # include <sys/ioctl.h>
88 # include "zos-sys-info.h"
89 #endif
90 
91 #if defined(__linux__)
92 # include <sched.h>
93 # include <sys/syscall.h>
94 # define gettid() syscall(SYS_gettid)
95 # define uv__accept4 accept4
96 #endif
97 
98 #if defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
99 # include <sanitizer/linux_syscall_hooks.h>
100 #endif
101 
102 static void uv__run_pending(uv_loop_t* loop);
103 
104 /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
105 STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
106 STATIC_ASSERT(sizeof(((uv_buf_t*) 0)->base) ==
107               sizeof(((struct iovec*) 0)->iov_base));
108 STATIC_ASSERT(sizeof(((uv_buf_t*) 0)->len) ==
109               sizeof(((struct iovec*) 0)->iov_len));
110 STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
111 STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
112 
113 
114 /* https://github.com/libuv/libuv/issues/1674 */
uv_clock_gettime(uv_clock_id clock_id,uv_timespec64_t * ts)115 int uv_clock_gettime(uv_clock_id clock_id, uv_timespec64_t* ts) {
116   struct timespec t;
117   int r;
118 
119   if (ts == NULL)
120     return UV_EFAULT;
121 
122   switch (clock_id) {
123     default:
124       return UV_EINVAL;
125     case UV_CLOCK_MONOTONIC:
126       r = clock_gettime(CLOCK_MONOTONIC, &t);
127       break;
128     case UV_CLOCK_REALTIME:
129       r = clock_gettime(CLOCK_REALTIME, &t);
130       break;
131   }
132 
133   if (r)
134     return UV__ERR(errno);
135 
136   ts->tv_sec = t.tv_sec;
137   ts->tv_nsec = t.tv_nsec;
138 
139   return 0;
140 }
141 
142 
uv_hrtime(void)143 uint64_t uv_hrtime(void) {
144   return uv__hrtime(UV_CLOCK_PRECISE);
145 }
146 
147 
uv_close(uv_handle_t * handle,uv_close_cb close_cb)148 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
149   assert(!uv__is_closing(handle));
150 #if defined(USE_OHOS_DFX) && defined(__aarch64__)
151   uv__multi_thread_check_unify(handle->loop, __func__);
152 #endif
153   handle->flags |= UV_HANDLE_CLOSING;
154   handle->close_cb = close_cb;
155 
156   switch (handle->type) {
157   case UV_NAMED_PIPE:
158     uv__pipe_close((uv_pipe_t*)handle);
159     break;
160 
161   case UV_TTY:
162     uv__stream_close((uv_stream_t*)handle);
163     break;
164 
165   case UV_TCP:
166     uv__tcp_close((uv_tcp_t*)handle);
167     break;
168 
169   case UV_UDP:
170     uv__udp_close((uv_udp_t*)handle);
171     break;
172 
173   case UV_PREPARE:
174     uv__prepare_close((uv_prepare_t*)handle);
175     break;
176 
177   case UV_CHECK:
178     uv__check_close((uv_check_t*)handle);
179     break;
180 
181   case UV_IDLE:
182     uv__idle_close((uv_idle_t*)handle);
183     break;
184 
185   case UV_ASYNC:
186     uv__async_close((uv_async_t*)handle);
187     break;
188 
189   case UV_TIMER:
190     uv__timer_close((uv_timer_t*)handle);
191     break;
192 
193   case UV_PROCESS:
194     uv__process_close((uv_process_t*)handle);
195     break;
196 
197   case UV_FS_EVENT:
198     uv__fs_event_close((uv_fs_event_t*)handle);
199 #if defined(__sun) || defined(__MVS__)
200     /*
201      * On Solaris, illumos, and z/OS we will not be able to dissociate the
202      * watcher for an event which is pending delivery, so we cannot always call
203      * uv__make_close_pending() straight away. The backend will call the
204      * function once the event has cleared.
205      */
206     return;
207 #endif
208     break;
209 
210   case UV_POLL:
211     uv__poll_close((uv_poll_t*)handle);
212     break;
213 
214   case UV_FS_POLL:
215     uv__fs_poll_close((uv_fs_poll_t*)handle);
216     /* Poll handles use file system requests, and one of them may still be
217      * running. The poll code will call uv__make_close_pending() for us. */
218     return;
219 
220   case UV_SIGNAL:
221     uv__signal_close((uv_signal_t*) handle);
222     break;
223 
224   default:
225     assert(0);
226   }
227 
228   uv__make_close_pending(handle);
229 }
230 
uv__socket_sockopt(uv_handle_t * handle,int optname,int * value)231 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
232   int r;
233   int fd;
234   socklen_t len;
235 
236   if (handle == NULL || value == NULL)
237     return UV_EINVAL;
238 
239   if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
240     fd = uv__stream_fd((uv_stream_t*) handle);
241   else if (handle->type == UV_UDP)
242     fd = ((uv_udp_t *) handle)->io_watcher.fd;
243   else
244     return UV_ENOTSUP;
245 
246   len = sizeof(*value);
247 
248   if (*value == 0)
249     r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
250   else
251     r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
252 
253   if (r < 0)
254     return UV__ERR(errno);
255 
256   return 0;
257 }
258 
uv__make_close_pending(uv_handle_t * handle)259 void uv__make_close_pending(uv_handle_t* handle) {
260   assert(handle->flags & UV_HANDLE_CLOSING);
261   assert(!(handle->flags & UV_HANDLE_CLOSED));
262   handle->next_closing = handle->loop->closing_handles;
263   handle->loop->closing_handles = handle;
264 }
265 
uv__getiovmax(void)266 int uv__getiovmax(void) {
267 #if defined(IOV_MAX)
268   return IOV_MAX;
269 #elif defined(_SC_IOV_MAX)
270   static _Atomic int iovmax_cached = -1;
271   int iovmax;
272 
273   iovmax = atomic_load_explicit(&iovmax_cached, memory_order_relaxed);
274   if (iovmax != -1)
275     return iovmax;
276 
277   /* On some embedded devices (arm-linux-uclibc based ip camera),
278    * sysconf(_SC_IOV_MAX) can not get the correct value. The return
279    * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
280    */
281   iovmax = sysconf(_SC_IOV_MAX);
282   if (iovmax == -1)
283     iovmax = 1;
284 
285   atomic_store_explicit(&iovmax_cached, iovmax, memory_order_relaxed);
286 
287   return iovmax;
288 #else
289   return 1024;
290 #endif
291 }
292 
293 
uv__finish_close(uv_handle_t * handle)294 static void uv__finish_close(uv_handle_t* handle) {
295   uv_signal_t* sh;
296 
297   /* Note: while the handle is in the UV_HANDLE_CLOSING state now, it's still
298    * possible for it to be active in the sense that uv__is_active() returns
299    * true.
300    *
301    * A good example is when the user calls uv_shutdown(), immediately followed
302    * by uv_close(). The handle is considered active at this point because the
303    * completion of the shutdown req is still pending.
304    */
305   assert(handle->flags & UV_HANDLE_CLOSING);
306   assert(!(handle->flags & UV_HANDLE_CLOSED));
307   handle->flags |= UV_HANDLE_CLOSED;
308 
309   switch (handle->type) {
310     case UV_PREPARE:
311     case UV_CHECK:
312     case UV_IDLE:
313     case UV_ASYNC:
314     case UV_TIMER:
315     case UV_PROCESS:
316     case UV_FS_EVENT:
317     case UV_FS_POLL:
318     case UV_POLL:
319       break;
320 
321     case UV_SIGNAL:
322       /* If there are any caught signals "trapped" in the signal pipe,
323        * we can't call the close callback yet. Reinserting the handle
324        * into the closing queue makes the event loop spin but that's
325        * okay because we only need to deliver the pending events.
326        */
327       sh = (uv_signal_t*) handle;
328       if (sh->caught_signals > sh->dispatched_signals) {
329         handle->flags ^= UV_HANDLE_CLOSED;
330         uv__make_close_pending(handle);  /* Back into the queue. */
331         return;
332       }
333       break;
334 
335     case UV_NAMED_PIPE:
336     case UV_TCP:
337     case UV_TTY:
338       uv__stream_destroy((uv_stream_t*)handle);
339       break;
340 
341     case UV_UDP:
342       uv__udp_finish_close((uv_udp_t*)handle);
343       break;
344 
345     default:
346       assert(0);
347       break;
348   }
349 
350   uv__handle_unref(handle);
351   uv__queue_remove(&handle->handle_queue);
352 
353   if (handle->close_cb) {
354     handle->close_cb(handle);
355   }
356 }
357 
358 
uv__run_closing_handles(uv_loop_t * loop)359 static void uv__run_closing_handles(uv_loop_t* loop) {
360   uv_handle_t* p;
361   uv_handle_t* q;
362 
363   p = loop->closing_handles;
364   loop->closing_handles = NULL;
365 
366   while (p) {
367     q = p->next_closing;
368     uv__finish_close(p);
369     p = q;
370   }
371 }
372 
373 
uv_is_closing(const uv_handle_t * handle)374 int uv_is_closing(const uv_handle_t* handle) {
375   return uv__is_closing(handle);
376 }
377 
378 
uv_backend_fd(const uv_loop_t * loop)379 int uv_backend_fd(const uv_loop_t* loop) {
380   return loop->backend_fd;
381 }
382 
383 
uv__loop_alive(const uv_loop_t * loop)384 static int uv__loop_alive(const uv_loop_t* loop) {
385   return uv__has_active_handles(loop) ||
386          uv__has_active_reqs(loop) ||
387          !uv__queue_empty(&loop->pending_queue) ||
388          loop->closing_handles != NULL;
389 }
390 
391 
uv__backend_timeout(const uv_loop_t * loop)392 static int uv__backend_timeout(const uv_loop_t* loop) {
393   if (loop->stop_flag == 0 &&
394       /* uv__loop_alive(loop) && */
395       (uv__has_active_handles(loop) || uv__has_active_reqs(loop)) &&
396       uv__queue_empty(&loop->pending_queue) &&
397       uv__queue_empty(&loop->idle_handles) &&
398       (loop->flags & UV_LOOP_REAP_CHILDREN) == 0 &&
399       loop->closing_handles == NULL)
400     return uv__next_timeout(loop);
401   return 0;
402 }
403 
404 
uv_backend_timeout(const uv_loop_t * loop)405 int uv_backend_timeout(const uv_loop_t* loop) {
406   if (uv__queue_empty(&loop->watcher_queue))
407     return uv__backend_timeout(loop);
408   /* Need to call uv_run to update the backend fd state. */
409   return 0;
410 }
411 
412 
uv_loop_alive(const uv_loop_t * loop)413 int uv_loop_alive(const uv_loop_t* loop) {
414   return uv__loop_alive(loop);
415 }
416 
417 
uv_loop_alive_taskpool(const uv_loop_t * loop,int initial_handles)418 int uv_loop_alive_taskpool(const uv_loop_t* loop, int initial_handles) {
419   return loop->active_handles > initial_handles ||
420          uv__has_active_reqs(loop) ||
421          !uv__queue_empty(&loop->pending_queue) ||
422          loop->closing_handles != NULL;
423 }
424 
425 
426 #ifdef USE_FFRT
427 int is_uv_loop_good_magic(const uv_loop_t* loop);
428 #endif
uv_run(uv_loop_t * loop,uv_run_mode mode)429 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
430   int timeout;
431   int r;
432   int can_sleep;
433 #if defined(USE_OHOS_DFX) && defined(__aarch64__)
434   uv__set_thread_id(loop);
435 #endif
436 
437 #ifdef USE_FFRT
438   if (!is_uv_loop_good_magic(loop)) {
439     return 0;
440   }
441 #endif
442 
443   r = uv__loop_alive(loop);
444   if (!r)
445     uv__update_time(loop);
446 
447   while (r != 0 && loop->stop_flag == 0) {
448 #ifdef USE_FFRT
449     if (!is_uv_loop_good_magic(loop)) {
450       return 0;
451     }
452 #endif
453 
454     uv__update_time(loop);
455     uv__run_timers(loop);
456 
457     can_sleep =
458         uv__queue_empty(&loop->pending_queue) &&
459         uv__queue_empty(&loop->idle_handles);
460 
461     uv__run_pending(loop);
462     uv__run_idle(loop);
463     uv__run_prepare(loop);
464 
465     timeout = 0;
466     if ((mode == UV_RUN_ONCE && can_sleep) || mode == UV_RUN_DEFAULT)
467       timeout = uv__backend_timeout(loop);
468 
469     uv__metrics_inc_loop_count(loop);
470 
471     uv__io_poll(loop, timeout);
472 
473     /* Process immediate callbacks (e.g. write_cb) a small fixed number of
474      * times to avoid loop starvation.*/
475     for (r = 0; r < 8 && !uv__queue_empty(&loop->pending_queue); r++)
476       uv__run_pending(loop);
477 
478     /* Run one final update on the provider_idle_time in case uv__io_poll
479      * returned because the timeout expired, but no events were received. This
480      * call will be ignored if the provider_entry_time was either never set (if
481      * the timeout == 0) or was already updated b/c an event was received.
482      */
483     uv__metrics_update_idle_time(loop);
484 
485     uv__run_check(loop);
486     uv__run_closing_handles(loop);
487 
488     if (mode == UV_RUN_ONCE) {
489       /* UV_RUN_ONCE implies forward progress: at least one callback must have
490        * been invoked when it returns. uv__io_poll() can return without doing
491        * I/O (meaning: no callbacks) when its timeout expires - which means we
492        * have pending timers that satisfy the forward progress constraint.
493        *
494        * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
495        * the check.
496        */
497       uv__update_time(loop);
498       uv__run_timers(loop);
499     }
500 
501     r = uv__loop_alive(loop);
502     if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
503       break;
504   }
505 
506   /* The if statement lets gcc compile it to a conditional store. Avoids
507    * dirtying a cache line.
508    */
509   if (loop->stop_flag != 0)
510     loop->stop_flag = 0;
511 
512   return r;
513 }
514 
515 
uv_update_time(uv_loop_t * loop)516 void uv_update_time(uv_loop_t* loop) {
517   uv__update_time(loop);
518 }
519 
520 
uv_is_active(const uv_handle_t * handle)521 int uv_is_active(const uv_handle_t* handle) {
522   return uv__is_active(handle);
523 }
524 
525 
526 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
uv__socket(int domain,int type,int protocol)527 int uv__socket(int domain, int type, int protocol) {
528   int sockfd;
529   int err;
530 
531 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
532   sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
533   if (sockfd != -1)
534     return sockfd;
535 
536   if (errno != EINVAL)
537     return UV__ERR(errno);
538 #endif
539 
540   sockfd = socket(domain, type, protocol);
541   if (sockfd == -1)
542     return UV__ERR(errno);
543 
544   err = uv__nonblock(sockfd, 1);
545   if (err == 0)
546     err = uv__cloexec(sockfd, 1);
547 
548   if (err) {
549     uv__close(sockfd);
550     return err;
551   }
552 
553 #if defined(SO_NOSIGPIPE)
554   {
555     int on = 1;
556     setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
557   }
558 #endif
559 
560   return sockfd;
561 }
562 
563 /* get a file pointer to a file in read-only and close-on-exec mode */
uv__open_file(const char * path)564 FILE* uv__open_file(const char* path) {
565   int fd;
566   FILE* fp;
567 
568   fd = uv__open_cloexec(path, O_RDONLY);
569   if (fd < 0)
570     return NULL;
571 
572    fp = fdopen(fd, "r");
573    if (fp == NULL)
574      uv__close(fd);
575 
576    return fp;
577 }
578 
579 
uv__accept(int sockfd)580 int uv__accept(int sockfd) {
581   int peerfd;
582   int err;
583 
584   (void) &err;
585   assert(sockfd >= 0);
586 
587   do
588 #ifdef uv__accept4
589     peerfd = uv__accept4(sockfd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
590 #else
591     peerfd = accept(sockfd, NULL, NULL);
592 #endif
593   while (peerfd == -1 && errno == EINTR);
594 
595   if (peerfd == -1)
596     return UV__ERR(errno);
597 
598 #ifndef uv__accept4
599   err = uv__cloexec(peerfd, 1);
600   if (err == 0)
601     err = uv__nonblock(peerfd, 1);
602 
603   if (err != 0) {
604     uv__close(peerfd);
605     return err;
606   }
607 #endif
608 
609   return peerfd;
610 }
611 
612 
613 /* close() on macos has the "interesting" quirk that it fails with EINTR
614  * without closing the file descriptor when a thread is in the cancel state.
615  * That's why libuv calls close$NOCANCEL() instead.
616  *
617  * glibc on linux has a similar issue: close() is a cancellation point and
618  * will unwind the thread when it's in the cancel state. Work around that
619  * by making the system call directly. Musl libc is unaffected.
620  */
uv__close_nocancel(int fd)621 int uv__close_nocancel(int fd) {
622 #if defined(__APPLE__)
623 #pragma GCC diagnostic push
624 #pragma GCC diagnostic ignored "-Wdollar-in-identifier-extension"
625 #if defined(__LP64__) || TARGET_OS_IPHONE
626   extern int close$NOCANCEL(int);
627   return close$NOCANCEL(fd);
628 #else
629   extern int close$NOCANCEL$UNIX2003(int);
630   return close$NOCANCEL$UNIX2003(fd);
631 #endif
632 #pragma GCC diagnostic pop
633 #elif defined(__linux__) && defined(__SANITIZE_THREAD__) && defined(__clang__)
634   long rc;
635   __sanitizer_syscall_pre_close(fd);
636   rc = syscall(SYS_close, fd);
637   __sanitizer_syscall_post_close(rc, fd);
638   return rc;
639 #elif defined(__linux__) && !defined(__SANITIZE_THREAD__)
640   return syscall(SYS_close, fd);
641 #else
642   return close(fd);
643 #endif
644 }
645 
646 
uv__close_nocheckstdio(int fd)647 int uv__close_nocheckstdio(int fd) {
648   int saved_errno;
649   int rc;
650 
651   assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
652 
653   saved_errno = errno;
654   rc = uv__close_nocancel(fd);
655   if (rc == -1) {
656     rc = UV__ERR(errno);
657     if (rc == UV_EINTR || rc == UV__ERR(EINPROGRESS))
658       rc = 0;    /* The close is in progress, not an error. */
659     errno = saved_errno;
660   }
661 
662   return rc;
663 }
664 
665 
uv__close(int fd)666 int uv__close(int fd) {
667   assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
668 #if defined(__MVS__)
669   SAVE_ERRNO(epoll_file_close(fd));
670 #endif
671   return uv__close_nocheckstdio(fd);
672 }
673 
674 #if UV__NONBLOCK_IS_IOCTL
uv__nonblock_ioctl(int fd,int set)675 int uv__nonblock_ioctl(int fd, int set) {
676   int r;
677 
678   do
679     r = ioctl(fd, FIONBIO, &set);
680   while (r == -1 && errno == EINTR);
681 
682   if (r)
683     return UV__ERR(errno);
684 
685   return 0;
686 }
687 #endif
688 
689 
uv__nonblock_fcntl(int fd,int set)690 int uv__nonblock_fcntl(int fd, int set) {
691   int flags;
692   int r;
693 
694   do
695     r = fcntl(fd, F_GETFL);
696   while (r == -1 && errno == EINTR);
697 
698   if (r == -1)
699     return UV__ERR(errno);
700 
701   /* Bail out now if already set/clear. */
702   if (!!(r & O_NONBLOCK) == !!set)
703     return 0;
704 
705   if (set)
706     flags = r | O_NONBLOCK;
707   else
708     flags = r & ~O_NONBLOCK;
709 
710   do
711     r = fcntl(fd, F_SETFL, flags);
712   while (r == -1 && errno == EINTR);
713 
714   if (r)
715     return UV__ERR(errno);
716 
717   return 0;
718 }
719 
720 
uv__cloexec(int fd,int set)721 int uv__cloexec(int fd, int set) {
722   int flags;
723   int r;
724 
725   flags = 0;
726   if (set)
727     flags = FD_CLOEXEC;
728 
729   do
730     r = fcntl(fd, F_SETFD, flags);
731   while (r == -1 && errno == EINTR);
732 
733   if (r)
734     return UV__ERR(errno);
735 
736   return 0;
737 }
738 
739 
uv__recvmsg(int fd,struct msghdr * msg,int flags)740 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
741 #if defined(__ANDROID__)   || \
742     defined(__DragonFly__) || \
743     defined(__FreeBSD__)   || \
744     defined(__NetBSD__)    || \
745     defined(__OpenBSD__)   || \
746     defined(__linux__)
747   ssize_t rc;
748   rc = recvmsg(fd, msg, flags | MSG_CMSG_CLOEXEC);
749   if (rc == -1)
750     return UV__ERR(errno);
751   return rc;
752 #else
753   struct cmsghdr* cmsg;
754   int* pfd;
755   int* end;
756   ssize_t rc;
757   rc = recvmsg(fd, msg, flags);
758   if (rc == -1)
759     return UV__ERR(errno);
760   if (msg->msg_controllen == 0)
761     return rc;
762   for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
763     if (cmsg->cmsg_type == SCM_RIGHTS)
764       for (pfd = (int*) CMSG_DATA(cmsg),
765            end = (int*) ((char*) cmsg + cmsg->cmsg_len);
766            pfd < end;
767            pfd += 1)
768         uv__cloexec(*pfd, 1);
769   return rc;
770 #endif
771 }
772 
773 
uv_cwd(char * buffer,size_t * size)774 int uv_cwd(char* buffer, size_t* size) {
775   char scratch[1 + UV__PATH_MAX];
776 
777   if (buffer == NULL || size == NULL)
778     return UV_EINVAL;
779 
780   /* Try to read directly into the user's buffer first... */
781   if (getcwd(buffer, *size) != NULL)
782     goto fixup;
783 
784   if (errno != ERANGE)
785     return UV__ERR(errno);
786 
787   /* ...or into scratch space if the user's buffer is too small
788    * so we can report how much space to provide on the next try.
789    */
790   if (getcwd(scratch, sizeof(scratch)) == NULL)
791     return UV__ERR(errno);
792 
793   buffer = scratch;
794 
795 fixup:
796 
797   *size = strlen(buffer);
798 
799   if (*size > 1 && buffer[*size - 1] == '/') {
800     *size -= 1;
801     buffer[*size] = '\0';
802   }
803 
804   if (buffer == scratch) {
805     *size += 1;
806     return UV_ENOBUFS;
807   }
808 
809   return 0;
810 }
811 
812 
uv_chdir(const char * dir)813 int uv_chdir(const char* dir) {
814   if (chdir(dir))
815     return UV__ERR(errno);
816 
817   return 0;
818 }
819 
820 
uv_disable_stdio_inheritance(void)821 void uv_disable_stdio_inheritance(void) {
822   int fd;
823 
824   /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
825    * first 16 file descriptors. After that, bail out after the first error.
826    */
827   for (fd = 0; ; fd++)
828     if (uv__cloexec(fd, 1) && fd > 15)
829       break;
830 }
831 
832 
uv_fileno(const uv_handle_t * handle,uv_os_fd_t * fd)833 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
834   int fd_out;
835 
836   switch (handle->type) {
837   case UV_TCP:
838   case UV_NAMED_PIPE:
839   case UV_TTY:
840     fd_out = uv__stream_fd((uv_stream_t*) handle);
841     break;
842 
843   case UV_UDP:
844     fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
845     break;
846 
847   case UV_POLL:
848     fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
849     break;
850 
851   default:
852     return UV_EINVAL;
853   }
854 
855   if (uv__is_closing(handle) || fd_out == -1)
856     return UV_EBADF;
857 
858   *fd = fd_out;
859   return 0;
860 }
861 
862 
uv__run_pending(uv_loop_t * loop)863 static void uv__run_pending(uv_loop_t* loop) {
864   struct uv__queue* q;
865   struct uv__queue pq;
866   uv__io_t* w;
867 
868   uv__queue_move(&loop->pending_queue, &pq);
869 
870   while (!uv__queue_empty(&pq)) {
871     q = uv__queue_head(&pq);
872     uv__queue_remove(q);
873     uv__queue_init(q);
874     w = uv__queue_data(q, uv__io_t, pending_queue);
875     w->cb(loop, w, POLLOUT);
876   }
877 }
878 
879 
next_power_of_two(unsigned int val)880 static unsigned int next_power_of_two(unsigned int val) {
881   val -= 1;
882   val |= val >> 1;
883   val |= val >> 2;
884   val |= val >> 4;
885   val |= val >> 8;
886   val |= val >> 16;
887   val += 1;
888   return val;
889 }
890 
maybe_resize(uv_loop_t * loop,unsigned int len)891 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
892   uv__io_t** watchers;
893   void* fake_watcher_list;
894   void* fake_watcher_count;
895   unsigned int nwatchers;
896   unsigned int i;
897 
898   if (len <= loop->nwatchers)
899     return;
900 
901   /* Preserve fake watcher list and count at the end of the watchers */
902   if (loop->watchers != NULL) {
903     fake_watcher_list = loop->watchers[loop->nwatchers];
904     fake_watcher_count = loop->watchers[loop->nwatchers + 1];
905   } else {
906     fake_watcher_list = NULL;
907     fake_watcher_count = NULL;
908   }
909 
910   nwatchers = next_power_of_two(len + 2) - 2;
911   watchers = uv__reallocf(loop->watchers,
912                           (nwatchers + 2) * sizeof(loop->watchers[0]));
913 
914   if (watchers == NULL)
915     abort();
916   for (i = loop->nwatchers; i < nwatchers; i++)
917     watchers[i] = NULL;
918   watchers[nwatchers] = fake_watcher_list;
919   watchers[nwatchers + 1] = fake_watcher_count;
920 
921   loop->watchers = watchers;
922   loop->nwatchers = nwatchers;
923 }
924 
925 
uv__io_init(uv__io_t * w,uv__io_cb cb,int fd)926 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
927   assert(cb != NULL);
928   assert(fd >= -1);
929   uv__queue_init(&w->pending_queue);
930   uv__queue_init(&w->watcher_queue);
931   w->cb = cb;
932   w->fd = fd;
933   w->events = 0;
934   w->pevents = 0;
935 }
936 
937 
uv__io_start(uv_loop_t * loop,uv__io_t * w,unsigned int events)938 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
939   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
940   assert(0 != events);
941   assert(w->fd >= 0);
942   assert(w->fd < INT_MAX);
943 
944   w->pevents |= events;
945   maybe_resize(loop, w->fd + 1);
946 
947 #if !defined(__sun)
948   /* The event ports backend needs to rearm all file descriptors on each and
949    * every tick of the event loop but the other backends allow us to
950    * short-circuit here if the event mask is unchanged.
951    */
952   if (w->events == w->pevents)
953     return;
954 #endif
955 
956   if (uv__queue_empty(&w->watcher_queue))
957     uv__queue_insert_tail(&loop->watcher_queue, &w->watcher_queue);
958 
959   if (loop->watchers[w->fd] == NULL) {
960     loop->watchers[w->fd] = w;
961     loop->nfds++;
962   }
963 }
964 
965 
uv__io_stop(uv_loop_t * loop,uv__io_t * w,unsigned int events)966 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
967   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
968   assert(0 != events);
969 
970   if (w->fd == -1)
971     return;
972 
973   assert(w->fd >= 0);
974 
975   /* Happens when uv__io_stop() is called on a handle that was never started. */
976   if ((unsigned) w->fd >= loop->nwatchers)
977     return;
978 
979   w->pevents &= ~events;
980 
981   if (w->pevents == 0) {
982     uv__queue_remove(&w->watcher_queue);
983     uv__queue_init(&w->watcher_queue);
984     w->events = 0;
985 
986     if (w == loop->watchers[w->fd]) {
987       assert(loop->nfds > 0);
988       loop->watchers[w->fd] = NULL;
989       loop->nfds--;
990     }
991   }
992   else if (uv__queue_empty(&w->watcher_queue))
993     uv__queue_insert_tail(&loop->watcher_queue, &w->watcher_queue);
994 }
995 
996 
uv__io_close(uv_loop_t * loop,uv__io_t * w)997 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
998   uv__io_stop(loop, w, POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI);
999   uv__queue_remove(&w->pending_queue);
1000 
1001   /* Remove stale events for this file descriptor */
1002   if (w->fd != -1)
1003     uv__platform_invalidate_fd(loop, w->fd);
1004 }
1005 
1006 
uv__io_feed(uv_loop_t * loop,uv__io_t * w)1007 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
1008   if (uv__queue_empty(&w->pending_queue))
1009     uv__queue_insert_tail(&loop->pending_queue, &w->pending_queue);
1010 }
1011 
1012 
uv__io_active(const uv__io_t * w,unsigned int events)1013 int uv__io_active(const uv__io_t* w, unsigned int events) {
1014   assert(0 == (events & ~(POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI)));
1015   assert(0 != events);
1016   return 0 != (w->pevents & events);
1017 }
1018 
1019 
uv__fd_exists(uv_loop_t * loop,int fd)1020 int uv__fd_exists(uv_loop_t* loop, int fd) {
1021   return (unsigned) fd < loop->nwatchers && loop->watchers[fd] != NULL;
1022 }
1023 
1024 
uv_getrusage(uv_rusage_t * rusage)1025 int uv_getrusage(uv_rusage_t* rusage) {
1026   struct rusage usage;
1027 
1028   if (getrusage(RUSAGE_SELF, &usage))
1029     return UV__ERR(errno);
1030 
1031   rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
1032   rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
1033 
1034   rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
1035   rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
1036 
1037 #if !defined(__MVS__) && !defined(__HAIKU__)
1038   rusage->ru_maxrss = usage.ru_maxrss;
1039   rusage->ru_ixrss = usage.ru_ixrss;
1040   rusage->ru_idrss = usage.ru_idrss;
1041   rusage->ru_isrss = usage.ru_isrss;
1042   rusage->ru_minflt = usage.ru_minflt;
1043   rusage->ru_majflt = usage.ru_majflt;
1044   rusage->ru_nswap = usage.ru_nswap;
1045   rusage->ru_inblock = usage.ru_inblock;
1046   rusage->ru_oublock = usage.ru_oublock;
1047   rusage->ru_msgsnd = usage.ru_msgsnd;
1048   rusage->ru_msgrcv = usage.ru_msgrcv;
1049   rusage->ru_nsignals = usage.ru_nsignals;
1050   rusage->ru_nvcsw = usage.ru_nvcsw;
1051   rusage->ru_nivcsw = usage.ru_nivcsw;
1052 #endif
1053 
1054   /* Most platforms report ru_maxrss in kilobytes; macOS and Solaris are
1055    * the outliers because of course they are.
1056    */
1057 #if defined(__APPLE__)
1058   rusage->ru_maxrss /= 1024;                  /* macOS and iOS report bytes. */
1059 #elif defined(__sun)
1060   rusage->ru_maxrss /= getpagesize() / 1024;  /* Solaris reports pages. */
1061 #endif
1062 
1063   return 0;
1064 }
1065 
1066 
uv__open_cloexec(const char * path,int flags)1067 int uv__open_cloexec(const char* path, int flags) {
1068 #if defined(O_CLOEXEC)
1069   int fd;
1070 
1071   fd = open(path, flags | O_CLOEXEC);
1072   if (fd == -1)
1073     return UV__ERR(errno);
1074 
1075   return fd;
1076 #else  /* O_CLOEXEC */
1077   int err;
1078   int fd;
1079 
1080   fd = open(path, flags);
1081   if (fd == -1)
1082     return UV__ERR(errno);
1083 
1084   err = uv__cloexec(fd, 1);
1085   if (err) {
1086     uv__close(fd);
1087     return err;
1088   }
1089 
1090   return fd;
1091 #endif  /* O_CLOEXEC */
1092 }
1093 
1094 
uv__slurp(const char * filename,char * buf,size_t len)1095 int uv__slurp(const char* filename, char* buf, size_t len) {
1096   ssize_t n;
1097   int fd;
1098 
1099   assert(len > 0);
1100 
1101   fd = uv__open_cloexec(filename, O_RDONLY);
1102   if (fd < 0)
1103     return fd;
1104 
1105   do
1106     n = read(fd, buf, len - 1);
1107   while (n == -1 && errno == EINTR);
1108 
1109   if (uv__close_nocheckstdio(fd))
1110     abort();
1111 
1112   if (n < 0)
1113     return UV__ERR(errno);
1114 
1115   buf[n] = '\0';
1116 
1117   return 0;
1118 }
1119 
1120 
uv__dup2_cloexec(int oldfd,int newfd)1121 int uv__dup2_cloexec(int oldfd, int newfd) {
1122 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__linux__)
1123   int r;
1124 
1125   r = dup3(oldfd, newfd, O_CLOEXEC);
1126   if (r == -1)
1127     return UV__ERR(errno);
1128 
1129   return r;
1130 #else
1131   int err;
1132   int r;
1133 
1134   r = dup2(oldfd, newfd);  /* Never retry. */
1135   if (r == -1)
1136     return UV__ERR(errno);
1137 
1138   err = uv__cloexec(newfd, 1);
1139   if (err != 0) {
1140     uv__close(newfd);
1141     return err;
1142   }
1143 
1144   return r;
1145 #endif
1146 }
1147 
1148 
uv_os_homedir(char * buffer,size_t * size)1149 int uv_os_homedir(char* buffer, size_t* size) {
1150   uv_passwd_t pwd;
1151   size_t len;
1152   int r;
1153 
1154   /* Check if the HOME environment variable is set first. The task of
1155      performing input validation on buffer and size is taken care of by
1156      uv_os_getenv(). */
1157   r = uv_os_getenv("HOME", buffer, size);
1158 
1159   if (r != UV_ENOENT)
1160     return r;
1161 
1162   /* HOME is not set, so call uv_os_get_passwd() */
1163   r = uv_os_get_passwd(&pwd);
1164 
1165   if (r != 0) {
1166     return r;
1167   }
1168 
1169   len = strlen(pwd.homedir);
1170 
1171   if (len >= *size) {
1172     *size = len + 1;
1173     uv_os_free_passwd(&pwd);
1174     return UV_ENOBUFS;
1175   }
1176 
1177   memcpy(buffer, pwd.homedir, len + 1);
1178   *size = len;
1179   uv_os_free_passwd(&pwd);
1180 
1181   return 0;
1182 }
1183 
1184 
uv_os_tmpdir(char * buffer,size_t * size)1185 int uv_os_tmpdir(char* buffer, size_t* size) {
1186   const char* buf;
1187   size_t len;
1188 
1189   if (buffer == NULL || size == NULL || *size == 0)
1190     return UV_EINVAL;
1191 
1192 #define CHECK_ENV_VAR(name)                                                   \
1193   do {                                                                        \
1194     buf = getenv(name);                                                       \
1195     if (buf != NULL)                                                          \
1196       goto return_buffer;                                                     \
1197   }                                                                           \
1198   while (0)
1199 
1200   /* Check the TMPDIR, TMP, TEMP, and TEMPDIR environment variables in order */
1201   CHECK_ENV_VAR("TMPDIR");
1202   CHECK_ENV_VAR("TMP");
1203   CHECK_ENV_VAR("TEMP");
1204   CHECK_ENV_VAR("TEMPDIR");
1205 
1206 #undef CHECK_ENV_VAR
1207 
1208   /* No temp environment variables defined */
1209   #if defined(__ANDROID__)
1210     buf = "/data/local/tmp";
1211   #else
1212     buf = "/tmp";
1213   #endif
1214 
1215 return_buffer:
1216   len = strlen(buf);
1217 
1218   if (len >= *size) {
1219     *size = len + 1;
1220     return UV_ENOBUFS;
1221   }
1222 
1223   /* The returned directory should not have a trailing slash. */
1224   if (len > 1 && buf[len - 1] == '/') {
1225     len--;
1226   }
1227 
1228   memcpy(buffer, buf, len + 1);
1229   buffer[len] = '\0';
1230   *size = len;
1231 
1232   return 0;
1233 }
1234 
1235 
uv__getpwuid_r(uv_passwd_t * pwd,uid_t uid)1236 static int uv__getpwuid_r(uv_passwd_t *pwd, uid_t uid) {
1237   struct passwd pw;
1238   struct passwd* result;
1239   char* buf;
1240   size_t bufsize;
1241   size_t name_size;
1242   size_t homedir_size;
1243   size_t shell_size;
1244   int r;
1245 
1246   if (pwd == NULL)
1247     return UV_EINVAL;
1248 
1249   /* Calling sysconf(_SC_GETPW_R_SIZE_MAX) would get the suggested size, but it
1250    * is frequently 1024 or 4096, so we can just use that directly. The pwent
1251    * will not usually be large. */
1252   for (bufsize = 2000;; bufsize *= 2) {
1253     buf = uv__malloc(bufsize);
1254 
1255     if (buf == NULL)
1256       return UV_ENOMEM;
1257 
1258     do
1259       r = getpwuid_r(uid, &pw, buf, bufsize, &result);
1260     while (r == EINTR);
1261 
1262     if (r != 0 || result == NULL)
1263       uv__free(buf);
1264 
1265     if (r != ERANGE)
1266       break;
1267   }
1268 
1269   if (r != 0)
1270     return UV__ERR(r);
1271 
1272   if (result == NULL)
1273     return UV_ENOENT;
1274 
1275   /* Allocate memory for the username, shell, and home directory */
1276   name_size = strlen(pw.pw_name) + 1;
1277   homedir_size = strlen(pw.pw_dir) + 1;
1278   shell_size = strlen(pw.pw_shell) + 1;
1279   pwd->username = uv__malloc(name_size + homedir_size + shell_size);
1280 
1281   if (pwd->username == NULL) {
1282     uv__free(buf);
1283     return UV_ENOMEM;
1284   }
1285 
1286   /* Copy the username */
1287   memcpy(pwd->username, pw.pw_name, name_size);
1288 
1289   /* Copy the home directory */
1290   pwd->homedir = pwd->username + name_size;
1291   memcpy(pwd->homedir, pw.pw_dir, homedir_size);
1292 
1293   /* Copy the shell */
1294   pwd->shell = pwd->homedir + homedir_size;
1295   memcpy(pwd->shell, pw.pw_shell, shell_size);
1296 
1297   /* Copy the uid and gid */
1298   pwd->uid = pw.pw_uid;
1299   pwd->gid = pw.pw_gid;
1300 
1301   uv__free(buf);
1302 
1303   return 0;
1304 }
1305 
1306 
uv_os_get_group(uv_group_t * grp,uv_uid_t gid)1307 int uv_os_get_group(uv_group_t* grp, uv_uid_t gid) {
1308 #if defined(__ANDROID__) && __ANDROID_API__ < 24
1309   /* This function getgrgid_r() was added in Android N (level 24) */
1310   return UV_ENOSYS;
1311 #else
1312   struct group gp;
1313   struct group* result;
1314   char* buf;
1315   char* gr_mem;
1316   size_t bufsize;
1317   size_t name_size;
1318   long members;
1319   size_t mem_size;
1320   int r;
1321 
1322   if (grp == NULL)
1323     return UV_EINVAL;
1324 
1325   /* Calling sysconf(_SC_GETGR_R_SIZE_MAX) would get the suggested size, but it
1326    * is frequently 1024 or 4096, so we can just use that directly. The pwent
1327    * will not usually be large. */
1328   for (bufsize = 2000;; bufsize *= 2) {
1329     buf = uv__malloc(bufsize);
1330 
1331     if (buf == NULL)
1332       return UV_ENOMEM;
1333 
1334     do
1335       r = getgrgid_r(gid, &gp, buf, bufsize, &result);
1336     while (r == EINTR);
1337 
1338     if (r != 0 || result == NULL)
1339       uv__free(buf);
1340 
1341     if (r != ERANGE)
1342       break;
1343   }
1344 
1345   if (r != 0)
1346     return UV__ERR(r);
1347 
1348   if (result == NULL)
1349     return UV_ENOENT;
1350 
1351   /* Allocate memory for the groupname and members. */
1352   name_size = strlen(gp.gr_name) + 1;
1353   members = 0;
1354   mem_size = sizeof(char*);
1355   for (r = 0; gp.gr_mem[r] != NULL; r++) {
1356     mem_size += strlen(gp.gr_mem[r]) + 1 + sizeof(char*);
1357     members++;
1358   }
1359 
1360   gr_mem = uv__malloc(name_size + mem_size);
1361   if (gr_mem == NULL) {
1362     uv__free(buf);
1363     return UV_ENOMEM;
1364   }
1365 
1366   /* Copy the members */
1367   grp->members = (char**) gr_mem;
1368   grp->members[members] = NULL;
1369   gr_mem = (char*) &grp->members[members + 1];
1370   for (r = 0; r < members; r++) {
1371     grp->members[r] = gr_mem;
1372     strcpy(gr_mem, gp.gr_mem[r]);
1373     gr_mem += strlen(gr_mem) + 1;
1374   }
1375   assert(gr_mem == (char*)grp->members + mem_size);
1376 
1377   /* Copy the groupname */
1378   grp->groupname = gr_mem;
1379   memcpy(grp->groupname, gp.gr_name, name_size);
1380   gr_mem += name_size;
1381 
1382   /* Copy the gid */
1383   grp->gid = gp.gr_gid;
1384 
1385   uv__free(buf);
1386 
1387   return 0;
1388 #endif
1389 }
1390 
1391 
uv_os_get_passwd(uv_passwd_t * pwd)1392 int uv_os_get_passwd(uv_passwd_t* pwd) {
1393   return uv__getpwuid_r(pwd, geteuid());
1394 }
1395 
1396 
uv_os_get_passwd2(uv_passwd_t * pwd,uv_uid_t uid)1397 int uv_os_get_passwd2(uv_passwd_t* pwd, uv_uid_t uid) {
1398   return uv__getpwuid_r(pwd, uid);
1399 }
1400 
1401 
uv_translate_sys_error(int sys_errno)1402 int uv_translate_sys_error(int sys_errno) {
1403   /* If < 0 then it's already a libuv error. */
1404   return sys_errno <= 0 ? sys_errno : -sys_errno;
1405 }
1406 
1407 
uv_os_environ(uv_env_item_t ** envitems,int * count)1408 int uv_os_environ(uv_env_item_t** envitems, int* count) {
1409   int i, j, cnt;
1410   uv_env_item_t* envitem;
1411 
1412   *envitems = NULL;
1413   *count = 0;
1414 
1415   for (i = 0; environ[i] != NULL; i++);
1416 
1417   *envitems = uv__calloc(i, sizeof(**envitems));
1418 
1419   if (*envitems == NULL)
1420     return UV_ENOMEM;
1421 
1422   for (j = 0, cnt = 0; j < i; j++) {
1423     char* buf;
1424     char* ptr;
1425 
1426     if (environ[j] == NULL)
1427       break;
1428 
1429     buf = uv__strdup(environ[j]);
1430     if (buf == NULL)
1431       goto fail;
1432 
1433     ptr = strchr(buf, '=');
1434     if (ptr == NULL) {
1435       uv__free(buf);
1436       continue;
1437     }
1438 
1439     *ptr = '\0';
1440 
1441     envitem = &(*envitems)[cnt];
1442     envitem->name = buf;
1443     envitem->value = ptr + 1;
1444 
1445     cnt++;
1446   }
1447 
1448   *count = cnt;
1449   return 0;
1450 
1451 fail:
1452   for (i = 0; i < cnt; i++) {
1453     envitem = &(*envitems)[cnt];
1454     uv__free(envitem->name);
1455   }
1456   uv__free(*envitems);
1457 
1458   *envitems = NULL;
1459   *count = 0;
1460   return UV_ENOMEM;
1461 }
1462 
1463 
uv_os_getenv(const char * name,char * buffer,size_t * size)1464 int uv_os_getenv(const char* name, char* buffer, size_t* size) {
1465   char* var;
1466   size_t len;
1467 
1468   if (name == NULL || buffer == NULL || size == NULL || *size == 0)
1469     return UV_EINVAL;
1470 
1471   var = getenv(name);
1472 
1473   if (var == NULL)
1474     return UV_ENOENT;
1475 
1476   len = strlen(var);
1477 
1478   if (len >= *size) {
1479     *size = len + 1;
1480     return UV_ENOBUFS;
1481   }
1482 
1483   memcpy(buffer, var, len + 1);
1484   *size = len;
1485 
1486   return 0;
1487 }
1488 
1489 
uv_os_setenv(const char * name,const char * value)1490 int uv_os_setenv(const char* name, const char* value) {
1491   if (name == NULL || value == NULL)
1492     return UV_EINVAL;
1493 
1494   if (setenv(name, value, 1) != 0)
1495     return UV__ERR(errno);
1496 
1497   return 0;
1498 }
1499 
1500 
uv_os_unsetenv(const char * name)1501 int uv_os_unsetenv(const char* name) {
1502   if (name == NULL)
1503     return UV_EINVAL;
1504 
1505   if (unsetenv(name) != 0)
1506     return UV__ERR(errno);
1507 
1508   return 0;
1509 }
1510 
1511 
uv_os_gethostname(char * buffer,size_t * size)1512 int uv_os_gethostname(char* buffer, size_t* size) {
1513   /*
1514     On some platforms, if the input buffer is not large enough, gethostname()
1515     succeeds, but truncates the result. libuv can detect this and return ENOBUFS
1516     instead by creating a large enough buffer and comparing the hostname length
1517     to the size input.
1518   */
1519   char buf[UV_MAXHOSTNAMESIZE];
1520   size_t len;
1521 
1522   if (buffer == NULL || size == NULL || *size == 0)
1523     return UV_EINVAL;
1524 
1525   if (gethostname(buf, sizeof(buf)) != 0)
1526     return UV__ERR(errno);
1527 
1528   buf[sizeof(buf) - 1] = '\0'; /* Null terminate, just to be safe. */
1529   len = strlen(buf);
1530 
1531   if (len >= *size) {
1532     *size = len + 1;
1533     return UV_ENOBUFS;
1534   }
1535 
1536   memcpy(buffer, buf, len + 1);
1537   *size = len;
1538   return 0;
1539 }
1540 
1541 
uv_get_osfhandle(int fd)1542 uv_os_fd_t uv_get_osfhandle(int fd) {
1543   return fd;
1544 }
1545 
uv_open_osfhandle(uv_os_fd_t os_fd)1546 int uv_open_osfhandle(uv_os_fd_t os_fd) {
1547   return os_fd;
1548 }
1549 
uv_os_getpid(void)1550 uv_pid_t uv_os_getpid(void) {
1551   return getpid();
1552 }
1553 
1554 
uv_os_getppid(void)1555 uv_pid_t uv_os_getppid(void) {
1556   return getppid();
1557 }
1558 
uv_cpumask_size(void)1559 int uv_cpumask_size(void) {
1560 #if UV__CPU_AFFINITY_SUPPORTED
1561   return CPU_SETSIZE;
1562 #else
1563   return UV_ENOTSUP;
1564 #endif
1565 }
1566 
uv_os_getpriority(uv_pid_t pid,int * priority)1567 int uv_os_getpriority(uv_pid_t pid, int* priority) {
1568   int r;
1569 
1570   if (priority == NULL)
1571     return UV_EINVAL;
1572 
1573   errno = 0;
1574   r = getpriority(PRIO_PROCESS, (int) pid);
1575 
1576   if (r == -1 && errno != 0)
1577     return UV__ERR(errno);
1578 
1579   *priority = r;
1580   return 0;
1581 }
1582 
1583 
uv_os_setpriority(uv_pid_t pid,int priority)1584 int uv_os_setpriority(uv_pid_t pid, int priority) {
1585   if (priority < UV_PRIORITY_HIGHEST || priority > UV_PRIORITY_LOW)
1586     return UV_EINVAL;
1587 
1588   if (setpriority(PRIO_PROCESS, (int) pid, priority) != 0)
1589     return UV__ERR(errno);
1590 
1591   return 0;
1592 }
1593 
1594 /**
1595  * If the function succeeds, the return value is 0.
1596  * If the function fails, the return value is non-zero.
1597  * for Linux, when schedule policy is SCHED_OTHER (default), priority is 0.
1598  * So the output parameter priority is actually the nice value.
1599 */
uv_thread_getpriority(uv_thread_t tid,int * priority)1600 int uv_thread_getpriority(uv_thread_t tid, int* priority) {
1601   int r;
1602   int policy;
1603   struct sched_param param;
1604 #ifdef __linux__
1605   pid_t pid = gettid();
1606 #endif
1607 
1608   if (priority == NULL)
1609     return UV_EINVAL;
1610 
1611   r = pthread_getschedparam(tid, &policy, &param);
1612   if (r != 0)
1613     return UV__ERR(errno);
1614 
1615 #ifdef __linux__
1616   if (SCHED_OTHER == policy && pthread_equal(tid, pthread_self())) {
1617     errno = 0;
1618     r = getpriority(PRIO_PROCESS, pid);
1619     if (r == -1 && errno != 0)
1620       return UV__ERR(errno);
1621     *priority = r;
1622     return 0;
1623   }
1624 #endif
1625 
1626   *priority = param.sched_priority;
1627   return 0;
1628 }
1629 
1630 #ifdef __linux__
set_nice_for_calling_thread(int priority)1631 static int set_nice_for_calling_thread(int priority) {
1632   int r;
1633   int nice;
1634 
1635   if (priority < UV_THREAD_PRIORITY_LOWEST || priority > UV_THREAD_PRIORITY_HIGHEST)
1636     return UV_EINVAL;
1637 
1638   pid_t pid = gettid();
1639   nice = 0 - priority * 2;
1640   r = setpriority(PRIO_PROCESS, pid, nice);
1641   if (r != 0)
1642     return UV__ERR(errno);
1643   return 0;
1644 }
1645 #endif
1646 
1647 /**
1648  * If the function succeeds, the return value is 0.
1649  * If the function fails, the return value is non-zero.
1650 */
uv_thread_setpriority(uv_thread_t tid,int priority)1651 int uv_thread_setpriority(uv_thread_t tid, int priority) {
1652   int r;
1653   int min;
1654   int max;
1655   int range;
1656   int prio;
1657   int policy;
1658   struct sched_param param;
1659 
1660   if (priority < UV_THREAD_PRIORITY_LOWEST || priority > UV_THREAD_PRIORITY_HIGHEST)
1661     return UV_EINVAL;
1662 
1663   r = pthread_getschedparam(tid, &policy, &param);
1664   if (r != 0)
1665     return UV__ERR(errno);
1666 
1667 #ifdef __linux__
1668 /**
1669  * for Linux, when schedule policy is SCHED_OTHER (default), priority must be 0,
1670  * we should set the nice value in this case.
1671 */
1672   if (SCHED_OTHER == policy && pthread_equal(tid, pthread_self()))
1673     return set_nice_for_calling_thread(priority);
1674 #endif
1675 
1676 #ifdef __PASE__
1677   min = 1;
1678   max = 127;
1679 #else
1680   min = sched_get_priority_min(policy);
1681   max = sched_get_priority_max(policy);
1682 #endif
1683 
1684   if (min == -1 || max == -1)
1685     return UV__ERR(errno);
1686 
1687   range = max - min;
1688 
1689   switch (priority) {
1690     case UV_THREAD_PRIORITY_HIGHEST:
1691       prio = max;
1692       break;
1693     case UV_THREAD_PRIORITY_ABOVE_NORMAL:
1694       prio = min + range * 3 / 4;
1695       break;
1696     case UV_THREAD_PRIORITY_NORMAL:
1697       prio = min + range / 2;
1698       break;
1699     case UV_THREAD_PRIORITY_BELOW_NORMAL:
1700       prio = min + range / 4;
1701       break;
1702     case UV_THREAD_PRIORITY_LOWEST:
1703       prio = min;
1704       break;
1705     default:
1706       return 0;
1707   }
1708 
1709   if (param.sched_priority != prio) {
1710     param.sched_priority = prio;
1711     r = pthread_setschedparam(tid, policy, &param);
1712     if (r != 0)
1713       return UV__ERR(errno);
1714   }
1715 
1716   return 0;
1717 }
1718 
uv_os_uname(uv_utsname_t * buffer)1719 int uv_os_uname(uv_utsname_t* buffer) {
1720   struct utsname buf;
1721   int r;
1722 
1723   if (buffer == NULL)
1724     return UV_EINVAL;
1725 
1726   if (uname(&buf) == -1) {
1727     r = UV__ERR(errno);
1728     goto error;
1729   }
1730 
1731   r = uv__strscpy(buffer->sysname, buf.sysname, sizeof(buffer->sysname));
1732   if (r == UV_E2BIG)
1733     goto error;
1734 
1735 #ifdef _AIX
1736   r = snprintf(buffer->release,
1737                sizeof(buffer->release),
1738                "%s.%s",
1739                buf.version,
1740                buf.release);
1741   if (r >= sizeof(buffer->release)) {
1742     r = UV_E2BIG;
1743     goto error;
1744   }
1745 #else
1746   r = uv__strscpy(buffer->release, buf.release, sizeof(buffer->release));
1747   if (r == UV_E2BIG)
1748     goto error;
1749 #endif
1750 
1751   r = uv__strscpy(buffer->version, buf.version, sizeof(buffer->version));
1752   if (r == UV_E2BIG)
1753     goto error;
1754 
1755 #if defined(_AIX) || defined(__PASE__)
1756   r = uv__strscpy(buffer->machine, "ppc64", sizeof(buffer->machine));
1757 #else
1758   r = uv__strscpy(buffer->machine, buf.machine, sizeof(buffer->machine));
1759 #endif
1760 
1761   if (r == UV_E2BIG)
1762     goto error;
1763 
1764   return 0;
1765 
1766 error:
1767   buffer->sysname[0] = '\0';
1768   buffer->release[0] = '\0';
1769   buffer->version[0] = '\0';
1770   buffer->machine[0] = '\0';
1771   return r;
1772 }
1773 
uv__getsockpeername(const uv_handle_t * handle,uv__peersockfunc func,struct sockaddr * name,int * namelen)1774 int uv__getsockpeername(const uv_handle_t* handle,
1775                         uv__peersockfunc func,
1776                         struct sockaddr* name,
1777                         int* namelen) {
1778   socklen_t socklen;
1779   uv_os_fd_t fd;
1780   int r;
1781 
1782   r = uv_fileno(handle, &fd);
1783   if (r < 0)
1784     return r;
1785 
1786   /* sizeof(socklen_t) != sizeof(int) on some systems. */
1787   socklen = (socklen_t) *namelen;
1788 
1789   if (func(fd, name, &socklen))
1790     return UV__ERR(errno);
1791 
1792   *namelen = (int) socklen;
1793   return 0;
1794 }
1795 
uv_gettimeofday(uv_timeval64_t * tv)1796 int uv_gettimeofday(uv_timeval64_t* tv) {
1797   struct timeval time;
1798 
1799   if (tv == NULL)
1800     return UV_EINVAL;
1801 
1802   if (gettimeofday(&time, NULL) != 0)
1803     return UV__ERR(errno);
1804 
1805   tv->tv_sec = (int64_t) time.tv_sec;
1806   tv->tv_usec = (int32_t) time.tv_usec;
1807   return 0;
1808 }
1809 
uv_sleep(unsigned int msec)1810 void uv_sleep(unsigned int msec) {
1811   struct timespec timeout;
1812   int rc;
1813 
1814   timeout.tv_sec = msec / 1000;
1815   timeout.tv_nsec = (msec % 1000) * 1000 * 1000;
1816 
1817   do
1818     rc = nanosleep(&timeout, &timeout);
1819   while (rc == -1 && errno == EINTR);
1820 
1821   assert(rc == 0);
1822 }
1823 
uv__search_path(const char * prog,char * buf,size_t * buflen)1824 int uv__search_path(const char* prog, char* buf, size_t* buflen) {
1825   char abspath[UV__PATH_MAX];
1826   size_t abspath_size;
1827   char trypath[UV__PATH_MAX];
1828   char* cloned_path;
1829   char* path_env;
1830   char* token;
1831   char* itr;
1832 
1833   if (buf == NULL || buflen == NULL || *buflen == 0)
1834     return UV_EINVAL;
1835 
1836   /*
1837    * Possibilities for prog:
1838    * i) an absolute path such as: /home/user/myprojects/nodejs/node
1839    * ii) a relative path such as: ./node or ../myprojects/nodejs/node
1840    * iii) a bare filename such as "node", after exporting PATH variable
1841    *     to its location.
1842    */
1843 
1844   /* Case i) and ii) absolute or relative paths */
1845   if (strchr(prog, '/') != NULL) {
1846     if (realpath(prog, abspath) != abspath)
1847       return UV__ERR(errno);
1848 
1849     abspath_size = strlen(abspath);
1850 
1851     *buflen -= 1;
1852     if (*buflen > abspath_size)
1853       *buflen = abspath_size;
1854 
1855     memcpy(buf, abspath, *buflen);
1856     buf[*buflen] = '\0';
1857 
1858     return 0;
1859   }
1860 
1861   /* Case iii). Search PATH environment variable */
1862   cloned_path = NULL;
1863   token = NULL;
1864   path_env = getenv("PATH");
1865 
1866   if (path_env == NULL)
1867     return UV_EINVAL;
1868 
1869   cloned_path = uv__strdup(path_env);
1870   if (cloned_path == NULL)
1871     return UV_ENOMEM;
1872 
1873   token = uv__strtok(cloned_path, ":", &itr);
1874   while (token != NULL) {
1875     snprintf(trypath, sizeof(trypath) - 1, "%s/%s", token, prog);
1876     if (realpath(trypath, abspath) == abspath) {
1877       /* Check the match is executable */
1878       if (access(abspath, X_OK) == 0) {
1879         abspath_size = strlen(abspath);
1880 
1881         *buflen -= 1;
1882         if (*buflen > abspath_size)
1883           *buflen = abspath_size;
1884 
1885         memcpy(buf, abspath, *buflen);
1886         buf[*buflen] = '\0';
1887 
1888         uv__free(cloned_path);
1889         return 0;
1890       }
1891     }
1892     token = uv__strtok(NULL, ":", &itr);
1893   }
1894   uv__free(cloned_path);
1895 
1896   /* Out of tokens (path entries), and no match found */
1897   return UV_EINVAL;
1898 }
1899 
1900 
uv_available_parallelism(void)1901 unsigned int uv_available_parallelism(void) {
1902 #ifdef __linux__
1903   cpu_set_t set;
1904   long rc;
1905 
1906   memset(&set, 0, sizeof(set));
1907 
1908   /* sysconf(_SC_NPROCESSORS_ONLN) in musl calls sched_getaffinity() but in
1909    * glibc it's... complicated... so for consistency try sched_getaffinity()
1910    * before falling back to sysconf(_SC_NPROCESSORS_ONLN).
1911    */
1912   if (0 == sched_getaffinity(0, sizeof(set), &set))
1913     rc = CPU_COUNT(&set);
1914   else
1915     rc = sysconf(_SC_NPROCESSORS_ONLN);
1916 
1917   if (rc < 1)
1918     rc = 1;
1919 
1920   return (unsigned) rc;
1921 #elif defined(__MVS__)
1922   int rc;
1923 
1924   rc = __get_num_online_cpus();
1925   if (rc < 1)
1926     rc = 1;
1927 
1928   return (unsigned) rc;
1929 #else  /* __linux__ */
1930   long rc;
1931 
1932   rc = sysconf(_SC_NPROCESSORS_ONLN);
1933   if (rc < 1)
1934     rc = 1;
1935 
1936   return (unsigned) rc;
1937 #endif  /* __linux__ */
1938 }
1939 
uv_register_task_to_event(struct uv_loop_s * loop,uv_post_task func,void * handler)1940 int uv_register_task_to_event(struct uv_loop_s* loop, uv_post_task func, void* handler)
1941 {
1942 #if defined(__aarch64__)
1943   if (loop == NULL)
1944     return -1;
1945 
1946   struct uv_loop_data* data = (struct uv_loop_data*)malloc(sizeof(struct uv_loop_data));
1947   if (data == NULL)
1948     return -1;
1949 
1950   (void)memset(data, 0, sizeof(struct uv_loop_data));
1951   data->post_task_func = func;
1952   data->event_handler = handler;
1953   loop->data = (void *)data;
1954   uv__loop_internal_fields_t* lfields_flag = uv__get_internal_fields(loop);
1955   lfields_flag->register_flag = 1;
1956   return 0;
1957 #else
1958   return -1;
1959 #endif
1960 }
1961 
1962 
uv_unregister_task_to_event(struct uv_loop_s * loop)1963 int uv_unregister_task_to_event(struct uv_loop_s* loop)
1964 {
1965 #if defined(__aarch64__)
1966   uv__loop_internal_fields_t* lfields_flag = uv__get_internal_fields(loop);
1967   if (loop == NULL || loop->data == NULL || lfields_flag->register_flag == 0)
1968     return -1;
1969   free(loop->data);
1970   loop->data = NULL;
1971   lfields_flag->register_flag = 0;
1972   return 0;
1973 #else
1974   return -1;
1975 #endif
1976 }
1977 
1978 
uv_check_data_valid(uv_loop_t * loop)1979 int uv_check_data_valid(uv_loop_t* loop) {
1980 #if defined(__aarch64__)
1981   uv__loop_internal_fields_t* lfields_flag = uv__get_internal_fields(loop);
1982   if (loop == NULL || loop->data == NULL || lfields_flag->register_flag == 0) {
1983     return -1;
1984   }
1985 
1986   if (((struct uv_loop_data*)loop->data)->post_task_func == NULL) {
1987     UV_LOGE("post_task_func NULL");
1988     return -1;
1989   }
1990   return 0;
1991 #else
1992   return -1;
1993 #endif
1994 }
1995 
1996