'make install' installs programs and man pages
[virt-mem.git] / lib / virt_mem.ml
1 (* Memory info 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
20 open Unix
21 open Printf
22 open ExtList
23 open ExtString
24
25 module C = Libvirt.Connect
26 module D = Libvirt.Domain
27
28 open Virt_mem_gettext.Gettext
29 open Virt_mem_utils
30 module MMap = Virt_mem_mmap
31
32 let min_kallsyms_tabsize = 1_000L
33 let max_kallsyms_tabsize = 250_000L
34
35 let kernel_size = 0x100_0000
36 let max_memory_peek = 0x1_000
37
38 type ksym = string
39
40 type image =
41     string
42     * Virt_mem_utils.architecture
43     * ([`Wordsize], [`Endian]) Virt_mem_mmap.t
44     * (ksym -> MMap.addr)
45
46 type kallsyms_compr =
47   | Compressed of (string * MMap.addr) list * MMap.addr
48   | Uncompressed of (string * MMap.addr) list
49
50 let start usage_msg =
51   (* Debug messages. *)
52   let debug = ref false in
53
54   (* Default wordsize. *)
55   let def_wordsize = ref None in
56   let set_wordsize = function
57     | "32" -> def_wordsize := Some W32
58     | "64" -> def_wordsize := Some W64
59     | "auto" -> def_wordsize := None
60     | str -> failwith (sprintf (f_"set_wordsize: %s: unknown wordsize") str)
61   in
62
63   (* Default endianness. *)
64   let def_endian = ref None in
65   let set_endian = function
66     | "auto" -> def_endian := None
67     | "le" | "little" | "littleendian" | "intel" ->
68         def_endian := Some Bitmatch.LittleEndian
69     | "be" | "big" | "bigendian" | "motorola" ->
70         def_endian := Some Bitmatch.BigEndian
71     | str -> failwith (sprintf (f_"set_endian: %s: unknown endianness") str)
72   in
73
74   (* Default architecture. *)
75   let def_architecture = ref None in
76   let set_architecture = function
77     | "auto" -> def_architecture := None
78     | arch ->
79         let arch = architecture_of_string arch in
80         def_architecture := Some arch;
81         def_endian := Some (endian_of_architecture arch);
82         def_wordsize := Some (wordsize_of_architecture arch)
83   in
84
85   (* Default text address. *)
86   let def_text_addr = ref 0L (* 0 = auto-detect *) in
87   let set_text_addr = function
88     | "auto" -> def_text_addr := 0L
89     | "i386" -> def_text_addr := 0xc010_0000_L (* common for x86 *)
90     | "x86-64"|"x86_64" -> def_text_addr := 0xffffffff_81000000_L (* x86-64? *)
91     | str -> def_text_addr := Int64.of_string str
92   in
93
94   (* List of kernel images. *)
95   let images = ref [] in
96   let uri = ref "" in
97
98   let memory_image filename =
99     images :=
100       (!def_wordsize, !def_endian, !def_architecture, !def_text_addr, filename)
101     :: !images
102   in
103
104   let argspec = Arg.align [
105     "-A", Arg.String set_architecture,
106       "arch " ^ s_"Set kernel architecture, endianness and word size";
107     "-E", Arg.String set_endian,
108       "endian " ^ s_"Set kernel endianness";
109     "-T", Arg.String set_text_addr,
110       "addr " ^ s_"Set kernel text address";
111     "-W", Arg.String set_wordsize,
112       "addr " ^ s_"Set kernel word size";
113     "-c", Arg.Set_string uri,
114       "uri " ^ s_ "Connect to URI";
115     "--connect", Arg.Set_string uri,
116       "uri " ^ s_ "Connect to URI";
117     "--debug", Arg.Set debug,
118       " " ^ s_"Debug mode (default: false)";
119     "-t", Arg.String memory_image,
120       "image " ^ s_"Use saved kernel memory image";
121   ] in
122
123   let anon_fun str =
124     raise (Arg.Bad (sprintf (f_"%s: unknown parameter") str)) in
125   let usage_msg = usage_msg ^ s_"\n\nOPTIONS" in
126   Arg.parse argspec anon_fun usage_msg;
127
128   let images = !images in
129   let debug = !debug in
130   let uri = if !uri = "" then None else Some !uri in
131
132   (* Get the kernel images. *)
133   let images =
134     if images = [] then (
135       let conn =
136         let name = uri in
137         try C.connect_readonly ?name ()
138         with Libvirt.Virterror err ->
139           prerr_endline (Libvirt.Virterror.to_string err);
140           (* If non-root and no explicit connection URI, print a warning. *)
141           if Unix.geteuid () <> 0 && name = None then (
142             print_endline (s_ "NB: If you want to monitor a local Xen hypervisor, you usually need to be root");
143           );
144           exit 1 in
145
146       (* List of active domains. *)
147       let doms =
148         let nr_active_doms = C.num_of_domains conn in
149         let active_doms =
150           Array.to_list (C.list_domains conn nr_active_doms) in
151         let active_doms =
152           List.map (D.lookup_by_id conn) active_doms in
153         active_doms in
154
155       (* Get their XML. *)
156       let xmls = List.map (fun dom -> dom, D.get_xml_desc dom) doms in
157
158       (* Parse the XML. *)
159       let xmls = List.map (fun (dom, xml) ->
160                              dom, Xml.parse_string xml) xmls in
161
162       (* XXX Do something with the XML XXX
163        * such as detecting arch, wordsize, endianness.
164        * XXXXXXXXXXXXXX
165        *
166        *
167        *
168        *)
169
170
171       List.map (
172         fun (dom, _) ->
173           let name = D.get_name dom in
174
175           let wordsize =
176             match !def_wordsize with
177             | None ->
178                 failwith
179                   (sprintf (f_"%s: use -W to define word size for this image")
180                      name);
181             | Some ws -> ws in
182           let endian =
183             match !def_endian with
184             | None ->
185                 failwith
186                   (sprintf (f_"%s: use -E to define endianness for this image")
187                      name);
188             | Some e -> e in
189
190           let arch =
191             match !def_architecture with
192             | Some I386 -> I386 | Some X86_64 -> X86_64
193             | _ ->
194                 failwith
195                   (sprintf (f_"%s: use -A to define architecture (i386/x86-64 only) for this image") name) in
196
197           if !def_text_addr = 0L then
198             failwith
199               (sprintf (f_"%s: use -T to define kernel load address for this image")
200                  name);
201
202           (* Read the kernel memory.
203            * Maximum 64K can be read over remote connections.
204            *)
205           let str = String.create kernel_size in
206           let rec loop i =
207             let remaining = kernel_size - i in
208             if remaining > 0 then (
209               let size = min remaining max_memory_peek in
210               D.memory_peek dom [D.Virtual]
211                 (!def_text_addr +^ Int64.of_int i) size str i;
212               loop (i + size)
213             )
214           in
215           loop 0;
216
217           (* Map the virtual memory. *)
218           let mem = MMap.of_string str !def_text_addr in
219
220           (* Force the wordsize and endianness. *)
221           let mem = MMap.set_wordsize mem wordsize in
222           let mem = MMap.set_endian mem endian in
223
224           (name, arch, mem)
225       ) xmls
226     ) else
227       List.map (
228         fun (wordsize, endian, arch, text_addr, filename) ->
229           (* Quite a lot of limitations on the kernel images we can
230            * handle at the moment ...
231            *)
232           (* XXX We could auto-detect wordsize easily. *)
233           let wordsize =
234             match wordsize with
235             | None ->
236                 failwith
237                   (sprintf (f_"%s: use -W to define word size for this image")
238                      filename);
239             | Some ws -> ws in
240           let endian =
241             match endian with
242             | None ->
243                 failwith
244                   (sprintf (f_"%s: use -E to define endianness for this image")
245                      filename);
246             | Some e -> e in
247
248           let arch =
249             match arch with
250             | Some I386 -> I386 | Some X86_64 -> X86_64
251             | _ ->
252                 failwith
253                   (sprintf (f_"%s: use -A to define architecture (i386/x86-64 only) for this image") filename) in
254
255           if text_addr = 0L then
256             failwith
257               (sprintf (f_"%s: use -T to define kernel load address for this image")
258                  filename);
259
260           (* Map the virtual memory. *)
261           let fd = openfile filename [O_RDONLY] 0 in
262           let mem = MMap.of_file fd text_addr in
263
264           (* Force the wordsize and endianness. *)
265           let mem = MMap.set_wordsize mem wordsize in
266           let mem = MMap.set_endian mem endian in
267
268           (filename, arch, mem)
269       ) images in
270
271   let images =
272     List.map (
273       fun (name, arch, mem) ->
274         (* Look for some common entries in the exported symbol table and
275          * from that find the symbol table itself.  These are just
276          * supposed to be symbols which are very likely to be present
277          * in any Linux kernel, although we only need one of them to be
278          * present to find the symbol table.
279          *
280          * NB. Must not be __initdata, must be in EXPORT_SYMBOL.
281          *)
282         let common_ksyms = [
283           "init_task";                  (* first task_struct *)
284           "root_mountflags";            (* flags for mounting root fs *)
285           "init_uts_ns";                (* uname strings *)
286           "sys_open";                   (* open(2) entry point *)
287           "sys_chdir";                  (* chdir(2) entry point *)
288           "sys_chroot";                 (* chroot(2) entry point *)
289           "sys_umask";                  (* umask(2) entry point *)
290           "schedule";                   (* scheduler entry point *)
291         ] in
292         (* Searching for <NUL>string<NUL> *)
293         let common_ksyms_nul = List.map (sprintf "\000%s\000") common_ksyms in
294
295         (* Search for these strings in the memory image. *)
296         let ksym_strings = List.map (MMap.find_all mem) common_ksyms_nul in
297         let ksym_strings = List.concat ksym_strings in
298         (* Adjust found addresses to start of the string (skip <NUL>). *)
299         let ksym_strings = List.map Int64.succ ksym_strings in
300
301         (* For any we found, try to look up the symbol table
302          * base addr and size.
303          *)
304         let ksymtabs = List.map (
305           fun addr ->
306             (* Search for 'addr' appearing in the image. *)
307             let addrs = MMap.find_pointer_all mem addr in
308
309             (* Now consider each of these addresses and search back
310              * until we reach the beginning of the (possible) symbol
311              * table.
312              *
313              * Kernel symbol table struct is:
314              * struct kernel_symbol {
315              *   unsigned long value;
316              *   const char *name;    <-- initial pointer
317              * } symbols[];
318              *)
319             let pred_long2 addr =
320               MMap.pred_long mem (MMap.pred_long mem addr)
321             in
322             let base_addrs = List.map (
323               fun addr ->
324                 let rec loop addr =
325                   (* '*addr' should point to a C identifier.  If it does,
326                    * step backwards to the previous symbol table entry.
327                    *)
328                   let addrp = MMap.follow_pointer mem addr in
329                   if MMap.is_C_identifier mem addrp then
330                     loop (pred_long2 addr)
331                   else
332                     MMap.succ_long mem addr
333                 in
334                 loop addr
335             ) addrs in
336
337             (* Also look for the end of the symbol table and
338              * calculate its size.
339              *)
340             let base_addrs_sizes = List.map (
341               fun base_addr ->
342                 let rec loop addr =
343                   let addr2 = MMap.succ_long mem addr in
344                   let addr2p = MMap.follow_pointer mem addr2 in
345                   if MMap.is_C_identifier mem addr2p then
346                     loop (MMap.succ_long mem addr2)
347                   else
348                     addr
349                 in
350                 let end_addr = loop base_addr in
351                 base_addr, end_addr -^ base_addr
352             ) base_addrs in
353
354             base_addrs_sizes
355         ) ksym_strings in
356         let ksymtabs = List.concat ksymtabs in
357
358         (* Simply ignore any symbol table candidates which are too small. *)
359         let ksymtabs = List.filter (fun (_, size) -> size > 64L) ksymtabs in
360
361         if debug then (
362           printf "%s: candidate symbol tables at:\n" name;
363           List.iter (
364             fun (addr, size) ->
365               printf "\t%Lx\t%Lx\t%!" addr size;
366               printf "first symbol: %s\n%!"
367                 (MMap.get_string mem
368                    (MMap.follow_pointer mem
369                       (MMap.succ_long mem addr)))
370           ) ksymtabs
371         );
372
373         (* Vote for the most popular symbol table candidate and from this
374          * generate a function to look up ksyms.
375          *)
376         let lookup_ksym =
377           let freqs = frequency ksymtabs in
378           match freqs with
379           | [] ->
380               eprintf (f_"%s: cannot find start of kernel symbol table\n") name;
381               (fun _ -> raise Not_found)
382
383           | (_, (ksymtab_addr, ksymtab_size)) :: _ ->
384               if debug then
385                 printf
386                   "%s: Kernel symbol table found at %Lx, size %Lx bytes\n%!"
387                   name ksymtab_addr ksymtab_size;
388
389               (* Load the whole symbol table as a bitstring. *)
390               let ksymtab =
391                 Bitmatch.bitstring_of_string
392                   (MMap.get_bytes mem ksymtab_addr
393                      (Int64.to_int ksymtab_size)) in
394
395               (* Function to look up an address in the symbol table. *)
396               let lookup_ksym sym =
397                 let bits = bits_of_wordsize (MMap.get_wordsize mem) in
398                 let e = MMap.get_endian mem in
399                 let rec loop bs =
400                   bitmatch bs with
401                   | { value : bits : endian(e);
402                       name_ptr : bits : endian(e) }
403                       when MMap.get_string mem name_ptr = sym ->
404                       value
405                   | { _ : bits : endian(e);
406                       _ : bits : endian(e);
407                       bs : -1 : bitstring } ->
408                       loop bs
409                   | { _ } -> raise Not_found
410                 in
411                 loop ksymtab
412               in
413
414               lookup_ksym
415         in
416
417         (* Now try to find the /proc/kallsyms table.  This is in an odd
418          * compressed format (but not a very successful compression
419          * format).  However if it exists we know that it will contain
420          * addresses of the common ksyms above, and it has some
421          * characteristics which make it easy to detect in the
422          * memory.
423          *
424          * kallsyms contains a complete list of symbols so is much
425          * more useful than the basic list of exports.
426          *)
427         let ksym_addrs = List.filter_map (
428           fun ksym -> try Some (lookup_ksym ksym) with Not_found -> None
429         ) common_ksyms in
430
431         (* Search for those kernel addresses in the image.  We're looking
432          * for the table kallsyms_addresses followed by kallsyms_num_syms
433          * (number of symbols in the table).
434          *)
435         let ksym_addrs = List.map (MMap.find_pointer_all mem) ksym_addrs in
436         let ksym_addrs = List.concat ksym_addrs in
437
438         (* Test each one to see if it's a candidate list of kernel
439          * addresses followed by length of list.
440          *)
441         let kallsymtabs = List.filter_map (
442           fun addr ->
443             (* Search upwards from address until we find the length field.
444              * If found, jump backwards by length and check all addresses.
445              *)
446             if debug then
447               printf "%s: testing candidate kallsyms at %Lx\n" name addr;
448             let rec loop addr =
449               let addrp = MMap.follow_pointer mem addr in
450               if MMap.is_mapped mem addrp then
451                 loop (MMap.succ_long mem addr) (* continue up the table *)
452               else
453                 if addrp >= min_kallsyms_tabsize &&
454                   addrp <= max_kallsyms_tabsize then (
455                   (* addrp might be the symbol count.  Count backwards and
456                    * check the full table.
457                    *)
458                   let num_entries = Int64.to_int addrp in
459                   let entry_size = bytes_of_wordsize (MMap.get_wordsize mem) in
460                   let start_addr =
461                     addr -^ Int64.of_int (entry_size * num_entries) in
462                   let end_addr = addr in
463                   let rec loop2 addr =
464                     if addr < end_addr then (
465                       let addrp = MMap.follow_pointer mem addr in
466                       if MMap.is_mapped mem addrp then
467                         loop2 (MMap.succ_long mem addr)
468                       else
469                         None (* can't verify the full address table *)
470                     ) else
471                       (* ok! *)
472                       let names_addr = MMap.succ_long mem end_addr in
473                       if debug then
474                         printf "%s: candidate kallsyms found at %Lx (names_addr at %Lx, num_entries %d)\n"
475                           name start_addr names_addr num_entries;
476                       Some (start_addr, num_entries, names_addr)
477                   in
478                   loop2 start_addr
479                 )
480                 else
481                   None (* forget it *)
482             in
483             match loop addr with
484             | None -> None
485             | Some (start_addr, num_entries, names_addr) ->
486                 (* As an additional verification, check the list of
487                  * kallsyms_names.
488                  *)
489                 try
490                   (* If the first byte is '\000' and is followed by a
491                    * C identifier, then this is old-school list of
492                    * symbols with prefix compression as in 2.6.9.
493                    * Otherwise Huffman-compressed kallsyms as in
494                    * 2.6.25.
495                    *)
496                   if MMap.get_byte mem names_addr = 0 &&
497                     MMap.is_C_identifier mem (names_addr+^1L) then (
498                     let names = ref [] in
499                     let prev = ref "" in
500                     let rec loop names_addr start_addr num =
501                       if num > 0 then (
502                         let prefix = MMap.get_byte mem names_addr in
503                         let prefix = String.sub !prev 0 prefix in
504                         let name = MMap.get_string mem (names_addr+^1L) in
505                         let len = String.length name in
506                         let name = prefix ^ name in
507                         prev := name;
508                         let names_addr = names_addr +^ Int64.of_int len +^ 2L in
509                         let sym_value = MMap.follow_pointer mem start_addr in
510                         let start_addr = MMap.succ_long mem start_addr in
511                         (*printf "%S -> %Lx\n" name sym_value;*)
512                         names := (name, sym_value) :: !names;
513                         loop names_addr start_addr (num-1)
514                       )
515                     in
516                     loop names_addr start_addr num_entries;
517                     let names = List.rev !names in
518
519                     Some (start_addr, num_entries, names_addr,
520                           Uncompressed names)
521                     )
522                   else ( (* new-style "compressed" names. *)
523                     let compressed_names = ref [] in
524                     let rec loop names_addr start_addr num =
525                       if num > 0 then (
526                         let len = MMap.get_byte mem names_addr in
527                         let name = MMap.get_bytes mem (names_addr+^1L) len in
528                         let names_addr = names_addr +^ Int64.of_int len +^ 1L in
529                         let sym_value = MMap.follow_pointer mem start_addr in
530                         let start_addr = MMap.succ_long mem start_addr in
531                         compressed_names :=
532                           (name, sym_value) :: !compressed_names;
533                         loop names_addr start_addr (num-1)
534                       ) else
535                         names_addr
536                     in
537                     let markers_addr = loop names_addr start_addr num_entries in
538                     let markers_addr = MMap.align mem markers_addr in
539                     let compressed_names = List.rev !compressed_names in
540
541                     Some (start_addr, num_entries, names_addr,
542                           Compressed (compressed_names, markers_addr))
543                   )
544                 with
545                   Invalid_argument _ -> None (* bad names list *)
546         ) ksym_addrs in
547
548         if debug then (
549           printf "%s: candidate kallsyms at:\n" name;
550           List.iter (
551             function
552             | (start_addr, num_entries, names_addr, Uncompressed _) ->
553                 printf "\t%Lx %d entries names_addr=%Lx old-style\n%!"
554                   start_addr num_entries names_addr
555             | (start_addr, num_entries, names_addr,
556                Compressed (_, markers_addr)) ->
557                 printf "\t%Lx %d entries names_addr=%Lx markers_addr=%Lx\n%!"
558                   start_addr num_entries names_addr markers_addr
559           ) kallsymtabs
560         );
561
562         (* Vote for the most popular symbol table candidate and
563          * enhance the function for looking up ksyms.
564          *)
565         let lookup_ksym =
566           let freqs = frequency kallsymtabs in
567           match freqs with
568           | [] ->
569               (* Can't find any kallsymtabs, just return the lookup_ksym
570                * function generated previously from the exported symbols.
571                *)
572               lookup_ksym
573
574           | (_, (_, _, _, Uncompressed names)) :: _ ->
575               let lookup_ksym name =
576                 try (* first look it up in kallsyms table. *)
577                   List.assoc name names
578                 with Not_found -> (* try the old exports table instead *)
579                   lookup_ksym name
580               in
581               lookup_ksym
582
583           | (_, (start_addr, num_entries, names_addr,
584                  Compressed (compressed_names, markers_addr))) :: _ ->
585               (* Skip the markers and look for the token table. *)
586               let num_markers = Int64.of_int ((num_entries + 255) / 256) in
587               let marker_size =
588                 Int64.of_int (bytes_of_wordsize (MMap.get_wordsize mem)) in
589               let tokens_addr = markers_addr +^ marker_size *^ num_markers in
590
591               (* Now read out the compression tokens, which are just
592                * 256 ASCIIZ strings that map bytes in the compression
593                * names to substrings.
594                *)
595               let tokens = Array.make 256 "" in
596               let rec loop i addr =
597                 if i < 256 then (
598                   let str = MMap.get_string mem addr in
599                   let len = String.length str in
600                   let addr = addr +^ Int64.of_int (len+1) in
601                   tokens.(i) <- str;
602                   loop (i+1) addr
603                 )
604               in
605               loop 0 tokens_addr;
606
607               (* Expand the compressed names using the tokens. *)
608               let names = List.filter_map (
609                 fun (name, sym_value) ->
610                   let f c = tokens.(Char.code c) in
611                   let name = String.replace_chars f name in
612                   (* First character in uncompressed output is the symbol
613                    * type, eg. 'T'/'t' for text etc.
614                    *)
615                   (* NOTE: Symbol names are NOT unique
616                    * (eg. 'con_start' is both a function and data in
617                    * some kernels).  XXX We need to handle this situation
618                    * better.
619                    *)
620                   (*let typ = name.[0] in*)
621                   let name = String.sub name 1 (String.length name - 1) in
622                   (*printf "%S -> %Lx\n" name sym_value;*)
623                   Some (name, sym_value)
624               ) compressed_names in
625
626               let lookup_ksym name =
627                 try (* first look it up in kallsyms table. *)
628                   List.assoc name names
629                 with Not_found -> (* try the old exports table instead *)
630                   lookup_ksym name
631               in
632
633               lookup_ksym in
634
635         (* Just wrap the lookup_ksym call in something which prints
636          * the query when debug is set.
637          *)
638         let lookup_ksym =
639           if debug then
640             let lookup_ksym sym =
641               try
642                 let value = lookup_ksym sym in
643                 printf "lookup_ksym %S = %Lx\n%!" sym value;
644                 value
645               with Not_found ->
646                 printf "lookup_ksym %S failed\n%!" sym;
647                 raise Not_found
648             in
649             lookup_ksym
650           else
651             lookup_ksym
652         in
653
654         ((name, arch, mem, lookup_ksym) : image)
655     ) images in
656
657   debug, images