bitmatch -> bitstring
[virt-mem.git] / lib / virt_mem_mmap_c.c
1 /* Memory info command for virtual domains.
2    (C) Copyright 2008 Richard W.M. Jones, Red Hat Inc.
3    http://libvirt.org/
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19    This contains hand-coded C functions written for speed.
20 */
21
22 #include <config.h>
23
24 #include <string.h>
25
26 #include <caml/config.h>
27 #include <caml/alloc.h>
28 #include <caml/memory.h>
29 #include <caml/mlvalues.h>
30 #include <caml/bigarray.h>
31
32 CAMLprim value
33 virt_mem_mmap_find_in (value startv, value alignv, value strv, value arrv)
34 {
35   CAMLparam4 (startv, alignv, strv, arrv);
36   CAMLlocal2 (rv, vv);
37   long start = Long_val (startv); /* Start offset for search. */
38   long align = Long_val (alignv); /* Alignment for search. */
39   char *str = String_val (strv);  /* String to search for. */
40   int strlen = caml_string_length (strv);
41   void *data = Data_bigarray_val (arrv); /* Data in bigarray. */
42   int datalen = Bigarray_val(arrv)->dim[0]; /* Total length of bigarray. */
43   long i, r = -1;
44   void *p;
45
46   /* memmem is a GNU extension.  Note that we cannot use strstr because
47    * OCaml strings may contain NULs, and in this case it is very likely
48    * that it does contain NULs.
49    */
50 #ifdef HAVE_MEMMEM
51   if (align == 1) {
52     p = memmem (data+start, datalen-start, str, strlen);
53     r = p ? p-data : -1;
54     goto ret;
55   }
56 #endif
57
58   p = data+start;
59   for (i = start; i < datalen-strlen; i += align) {
60     if (memcmp (p, str, strlen) == 0) {
61       r = p-data;
62       goto ret;
63     }
64     p += align;
65   }
66
67  ret:
68   if (r == -1)
69     rv = Val_int (0);           /* None */
70   else {
71     vv = Val_long (r);          /* Some r */
72     rv = caml_alloc (1, 0);
73     Store_field (rv, 0, vv);
74   }
75
76   CAMLreturn (rv);
77 }