From 75f0ba1c3ab89fac82cc7e43bd25ec0b9441b1e1 Mon Sep 17 00:00:00 2001 From: pqwy Date: Mon, 21 Jul 2014 03:12:54 +0100 Subject: [PATCH] assure `of_bigarray` can't create invalid cstructs breaks compatibility: * len and off can't point out outside of bigarray * if given, len is not clipped to size of the given bigarray --- lib/cstruct.ml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/cstruct.ml b/lib/cstruct.ml index b9a3b47f..d57b48f1 100644 --- a/lib/cstruct.ml +++ b/lib/cstruct.ml @@ -29,18 +29,21 @@ type t = { } with sexp let of_bigarray ?(off=0) ?len buffer = + let dim = Bigarray.Array1.dim buffer in let len = match len with - |None -> Bigarray.Array1.dim buffer - |Some len -> min len (Bigarray.Array1.dim buffer) - in { buffer; off; len } + | None -> dim - off + | Some len -> len in + if off < 0 || len < 0 || off + len > dim then + raise (Invalid_argument "Cstruct.of_bigarray"); + { buffer; off; len } let to_bigarray buffer = Bigarray.Array1.sub buffer.buffer buffer.off buffer.len let create len = - let ba = Bigarray.Array1.create Bigarray.char Bigarray.c_layout len in - of_bigarray ba + let buffer = Bigarray.(Array1.create char c_layout len) in + { buffer ; len ; off = 0 } let check_bounds t len = Bigarray.Array1.dim t.buffer >= len