1 /*
2  * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <pthread.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #include <sys/uio.h>
35 #include <unistd.h>
36 #include <errno.h>
37 
38 // Android-changed: Fuchsia: Fix poll.h include location
39 // #include <sys/poll.h>
40 #if !defined(__Fuchsia__)
41 #include <sys/poll.h>
42 #else
43 #include <poll.h>
44 #endif
45 
46 #include <AsynchronousCloseMonitor.h>
47 
48 extern "C" {
49 
50 /*
51  * Signal to unblock thread
52  */
53 // Android-changed: Bionic (and AsynchronousCloseMonitor) expects libcore to use
54 // __SIGRTMIN + 2, not __SIGRTMAX - 2
55 static int sigWakeup = (__SIGRTMIN + 2);
56 
57 /*
58  * Close or dup2 a file descriptor ensuring that all threads blocked on
59  * the file descriptor are notified via a wakeup signal.
60  *
61  *      fd1 < 0    => close(fd2)
62  *      fd1 >= 0   => dup2(fd1, fd2)
63  *
64  * Returns -1 with errno set if operation fails.
65  */
closefd(int fd1,int fd2)66 static int closefd(int fd1, int fd2) {
67     int rv, orig_errno;
68 
69     AsynchronousCloseMonitor::signalBlockedThreads(fd2);
70 
71     /*
72      * And close/dup the file descriptor
73      * (restart if interrupted by signal)
74      */
75     do {
76       if (fd1 < 0) {
77         rv = close(fd2);
78       } else {
79         rv = dup2(fd1, fd2);
80       }
81     } while (rv == -1 && errno == EINTR);
82     return rv;
83 }
84 
85 /*
86  * Wrapper for dup2 - same semantics as dup2 system call except
87  * that any threads blocked in an I/O system call on fd2 will be
88  * preempted and return -1/EBADF;
89  */
NET_Dup2(int fd,int fd2)90 int NET_Dup2(int fd, int fd2) {
91     if (fd < 0) {
92         errno = EBADF;
93         return -1;
94     }
95     return closefd(fd, fd2);
96 }
97 
98 /*
99  * Wrapper for close - same semantics as close system call
100  * except that any threads blocked in an I/O on fd will be
101  * preempted and the I/O system call will return -1/EBADF.
102  */
NET_SocketClose(int fd)103 int NET_SocketClose(int fd) {
104     return closefd(-1, fd);
105 }
106 
107 /************** Basic I/O operations here ***************/
108 
109 /*
110  * Macro to perform a blocking IO operation. Restarts
111  * automatically if interrupted by signal (other than
112  * our wakeup signal)
113  */
114 #define BLOCKING_IO_RETURN_INT(FD, FUNC) {      \
115     int ret;                                    \
116     int _syscallErrno; \
117     do {                                        \
118         bool _wasSignaled; \
119         {                                       \
120             AsynchronousCloseMonitor _monitor(FD); \
121             ret = FUNC;                            \
122             _syscallErrno = errno; \
123             _wasSignaled = _monitor.wasSignaled(); \
124         } \
125         errno = _wasSignaled ? EBADF : _syscallErrno; \
126     } while (ret == -1 && errno == EINTR);      \
127     return ret;                                 \
128 }
129 
130 
NET_Read(int s,void * buf,size_t len)131 int NET_Read(int s, void* buf, size_t len) {
132     BLOCKING_IO_RETURN_INT( s, recv(s, buf, len, 0) );
133 }
134 
NET_ReadV(int s,const struct iovec * vector,int count)135 int NET_ReadV(int s, const struct iovec * vector, int count) {
136     BLOCKING_IO_RETURN_INT( s, readv(s, vector, count) );
137 }
138 
NET_RecvFrom(int s,void * buf,int len,unsigned int flags,struct sockaddr * from,int * fromlen)139 int NET_RecvFrom(int s, void *buf, int len, unsigned int flags,
140        struct sockaddr *from, int *fromlen) {
141     socklen_t socklen = *fromlen;
142     BLOCKING_IO_RETURN_INT( s, recvfrom(s, buf, len, flags, from, &socklen) );
143     *fromlen = socklen;
144 }
145 
NET_Send(int s,void * msg,int len,unsigned int flags)146 int NET_Send(int s, void *msg, int len, unsigned int flags) {
147     BLOCKING_IO_RETURN_INT( s, send(s, msg, len, flags) );
148 }
149 
NET_WriteV(int s,const struct iovec * vector,int count)150 int NET_WriteV(int s, const struct iovec * vector, int count) {
151     BLOCKING_IO_RETURN_INT( s, writev(s, vector, count) );
152 }
153 
NET_SendTo(int s,const void * msg,int len,unsigned int flags,const struct sockaddr * to,int tolen)154 int NET_SendTo(int s, const void *msg, int len,  unsigned  int
155        flags, const struct sockaddr *to, int tolen) {
156     BLOCKING_IO_RETURN_INT( s, sendto(s, msg, len, flags, to, tolen) );
157 }
158 
NET_Accept(int s,struct sockaddr * addr,int * addrlen)159 int NET_Accept(int s, struct sockaddr *addr, int *addrlen) {
160     socklen_t socklen = *addrlen;
161     BLOCKING_IO_RETURN_INT( s, accept(s, addr, &socklen) );
162     *addrlen = socklen;
163 }
164 
NET_Connect(int s,struct sockaddr * addr,int addrlen)165 int NET_Connect(int s, struct sockaddr *addr, int addrlen) {
166     BLOCKING_IO_RETURN_INT( s, connect(s, addr, addrlen) );
167 }
168 
169 #ifndef USE_SELECT
NET_Poll(struct pollfd * ufds,unsigned int nfds,int timeout)170 int NET_Poll(struct pollfd *ufds, unsigned int nfds, int timeout) {
171     BLOCKING_IO_RETURN_INT( ufds[0].fd, poll(ufds, nfds, timeout) );
172 }
173 #else
NET_Select(int s,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout)174 int NET_Select(int s, fd_set *readfds, fd_set *writefds,
175                fd_set *exceptfds, struct timeval *timeout) {
176     BLOCKING_IO_RETURN_INT( s-1,
177                             select(s, readfds, writefds, exceptfds, timeout) );
178 }
179 #endif
180 
181 /*
182  * Wrapper for poll(s, timeout).
183  * Auto restarts with adjusted timeout if interrupted by
184  * signal other than our wakeup signal.
185  *
186  * If s < 0, exits early rather than delegating to poll().
187  * TODO: Investigate whether it'd be better to handle this
188  * case at the caller so that this function is never called
189  * for s < 0.
190  */
NET_Timeout(int s,long timeout)191 int NET_Timeout(int s, long timeout) {
192     long prevtime = 0, newtime;
193     struct timeval t;
194 
195     /*
196      * b/27763633
197      * Avoid blocking calls to poll() for invalid sockets, e.g. when
198      * called from PlainSocketImpl_socketAccept with fd == -1.
199      */
200     if (s < 0) {
201         errno = EBADF;
202         return -1;
203     }
204 
205     /*
206      * Pick up current time as may need to adjust timeout
207      */
208     if (timeout > 0) {
209         gettimeofday(&t, NULL);
210         prevtime = t.tv_sec * 1000  +  t.tv_usec / 1000;
211     }
212 
213     for(;;) {
214         struct pollfd pfd;
215         int rv;
216 
217         /*
218          * Poll the fd. If interrupted by our wakeup signal
219          * errno will be set to EBADF.
220          */
221         pfd.fd = s;
222         pfd.events = POLLIN | POLLERR;
223 
224         bool wasSignaled;
225         int syscallErrno;
226         {
227           AsynchronousCloseMonitor monitor(s);
228           rv = poll(&pfd, 1, timeout);
229           syscallErrno = errno;
230           wasSignaled = monitor.wasSignaled();
231         }
232         errno = wasSignaled ? EBADF : syscallErrno;
233 
234         /*
235          * If interrupted then adjust timeout. If timeout
236          * has expired return 0 (indicating timeout expired).
237          */
238         if (rv < 0 && errno == EINTR) {
239             if (timeout > 0) {
240                 gettimeofday(&t, NULL);
241                 newtime = t.tv_sec * 1000  +  t.tv_usec / 1000;
242                 timeout -= newtime - prevtime;
243                 if (timeout <= 0) {
244                     return 0;
245                 }
246                 prevtime = newtime;
247             }
248         } else {
249             return rv;
250         }
251 
252     }
253 }
254 
255 }
256