revise installing a license file
[platform/upstream/nodejs.git] / deps / uv / 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>
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <limits.h> /* INT_MAX, PATH_MAX, IOV_MAX */
39 #include <sys/uio.h> /* writev */
40 #include <sys/resource.h> /* getrusage */
41 #include <pwd.h>
42
43 #ifdef __linux__
44 # include <sys/ioctl.h>
45 #endif
46
47 #ifdef __sun
48 # include <sys/types.h>
49 # include <sys/wait.h>
50 #endif
51
52 #ifdef __APPLE__
53 # include <mach-o/dyld.h> /* _NSGetExecutablePath */
54 # include <sys/filio.h>
55 # include <sys/ioctl.h>
56 #endif
57
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
59 # include <sys/sysctl.h>
60 # include <sys/filio.h>
61 # include <sys/ioctl.h>
62 # include <sys/wait.h>
63 # define UV__O_CLOEXEC O_CLOEXEC
64 # if defined(__FreeBSD__) && __FreeBSD__ >= 10
65 #  define uv__accept4 accept4
66 #  define UV__SOCK_NONBLOCK SOCK_NONBLOCK
67 #  define UV__SOCK_CLOEXEC  SOCK_CLOEXEC
68 # endif
69 # if !defined(F_DUP2FD_CLOEXEC) && defined(_F_DUP2FD_CLOEXEC)
70 #  define F_DUP2FD_CLOEXEC  _F_DUP2FD_CLOEXEC
71 # endif
72 #endif
73
74 #ifdef _AIX
75 #include <sys/ioctl.h>
76 #endif
77
78 #if defined(__ANDROID_API__) && __ANDROID_API__ < 21
79 # include <dlfcn.h>  /* for dlsym */
80 #endif
81
82 static int uv__run_pending(uv_loop_t* loop);
83
84 /* Verify that uv_buf_t is ABI-compatible with struct iovec. */
85 STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
86 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
87               sizeof(((struct iovec*) 0)->iov_base));
88 STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
89               sizeof(((struct iovec*) 0)->iov_len));
90 STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
91 STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));
92
93
94 uint64_t uv_hrtime(void) {
95   return uv__hrtime(UV_CLOCK_PRECISE);
96 }
97
98
99 void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
100   assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
101
102   handle->flags |= UV_CLOSING;
103   handle->close_cb = close_cb;
104
105   switch (handle->type) {
106   case UV_NAMED_PIPE:
107     uv__pipe_close((uv_pipe_t*)handle);
108     break;
109
110   case UV_TTY:
111     uv__stream_close((uv_stream_t*)handle);
112     break;
113
114   case UV_TCP:
115     uv__tcp_close((uv_tcp_t*)handle);
116     break;
117
118   case UV_UDP:
119     uv__udp_close((uv_udp_t*)handle);
120     break;
121
122   case UV_PREPARE:
123     uv__prepare_close((uv_prepare_t*)handle);
124     break;
125
126   case UV_CHECK:
127     uv__check_close((uv_check_t*)handle);
128     break;
129
130   case UV_IDLE:
131     uv__idle_close((uv_idle_t*)handle);
132     break;
133
134   case UV_ASYNC:
135     uv__async_close((uv_async_t*)handle);
136     break;
137
138   case UV_TIMER:
139     uv__timer_close((uv_timer_t*)handle);
140     break;
141
142   case UV_PROCESS:
143     uv__process_close((uv_process_t*)handle);
144     break;
145
146   case UV_FS_EVENT:
147     uv__fs_event_close((uv_fs_event_t*)handle);
148     break;
149
150   case UV_POLL:
151     uv__poll_close((uv_poll_t*)handle);
152     break;
153
154   case UV_FS_POLL:
155     uv__fs_poll_close((uv_fs_poll_t*)handle);
156     break;
157
158   case UV_SIGNAL:
159     uv__signal_close((uv_signal_t*) handle);
160     /* Signal handles may not be closed immediately. The signal code will */
161     /* itself close uv__make_close_pending whenever appropriate. */
162     return;
163
164   default:
165     assert(0);
166   }
167
168   uv__make_close_pending(handle);
169 }
170
171 int uv__socket_sockopt(uv_handle_t* handle, int optname, int* value) {
172   int r;
173   int fd;
174   socklen_t len;
175
176   if (handle == NULL || value == NULL)
177     return -EINVAL;
178
179   if (handle->type == UV_TCP || handle->type == UV_NAMED_PIPE)
180     fd = uv__stream_fd((uv_stream_t*) handle);
181   else if (handle->type == UV_UDP)
182     fd = ((uv_udp_t *) handle)->io_watcher.fd;
183   else
184     return -ENOTSUP;
185
186   len = sizeof(*value);
187
188   if (*value == 0)
189     r = getsockopt(fd, SOL_SOCKET, optname, value, &len);
190   else
191     r = setsockopt(fd, SOL_SOCKET, optname, (const void*) value, len);
192
193   if (r < 0)
194     return -errno;
195
196   return 0;
197 }
198
199 void uv__make_close_pending(uv_handle_t* handle) {
200   assert(handle->flags & UV_CLOSING);
201   assert(!(handle->flags & UV_CLOSED));
202   handle->next_closing = handle->loop->closing_handles;
203   handle->loop->closing_handles = handle;
204 }
205
206 int uv__getiovmax(void) {
207 #if defined(IOV_MAX)
208   return IOV_MAX;
209 #elif defined(_SC_IOV_MAX)
210   static int iovmax = -1;
211   if (iovmax == -1) {
212     iovmax = sysconf(_SC_IOV_MAX);
213     /* On some embedded devices (arm-linux-uclibc based ip camera),
214      * sysconf(_SC_IOV_MAX) can not get the correct value. The return
215      * value is -1 and the errno is EINPROGRESS. Degrade the value to 1.
216      */
217     if (iovmax == -1) iovmax = 1;
218   }
219   return iovmax;
220 #else
221   return 1024;
222 #endif
223 }
224
225
226 static void uv__finish_close(uv_handle_t* handle) {
227   /* Note: while the handle is in the UV_CLOSING state now, it's still possible
228    * for it to be active in the sense that uv__is_active() returns true.
229    * A good example is when the user calls uv_shutdown(), immediately followed
230    * by uv_close(). The handle is considered active at this point because the
231    * completion of the shutdown req is still pending.
232    */
233   assert(handle->flags & UV_CLOSING);
234   assert(!(handle->flags & UV_CLOSED));
235   handle->flags |= UV_CLOSED;
236
237   switch (handle->type) {
238     case UV_PREPARE:
239     case UV_CHECK:
240     case UV_IDLE:
241     case UV_ASYNC:
242     case UV_TIMER:
243     case UV_PROCESS:
244     case UV_FS_EVENT:
245     case UV_FS_POLL:
246     case UV_POLL:
247     case UV_SIGNAL:
248       break;
249
250     case UV_NAMED_PIPE:
251     case UV_TCP:
252     case UV_TTY:
253       uv__stream_destroy((uv_stream_t*)handle);
254       break;
255
256     case UV_UDP:
257       uv__udp_finish_close((uv_udp_t*)handle);
258       break;
259
260     default:
261       assert(0);
262       break;
263   }
264
265   uv__handle_unref(handle);
266   QUEUE_REMOVE(&handle->handle_queue);
267
268   if (handle->close_cb) {
269     handle->close_cb(handle);
270   }
271 }
272
273
274 static void uv__run_closing_handles(uv_loop_t* loop) {
275   uv_handle_t* p;
276   uv_handle_t* q;
277
278   p = loop->closing_handles;
279   loop->closing_handles = NULL;
280
281   while (p) {
282     q = p->next_closing;
283     uv__finish_close(p);
284     p = q;
285   }
286 }
287
288
289 int uv_is_closing(const uv_handle_t* handle) {
290   return uv__is_closing(handle);
291 }
292
293
294 int uv_backend_fd(const uv_loop_t* loop) {
295   return loop->backend_fd;
296 }
297
298
299 int uv_backend_timeout(const uv_loop_t* loop) {
300   if (loop->stop_flag != 0)
301     return 0;
302
303   if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
304     return 0;
305
306   if (!QUEUE_EMPTY(&loop->idle_handles))
307     return 0;
308
309   if (!QUEUE_EMPTY(&loop->pending_queue))
310     return 0;
311
312   if (loop->closing_handles)
313     return 0;
314
315   return uv__next_timeout(loop);
316 }
317
318
319 static int uv__loop_alive(const uv_loop_t* loop) {
320   return uv__has_active_handles(loop) ||
321          uv__has_active_reqs(loop) ||
322          loop->closing_handles != NULL;
323 }
324
325
326 int uv_loop_alive(const uv_loop_t* loop) {
327     return uv__loop_alive(loop);
328 }
329
330
331 int uv_run(uv_loop_t* loop, uv_run_mode mode) {
332   int timeout;
333   int r;
334   int ran_pending;
335
336   r = uv__loop_alive(loop);
337   if (!r)
338     uv__update_time(loop);
339
340   while (r != 0 && loop->stop_flag == 0) {
341     uv__update_time(loop);
342     uv__run_timers(loop);
343     ran_pending = uv__run_pending(loop);
344     uv__run_idle(loop);
345     uv__run_prepare(loop);
346
347     timeout = 0;
348     if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
349       timeout = uv_backend_timeout(loop);
350
351     uv__io_poll(loop, timeout);
352     uv__run_check(loop);
353     uv__run_closing_handles(loop);
354
355     if (mode == UV_RUN_ONCE) {
356       /* UV_RUN_ONCE implies forward progress: at least one callback must have
357        * been invoked when it returns. uv__io_poll() can return without doing
358        * I/O (meaning: no callbacks) when its timeout expires - which means we
359        * have pending timers that satisfy the forward progress constraint.
360        *
361        * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
362        * the check.
363        */
364       uv__update_time(loop);
365       uv__run_timers(loop);
366     }
367
368     r = uv__loop_alive(loop);
369     if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
370       break;
371   }
372
373   /* The if statement lets gcc compile it to a conditional store. Avoids
374    * dirtying a cache line.
375    */
376   if (loop->stop_flag != 0)
377     loop->stop_flag = 0;
378
379   return r;
380 }
381
382
383 void uv_update_time(uv_loop_t* loop) {
384   uv__update_time(loop);
385 }
386
387
388 int uv_is_active(const uv_handle_t* handle) {
389   return uv__is_active(handle);
390 }
391
392
393 /* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
394 int uv__socket(int domain, int type, int protocol) {
395   int sockfd;
396   int err;
397
398 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
399   sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
400   if (sockfd != -1)
401     return sockfd;
402
403   if (errno != EINVAL)
404     return -errno;
405 #endif
406
407   sockfd = socket(domain, type, protocol);
408   if (sockfd == -1)
409     return -errno;
410
411   err = uv__nonblock(sockfd, 1);
412   if (err == 0)
413     err = uv__cloexec(sockfd, 1);
414
415   if (err) {
416     uv__close(sockfd);
417     return err;
418   }
419
420 #if defined(SO_NOSIGPIPE)
421   {
422     int on = 1;
423     setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
424   }
425 #endif
426
427   return sockfd;
428 }
429
430
431 int uv__accept(int sockfd) {
432   int peerfd;
433   int err;
434
435   assert(sockfd >= 0);
436
437   while (1) {
438 #if defined(__linux__) || __FreeBSD__ >= 10
439     static int no_accept4;
440
441     if (no_accept4)
442       goto skip;
443
444     peerfd = uv__accept4(sockfd,
445                          NULL,
446                          NULL,
447                          UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
448     if (peerfd != -1)
449       return peerfd;
450
451     if (errno == EINTR)
452       continue;
453
454     if (errno != ENOSYS)
455       return -errno;
456
457     no_accept4 = 1;
458 skip:
459 #endif
460
461     peerfd = accept(sockfd, NULL, NULL);
462     if (peerfd == -1) {
463       if (errno == EINTR)
464         continue;
465       return -errno;
466     }
467
468     err = uv__cloexec(peerfd, 1);
469     if (err == 0)
470       err = uv__nonblock(peerfd, 1);
471
472     if (err) {
473       uv__close(peerfd);
474       return err;
475     }
476
477     return peerfd;
478   }
479 }
480
481
482 int uv__close(int fd) {
483   int saved_errno;
484   int rc;
485
486   assert(fd > -1);  /* Catch uninitialized io_watcher.fd bugs. */
487   assert(fd > STDERR_FILENO);  /* Catch stdio close bugs. */
488
489   saved_errno = errno;
490   rc = close(fd);
491   if (rc == -1) {
492     rc = -errno;
493     if (rc == -EINTR)
494       rc = -EINPROGRESS;  /* For platform/libc consistency. */
495     errno = saved_errno;
496   }
497
498   return rc;
499 }
500
501
502 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) || \
503     defined(_AIX) || defined(__DragonFly__)
504
505 int uv__nonblock(int fd, int set) {
506   int r;
507
508   do
509     r = ioctl(fd, FIONBIO, &set);
510   while (r == -1 && errno == EINTR);
511
512   if (r)
513     return -errno;
514
515   return 0;
516 }
517
518
519 int uv__cloexec(int fd, int set) {
520   int r;
521
522   do
523     r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
524   while (r == -1 && errno == EINTR);
525
526   if (r)
527     return -errno;
528
529   return 0;
530 }
531
532 #else /* !(defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) || \
533            defined(_AIX) || defined(__DragonFly__)) */
534
535 int uv__nonblock(int fd, int set) {
536   int flags;
537   int r;
538
539   do
540     r = fcntl(fd, F_GETFL);
541   while (r == -1 && errno == EINTR);
542
543   if (r == -1)
544     return -errno;
545
546   /* Bail out now if already set/clear. */
547   if (!!(r & O_NONBLOCK) == !!set)
548     return 0;
549
550   if (set)
551     flags = r | O_NONBLOCK;
552   else
553     flags = r & ~O_NONBLOCK;
554
555   do
556     r = fcntl(fd, F_SETFL, flags);
557   while (r == -1 && errno == EINTR);
558
559   if (r)
560     return -errno;
561
562   return 0;
563 }
564
565
566 int uv__cloexec(int fd, int set) {
567   int flags;
568   int r;
569
570   do
571     r = fcntl(fd, F_GETFD);
572   while (r == -1 && errno == EINTR);
573
574   if (r == -1)
575     return -errno;
576
577   /* Bail out now if already set/clear. */
578   if (!!(r & FD_CLOEXEC) == !!set)
579     return 0;
580
581   if (set)
582     flags = r | FD_CLOEXEC;
583   else
584     flags = r & ~FD_CLOEXEC;
585
586   do
587     r = fcntl(fd, F_SETFD, flags);
588   while (r == -1 && errno == EINTR);
589
590   if (r)
591     return -errno;
592
593   return 0;
594 }
595
596 #endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) || \
597           defined(_AIX) || defined(__DragonFly__) */
598
599
600 /* This function is not execve-safe, there is a race window
601  * between the call to dup() and fcntl(FD_CLOEXEC).
602  */
603 int uv__dup(int fd) {
604   int err;
605
606   fd = dup(fd);
607
608   if (fd == -1)
609     return -errno;
610
611   err = uv__cloexec(fd, 1);
612   if (err) {
613     uv__close(fd);
614     return err;
615   }
616
617   return fd;
618 }
619
620
621 ssize_t uv__recvmsg(int fd, struct msghdr* msg, int flags) {
622   struct cmsghdr* cmsg;
623   ssize_t rc;
624   int* pfd;
625   int* end;
626 #if defined(__linux__)
627   static int no_msg_cmsg_cloexec;
628   if (no_msg_cmsg_cloexec == 0) {
629     rc = recvmsg(fd, msg, flags | 0x40000000);  /* MSG_CMSG_CLOEXEC */
630     if (rc != -1)
631       return rc;
632     if (errno != EINVAL)
633       return -errno;
634     rc = recvmsg(fd, msg, flags);
635     if (rc == -1)
636       return -errno;
637     no_msg_cmsg_cloexec = 1;
638   } else {
639     rc = recvmsg(fd, msg, flags);
640   }
641 #else
642   rc = recvmsg(fd, msg, flags);
643 #endif
644   if (rc == -1)
645     return -errno;
646   if (msg->msg_controllen == 0)
647     return rc;
648   for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg))
649     if (cmsg->cmsg_type == SCM_RIGHTS)
650       for (pfd = (int*) CMSG_DATA(cmsg),
651            end = (int*) ((char*) cmsg + cmsg->cmsg_len);
652            pfd < end;
653            pfd += 1)
654         uv__cloexec(*pfd, 1);
655   return rc;
656 }
657
658
659 int uv_cwd(char* buffer, size_t* size) {
660   if (buffer == NULL || size == NULL)
661     return -EINVAL;
662
663   if (getcwd(buffer, *size) == NULL)
664     return -errno;
665
666   *size = strlen(buffer);
667   if (*size > 1 && buffer[*size - 1] == '/') {
668     buffer[*size-1] = '\0';
669     (*size)--;
670   }
671
672   return 0;
673 }
674
675
676 int uv_chdir(const char* dir) {
677   if (chdir(dir))
678     return -errno;
679
680   return 0;
681 }
682
683
684 void uv_disable_stdio_inheritance(void) {
685   int fd;
686
687   /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
688    * first 16 file descriptors. After that, bail out after the first error.
689    */
690   for (fd = 0; ; fd++)
691     if (uv__cloexec(fd, 1) && fd > 15)
692       break;
693 }
694
695
696 int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) {
697   int fd_out;
698
699   switch (handle->type) {
700   case UV_TCP:
701   case UV_NAMED_PIPE:
702   case UV_TTY:
703     fd_out = uv__stream_fd((uv_stream_t*) handle);
704     break;
705
706   case UV_UDP:
707     fd_out = ((uv_udp_t *) handle)->io_watcher.fd;
708     break;
709
710   case UV_POLL:
711     fd_out = ((uv_poll_t *) handle)->io_watcher.fd;
712     break;
713
714   default:
715     return -EINVAL;
716   }
717
718   if (uv__is_closing(handle) || fd_out == -1)
719     return -EBADF;
720
721   *fd = fd_out;
722   return 0;
723 }
724
725
726 static int uv__run_pending(uv_loop_t* loop) {
727   QUEUE* q;
728   QUEUE pq;
729   uv__io_t* w;
730
731   if (QUEUE_EMPTY(&loop->pending_queue))
732     return 0;
733
734   QUEUE_MOVE(&loop->pending_queue, &pq);
735
736   while (!QUEUE_EMPTY(&pq)) {
737     q = QUEUE_HEAD(&pq);
738     QUEUE_REMOVE(q);
739     QUEUE_INIT(q);
740     w = QUEUE_DATA(q, uv__io_t, pending_queue);
741     w->cb(loop, w, UV__POLLOUT);
742   }
743
744   return 1;
745 }
746
747
748 static unsigned int next_power_of_two(unsigned int val) {
749   val -= 1;
750   val |= val >> 1;
751   val |= val >> 2;
752   val |= val >> 4;
753   val |= val >> 8;
754   val |= val >> 16;
755   val += 1;
756   return val;
757 }
758
759 static void maybe_resize(uv_loop_t* loop, unsigned int len) {
760   uv__io_t** watchers;
761   void* fake_watcher_list;
762   void* fake_watcher_count;
763   unsigned int nwatchers;
764   unsigned int i;
765
766   if (len <= loop->nwatchers)
767     return;
768
769   /* Preserve fake watcher list and count at the end of the watchers */
770   if (loop->watchers != NULL) {
771     fake_watcher_list = loop->watchers[loop->nwatchers];
772     fake_watcher_count = loop->watchers[loop->nwatchers + 1];
773   } else {
774     fake_watcher_list = NULL;
775     fake_watcher_count = NULL;
776   }
777
778   nwatchers = next_power_of_two(len + 2) - 2;
779   watchers = uv__realloc(loop->watchers,
780                          (nwatchers + 2) * sizeof(loop->watchers[0]));
781
782   if (watchers == NULL)
783     abort();
784   for (i = loop->nwatchers; i < nwatchers; i++)
785     watchers[i] = NULL;
786   watchers[nwatchers] = fake_watcher_list;
787   watchers[nwatchers + 1] = fake_watcher_count;
788
789   loop->watchers = watchers;
790   loop->nwatchers = nwatchers;
791 }
792
793
794 void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
795   assert(cb != NULL);
796   assert(fd >= -1);
797   QUEUE_INIT(&w->pending_queue);
798   QUEUE_INIT(&w->watcher_queue);
799   w->cb = cb;
800   w->fd = fd;
801   w->events = 0;
802   w->pevents = 0;
803
804 #if defined(UV_HAVE_KQUEUE)
805   w->rcount = 0;
806   w->wcount = 0;
807 #endif /* defined(UV_HAVE_KQUEUE) */
808 }
809
810
811 void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
812   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
813   assert(0 != events);
814   assert(w->fd >= 0);
815   assert(w->fd < INT_MAX);
816
817   w->pevents |= events;
818   maybe_resize(loop, w->fd + 1);
819
820 #if !defined(__sun)
821   /* The event ports backend needs to rearm all file descriptors on each and
822    * every tick of the event loop but the other backends allow us to
823    * short-circuit here if the event mask is unchanged.
824    */
825   if (w->events == w->pevents) {
826     if (w->events == 0 && !QUEUE_EMPTY(&w->watcher_queue)) {
827       QUEUE_REMOVE(&w->watcher_queue);
828       QUEUE_INIT(&w->watcher_queue);
829     }
830     return;
831   }
832 #endif
833
834   if (QUEUE_EMPTY(&w->watcher_queue))
835     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
836
837   if (loop->watchers[w->fd] == NULL) {
838     loop->watchers[w->fd] = w;
839     loop->nfds++;
840   }
841 }
842
843
844 void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
845   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
846   assert(0 != events);
847
848   if (w->fd == -1)
849     return;
850
851   assert(w->fd >= 0);
852
853   /* Happens when uv__io_stop() is called on a handle that was never started. */
854   if ((unsigned) w->fd >= loop->nwatchers)
855     return;
856
857   w->pevents &= ~events;
858
859   if (w->pevents == 0) {
860     QUEUE_REMOVE(&w->watcher_queue);
861     QUEUE_INIT(&w->watcher_queue);
862
863     if (loop->watchers[w->fd] != NULL) {
864       assert(loop->watchers[w->fd] == w);
865       assert(loop->nfds > 0);
866       loop->watchers[w->fd] = NULL;
867       loop->nfds--;
868       w->events = 0;
869     }
870   }
871   else if (QUEUE_EMPTY(&w->watcher_queue))
872     QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
873 }
874
875
876 void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
877   uv__io_stop(loop, w, UV__POLLIN | UV__POLLOUT);
878   QUEUE_REMOVE(&w->pending_queue);
879
880   /* Remove stale events for this file descriptor */
881   uv__platform_invalidate_fd(loop, w->fd);
882 }
883
884
885 void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
886   if (QUEUE_EMPTY(&w->pending_queue))
887     QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
888 }
889
890
891 int uv__io_active(const uv__io_t* w, unsigned int events) {
892   assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
893   assert(0 != events);
894   return 0 != (w->pevents & events);
895 }
896
897
898 int uv_getrusage(uv_rusage_t* rusage) {
899   struct rusage usage;
900
901   if (getrusage(RUSAGE_SELF, &usage))
902     return -errno;
903
904   rusage->ru_utime.tv_sec = usage.ru_utime.tv_sec;
905   rusage->ru_utime.tv_usec = usage.ru_utime.tv_usec;
906
907   rusage->ru_stime.tv_sec = usage.ru_stime.tv_sec;
908   rusage->ru_stime.tv_usec = usage.ru_stime.tv_usec;
909
910   rusage->ru_maxrss = usage.ru_maxrss;
911   rusage->ru_ixrss = usage.ru_ixrss;
912   rusage->ru_idrss = usage.ru_idrss;
913   rusage->ru_isrss = usage.ru_isrss;
914   rusage->ru_minflt = usage.ru_minflt;
915   rusage->ru_majflt = usage.ru_majflt;
916   rusage->ru_nswap = usage.ru_nswap;
917   rusage->ru_inblock = usage.ru_inblock;
918   rusage->ru_oublock = usage.ru_oublock;
919   rusage->ru_msgsnd = usage.ru_msgsnd;
920   rusage->ru_msgrcv = usage.ru_msgrcv;
921   rusage->ru_nsignals = usage.ru_nsignals;
922   rusage->ru_nvcsw = usage.ru_nvcsw;
923   rusage->ru_nivcsw = usage.ru_nivcsw;
924
925   return 0;
926 }
927
928
929 int uv__open_cloexec(const char* path, int flags) {
930   int err;
931   int fd;
932
933 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 9) || \
934     defined(__DragonFly__)
935   static int no_cloexec;
936
937   if (!no_cloexec) {
938     fd = open(path, flags | UV__O_CLOEXEC);
939     if (fd != -1)
940       return fd;
941
942     if (errno != EINVAL)
943       return -errno;
944
945     /* O_CLOEXEC not supported. */
946     no_cloexec = 1;
947   }
948 #endif
949
950   fd = open(path, flags);
951   if (fd == -1)
952     return -errno;
953
954   err = uv__cloexec(fd, 1);
955   if (err) {
956     uv__close(fd);
957     return err;
958   }
959
960   return fd;
961 }
962
963
964 int uv__dup2_cloexec(int oldfd, int newfd) {
965   int r;
966 #if defined(__FreeBSD__) && __FreeBSD__ >= 10
967   r = dup3(oldfd, newfd, O_CLOEXEC);
968   if (r == -1)
969     return -errno;
970   return r;
971 #elif defined(__FreeBSD__) && defined(F_DUP2FD_CLOEXEC)
972   r = fcntl(oldfd, F_DUP2FD_CLOEXEC, newfd);
973   if (r != -1)
974     return r;
975   if (errno != EINVAL)
976     return -errno;
977   /* Fall through. */
978 #elif defined(__linux__)
979   static int no_dup3;
980   if (!no_dup3) {
981     do
982       r = uv__dup3(oldfd, newfd, UV__O_CLOEXEC);
983     while (r == -1 && errno == EBUSY);
984     if (r != -1)
985       return r;
986     if (errno != ENOSYS)
987       return -errno;
988     /* Fall through. */
989     no_dup3 = 1;
990   }
991 #endif
992   {
993     int err;
994     do
995       r = dup2(oldfd, newfd);
996 #if defined(__linux__)
997     while (r == -1 && errno == EBUSY);
998 #else
999     while (0);  /* Never retry. */
1000 #endif
1001
1002     if (r == -1)
1003       return -errno;
1004
1005     err = uv__cloexec(newfd, 1);
1006     if (err) {
1007       uv__close(newfd);
1008       return err;
1009     }
1010
1011     return r;
1012   }
1013 }
1014
1015
1016 int uv_os_homedir(char* buffer, size_t* size) {
1017   struct passwd pw;
1018   struct passwd* result;
1019   char* buf;
1020   uid_t uid;
1021   size_t bufsize;
1022   size_t len;
1023   long initsize;
1024   int r;
1025 #if defined(__ANDROID_API__) && __ANDROID_API__ < 21
1026   int (*getpwuid_r)(uid_t, struct passwd*, char*, size_t, struct passwd**);
1027 #endif
1028
1029   if (buffer == NULL || size == NULL || *size == 0)
1030     return -EINVAL;
1031
1032   /* Check if the HOME environment variable is set first */
1033   buf = getenv("HOME");
1034
1035   if (buf != NULL) {
1036     len = strlen(buf);
1037
1038     if (len >= *size) {
1039       *size = len;
1040       return -ENOBUFS;
1041     }
1042
1043     memcpy(buffer, buf, len + 1);
1044     *size = len;
1045
1046     return 0;
1047   }
1048
1049 #if defined(__ANDROID_API__) && __ANDROID_API__ < 21
1050   getpwuid_r = dlsym(RTLD_DEFAULT, "getpwuid_r");
1051   if (getpwuid_r == NULL)
1052     return -ENOSYS;
1053 #endif
1054
1055   /* HOME is not set, so call getpwuid() */
1056   initsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1057
1058   if (initsize <= 0)
1059     bufsize = 4096;
1060   else
1061     bufsize = (size_t) initsize;
1062
1063   uid = getuid();
1064   buf = NULL;
1065
1066   for (;;) {
1067     uv__free(buf);
1068     buf = uv__malloc(bufsize);
1069
1070     if (buf == NULL)
1071       return -ENOMEM;
1072
1073     r = getpwuid_r(uid, &pw, buf, bufsize, &result);
1074
1075     if (r != ERANGE)
1076       break;
1077
1078     bufsize *= 2;
1079   }
1080
1081   if (r != 0) {
1082     uv__free(buf);
1083     return -r;
1084   }
1085
1086   if (result == NULL) {
1087     uv__free(buf);
1088     return -ENOENT;
1089   }
1090
1091   len = strlen(pw.pw_dir);
1092
1093   if (len >= *size) {
1094     *size = len;
1095     uv__free(buf);
1096     return -ENOBUFS;
1097   }
1098
1099   memcpy(buffer, pw.pw_dir, len + 1);
1100   *size = len;
1101   uv__free(buf);
1102
1103   return 0;
1104 }