-
Notifications
You must be signed in to change notification settings - Fork 1.2k
caml_leave_blocking section and errno corruption #5982
Description
Original bug ID: 5982
Reporter: @diml
Assigned to: @diml
Status: closed (set by @xavierleroy on 2015-12-11T18:18:54Z)
Resolution: fixed
Priority: normal
Severity: minor
Version: 4.01.0+dev
Target version: 4.02.0+dev
Fixed in version: 4.01.0+dev
Category: runtime system and C interface
Monitored by: @ygrek @hcarty
Bug description
This is a widespread idiom for writing C stubs:
enter_blocking_section();
retcode = select(maxfd + 1, &read, &write, &except, tvp);
leave_blocking_section();
if (retcode == -1) uerror("select", Nothing);
Here [uerror] uses the global variable [errno]. The problem is that [leave_blocking_section] can run arbitrary code and so modify [errno]. It can run signal handlers for instance. Attached is an example of program where the call to select is expected to fail with EINTR but instead fails with EROFS.
Obviously bindings should be written this way:
enter_blocking_section();
retcode = select(maxfd + 1, &read, &write, &except, tvp);
saved_errno = errno;
leave_blocking_section();
if (retcode == -1) unix_error(saved_errno, "select", Nothing);
But since this is very common I propose that [leave_blocking_section] saves and restores [errno].
Additional information
let () =
(* Force initialization of the thread library. This modify
[caml_try_leave_blocking_section_hook] so that all
signals are executed by [caml_leave_blocking_section]
and never asynchronously. *)
ignore (Thread.self ());
Sys.set_signal Sys.sigalrm
(Sys.Signal_handle (fun _ ->
try
(* This will modify [errno]. *)
ignore (Unix.openfile "/etc/passwd" [Unix.O_WRONLY] 0)
with _ ->
()));
ignore (Unix.alarm 1);
try
ignore (Unix.select [] [] [] (-1.0))
with exn ->
prerr_endline (Printexc.to_string exn);
exit 2