Skip to content

Commit

Permalink
Io.copy_channels: make it reentrant (ocaml#11194)
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolás Ojeda Bär <[email protected]>
  • Loading branch information
nojb authored Dec 12, 2024
1 parent 046fe80 commit ef02bd7
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
3 changes: 3 additions & 0 deletions doc/changes/11194.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- Fix bug that could result in corrupted file copies by Dune, for example when
using the `copy_files#` stanza or the `copy#` action. (@nojb, #11194, fixes
#11193)
18 changes: 14 additions & 4 deletions otherlibs/stdune/src/io.ml
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,25 @@ let input_zero_separated =

let copy_channels =
let buf_len = 65536 in
let buf = Bytes.create buf_len in
let rec loop ic oc =
let global_buf = Bytes.create buf_len in
let rec loop buf ic oc =
match input ic buf 0 buf_len with
| 0 -> ()
| n ->
output oc buf 0 n;
loop ic oc
loop buf ic oc
in
loop
let busy = ref false in
fun ic oc ->
if !busy
then loop (Bytes.create buf_len) ic oc
else (
busy := true;
match loop global_buf ic oc with
| () -> busy := false
| exception exn ->
busy := false;
Exn.reraise exn)
;;

let setup_copy ?(chmod = Fun.id) ~src ~dst () =
Expand Down
3 changes: 0 additions & 3 deletions otherlibs/stdune/src/io.mli
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ val close_in : in_channel -> unit
val close_out : out_channel -> unit
val close_both : in_channel * out_channel -> unit
val input_lines : in_channel -> string list

(** This function is not safe to use from multiple threads, even if operating on
unrelated channels because it uses a statically-allocated global buffer. *)
val copy_channels : in_channel -> out_channel -> unit

(** Try to read everything from a channel. Returns [Error ()] if the contents
Expand Down

0 comments on commit ef02bd7

Please sign in to comment.