generator: Add OCaml bindings.
[hivex.git] / ocaml / t / hivex_200_write.ml
1 (* hivex OCaml bindings
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  *)
18
19 (* Test some significant write operations.  Take the minimal hive
20  * and algorithmically construct a large, deep hive.
21  *)
22
23 open Unix
24 open Printf
25 let (//) = Filename.concat
26 let srcdir = try Sys.getenv "srcdir" with Not_found -> "."
27
28 let () =
29   let h = Hivex.open_file (srcdir // "../images/minimal") [Hivex.OPEN_WRITE] in
30
31   let degrees = [| 3; 1; 4; 1; 5; 9; 2 |] (* ~1000 nodes *) in
32   let numbers = [| "Zero"; "One"; "Two"; "Three"; "Four";
33                    "Five"; "Six"; "Seven"; "Eight"; "Nine" |] in
34   let animals = [| "Horse"; "Ant"; "Mouse"; "Rabbit"; "Cat";
35                    "Giraffe"; "Kangaroo"; "Tiger"; "Zebra"; "Elephant" |] in
36
37   let rec iter depth posn parent =
38     if depth < Array.length degrees then (
39       let degree = degrees.(depth) in
40       for i = 0 to degree-1 do
41         let node_name = numbers.(depth) ^ " " ^ animals.(i) in
42         let node = Hivex.node_add_child h parent node_name in
43         iter (depth+1) i node
44       done;
45       let values = Array.init (10-posn) (
46         fun i ->
47           { Hivex.key = animals.(i);
48             t = Hivex.REG_SZ;
49             value = utf16le_of_ascii numbers.(i) }
50       ) in
51       Hivex.node_set_values h parent values
52     )
53
54   (* Make a nul-terminated UTF16-LE string from an ASCII string. *)
55   and utf16le_of_ascii str =
56     let len = String.length str in
57     let len' = len * 2 + 2 in
58     let str' = String.create len' in
59     for i = 0 to len-1 do
60       str'.[i*2] <- str.[i];
61       str'.[i*2+1] <- '\000'
62     done;
63     str'.[len'-2] <- '\000';
64     str'.[len'-1] <- '\000';
65     str'
66   in
67   iter 0 0 (Hivex.root h);
68
69   (* Discard the changes. *)
70   Hivex.close h;
71
72   (* Gc.compact is a good way to ensure we don't have
73    * heap corruption or double-freeing.
74    *)
75   Gc.compact ()