Commits

xleroy  committed b68a229

PR#5742: missing bound checks in Array.sub (picking r12891 from 4.00 branch)

git-svn-id: http://caml.inria.fr/svn/ocaml/trunk@12892f963ae5c-01c2-4b8c-9fe0-0dff7051ff02

  • Participants
  • Parent commits 8c700ee

Comments (0)

Files changed (3)

 - PR#5700: crash with native-code stack backtraces under MacOS 10.8 x86-64
 - PR#5712: some documentation problems
 - PR#5719: ocamlyacc generates code that is not warning 33-compliant
+- PR#5742: missing bound checks in Array.sub
+
 
 OCaml 4.00.0:
 -------------

File stdlib/array.ml

 external unsafe_set: 'a array -> int -> 'a -> unit = "%array_unsafe_set"
 external make: int -> 'a -> 'a array = "caml_make_vect"
 external create: int -> 'a -> 'a array = "caml_make_vect"
-external sub : 'a array -> int -> int -> 'a array = "caml_array_sub"
+external unsafe_sub : 'a array -> int -> int -> 'a array = "caml_array_sub"
 external append_prim : 'a array -> 'a array -> 'a array = "caml_array_append"
 external concat : 'a array list -> 'a array = "caml_array_concat"
 external unsafe_blit : 'a array -> int -> 'a array -> int -> int -> unit = "caml_array_blit"
 let create_matrix = make_matrix
 
 let copy a =
-  let l = length a in if l = 0 then [||] else sub a 0 l
+  let l = length a in if l = 0 then [||] else unsafe_sub a 0 l
 
 let append a1 a2 =
   let l1 = length a1 in
   if l1 = 0 then copy a2
-  else if length a2 = 0 then sub a1 0 l1
+  else if length a2 = 0 then unsafe_sub a1 0 l1
   else append_prim a1 a2
 
+let sub a ofs len =
+  if len < 0 || ofs > length a - len
+  then invalid_arg "Array.sub"
+  else unsafe_sub a ofs len
+
 let fill a ofs len v =
   if ofs < 0 || len < 0 || ofs > length a - len
   then invalid_arg "Array.fill"

File testsuite/tests/basic/arrays.ml

   if a <> [|"a"; "a"; "a"; "a"; "a"; "b1"; "b1"; "b2"; "b3"; "a"|]
   then print_string "Test7: failed(2)\n"
 
+let test8 () =
+  (try
+    ignore (Array.sub [||] 0 1); print_string "Test 8.1: failed\n"
+  with Invalid_argument _ -> ());
+  (try
+    ignore (Array.sub [|3;4|] 1 (-1)); print_string "Test 8.2: failed\n"
+  with Invalid_argument _ -> ());
+  (try
+    ignore (Array.sub [|3;4|] max_int 1); print_string "Test 8.3: failed\n"
+  with Invalid_argument _ -> ())
+
 let _ =
   test1();
   test2();
   test5();
   test6();
   test7();
+  test8();
   exit 0