1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2017 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Macro and helper trait for handling interrupted routines.

use std::io;

use libc::EINTR;

/// Trait for determining if a result indicates the operation was interrupted.
pub trait InterruptibleResult {
    /// Returns `true` if this result indicates the operation was interrupted and should be retried,
    /// and `false` in all other cases.
    fn is_interrupted(&self) -> bool;
}

impl<T> InterruptibleResult for crate::Result<T> {
    fn is_interrupted(&self) -> bool {
        matches!(self, Err(e) if e.errno() == EINTR)
    }
}

impl<T> InterruptibleResult for io::Result<T> {
    fn is_interrupted(&self) -> bool {
        matches!(self, Err(e) if e.kind() == io::ErrorKind::Interrupted)
    }
}

/// Macro that retries the given expression every time its result indicates it was interrupted (i.e.
/// returned `EINTR`). This is useful for operations that are prone to being interrupted by
/// signals, such as blocking syscalls.
///
/// The given expression `$x` can return
///
/// * `crate::linux::Result` in which case the expression is retried if the `Error::errno()` is
///   `EINTR`.
/// * `std::io::Result` in which case the expression is retried if the `ErrorKind` is
///   `ErrorKind::Interrupted`.
///
/// Note that if expression returns i32 (i.e. either -1 or error code), then handle_eintr_errno()
/// or handle_eintr_rc() should be used instead.
///
/// In all cases where the result does not indicate that the expression was interrupted, the result
/// is returned verbatim to the caller of this macro.
///
/// See the section titled _Interruption of system calls and library functions by signal handlers_
/// on the man page for `signal(7)` to see more information about interruptible syscalls.
///
/// To summarize, routines that use one of these syscalls _might_ need to handle `EINTR`:
///
/// * `accept(2)`
/// * `clock_nanosleep(2)`
/// * `connect(2)`
/// * `epoll_pwait(2)`
/// * `epoll_wait(2)`
/// * `fcntl(2)`
/// * `fifo(7)`
/// * `flock(2)`
/// * `futex(2)`
/// * `getrandom(2)`
/// * `inotify(7)`
/// * `io_getevents(2)`
/// * `ioctl(2)`
/// * `mq_receive(3)`
/// * `mq_send(3)`
/// * `mq_timedreceive(3)`
/// * `mq_timedsend(3)`
/// * `msgrcv(2)`
/// * `msgsnd(2)`
/// * `nanosleep(2)`
/// * `open(2)`
/// * `pause(2)`
/// * `poll(2)`
/// * `ppoll(2)`
/// * `pselect(2)`
/// * `pthread_cond_wait(3)`
/// * `pthread_mutex_lock(3)`
/// * `read(2)`
/// * `readv(2)`
/// * `recv(2)`
/// * `recvfrom(2)`
/// * `recvmmsg(2)`
/// * `recvmsg(2)`
/// * `select(2)`
/// * `sem_timedwait(3)`
/// * `sem_wait(3)`
/// * `semop(2)`
/// * `semtimedop(2)`
/// * `send(2)`
/// * `sendmsg(2)`
/// * `sendto(2)`
/// * `setsockopt(2)`
/// * `sigsuspend(2)`
/// * `sigtimedwait(2)`
/// * `sigwaitinfo(2)`
/// * `sleep(3)`
/// * `usleep(3)`
/// * `wait(2)`
/// * `wait3(2)`
/// * `wait4(2)`
/// * `waitid(2)`
/// * `waitpid(2)`
/// * `write(2)`
/// * `writev(2)`
///
/// # Examples
///
/// ```
/// # use base::handle_eintr;
/// # use std::io::stdin;
/// # fn main() {
/// let mut line = String::new();
/// let res = handle_eintr!(stdin().read_line(&mut line));
/// # }
/// ```
#[macro_export]
macro_rules! handle_eintr {
    ($x:expr) => {{
        use $crate::unix::handle_eintr::InterruptibleResult;
        let res;
        loop {
            match $x {
                ref v if v.is_interrupted() => continue,
                v => {
                    res = v;
                    break;
                }
            }
        }
        res
    }};
}

/// Macro that retries the given expression every time its result indicates it was interrupted.
/// It is intended to use with system functions that return `EINTR` and other error codes
/// directly as their result.
/// Most of reentrant functions use this way of signalling errors.
#[macro_export]
macro_rules! handle_eintr_rc {
    ($x:expr) => {{
        use libc::EINTR;
        let mut res;
        loop {
            res = $x;
            if res != EINTR {
                break;
            }
        }
        res
    }};
}

/// Macro that retries the given expression every time its result indicates it was interrupted.
/// It is intended to use with system functions that signal error by returning `-1` and setting
/// `errno` to appropriate error code (`EINTR`, `EINVAL`, etc.)
/// Most of standard non-reentrant libc functions use this way of signalling errors.
#[macro_export]
macro_rules! handle_eintr_errno {
    ($x:expr) => {{
        use libc::EINTR;
        use $crate::Error;
        let mut res;
        loop {
            res = $x;
            if res != -1 || Error::last() != Error::new(EINTR) {
                break;
            }
        }
        res
    }};
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Error as SysError;

    // Sets errno to the given error code.
    fn set_errno(e: i32) {
        #[cfg(target_os = "android")]
        unsafe fn errno_location() -> *mut libc::c_int {
            libc::__errno()
        }
        #[cfg(target_os = "linux")]
        unsafe fn errno_location() -> *mut libc::c_int {
            libc::__errno_location()
        }
        #[cfg(target_os = "macos")]
        unsafe fn errno_location() -> *mut libc::c_int {
            libc::__error()
        }

        // SAFETY: trivially safe
        unsafe {
            *errno_location() = e;
        }
    }

    #[test]
    fn i32_eintr_rc() {
        let mut count = 3;
        let mut dummy = || {
            count -= 1;
            if count > 0 {
                EINTR
            } else {
                0
            }
        };
        let res = handle_eintr_rc!(dummy());
        assert_eq!(res, 0);
        assert_eq!(count, 0);
    }

    #[test]
    fn i32_eintr_errno() {
        let mut count = 3;
        let mut dummy = || {
            count -= 1;
            if count > 0 {
                set_errno(EINTR);
                -1
            } else {
                56
            }
        };
        let res = handle_eintr_errno!(dummy());
        assert_eq!(res, 56);
        assert_eq!(count, 0);
    }

    #[test]
    fn sys_eintr() {
        let mut count = 7;
        let mut dummy = || {
            count -= 1;
            if count > 1 {
                Err(SysError::new(EINTR))
            } else {
                Ok(101)
            }
        };
        let res = handle_eintr!(dummy());
        assert_eq!(res, Ok(101));
        assert_eq!(count, 1);
    }

    #[test]
    fn io_eintr() {
        let mut count = 108;
        let mut dummy = || {
            count -= 1;
            if count > 99 {
                Err(io::Error::new(
                    io::ErrorKind::Interrupted,
                    "interrupted again :(",
                ))
            } else {
                Ok(32)
            }
        };
        let res = handle_eintr!(dummy());
        assert_eq!(res.unwrap(), 32);
        assert_eq!(count, 99);
    }
}