Debian Codegraph @

lib/spawn.ml

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 let proto_version = 0
12 let prefer_sock = Sys.os_type = "Win32"
13 let accept_timeout = 10.0
14
15 let pr_err s = Printf.eprintf "(Spawn ,%d) %s\n%!" (Unix.getpid ()) s
16 let prerr_endline s = if CDebug.(get_flag misc) then begin pr_err s end else ()
17
18 type req = ReqDie | Hello of int * int
19
20 module type Control = sig
21 type handle
22
23 val kill : handle -> unit
24 val wait : handle -> Unix.process_status
25 val unixpid : handle -> int
26 val uid : handle -> string
27 val is_alive : handle -> bool
28
29 end
30
31 module type MainLoopModel = sig
32 type async_chan
33 type condition
34 type watch_id
35
36 val add_watch : callback:(condition list -> bool) -> async_chan -> watch_id
37 val remove_watch : watch_id -> unit
38 val read_all : async_chan -> string
39 val async_chan_of_file_or_socket : Unix.file_descr -> async_chan
40 end
41
42 (* Common code *)
43
44 (* According to http://caml.inria.fr/mantis/view.php?id=5325
45 * you can't use the same socket for both writing and reading (may change
46 * in 4.03 *)
47 let mk_socket_channel () =
48 let open Unix in
49 let sr = socket PF_INET SOCK_STREAM 0 in
50 bind sr (ADDR_INET (inet_addr_loopback,0)); listen sr 1;
51 let sw = socket PF_INET SOCK_STREAM 0 in
52 bind sw (ADDR_INET (inet_addr_loopback,0)); listen sw 1;
53 match getsockname sr, getsockname sw with
54 | ADDR_INET(host, portr), ADDR_INET(_, portw) ->
55 (sr, sw),
56 string_of_inet_addr host
57 ^":"^ string_of_int portr ^":"^ string_of_int portw
58 | _ -> assert false
59
60 let accept (sr,sw) =
61 let r, _, _ = Unix.select [sr] [] [] accept_timeout in
62 if r = [] then raise (Failure (Printf.sprintf
63 "The spawned process did not connect back in %2.1fs" accept_timeout));
64 let csr, _ = Unix.accept sr in
65 Unix.close sr;
66 let cin = Unix.in_channel_of_descr csr in
67 set_binary_mode_in cin true;
68 let w, _, _ = Unix.select [sw] [] [] accept_timeout in
69 if w = [] then raise (Failure (Printf.sprintf
70 "The spawned process did not connect back in %2.1fs" accept_timeout));
71 let csw, _ = Unix.accept sw in
72 Unix.close sw;
73 let cout = Unix.out_channel_of_descr csw in
74 set_binary_mode_out cout true;
75 (csr, csw), cin, cout
76
77 let spawn_sock env prog args =
78 let main_sock, main_sock_name = mk_socket_channel () in
79 let extra = [| "-main-channel"; main_sock_name |] in
80 let args = Array.append [| prog |] (Array.append args extra) in
81 prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args));
82 let pid =
83 Unix.create_process_env prog args env Unix.stdin Unix.stdout Unix.stderr in
84 prerr_endline ("PID " ^ string_of_int pid);
85 if pid = 0 then begin
86 Unix.sleep 1; (* to avoid respawning like crazy *)
87 raise (Failure "create_process failed")
88 end;
89 let cs, cin, cout = accept main_sock in
90 pid, cin, cout, cs
91
92 let spawn_pipe env prog args =
93 let master2worker_r,master2worker_w = Unix.pipe () in
94 let worker2master_r,worker2master_w = Unix.pipe () in
95 let extra = [| "-main-channel"; "stdfds" |] in
96 let args = Array.append [|prog|] (Array.append args extra) in
97 Unix.set_close_on_exec master2worker_w;
98 Unix.set_close_on_exec worker2master_r;
99 prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args));
100 let pid =
101 Unix.create_process_env
102 prog args env master2worker_r worker2master_w Unix.stderr in
103 if pid = 0 then begin
104 Unix.sleep 1; (* to avoid respawning like crazy *)
105 raise (Failure "create_process failed")
106 end;
107 prerr_endline ("PID " ^ string_of_int pid);
108 Unix.close master2worker_r;
109 Unix.close worker2master_w;
110 let cin = Unix.in_channel_of_descr worker2master_r in
111 let cout = Unix.out_channel_of_descr master2worker_w in
112 set_binary_mode_in cin true;
113 set_binary_mode_out cout true;
114 pid, cin, cout, (worker2master_r, master2worker_w)
115
116 let filter_args args =
117 let rec aux = function
118 | "-control-channel" :: _ :: rest -> aux rest
119 | "-main-channel" :: _ :: rest -> aux rest
120 | x :: rest -> x :: aux rest
121 | [] -> [] in
122 Array.of_list (aux (Array.to_list args))
123
124 let spawn_with_control prefer_sock env prog args =
125 (* on non-Unix systems we create a control channel *)
126 let not_Unix = Sys.os_type <> "Unix" in
127 let args = filter_args args in
128 let args, control_sock =
129 if not_Unix then
130 let control_sock, control_sock_name = mk_socket_channel () in
131 let extra = [| "-control-channel"; control_sock_name |] in
132 Array.append args extra, Some control_sock
133 else
134 args, None in
135 let (pid, cin, cout, s), is_sock =
136 if not_Unix (* pipes only work well on Unix *) || prefer_sock
137 then spawn_sock env prog args, true
138 else spawn_pipe env prog args, false in
139 let oob_resp, oob_req =
140 if not_Unix then
141 let _, oob_resp, oob_req = accept (Option.get control_sock) in
142 Some oob_resp, Some oob_req
143 else
144 None, None in
145 pid, oob_resp, oob_req, cin, cout, s, is_sock
146
147 let output_death_sentence pid oob_req =
148 prerr_endline ("death sentence for " ^ pid);
149 try output_value oob_req ReqDie; flush oob_req
150 with e when CErrors.noncritical e -> prerr_endline ("death sentence: " ^ Printexc.to_string e)
151
152 (* spawn a process and read its output asynchronously *)
153 module Async(ML : MainLoopModel) = struct
154
155 type process = {
156 cin : in_channel;
157 cout : out_channel;
158 oob_resp : in_channel option;
159 oob_req : out_channel option;
160 gchan : ML.async_chan;
161 pid : int;
162 mutable watch : ML.watch_id option;
163 mutable alive : bool;
164 }
165
166 type callback = ML.condition list -> read_all:(unit -> string) -> bool
167 type handle = process
168
169 let is_alive p = p.alive
170 let uid { pid; } = string_of_int pid
171 let unixpid { pid; } = pid
172
173 let kill ({ pid = unixpid; oob_resp; oob_req; cin; cout; alive; watch } as p) =
174 p.alive <- false;
175 if not alive then prerr_endline "This process is already dead"
176 else begin try
177 Option.iter ML.remove_watch watch;
178 Option.iter (output_death_sentence (uid p)) oob_req;
179 close_in_noerr cin;
180 close_out_noerr cout;
181 Option.iter close_in_noerr oob_resp;
182 Option.iter close_out_noerr oob_req;
183 if Sys.os_type = "Unix" then Unix.kill unixpid Sys.sigkill;
184 p.watch <- None
185 with e when CErrors.noncritical e -> prerr_endline ("kill: "^Printexc.to_string e) end
186
187 let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ())
188 prog args callback
189 =
190 let pid, oob_resp, oob_req, cin, cout, main, is_sock =
191 spawn_with_control prefer_sock env prog args in
192 Unix.set_nonblock (fst main);
193 let gchan = ML.async_chan_of_file_or_socket (fst main) in
194 let alive, watch = true, None in
195 let p = { cin; cout; gchan; pid; oob_resp; oob_req; alive; watch } in
196 p.watch <- Some (
197 ML.add_watch ~callback:(fun cl ->
198 try
199 let live = callback cl ~read_all:(fun () -> ML.read_all gchan) in
200 if not live then kill p;
201 live
202 with e when CErrors.noncritical e ->
203 pr_err ("Async reader raised: " ^ (Printexc.to_string e));
204 kill p;
205 false) gchan
206 );
207 p, cout
208
209 let rec wait p =
210 (* On windows kill is not reliable, so wait may never return. *)
211 if Sys.os_type = "Unix" then
212 try snd (Unix.waitpid [] p.pid)
213 with
214 | Unix.Unix_error (Unix.EINTR, _, _) -> wait p
215 | Unix.Unix_error _ -> Unix.WEXITED 0o400
216 else Unix.WEXITED 0o400
217
218 end
219
220 module Sync () = struct
221
222 type process = {
223 cin : in_channel;
224 cout : out_channel;
225 oob_resp : in_channel option;
226 oob_req : out_channel option;
227 pid : int;
228 mutable alive : bool;
229 }
230
231 type handle = process
232
233 let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ()) prog args =
234 let pid, oob_resp, oob_req, cin, cout, _, _ =
235 spawn_with_control prefer_sock env prog args in
236 { cin; cout; pid; oob_resp; oob_req; alive = true }, cin, cout
237
238 let is_alive p = p.alive
239 let uid { pid; } = string_of_int pid
240 let unixpid { pid = pid; } = pid
241
242 let kill ({ pid = unixpid; oob_req; oob_resp; cin; cout; alive } as p) =
243 p.alive <- false;
244 if not alive then prerr_endline "This process is already dead"
245 else begin try
246 Option.iter (output_death_sentence (uid p)) oob_req;
247 close_in_noerr cin;
248 close_out_noerr cout;
249 Option.iter close_in_noerr oob_resp;
250 Option.iter close_out_noerr oob_req;
251 if Sys.os_type = "Unix" then Unix.kill unixpid Sys.sigkill;
252 with e when CErrors.noncritical e -> prerr_endline ("kill: "^Printexc.to_string e) end
253
254 let rec wait p =
255 (* On windows kill is not reliable, so wait may never return. *)
256 if Sys.os_type = "Unix" then
257 try snd (Unix.waitpid [] p.pid)
258 with
259 | Unix.Unix_error (Unix.EINTR, _, _) -> wait p
260 | Unix.Unix_error _ -> Unix.WEXITED 0o400
261 else Unix.WEXITED 0o400
262
263 end