@@ -19,14 +19,112 @@ const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
1919const MAX_ACCEPTS_PER_PASS : usize = 64 ;
2020
2121pub fn run ( directory : & Path ) -> Result < ( ) > {
22+ // First, before bind starts the sweeper thread: every thread created after
23+ // this inherits the mask, so only the signal thread ever receives them.
24+ #[ cfg( unix) ]
25+ let signals = signals:: block ( ) ?;
2226 // Before bind, so a failure here leaves nothing to clean up.
2327 let wake = Wake :: new ( ) ?;
2428 let ( runtime, listener) = platform:: Runtime :: bind ( directory) ?;
2529 // Created after bind so bind I/O does not consume the acquire window.
2630 let control = Arc :: new ( Control :: new ( wake, Ownership :: new ( Instant :: now ( ) ) ) ) ;
31+ #[ cfg( unix) ]
32+ if let Err ( error) = signals:: stop_on ( signals, & control) {
33+ let _ = runtime. finish ( ) ;
34+ return Err ( error) ;
35+ }
2736 serve ( runtime, listener, control, Settings :: default ( ) )
2837}
2938
39+ /// Turns SIGTERM and SIGINT into an orderly stop, so children are killed and
40+ /// the runtime directory is removed instead of the daemon dying with both left
41+ /// behind.
42+ ///
43+ /// Children inherit the signal mask across `exec`. portable-pty resets it for
44+ /// PTY children; anything else the daemon spawns must reset it itself.
45+ #[ cfg( unix) ]
46+ mod signals {
47+ use std:: io;
48+ use std:: sync:: Arc ;
49+ use std:: thread;
50+ use std:: time:: { Duration , Instant } ;
51+
52+ use anyhow:: { Context , Result } ;
53+
54+ use super :: Control ;
55+
56+ const STOP : [ libc:: c_int ; 2 ] = [ libc:: SIGTERM , libc:: SIGINT ] ;
57+ /// A second signal this soon after the first is part of the same stop
58+ /// (Ctrl-C plus a wrapper's SIGTERM), not a sign that the stop is stuck.
59+ const REPEAT_GRACE : Duration = Duration :: from_secs ( 1 ) ;
60+
61+ pub ( super ) struct Blocked ( libc:: sigset_t ) ;
62+
63+ /// Blocks the stop signals on the calling thread, and restores their
64+ /// default action: macOS never delivers an ignored signal to `sigwait`,
65+ /// and a launcher may have left SIGINT ignored.
66+ pub ( super ) fn block ( ) -> Result < Blocked > {
67+ // SAFETY: plain libc calls on a local, initialized signal set.
68+ unsafe {
69+ let mut set: libc:: sigset_t = std:: mem:: zeroed ( ) ;
70+ libc:: sigemptyset ( & mut set) ;
71+ for signal in STOP {
72+ libc:: sigaddset ( & mut set, signal) ;
73+ }
74+ let result = libc:: pthread_sigmask ( libc:: SIG_BLOCK , & set, std:: ptr:: null_mut ( ) ) ;
75+ if result != 0 {
76+ return Err ( io:: Error :: from_raw_os_error ( result) )
77+ . context ( "failed to block stop signals" ) ;
78+ }
79+ // Only after blocking, so there is no window where the default
80+ // action could kill the daemon.
81+ for signal in STOP {
82+ libc:: signal ( signal, libc:: SIG_DFL ) ;
83+ }
84+ Ok ( Blocked ( set) )
85+ }
86+ }
87+
88+ pub ( super ) fn stop_on ( signals : Blocked , control : & Arc < Control > ) -> Result < ( ) > {
89+ let control = Arc :: clone ( control) ;
90+ thread:: Builder :: new ( )
91+ . name ( "opencode-pty-signals" . into ( ) )
92+ . spawn ( move || {
93+ wait ( & signals) ;
94+ let stopped = Instant :: now ( ) ;
95+ control. request_stop ( ) ;
96+ loop {
97+ let signal = wait ( & signals) ;
98+ if stopped. elapsed ( ) >= REPEAT_GRACE {
99+ // The orderly stop is stuck. Exit without running exit
100+ // handlers, which other threads may be blocking.
101+ // SAFETY: `_exit` is always safe to call.
102+ unsafe { libc:: _exit ( 128 + signal) } ;
103+ }
104+ }
105+ } )
106+ . context ( "failed to start the signal thread" ) ?;
107+ Ok ( ( ) )
108+ }
109+
110+ fn wait ( signals : & Blocked ) -> libc:: c_int {
111+ loop {
112+ let mut signal = 0 ;
113+ // SAFETY: valid set and out pointer; `sigwait` returns an error
114+ // number instead of setting errno, and fills `signal` on success.
115+ let result = unsafe { libc:: sigwait ( & signals. 0 , & mut signal) } ;
116+ if result == 0 {
117+ return signal;
118+ }
119+ // EINTR (after SIGSTOP and SIGCONT) just retries. Nothing else is
120+ // expected for valid signals; pause so it can't spin.
121+ if result != libc:: EINTR {
122+ thread:: sleep ( Duration :: from_millis ( 100 ) ) ;
123+ }
124+ }
125+ }
126+ }
127+
30128struct Settings {
31129 /// Longest the loop sleeps without a wake or deadline.
32130 safety_net : Duration ,
0 commit comments