Add the test0* functions, used to test language bindings.
[libguestfs.git] / src / generator.ml
1 #!/usr/bin/env ocaml
2 (* libguestfs
3  * Copyright (C) 2009 Red Hat Inc.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  *)
19
20 (* This script generates a large amount of code and documentation for
21  * all the daemon actions.
22  *
23  * To add a new action there are only two files you need to change,
24  * this one to describe the interface (see the big table below), and
25  * daemon/<somefile>.c to write the implementation.
26  *
27  * After editing this file, run it (./src/generator.ml) to regenerate
28  * all the output files.
29  *
30  * IMPORTANT: This script should NOT print any warnings.  If it prints
31  * warnings, you should treat them as errors.
32  * [Need to add -warn-error to ocaml command line]
33  *)
34
35 #load "unix.cma";;
36 #load "str.cma";;
37
38 open Printf
39
40 type style = ret * args
41 and ret =
42     (* "RErr" as a return value means an int used as a simple error
43      * indication, ie. 0 or -1.
44      *)
45   | RErr
46     (* "RInt" as a return value means an int which is -1 for error
47      * or any value >= 0 on success.  Only use this for smallish
48      * positive ints (0 <= i < 2^30).
49      *)
50   | RInt of string
51     (* "RInt64" is the same as RInt, but is guaranteed to be able
52      * to return a full 64 bit value, _except_ that -1 means error
53      * (so -1 cannot be a valid, non-error return value).
54      *)
55   | RInt64 of string
56     (* "RBool" is a bool return value which can be true/false or
57      * -1 for error.
58      *)
59   | RBool of string
60     (* "RConstString" is a string that refers to a constant value.
61      * Try to avoid using this.  In particular you cannot use this
62      * for values returned from the daemon, because there is no
63      * thread-safe way to return them in the C API.
64      *)
65   | RConstString of string
66     (* "RString" and "RStringList" are caller-frees. *)
67   | RString of string
68   | RStringList of string
69     (* Some limited tuples are possible: *)
70   | RIntBool of string * string
71     (* LVM PVs, VGs and LVs. *)
72   | RPVList of string
73   | RVGList of string
74   | RLVList of string
75     (* Stat buffers. *)
76   | RStat of string
77   | RStatVFS of string
78     (* Key-value pairs of untyped strings.  Turns into a hashtable or
79      * dictionary in languages which support it.  DON'T use this as a
80      * general "bucket" for results.  Prefer a stronger typed return
81      * value if one is available, or write a custom struct.  Don't use
82      * this if the list could potentially be very long, since it is
83      * inefficient.  Keys should be unique.  NULLs are not permitted.
84      *)
85   | RHashtable of string
86
87 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
88
89     (* Note in future we should allow a "variable args" parameter as
90      * the final parameter, to allow commands like
91      *   chmod mode file [file(s)...]
92      * This is not implemented yet, but many commands (such as chmod)
93      * are currently defined with the argument order keeping this future
94      * possibility in mind.
95      *)
96 and argt =
97   | String of string    (* const char *name, cannot be NULL *)
98   | OptString of string (* const char *name, may be NULL *)
99   | StringList of string(* list of strings (each string cannot be NULL) *)
100   | Bool of string      (* boolean *)
101   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
102     (* These are treated as filenames (simple string parameters) in
103      * the C API and bindings.  But in the RPC protocol, we transfer
104      * the actual file content up to or down from the daemon.
105      * FileIn: local machine -> daemon (in request)
106      * FileOut: daemon -> local machine (in reply)
107      * In guestfish (only), the special name "-" means read from
108      * stdin or write to stdout.
109      *)
110   | FileIn of string
111   | FileOut of string
112
113 type flags =
114   | ProtocolLimitWarning  (* display warning about protocol size limits *)
115   | DangerWillRobinson    (* flags particularly dangerous commands *)
116   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
117   | FishAction of string  (* call this function in guestfish *)
118   | NotInFish             (* do not export via guestfish *)
119   | NotInDocs             (* do not add this function to documentation *)
120
121 let protocol_limit_warning =
122   "Because of the message protocol, there is a transfer limit 
123 of somewhere between 2MB and 4MB.  To transfer large files you should use
124 FTP."
125
126 let danger_will_robinson =
127   "B<This command is dangerous.  Without careful use you
128 can easily destroy all your data>."
129
130 (* You can supply zero or as many tests as you want per API call.
131  *
132  * Note that the test environment has 3 block devices, of size 500MB,
133  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc).
134  * Note for partitioning purposes, the 500MB device has 63 cylinders.
135  *
136  * To be able to run the tests in a reasonable amount of time,
137  * the virtual machine and block devices are reused between tests.
138  * So don't try testing kill_subprocess :-x
139  *
140  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
141  *
142  * If the appliance is running an older Linux kernel (eg. RHEL 5) then
143  * devices are named /dev/hda etc.  To cope with this, the test suite
144  * adds some hairly logic to detect this case, and then automagically
145  * replaces all strings which match "/dev/sd.*" with "/dev/hd.*".
146  * When writing test cases you shouldn't have to worry about this
147  * difference.
148  *
149  * Don't assume anything about the previous contents of the block
150  * devices.  Use 'Init*' to create some initial scenarios.
151  *
152  * You can add a prerequisite clause to any individual test.  This
153  * is a run-time check, which, if it fails, causes the test to be
154  * skipped.  Useful if testing a command which might not work on
155  * all variations of libguestfs builds.  A test that has prerequisite
156  * of 'Always' is run unconditionally.
157  *
158  * In addition, packagers can skip individual tests by setting the
159  * environment variables:     eg:
160  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
161  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
162  *)
163 type tests = (test_init * test_prereq * test) list
164 and test =
165     (* Run the command sequence and just expect nothing to fail. *)
166   | TestRun of seq
167     (* Run the command sequence and expect the output of the final
168      * command to be the string.
169      *)
170   | TestOutput of seq * string
171     (* Run the command sequence and expect the output of the final
172      * command to be the list of strings.
173      *)
174   | TestOutputList of seq * string list
175     (* Run the command sequence and expect the output of the final
176      * command to be the integer.
177      *)
178   | TestOutputInt of seq * int
179     (* Run the command sequence and expect the output of the final
180      * command to be a true value (!= 0 or != NULL).
181      *)
182   | TestOutputTrue of seq
183     (* Run the command sequence and expect the output of the final
184      * command to be a false value (== 0 or == NULL, but not an error).
185      *)
186   | TestOutputFalse of seq
187     (* Run the command sequence and expect the output of the final
188      * command to be a list of the given length (but don't care about
189      * content).
190      *)
191   | TestOutputLength of seq * int
192     (* Run the command sequence and expect the output of the final
193      * command to be a structure.
194      *)
195   | TestOutputStruct of seq * test_field_compare list
196     (* Run the command sequence and expect the final command (only)
197      * to fail.
198      *)
199   | TestLastFail of seq
200
201 and test_field_compare =
202   | CompareWithInt of string * int
203   | CompareWithString of string * string
204   | CompareFieldsIntEq of string * string
205   | CompareFieldsStrEq of string * string
206
207 (* Test prerequisites. *)
208 and test_prereq =
209     (* Test always runs. *)
210   | Always
211     (* Test is currently disabled - eg. it fails, or it tests some
212      * unimplemented feature.
213      *)
214   | Disabled
215     (* 'string' is some C code (a function body) that should return
216      * true or false.  The test will run if the code returns true.
217      *)
218   | If of string
219     (* As for 'If' but the test runs _unless_ the code returns true. *)
220   | Unless of string
221
222 (* Some initial scenarios for testing. *)
223 and test_init =
224     (* Do nothing, block devices could contain random stuff including
225      * LVM PVs, and some filesystems might be mounted.  This is usually
226      * a bad idea.
227      *)
228   | InitNone
229     (* Block devices are empty and no filesystems are mounted. *)
230   | InitEmpty
231     (* /dev/sda contains a single partition /dev/sda1, which is formatted
232      * as ext2, empty [except for lost+found] and mounted on /.
233      * /dev/sdb and /dev/sdc may have random content.
234      * No LVM.
235      *)
236   | InitBasicFS
237     (* /dev/sda:
238      *   /dev/sda1 (is a PV):
239      *     /dev/VG/LV (size 8MB):
240      *       formatted as ext2, empty [except for lost+found], mounted on /
241      * /dev/sdb and /dev/sdc may have random content.
242      *)
243   | InitBasicFSonLVM
244
245 (* Sequence of commands for testing. *)
246 and seq = cmd list
247 and cmd = string list
248
249 (* Note about long descriptions: When referring to another
250  * action, use the format C<guestfs_other> (ie. the full name of
251  * the C function).  This will be replaced as appropriate in other
252  * language bindings.
253  *
254  * Apart from that, long descriptions are just perldoc paragraphs.
255  *)
256
257 (* These test functions are used in the language binding tests. *)
258
259 let test_all_args = [
260   String "str";
261   OptString "optstr";
262   StringList "strlist";
263   Bool "b";
264   Int "integer";
265   FileIn "filein";
266   FileOut "fileout";
267 ]
268
269 let test_all_rets = [
270   (* except for RErr, which is tested thoroughly elsewhere *)
271   "test0rint",         RInt "valout";
272   "test0rint64",       RInt64 "valout";
273   "test0rbool",        RBool "valout";
274   "test0rconststring", RConstString "valout";
275   "test0rstring",      RString "valout";
276   "test0rstringlist",  RStringList "valout";
277   "test0rintbool",     RIntBool ("valout", "valout");
278   "test0rpvlist",      RPVList "valout";
279   "test0rvglist",      RVGList "valout";
280   "test0rlvlist",      RLVList "valout";
281   "test0rstat",        RStat "valout";
282   "test0rstatvfs",     RStatVFS "valout";
283   "test0rhashtable",   RHashtable "valout";
284 ]
285
286 let test_functions = [
287   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
288    [],
289    "internal test function - do not use",
290    "\
291 This is an internal test function which is used to test whether
292 the automatically generated bindings can handle every possible
293 parameter type correctly.
294
295 It echos the contents of each parameter to stdout.
296
297 You probably don't want to call this function.");
298 ] @ List.flatten (
299   List.map (
300     fun (name, ret) ->
301       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
302         [],
303         "internal test function - do not use",
304         "\
305 This is an internal test function which is used to test whether
306 the automatically generated bindings can handle every possible
307 return type correctly.
308
309 It converts string C<val> to the return type.
310
311 You probably don't want to call this function.");
312        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
313         [],
314         "internal test function - do not use",
315         "\
316 This is an internal test function which is used to test whether
317 the automatically generated bindings can handle every possible
318 return type correctly.
319
320 This function always returns an error.
321
322 You probably don't want to call this function.")]
323   ) test_all_rets
324 )
325
326 (* non_daemon_functions are any functions which don't get processed
327  * in the daemon, eg. functions for setting and getting local
328  * configuration values.
329  *)
330
331 let non_daemon_functions = test_functions @ [
332   ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
333    [],
334    "launch the qemu subprocess",
335    "\
336 Internally libguestfs is implemented by running a virtual machine
337 using L<qemu(1)>.
338
339 You should call this after configuring the handle
340 (eg. adding drives) but before performing any actions.");
341
342   ("wait_ready", (RErr, []), -1, [NotInFish],
343    [],
344    "wait until the qemu subprocess launches",
345    "\
346 Internally libguestfs is implemented by running a virtual machine
347 using L<qemu(1)>.
348
349 You should call this after C<guestfs_launch> to wait for the launch
350 to complete.");
351
352   ("kill_subprocess", (RErr, []), -1, [],
353    [],
354    "kill the qemu subprocess",
355    "\
356 This kills the qemu subprocess.  You should never need to call this.");
357
358   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
359    [],
360    "add an image to examine or modify",
361    "\
362 This function adds a virtual machine disk image C<filename> to the
363 guest.  The first time you call this function, the disk appears as IDE
364 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
365 so on.
366
367 You don't necessarily need to be root when using libguestfs.  However
368 you obviously do need sufficient permissions to access the filename
369 for whatever operations you want to perform (ie. read access if you
370 just want to read the image or write access if you want to modify the
371 image).
372
373 This is equivalent to the qemu parameter C<-drive file=filename>.");
374
375   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
376    [],
377    "add a CD-ROM disk image to examine",
378    "\
379 This function adds a virtual CD-ROM disk image to the guest.
380
381 This is equivalent to the qemu parameter C<-cdrom filename>.");
382
383   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
384    [],
385    "add qemu parameters",
386    "\
387 This can be used to add arbitrary qemu command line parameters
388 of the form C<-param value>.  Actually it's not quite arbitrary - we
389 prevent you from setting some parameters which would interfere with
390 parameters that we use.
391
392 The first character of C<param> string must be a C<-> (dash).
393
394 C<value> can be NULL.");
395
396   ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
397    [],
398    "set the qemu binary",
399    "\
400 Set the qemu binary that we will use.
401
402 The default is chosen when the library was compiled by the
403 configure script.
404
405 You can also override this by setting the C<LIBGUESTFS_QEMU>
406 environment variable.
407
408 Setting C<qemu> to C<NULL> restores the default qemu binary.");
409
410   ("get_qemu", (RConstString "qemu", []), -1, [],
411    [],
412    "get the qemu binary",
413    "\
414 Return the current qemu binary.
415
416 This is always non-NULL.  If it wasn't set already, then this will
417 return the default qemu binary name.");
418
419   ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
420    [],
421    "set the search path",
422    "\
423 Set the path that libguestfs searches for kernel and initrd.img.
424
425 The default is C<$libdir/guestfs> unless overridden by setting
426 C<LIBGUESTFS_PATH> environment variable.
427
428 Setting C<path> to C<NULL> restores the default path.");
429
430   ("get_path", (RConstString "path", []), -1, [],
431    [],
432    "get the search path",
433    "\
434 Return the current search path.
435
436 This is always non-NULL.  If it wasn't set already, then this will
437 return the default path.");
438
439   ("set_append", (RErr, [String "append"]), -1, [FishAlias "append"],
440    [],
441    "add options to kernel command line",
442    "\
443 This function is used to add additional options to the
444 guest kernel command line.
445
446 The default is C<NULL> unless overridden by setting
447 C<LIBGUESTFS_APPEND> environment variable.
448
449 Setting C<append> to C<NULL> means I<no> additional options
450 are passed (libguestfs always adds a few of its own).");
451
452   ("get_append", (RConstString "append", []), -1, [],
453    [],
454    "get the additional kernel options",
455    "\
456 Return the additional kernel options which are added to the
457 guest kernel command line.
458
459 If C<NULL> then no options are added.");
460
461   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
462    [],
463    "set autosync mode",
464    "\
465 If C<autosync> is true, this enables autosync.  Libguestfs will make a
466 best effort attempt to run C<guestfs_umount_all> followed by
467 C<guestfs_sync> when the handle is closed
468 (also if the program exits without closing handles).
469
470 This is disabled by default (except in guestfish where it is
471 enabled by default).");
472
473   ("get_autosync", (RBool "autosync", []), -1, [],
474    [],
475    "get autosync mode",
476    "\
477 Get the autosync flag.");
478
479   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
480    [],
481    "set verbose mode",
482    "\
483 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
484
485 Verbose messages are disabled unless the environment variable
486 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
487
488   ("get_verbose", (RBool "verbose", []), -1, [],
489    [],
490    "get verbose mode",
491    "\
492 This returns the verbose messages flag.");
493
494   ("is_ready", (RBool "ready", []), -1, [],
495    [],
496    "is ready to accept commands",
497    "\
498 This returns true iff this handle is ready to accept commands
499 (in the C<READY> state).
500
501 For more information on states, see L<guestfs(3)>.");
502
503   ("is_config", (RBool "config", []), -1, [],
504    [],
505    "is in configuration state",
506    "\
507 This returns true iff this handle is being configured
508 (in the C<CONFIG> state).
509
510 For more information on states, see L<guestfs(3)>.");
511
512   ("is_launching", (RBool "launching", []), -1, [],
513    [],
514    "is launching subprocess",
515    "\
516 This returns true iff this handle is launching the subprocess
517 (in the C<LAUNCHING> state).
518
519 For more information on states, see L<guestfs(3)>.");
520
521   ("is_busy", (RBool "busy", []), -1, [],
522    [],
523    "is busy processing a command",
524    "\
525 This returns true iff this handle is busy processing a command
526 (in the C<BUSY> state).
527
528 For more information on states, see L<guestfs(3)>.");
529
530   ("get_state", (RInt "state", []), -1, [],
531    [],
532    "get the current state",
533    "\
534 This returns the current state as an opaque integer.  This is
535 only useful for printing debug and internal error messages.
536
537 For more information on states, see L<guestfs(3)>.");
538
539   ("set_busy", (RErr, []), -1, [NotInFish],
540    [],
541    "set state to busy",
542    "\
543 This sets the state to C<BUSY>.  This is only used when implementing
544 actions using the low-level API.
545
546 For more information on states, see L<guestfs(3)>.");
547
548   ("set_ready", (RErr, []), -1, [NotInFish],
549    [],
550    "set state to ready",
551    "\
552 This sets the state to C<READY>.  This is only used when implementing
553 actions using the low-level API.
554
555 For more information on states, see L<guestfs(3)>.");
556
557   ("end_busy", (RErr, []), -1, [NotInFish],
558    [],
559    "leave the busy state",
560    "\
561 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
562 state as is.  This is only used when implementing
563 actions using the low-level API.
564
565 For more information on states, see L<guestfs(3)>.");
566
567 ]
568
569 (* daemon_functions are any functions which cause some action
570  * to take place in the daemon.
571  *)
572
573 let daemon_functions = [
574   ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
575    [InitEmpty, Always, TestOutput (
576       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
577        ["mkfs"; "ext2"; "/dev/sda1"];
578        ["mount"; "/dev/sda1"; "/"];
579        ["write_file"; "/new"; "new file contents"; "0"];
580        ["cat"; "/new"]], "new file contents")],
581    "mount a guest disk at a position in the filesystem",
582    "\
583 Mount a guest disk at a position in the filesystem.  Block devices
584 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
585 the guest.  If those block devices contain partitions, they will have
586 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
587 names can be used.
588
589 The rules are the same as for L<mount(2)>:  A filesystem must
590 first be mounted on C</> before others can be mounted.  Other
591 filesystems can only be mounted on directories which already
592 exist.
593
594 The mounted filesystem is writable, if we have sufficient permissions
595 on the underlying device.
596
597 The filesystem options C<sync> and C<noatime> are set with this
598 call, in order to improve reliability.");
599
600   ("sync", (RErr, []), 2, [],
601    [ InitEmpty, Always, TestRun [["sync"]]],
602    "sync disks, writes are flushed through to the disk image",
603    "\
604 This syncs the disk, so that any writes are flushed through to the
605 underlying disk image.
606
607 You should always call this if you have modified a disk image, before
608 closing the handle.");
609
610   ("touch", (RErr, [String "path"]), 3, [],
611    [InitBasicFS, Always, TestOutputTrue (
612       [["touch"; "/new"];
613        ["exists"; "/new"]])],
614    "update file timestamps or create a new file",
615    "\
616 Touch acts like the L<touch(1)> command.  It can be used to
617 update the timestamps on a file, or, if the file does not exist,
618 to create a new zero-length file.");
619
620   ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
621    [InitBasicFS, Always, TestOutput (
622       [["write_file"; "/new"; "new file contents"; "0"];
623        ["cat"; "/new"]], "new file contents")],
624    "list the contents of a file",
625    "\
626 Return the contents of the file named C<path>.
627
628 Note that this function cannot correctly handle binary files
629 (specifically, files containing C<\\0> character which is treated
630 as end of string).  For those you need to use the C<guestfs_download>
631 function which has a more complex interface.");
632
633   ("ll", (RString "listing", [String "directory"]), 5, [],
634    [], (* XXX Tricky to test because it depends on the exact format
635         * of the 'ls -l' command, which changes between F10 and F11.
636         *)
637    "list the files in a directory (long format)",
638    "\
639 List the files in C<directory> (relative to the root directory,
640 there is no cwd) in the format of 'ls -la'.
641
642 This command is mostly useful for interactive sessions.  It
643 is I<not> intended that you try to parse the output string.");
644
645   ("ls", (RStringList "listing", [String "directory"]), 6, [],
646    [InitBasicFS, Always, TestOutputList (
647       [["touch"; "/new"];
648        ["touch"; "/newer"];
649        ["touch"; "/newest"];
650        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
651    "list the files in a directory",
652    "\
653 List the files in C<directory> (relative to the root directory,
654 there is no cwd).  The '.' and '..' entries are not returned, but
655 hidden files are shown.
656
657 This command is mostly useful for interactive sessions.  Programs
658 should probably use C<guestfs_readdir> instead.");
659
660   ("list_devices", (RStringList "devices", []), 7, [],
661    [InitEmpty, Always, TestOutputList (
662       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"])],
663    "list the block devices",
664    "\
665 List all the block devices.
666
667 The full block device names are returned, eg. C</dev/sda>");
668
669   ("list_partitions", (RStringList "partitions", []), 8, [],
670    [InitBasicFS, Always, TestOutputList (
671       [["list_partitions"]], ["/dev/sda1"]);
672     InitEmpty, Always, TestOutputList (
673       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
674        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
675    "list the partitions",
676    "\
677 List all the partitions detected on all block devices.
678
679 The full partition device names are returned, eg. C</dev/sda1>
680
681 This does not return logical volumes.  For that you will need to
682 call C<guestfs_lvs>.");
683
684   ("pvs", (RStringList "physvols", []), 9, [],
685    [InitBasicFSonLVM, Always, TestOutputList (
686       [["pvs"]], ["/dev/sda1"]);
687     InitEmpty, Always, TestOutputList (
688       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
689        ["pvcreate"; "/dev/sda1"];
690        ["pvcreate"; "/dev/sda2"];
691        ["pvcreate"; "/dev/sda3"];
692        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
693    "list the LVM physical volumes (PVs)",
694    "\
695 List all the physical volumes detected.  This is the equivalent
696 of the L<pvs(8)> command.
697
698 This returns a list of just the device names that contain
699 PVs (eg. C</dev/sda2>).
700
701 See also C<guestfs_pvs_full>.");
702
703   ("vgs", (RStringList "volgroups", []), 10, [],
704    [InitBasicFSonLVM, Always, TestOutputList (
705       [["vgs"]], ["VG"]);
706     InitEmpty, Always, TestOutputList (
707       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
708        ["pvcreate"; "/dev/sda1"];
709        ["pvcreate"; "/dev/sda2"];
710        ["pvcreate"; "/dev/sda3"];
711        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
712        ["vgcreate"; "VG2"; "/dev/sda3"];
713        ["vgs"]], ["VG1"; "VG2"])],
714    "list the LVM volume groups (VGs)",
715    "\
716 List all the volumes groups detected.  This is the equivalent
717 of the L<vgs(8)> command.
718
719 This returns a list of just the volume group names that were
720 detected (eg. C<VolGroup00>).
721
722 See also C<guestfs_vgs_full>.");
723
724   ("lvs", (RStringList "logvols", []), 11, [],
725    [InitBasicFSonLVM, Always, TestOutputList (
726       [["lvs"]], ["/dev/VG/LV"]);
727     InitEmpty, Always, TestOutputList (
728       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
729        ["pvcreate"; "/dev/sda1"];
730        ["pvcreate"; "/dev/sda2"];
731        ["pvcreate"; "/dev/sda3"];
732        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
733        ["vgcreate"; "VG2"; "/dev/sda3"];
734        ["lvcreate"; "LV1"; "VG1"; "50"];
735        ["lvcreate"; "LV2"; "VG1"; "50"];
736        ["lvcreate"; "LV3"; "VG2"; "50"];
737        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
738    "list the LVM logical volumes (LVs)",
739    "\
740 List all the logical volumes detected.  This is the equivalent
741 of the L<lvs(8)> command.
742
743 This returns a list of the logical volume device names
744 (eg. C</dev/VolGroup00/LogVol00>).
745
746 See also C<guestfs_lvs_full>.");
747
748   ("pvs_full", (RPVList "physvols", []), 12, [],
749    [], (* XXX how to test? *)
750    "list the LVM physical volumes (PVs)",
751    "\
752 List all the physical volumes detected.  This is the equivalent
753 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
754
755   ("vgs_full", (RVGList "volgroups", []), 13, [],
756    [], (* XXX how to test? *)
757    "list the LVM volume groups (VGs)",
758    "\
759 List all the volumes groups detected.  This is the equivalent
760 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
761
762   ("lvs_full", (RLVList "logvols", []), 14, [],
763    [], (* XXX how to test? *)
764    "list the LVM logical volumes (LVs)",
765    "\
766 List all the logical volumes detected.  This is the equivalent
767 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
768
769   ("read_lines", (RStringList "lines", [String "path"]), 15, [],
770    [InitBasicFS, Always, TestOutputList (
771       [["write_file"; "/new"; "line1\r\nline2\nline3"; "0"];
772        ["read_lines"; "/new"]], ["line1"; "line2"; "line3"]);
773     InitBasicFS, Always, TestOutputList (
774       [["write_file"; "/new"; ""; "0"];
775        ["read_lines"; "/new"]], [])],
776    "read file as lines",
777    "\
778 Return the contents of the file named C<path>.
779
780 The file contents are returned as a list of lines.  Trailing
781 C<LF> and C<CRLF> character sequences are I<not> returned.
782
783 Note that this function cannot correctly handle binary files
784 (specifically, files containing C<\\0> character which is treated
785 as end of line).  For those you need to use the C<guestfs_read_file>
786 function which has a more complex interface.");
787
788   ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
789    [], (* XXX Augeas code needs tests. *)
790    "create a new Augeas handle",
791    "\
792 Create a new Augeas handle for editing configuration files.
793 If there was any previous Augeas handle associated with this
794 guestfs session, then it is closed.
795
796 You must call this before using any other C<guestfs_aug_*>
797 commands.
798
799 C<root> is the filesystem root.  C<root> must not be NULL,
800 use C</> instead.
801
802 The flags are the same as the flags defined in
803 E<lt>augeas.hE<gt>, the logical I<or> of the following
804 integers:
805
806 =over 4
807
808 =item C<AUG_SAVE_BACKUP> = 1
809
810 Keep the original file with a C<.augsave> extension.
811
812 =item C<AUG_SAVE_NEWFILE> = 2
813
814 Save changes into a file with extension C<.augnew>, and
815 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
816
817 =item C<AUG_TYPE_CHECK> = 4
818
819 Typecheck lenses (can be expensive).
820
821 =item C<AUG_NO_STDINC> = 8
822
823 Do not use standard load path for modules.
824
825 =item C<AUG_SAVE_NOOP> = 16
826
827 Make save a no-op, just record what would have been changed.
828
829 =item C<AUG_NO_LOAD> = 32
830
831 Do not load the tree in C<guestfs_aug_init>.
832
833 =back
834
835 To close the handle, you can call C<guestfs_aug_close>.
836
837 To find out more about Augeas, see L<http://augeas.net/>.");
838
839   ("aug_close", (RErr, []), 26, [],
840    [], (* XXX Augeas code needs tests. *)
841    "close the current Augeas handle",
842    "\
843 Close the current Augeas handle and free up any resources
844 used by it.  After calling this, you have to call
845 C<guestfs_aug_init> again before you can use any other
846 Augeas functions.");
847
848   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
849    [], (* XXX Augeas code needs tests. *)
850    "define an Augeas variable",
851    "\
852 Defines an Augeas variable C<name> whose value is the result
853 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
854 undefined.
855
856 On success this returns the number of nodes in C<expr>, or
857 C<0> if C<expr> evaluates to something which is not a nodeset.");
858
859   ("aug_defnode", (RIntBool ("nrnodes", "created"), [String "name"; String "expr"; String "val"]), 18, [],
860    [], (* XXX Augeas code needs tests. *)
861    "define an Augeas node",
862    "\
863 Defines a variable C<name> whose value is the result of
864 evaluating C<expr>.
865
866 If C<expr> evaluates to an empty nodeset, a node is created,
867 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
868 C<name> will be the nodeset containing that single node.
869
870 On success this returns a pair containing the
871 number of nodes in the nodeset, and a boolean flag
872 if a node was created.");
873
874   ("aug_get", (RString "val", [String "path"]), 19, [],
875    [], (* XXX Augeas code needs tests. *)
876    "look up the value of an Augeas path",
877    "\
878 Look up the value associated with C<path>.  If C<path>
879 matches exactly one node, the C<value> is returned.");
880
881   ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
882    [], (* XXX Augeas code needs tests. *)
883    "set Augeas path to value",
884    "\
885 Set the value associated with C<path> to C<value>.");
886
887   ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
888    [], (* XXX Augeas code needs tests. *)
889    "insert a sibling Augeas node",
890    "\
891 Create a new sibling C<label> for C<path>, inserting it into
892 the tree before or after C<path> (depending on the boolean
893 flag C<before>).
894
895 C<path> must match exactly one existing node in the tree, and
896 C<label> must be a label, ie. not contain C</>, C<*> or end
897 with a bracketed index C<[N]>.");
898
899   ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
900    [], (* XXX Augeas code needs tests. *)
901    "remove an Augeas path",
902    "\
903 Remove C<path> and all of its children.
904
905 On success this returns the number of entries which were removed.");
906
907   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
908    [], (* XXX Augeas code needs tests. *)
909    "move Augeas node",
910    "\
911 Move the node C<src> to C<dest>.  C<src> must match exactly
912 one node.  C<dest> is overwritten if it exists.");
913
914   ("aug_match", (RStringList "matches", [String "path"]), 24, [],
915    [], (* XXX Augeas code needs tests. *)
916    "return Augeas nodes which match path",
917    "\
918 Returns a list of paths which match the path expression C<path>.
919 The returned paths are sufficiently qualified so that they match
920 exactly one node in the current tree.");
921
922   ("aug_save", (RErr, []), 25, [],
923    [], (* XXX Augeas code needs tests. *)
924    "write all pending Augeas changes to disk",
925    "\
926 This writes all pending changes to disk.
927
928 The flags which were passed to C<guestfs_aug_init> affect exactly
929 how files are saved.");
930
931   ("aug_load", (RErr, []), 27, [],
932    [], (* XXX Augeas code needs tests. *)
933    "load files into the tree",
934    "\
935 Load files into the tree.
936
937 See C<aug_load> in the Augeas documentation for the full gory
938 details.");
939
940   ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
941    [], (* XXX Augeas code needs tests. *)
942    "list Augeas nodes under a path",
943    "\
944 This is just a shortcut for listing C<guestfs_aug_match>
945 C<path/*> and sorting the resulting nodes into alphabetical order.");
946
947   ("rm", (RErr, [String "path"]), 29, [],
948    [InitBasicFS, Always, TestRun
949       [["touch"; "/new"];
950        ["rm"; "/new"]];
951     InitBasicFS, Always, TestLastFail
952       [["rm"; "/new"]];
953     InitBasicFS, Always, TestLastFail
954       [["mkdir"; "/new"];
955        ["rm"; "/new"]]],
956    "remove a file",
957    "\
958 Remove the single file C<path>.");
959
960   ("rmdir", (RErr, [String "path"]), 30, [],
961    [InitBasicFS, Always, TestRun
962       [["mkdir"; "/new"];
963        ["rmdir"; "/new"]];
964     InitBasicFS, Always, TestLastFail
965       [["rmdir"; "/new"]];
966     InitBasicFS, Always, TestLastFail
967       [["touch"; "/new"];
968        ["rmdir"; "/new"]]],
969    "remove a directory",
970    "\
971 Remove the single directory C<path>.");
972
973   ("rm_rf", (RErr, [String "path"]), 31, [],
974    [InitBasicFS, Always, TestOutputFalse
975       [["mkdir"; "/new"];
976        ["mkdir"; "/new/foo"];
977        ["touch"; "/new/foo/bar"];
978        ["rm_rf"; "/new"];
979        ["exists"; "/new"]]],
980    "remove a file or directory recursively",
981    "\
982 Remove the file or directory C<path>, recursively removing the
983 contents if its a directory.  This is like the C<rm -rf> shell
984 command.");
985
986   ("mkdir", (RErr, [String "path"]), 32, [],
987    [InitBasicFS, Always, TestOutputTrue
988       [["mkdir"; "/new"];
989        ["is_dir"; "/new"]];
990     InitBasicFS, Always, TestLastFail
991       [["mkdir"; "/new/foo/bar"]]],
992    "create a directory",
993    "\
994 Create a directory named C<path>.");
995
996   ("mkdir_p", (RErr, [String "path"]), 33, [],
997    [InitBasicFS, Always, TestOutputTrue
998       [["mkdir_p"; "/new/foo/bar"];
999        ["is_dir"; "/new/foo/bar"]];
1000     InitBasicFS, Always, TestOutputTrue
1001       [["mkdir_p"; "/new/foo/bar"];
1002        ["is_dir"; "/new/foo"]];
1003     InitBasicFS, Always, TestOutputTrue
1004       [["mkdir_p"; "/new/foo/bar"];
1005        ["is_dir"; "/new"]]],
1006    "create a directory and parents",
1007    "\
1008 Create a directory named C<path>, creating any parent directories
1009 as necessary.  This is like the C<mkdir -p> shell command.");
1010
1011   ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1012    [], (* XXX Need stat command to test *)
1013    "change file mode",
1014    "\
1015 Change the mode (permissions) of C<path> to C<mode>.  Only
1016 numeric modes are supported.");
1017
1018   ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1019    [], (* XXX Need stat command to test *)
1020    "change file owner and group",
1021    "\
1022 Change the file owner to C<owner> and group to C<group>.
1023
1024 Only numeric uid and gid are supported.  If you want to use
1025 names, you will need to locate and parse the password file
1026 yourself (Augeas support makes this relatively easy).");
1027
1028   ("exists", (RBool "existsflag", [String "path"]), 36, [],
1029    [InitBasicFS, Always, TestOutputTrue (
1030       [["touch"; "/new"];
1031        ["exists"; "/new"]]);
1032     InitBasicFS, Always, TestOutputTrue (
1033       [["mkdir"; "/new"];
1034        ["exists"; "/new"]])],
1035    "test if file or directory exists",
1036    "\
1037 This returns C<true> if and only if there is a file, directory
1038 (or anything) with the given C<path> name.
1039
1040 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1041
1042   ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1043    [InitBasicFS, Always, TestOutputTrue (
1044       [["touch"; "/new"];
1045        ["is_file"; "/new"]]);
1046     InitBasicFS, Always, TestOutputFalse (
1047       [["mkdir"; "/new"];
1048        ["is_file"; "/new"]])],
1049    "test if file exists",
1050    "\
1051 This returns C<true> if and only if there is a file
1052 with the given C<path> name.  Note that it returns false for
1053 other objects like directories.
1054
1055 See also C<guestfs_stat>.");
1056
1057   ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1058    [InitBasicFS, Always, TestOutputFalse (
1059       [["touch"; "/new"];
1060        ["is_dir"; "/new"]]);
1061     InitBasicFS, Always, TestOutputTrue (
1062       [["mkdir"; "/new"];
1063        ["is_dir"; "/new"]])],
1064    "test if file exists",
1065    "\
1066 This returns C<true> if and only if there is a directory
1067 with the given C<path> name.  Note that it returns false for
1068 other objects like files.
1069
1070 See also C<guestfs_stat>.");
1071
1072   ("pvcreate", (RErr, [String "device"]), 39, [],
1073    [InitEmpty, Always, TestOutputList (
1074       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1075        ["pvcreate"; "/dev/sda1"];
1076        ["pvcreate"; "/dev/sda2"];
1077        ["pvcreate"; "/dev/sda3"];
1078        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1079    "create an LVM physical volume",
1080    "\
1081 This creates an LVM physical volume on the named C<device>,
1082 where C<device> should usually be a partition name such
1083 as C</dev/sda1>.");
1084
1085   ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1086    [InitEmpty, Always, TestOutputList (
1087       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1088        ["pvcreate"; "/dev/sda1"];
1089        ["pvcreate"; "/dev/sda2"];
1090        ["pvcreate"; "/dev/sda3"];
1091        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1092        ["vgcreate"; "VG2"; "/dev/sda3"];
1093        ["vgs"]], ["VG1"; "VG2"])],
1094    "create an LVM volume group",
1095    "\
1096 This creates an LVM volume group called C<volgroup>
1097 from the non-empty list of physical volumes C<physvols>.");
1098
1099   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1100    [InitEmpty, Always, TestOutputList (
1101       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1102        ["pvcreate"; "/dev/sda1"];
1103        ["pvcreate"; "/dev/sda2"];
1104        ["pvcreate"; "/dev/sda3"];
1105        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1106        ["vgcreate"; "VG2"; "/dev/sda3"];
1107        ["lvcreate"; "LV1"; "VG1"; "50"];
1108        ["lvcreate"; "LV2"; "VG1"; "50"];
1109        ["lvcreate"; "LV3"; "VG2"; "50"];
1110        ["lvcreate"; "LV4"; "VG2"; "50"];
1111        ["lvcreate"; "LV5"; "VG2"; "50"];
1112        ["lvs"]],
1113       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1114        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1115    "create an LVM volume group",
1116    "\
1117 This creates an LVM volume group called C<logvol>
1118 on the volume group C<volgroup>, with C<size> megabytes.");
1119
1120   ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1121    [InitEmpty, Always, TestOutput (
1122       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1123        ["mkfs"; "ext2"; "/dev/sda1"];
1124        ["mount"; "/dev/sda1"; "/"];
1125        ["write_file"; "/new"; "new file contents"; "0"];
1126        ["cat"; "/new"]], "new file contents")],
1127    "make a filesystem",
1128    "\
1129 This creates a filesystem on C<device> (usually a partition
1130 or LVM logical volume).  The filesystem type is C<fstype>, for
1131 example C<ext3>.");
1132
1133   ("sfdisk", (RErr, [String "device";
1134                      Int "cyls"; Int "heads"; Int "sectors";
1135                      StringList "lines"]), 43, [DangerWillRobinson],
1136    [],
1137    "create partitions on a block device",
1138    "\
1139 This is a direct interface to the L<sfdisk(8)> program for creating
1140 partitions on block devices.
1141
1142 C<device> should be a block device, for example C</dev/sda>.
1143
1144 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1145 and sectors on the device, which are passed directly to sfdisk as
1146 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1147 of these, then the corresponding parameter is omitted.  Usually for
1148 'large' disks, you can just pass C<0> for these, but for small
1149 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1150 out the right geometry and you will need to tell it.
1151
1152 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1153 information refer to the L<sfdisk(8)> manpage.
1154
1155 To create a single partition occupying the whole disk, you would
1156 pass C<lines> as a single element list, when the single element being
1157 the string C<,> (comma).
1158
1159 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1160
1161   ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1162    [InitBasicFS, Always, TestOutput (
1163       [["write_file"; "/new"; "new file contents"; "0"];
1164        ["cat"; "/new"]], "new file contents");
1165     InitBasicFS, Always, TestOutput (
1166       [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1167        ["cat"; "/new"]], "\nnew file contents\n");
1168     InitBasicFS, Always, TestOutput (
1169       [["write_file"; "/new"; "\n\n"; "0"];
1170        ["cat"; "/new"]], "\n\n");
1171     InitBasicFS, Always, TestOutput (
1172       [["write_file"; "/new"; ""; "0"];
1173        ["cat"; "/new"]], "");
1174     InitBasicFS, Always, TestOutput (
1175       [["write_file"; "/new"; "\n\n\n"; "0"];
1176        ["cat"; "/new"]], "\n\n\n");
1177     InitBasicFS, Always, TestOutput (
1178       [["write_file"; "/new"; "\n"; "0"];
1179        ["cat"; "/new"]], "\n")],
1180    "create a file",
1181    "\
1182 This call creates a file called C<path>.  The contents of the
1183 file is the string C<content> (which can contain any 8 bit data),
1184 with length C<size>.
1185
1186 As a special case, if C<size> is C<0>
1187 then the length is calculated using C<strlen> (so in this case
1188 the content cannot contain embedded ASCII NULs).
1189
1190 I<NB.> Owing to a bug, writing content containing ASCII NUL
1191 characters does I<not> work, even if the length is specified.
1192 We hope to resolve this bug in a future version.  In the meantime
1193 use C<guestfs_upload>.");
1194
1195   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1196    [InitEmpty, Always, TestOutputList (
1197       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1198        ["mkfs"; "ext2"; "/dev/sda1"];
1199        ["mount"; "/dev/sda1"; "/"];
1200        ["mounts"]], ["/dev/sda1"]);
1201     InitEmpty, Always, TestOutputList (
1202       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1203        ["mkfs"; "ext2"; "/dev/sda1"];
1204        ["mount"; "/dev/sda1"; "/"];
1205        ["umount"; "/"];
1206        ["mounts"]], [])],
1207    "unmount a filesystem",
1208    "\
1209 This unmounts the given filesystem.  The filesystem may be
1210 specified either by its mountpoint (path) or the device which
1211 contains the filesystem.");
1212
1213   ("mounts", (RStringList "devices", []), 46, [],
1214    [InitBasicFS, Always, TestOutputList (
1215       [["mounts"]], ["/dev/sda1"])],
1216    "show mounted filesystems",
1217    "\
1218 This returns the list of currently mounted filesystems.  It returns
1219 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1220
1221 Some internal mounts are not shown.");
1222
1223   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1224    [InitBasicFS, Always, TestOutputList (
1225       [["umount_all"];
1226        ["mounts"]], []);
1227     (* check that umount_all can unmount nested mounts correctly: *)
1228     InitEmpty, Always, TestOutputList (
1229       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ",10 ,20 ,"];
1230        ["mkfs"; "ext2"; "/dev/sda1"];
1231        ["mkfs"; "ext2"; "/dev/sda2"];
1232        ["mkfs"; "ext2"; "/dev/sda3"];
1233        ["mount"; "/dev/sda1"; "/"];
1234        ["mkdir"; "/mp1"];
1235        ["mount"; "/dev/sda2"; "/mp1"];
1236        ["mkdir"; "/mp1/mp2"];
1237        ["mount"; "/dev/sda3"; "/mp1/mp2"];
1238        ["mkdir"; "/mp1/mp2/mp3"];
1239        ["umount_all"];
1240        ["mounts"]], [])],
1241    "unmount all filesystems",
1242    "\
1243 This unmounts all mounted filesystems.
1244
1245 Some internal mounts are not unmounted by this call.");
1246
1247   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1248    [],
1249    "remove all LVM LVs, VGs and PVs",
1250    "\
1251 This command removes all LVM logical volumes, volume groups
1252 and physical volumes.");
1253
1254   ("file", (RString "description", [String "path"]), 49, [],
1255    [InitBasicFS, Always, TestOutput (
1256       [["touch"; "/new"];
1257        ["file"; "/new"]], "empty");
1258     InitBasicFS, Always, TestOutput (
1259       [["write_file"; "/new"; "some content\n"; "0"];
1260        ["file"; "/new"]], "ASCII text");
1261     InitBasicFS, Always, TestLastFail (
1262       [["file"; "/nofile"]])],
1263    "determine file type",
1264    "\
1265 This call uses the standard L<file(1)> command to determine
1266 the type or contents of the file.  This also works on devices,
1267 for example to find out whether a partition contains a filesystem.
1268
1269 The exact command which runs is C<file -bsL path>.  Note in
1270 particular that the filename is not prepended to the output
1271 (the C<-b> option).");
1272
1273   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1274    [InitBasicFS, Always, TestOutput (
1275       [["upload"; "test-command"; "/test-command"];
1276        ["chmod"; "493"; "/test-command"];
1277        ["command"; "/test-command 1"]], "Result1");
1278     InitBasicFS, Always, TestOutput (
1279       [["upload"; "test-command"; "/test-command"];
1280        ["chmod"; "493"; "/test-command"];
1281        ["command"; "/test-command 2"]], "Result2\n");
1282     InitBasicFS, Always, TestOutput (
1283       [["upload"; "test-command"; "/test-command"];
1284        ["chmod"; "493"; "/test-command"];
1285        ["command"; "/test-command 3"]], "\nResult3");
1286     InitBasicFS, Always, TestOutput (
1287       [["upload"; "test-command"; "/test-command"];
1288        ["chmod"; "493"; "/test-command"];
1289        ["command"; "/test-command 4"]], "\nResult4\n");
1290     InitBasicFS, Always, TestOutput (
1291       [["upload"; "test-command"; "/test-command"];
1292        ["chmod"; "493"; "/test-command"];
1293        ["command"; "/test-command 5"]], "\nResult5\n\n");
1294     InitBasicFS, Always, TestOutput (
1295       [["upload"; "test-command"; "/test-command"];
1296        ["chmod"; "493"; "/test-command"];
1297        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1298     InitBasicFS, Always, TestOutput (
1299       [["upload"; "test-command"; "/test-command"];
1300        ["chmod"; "493"; "/test-command"];
1301        ["command"; "/test-command 7"]], "");
1302     InitBasicFS, Always, TestOutput (
1303       [["upload"; "test-command"; "/test-command"];
1304        ["chmod"; "493"; "/test-command"];
1305        ["command"; "/test-command 8"]], "\n");
1306     InitBasicFS, Always, TestOutput (
1307       [["upload"; "test-command"; "/test-command"];
1308        ["chmod"; "493"; "/test-command"];
1309        ["command"; "/test-command 9"]], "\n\n");
1310     InitBasicFS, Always, TestOutput (
1311       [["upload"; "test-command"; "/test-command"];
1312        ["chmod"; "493"; "/test-command"];
1313        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1314     InitBasicFS, Always, TestOutput (
1315       [["upload"; "test-command"; "/test-command"];
1316        ["chmod"; "493"; "/test-command"];
1317        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1318     InitBasicFS, Always, TestLastFail (
1319       [["upload"; "test-command"; "/test-command"];
1320        ["chmod"; "493"; "/test-command"];
1321        ["command"; "/test-command"]])],
1322    "run a command from the guest filesystem",
1323    "\
1324 This call runs a command from the guest filesystem.  The
1325 filesystem must be mounted, and must contain a compatible
1326 operating system (ie. something Linux, with the same
1327 or compatible processor architecture).
1328
1329 The single parameter is an argv-style list of arguments.
1330 The first element is the name of the program to run.
1331 Subsequent elements are parameters.  The list must be
1332 non-empty (ie. must contain a program name).
1333
1334 The return value is anything printed to I<stdout> by
1335 the command.
1336
1337 If the command returns a non-zero exit status, then
1338 this function returns an error message.  The error message
1339 string is the content of I<stderr> from the command.
1340
1341 The C<$PATH> environment variable will contain at least
1342 C</usr/bin> and C</bin>.  If you require a program from
1343 another location, you should provide the full path in the
1344 first parameter.
1345
1346 Shared libraries and data files required by the program
1347 must be available on filesystems which are mounted in the
1348 correct places.  It is the caller's responsibility to ensure
1349 all filesystems that are needed are mounted at the right
1350 locations.");
1351
1352   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1353    [InitBasicFS, Always, TestOutputList (
1354       [["upload"; "test-command"; "/test-command"];
1355        ["chmod"; "493"; "/test-command"];
1356        ["command_lines"; "/test-command 1"]], ["Result1"]);
1357     InitBasicFS, Always, TestOutputList (
1358       [["upload"; "test-command"; "/test-command"];
1359        ["chmod"; "493"; "/test-command"];
1360        ["command_lines"; "/test-command 2"]], ["Result2"]);
1361     InitBasicFS, Always, TestOutputList (
1362       [["upload"; "test-command"; "/test-command"];
1363        ["chmod"; "493"; "/test-command"];
1364        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1365     InitBasicFS, Always, TestOutputList (
1366       [["upload"; "test-command"; "/test-command"];
1367        ["chmod"; "493"; "/test-command"];
1368        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1369     InitBasicFS, Always, TestOutputList (
1370       [["upload"; "test-command"; "/test-command"];
1371        ["chmod"; "493"; "/test-command"];
1372        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1373     InitBasicFS, Always, TestOutputList (
1374       [["upload"; "test-command"; "/test-command"];
1375        ["chmod"; "493"; "/test-command"];
1376        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1377     InitBasicFS, Always, TestOutputList (
1378       [["upload"; "test-command"; "/test-command"];
1379        ["chmod"; "493"; "/test-command"];
1380        ["command_lines"; "/test-command 7"]], []);
1381     InitBasicFS, Always, TestOutputList (
1382       [["upload"; "test-command"; "/test-command"];
1383        ["chmod"; "493"; "/test-command"];
1384        ["command_lines"; "/test-command 8"]], [""]);
1385     InitBasicFS, Always, TestOutputList (
1386       [["upload"; "test-command"; "/test-command"];
1387        ["chmod"; "493"; "/test-command"];
1388        ["command_lines"; "/test-command 9"]], ["";""]);
1389     InitBasicFS, Always, TestOutputList (
1390       [["upload"; "test-command"; "/test-command"];
1391        ["chmod"; "493"; "/test-command"];
1392        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1393     InitBasicFS, Always, TestOutputList (
1394       [["upload"; "test-command"; "/test-command"];
1395        ["chmod"; "493"; "/test-command"];
1396        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1397    "run a command, returning lines",
1398    "\
1399 This is the same as C<guestfs_command>, but splits the
1400 result into a list of lines.");
1401
1402   ("stat", (RStat "statbuf", [String "path"]), 52, [],
1403    [InitBasicFS, Always, TestOutputStruct (
1404       [["touch"; "/new"];
1405        ["stat"; "/new"]], [CompareWithInt ("size", 0)])],
1406    "get file information",
1407    "\
1408 Returns file information for the given C<path>.
1409
1410 This is the same as the C<stat(2)> system call.");
1411
1412   ("lstat", (RStat "statbuf", [String "path"]), 53, [],
1413    [InitBasicFS, Always, TestOutputStruct (
1414       [["touch"; "/new"];
1415        ["lstat"; "/new"]], [CompareWithInt ("size", 0)])],
1416    "get file information for a symbolic link",
1417    "\
1418 Returns file information for the given C<path>.
1419
1420 This is the same as C<guestfs_stat> except that if C<path>
1421 is a symbolic link, then the link is stat-ed, not the file it
1422 refers to.
1423
1424 This is the same as the C<lstat(2)> system call.");
1425
1426   ("statvfs", (RStatVFS "statbuf", [String "path"]), 54, [],
1427    [InitBasicFS, Always, TestOutputStruct (
1428       [["statvfs"; "/"]], [CompareWithInt ("bfree", 487702);
1429                            CompareWithInt ("blocks", 490020);
1430                            CompareWithInt ("bsize", 1024)])],
1431    "get file system statistics",
1432    "\
1433 Returns file system statistics for any mounted file system.
1434 C<path> should be a file or directory in the mounted file system
1435 (typically it is the mount point itself, but it doesn't need to be).
1436
1437 This is the same as the C<statvfs(2)> system call.");
1438
1439   ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1440    [], (* XXX test *)
1441    "get ext2/ext3/ext4 superblock details",
1442    "\
1443 This returns the contents of the ext2, ext3 or ext4 filesystem
1444 superblock on C<device>.
1445
1446 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
1447 manpage for more details.  The list of fields returned isn't
1448 clearly defined, and depends on both the version of C<tune2fs>
1449 that libguestfs was built against, and the filesystem itself.");
1450
1451   ("blockdev_setro", (RErr, [String "device"]), 56, [],
1452    [InitEmpty, Always, TestOutputTrue (
1453       [["blockdev_setro"; "/dev/sda"];
1454        ["blockdev_getro"; "/dev/sda"]])],
1455    "set block device to read-only",
1456    "\
1457 Sets the block device named C<device> to read-only.
1458
1459 This uses the L<blockdev(8)> command.");
1460
1461   ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1462    [InitEmpty, Always, TestOutputFalse (
1463       [["blockdev_setrw"; "/dev/sda"];
1464        ["blockdev_getro"; "/dev/sda"]])],
1465    "set block device to read-write",
1466    "\
1467 Sets the block device named C<device> to read-write.
1468
1469 This uses the L<blockdev(8)> command.");
1470
1471   ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1472    [InitEmpty, Always, TestOutputTrue (
1473       [["blockdev_setro"; "/dev/sda"];
1474        ["blockdev_getro"; "/dev/sda"]])],
1475    "is block device set to read-only",
1476    "\
1477 Returns a boolean indicating if the block device is read-only
1478 (true if read-only, false if not).
1479
1480 This uses the L<blockdev(8)> command.");
1481
1482   ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1483    [InitEmpty, Always, TestOutputInt (
1484       [["blockdev_getss"; "/dev/sda"]], 512)],
1485    "get sectorsize of block device",
1486    "\
1487 This returns the size of sectors on a block device.
1488 Usually 512, but can be larger for modern devices.
1489
1490 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1491 for that).
1492
1493 This uses the L<blockdev(8)> command.");
1494
1495   ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1496    [InitEmpty, Always, TestOutputInt (
1497       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1498    "get blocksize of block device",
1499    "\
1500 This returns the block size of a device.
1501
1502 (Note this is different from both I<size in blocks> and
1503 I<filesystem block size>).
1504
1505 This uses the L<blockdev(8)> command.");
1506
1507   ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1508    [], (* XXX test *)
1509    "set blocksize of block device",
1510    "\
1511 This sets the block size of a device.
1512
1513 (Note this is different from both I<size in blocks> and
1514 I<filesystem block size>).
1515
1516 This uses the L<blockdev(8)> command.");
1517
1518   ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1519    [InitEmpty, Always, TestOutputInt (
1520       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1521    "get total size of device in 512-byte sectors",
1522    "\
1523 This returns the size of the device in units of 512-byte sectors
1524 (even if the sectorsize isn't 512 bytes ... weird).
1525
1526 See also C<guestfs_blockdev_getss> for the real sector size of
1527 the device, and C<guestfs_blockdev_getsize64> for the more
1528 useful I<size in bytes>.
1529
1530 This uses the L<blockdev(8)> command.");
1531
1532   ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1533    [InitEmpty, Always, TestOutputInt (
1534       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1535    "get total size of device in bytes",
1536    "\
1537 This returns the size of the device in bytes.
1538
1539 See also C<guestfs_blockdev_getsz>.
1540
1541 This uses the L<blockdev(8)> command.");
1542
1543   ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1544    [InitEmpty, Always, TestRun
1545       [["blockdev_flushbufs"; "/dev/sda"]]],
1546    "flush device buffers",
1547    "\
1548 This tells the kernel to flush internal buffers associated
1549 with C<device>.
1550
1551 This uses the L<blockdev(8)> command.");
1552
1553   ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1554    [InitEmpty, Always, TestRun
1555       [["blockdev_rereadpt"; "/dev/sda"]]],
1556    "reread partition table",
1557    "\
1558 Reread the partition table on C<device>.
1559
1560 This uses the L<blockdev(8)> command.");
1561
1562   ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1563    [InitBasicFS, Always, TestOutput (
1564       (* Pick a file from cwd which isn't likely to change. *)
1565     [["upload"; "COPYING.LIB"; "/COPYING.LIB"];
1566      ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1567    "upload a file from the local machine",
1568    "\
1569 Upload local file C<filename> to C<remotefilename> on the
1570 filesystem.
1571
1572 C<filename> can also be a named pipe.
1573
1574 See also C<guestfs_download>.");
1575
1576   ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1577    [InitBasicFS, Always, TestOutput (
1578       (* Pick a file from cwd which isn't likely to change. *)
1579     [["upload"; "COPYING.LIB"; "/COPYING.LIB"];
1580      ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1581      ["upload"; "testdownload.tmp"; "/upload"];
1582      ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1583    "download a file to the local machine",
1584    "\
1585 Download file C<remotefilename> and save it as C<filename>
1586 on the local machine.
1587
1588 C<filename> can also be a named pipe.
1589
1590 See also C<guestfs_upload>, C<guestfs_cat>.");
1591
1592   ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1593    [InitBasicFS, Always, TestOutput (
1594       [["write_file"; "/new"; "test\n"; "0"];
1595        ["checksum"; "crc"; "/new"]], "935282863");
1596     InitBasicFS, Always, TestLastFail (
1597       [["checksum"; "crc"; "/new"]]);
1598     InitBasicFS, Always, TestOutput (
1599       [["write_file"; "/new"; "test\n"; "0"];
1600        ["checksum"; "md5"; "/new"]], "d8e8fca2dc0f896fd7cb4cb0031ba249");
1601     InitBasicFS, Always, TestOutput (
1602       [["write_file"; "/new"; "test\n"; "0"];
1603        ["checksum"; "sha1"; "/new"]], "4e1243bd22c66e76c2ba9eddc1f91394e57f9f83");
1604     InitBasicFS, Always, TestOutput (
1605       [["write_file"; "/new"; "test\n"; "0"];
1606        ["checksum"; "sha224"; "/new"]], "52f1bf093f4b7588726035c176c0cdb4376cfea53819f1395ac9e6ec");
1607     InitBasicFS, Always, TestOutput (
1608       [["write_file"; "/new"; "test\n"; "0"];
1609        ["checksum"; "sha256"; "/new"]], "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2");
1610     InitBasicFS, Always, TestOutput (
1611       [["write_file"; "/new"; "test\n"; "0"];
1612        ["checksum"; "sha384"; "/new"]], "109bb6b5b6d5547c1ce03c7a8bd7d8f80c1cb0957f50c4f7fda04692079917e4f9cad52b878f3d8234e1a170b154b72d");
1613     InitBasicFS, Always, TestOutput (
1614       [["write_file"; "/new"; "test\n"; "0"];
1615        ["checksum"; "sha512"; "/new"]], "0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123")],
1616    "compute MD5, SHAx or CRC checksum of file",
1617    "\
1618 This call computes the MD5, SHAx or CRC checksum of the
1619 file named C<path>.
1620
1621 The type of checksum to compute is given by the C<csumtype>
1622 parameter which must have one of the following values:
1623
1624 =over 4
1625
1626 =item C<crc>
1627
1628 Compute the cyclic redundancy check (CRC) specified by POSIX
1629 for the C<cksum> command.
1630
1631 =item C<md5>
1632
1633 Compute the MD5 hash (using the C<md5sum> program).
1634
1635 =item C<sha1>
1636
1637 Compute the SHA1 hash (using the C<sha1sum> program).
1638
1639 =item C<sha224>
1640
1641 Compute the SHA224 hash (using the C<sha224sum> program).
1642
1643 =item C<sha256>
1644
1645 Compute the SHA256 hash (using the C<sha256sum> program).
1646
1647 =item C<sha384>
1648
1649 Compute the SHA384 hash (using the C<sha384sum> program).
1650
1651 =item C<sha512>
1652
1653 Compute the SHA512 hash (using the C<sha512sum> program).
1654
1655 =back
1656
1657 The checksum is returned as a printable string.");
1658
1659   ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1660    [InitBasicFS, Always, TestOutput (
1661       [["tar_in"; "../images/helloworld.tar"; "/"];
1662        ["cat"; "/hello"]], "hello\n")],
1663    "unpack tarfile to directory",
1664    "\
1665 This command uploads and unpacks local file C<tarfile> (an
1666 I<uncompressed> tar file) into C<directory>.
1667
1668 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1669
1670   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1671    [],
1672    "pack directory into tarfile",
1673    "\
1674 This command packs the contents of C<directory> and downloads
1675 it to local file C<tarfile>.
1676
1677 To download a compressed tarball, use C<guestfs_tgz_out>.");
1678
1679   ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1680    [InitBasicFS, Always, TestOutput (
1681       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1682        ["cat"; "/hello"]], "hello\n")],
1683    "unpack compressed tarball to directory",
1684    "\
1685 This command uploads and unpacks local file C<tarball> (a
1686 I<gzip compressed> tar file) into C<directory>.
1687
1688 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1689
1690   ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1691    [],
1692    "pack directory into compressed tarball",
1693    "\
1694 This command packs the contents of C<directory> and downloads
1695 it to local file C<tarball>.
1696
1697 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1698
1699   ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1700    [InitBasicFS, Always, TestLastFail (
1701       [["umount"; "/"];
1702        ["mount_ro"; "/dev/sda1"; "/"];
1703        ["touch"; "/new"]]);
1704     InitBasicFS, Always, TestOutput (
1705       [["write_file"; "/new"; "data"; "0"];
1706        ["umount"; "/"];
1707        ["mount_ro"; "/dev/sda1"; "/"];
1708        ["cat"; "/new"]], "data")],
1709    "mount a guest disk, read-only",
1710    "\
1711 This is the same as the C<guestfs_mount> command, but it
1712 mounts the filesystem with the read-only (I<-o ro>) flag.");
1713
1714   ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1715    [],
1716    "mount a guest disk with mount options",
1717    "\
1718 This is the same as the C<guestfs_mount> command, but it
1719 allows you to set the mount options as for the
1720 L<mount(8)> I<-o> flag.");
1721
1722   ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1723    [],
1724    "mount a guest disk with mount options and vfstype",
1725    "\
1726 This is the same as the C<guestfs_mount> command, but it
1727 allows you to set both the mount options and the vfstype
1728 as for the L<mount(8)> I<-o> and I<-t> flags.");
1729
1730   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1731    [],
1732    "debugging and internals",
1733    "\
1734 The C<guestfs_debug> command exposes some internals of
1735 C<guestfsd> (the guestfs daemon) that runs inside the
1736 qemu subprocess.
1737
1738 There is no comprehensive help for this command.  You have
1739 to look at the file C<daemon/debug.c> in the libguestfs source
1740 to find out what you can do.");
1741
1742   ("lvremove", (RErr, [String "device"]), 77, [],
1743    [InitEmpty, Always, TestOutputList (
1744       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1745        ["pvcreate"; "/dev/sda1"];
1746        ["vgcreate"; "VG"; "/dev/sda1"];
1747        ["lvcreate"; "LV1"; "VG"; "50"];
1748        ["lvcreate"; "LV2"; "VG"; "50"];
1749        ["lvremove"; "/dev/VG/LV1"];
1750        ["lvs"]], ["/dev/VG/LV2"]);
1751     InitEmpty, Always, TestOutputList (
1752       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1753        ["pvcreate"; "/dev/sda1"];
1754        ["vgcreate"; "VG"; "/dev/sda1"];
1755        ["lvcreate"; "LV1"; "VG"; "50"];
1756        ["lvcreate"; "LV2"; "VG"; "50"];
1757        ["lvremove"; "/dev/VG"];
1758        ["lvs"]], []);
1759     InitEmpty, Always, TestOutputList (
1760       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1761        ["pvcreate"; "/dev/sda1"];
1762        ["vgcreate"; "VG"; "/dev/sda1"];
1763        ["lvcreate"; "LV1"; "VG"; "50"];
1764        ["lvcreate"; "LV2"; "VG"; "50"];
1765        ["lvremove"; "/dev/VG"];
1766        ["vgs"]], ["VG"])],
1767    "remove an LVM logical volume",
1768    "\
1769 Remove an LVM logical volume C<device>, where C<device> is
1770 the path to the LV, such as C</dev/VG/LV>.
1771
1772 You can also remove all LVs in a volume group by specifying
1773 the VG name, C</dev/VG>.");
1774
1775   ("vgremove", (RErr, [String "vgname"]), 78, [],
1776    [InitEmpty, Always, TestOutputList (
1777       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1778        ["pvcreate"; "/dev/sda1"];
1779        ["vgcreate"; "VG"; "/dev/sda1"];
1780        ["lvcreate"; "LV1"; "VG"; "50"];
1781        ["lvcreate"; "LV2"; "VG"; "50"];
1782        ["vgremove"; "VG"];
1783        ["lvs"]], []);
1784     InitEmpty, Always, TestOutputList (
1785       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1786        ["pvcreate"; "/dev/sda1"];
1787        ["vgcreate"; "VG"; "/dev/sda1"];
1788        ["lvcreate"; "LV1"; "VG"; "50"];
1789        ["lvcreate"; "LV2"; "VG"; "50"];
1790        ["vgremove"; "VG"];
1791        ["vgs"]], [])],
1792    "remove an LVM volume group",
1793    "\
1794 Remove an LVM volume group C<vgname>, (for example C<VG>).
1795
1796 This also forcibly removes all logical volumes in the volume
1797 group (if any).");
1798
1799   ("pvremove", (RErr, [String "device"]), 79, [],
1800    [InitEmpty, Always, TestOutputList (
1801       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1802        ["pvcreate"; "/dev/sda1"];
1803        ["vgcreate"; "VG"; "/dev/sda1"];
1804        ["lvcreate"; "LV1"; "VG"; "50"];
1805        ["lvcreate"; "LV2"; "VG"; "50"];
1806        ["vgremove"; "VG"];
1807        ["pvremove"; "/dev/sda1"];
1808        ["lvs"]], []);
1809     InitEmpty, Always, TestOutputList (
1810       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1811        ["pvcreate"; "/dev/sda1"];
1812        ["vgcreate"; "VG"; "/dev/sda1"];
1813        ["lvcreate"; "LV1"; "VG"; "50"];
1814        ["lvcreate"; "LV2"; "VG"; "50"];
1815        ["vgremove"; "VG"];
1816        ["pvremove"; "/dev/sda1"];
1817        ["vgs"]], []);
1818     InitEmpty, Always, TestOutputList (
1819       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
1820        ["pvcreate"; "/dev/sda1"];
1821        ["vgcreate"; "VG"; "/dev/sda1"];
1822        ["lvcreate"; "LV1"; "VG"; "50"];
1823        ["lvcreate"; "LV2"; "VG"; "50"];
1824        ["vgremove"; "VG"];
1825        ["pvremove"; "/dev/sda1"];
1826        ["pvs"]], [])],
1827    "remove an LVM physical volume",
1828    "\
1829 This wipes a physical volume C<device> so that LVM will no longer
1830 recognise it.
1831
1832 The implementation uses the C<pvremove> command which refuses to
1833 wipe physical volumes that contain any volume groups, so you have
1834 to remove those first.");
1835
1836   ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
1837    [InitBasicFS, Always, TestOutput (
1838       [["set_e2label"; "/dev/sda1"; "testlabel"];
1839        ["get_e2label"; "/dev/sda1"]], "testlabel")],
1840    "set the ext2/3/4 filesystem label",
1841    "\
1842 This sets the ext2/3/4 filesystem label of the filesystem on
1843 C<device> to C<label>.  Filesystem labels are limited to
1844 16 characters.
1845
1846 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
1847 to return the existing label on a filesystem.");
1848
1849   ("get_e2label", (RString "label", [String "device"]), 81, [],
1850    [],
1851    "get the ext2/3/4 filesystem label",
1852    "\
1853 This returns the ext2/3/4 filesystem label of the filesystem on
1854 C<device>.");
1855
1856   ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
1857    [InitBasicFS, Always, TestOutput (
1858       [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
1859        ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
1860     InitBasicFS, Always, TestOutput (
1861       [["set_e2uuid"; "/dev/sda1"; "clear"];
1862        ["get_e2uuid"; "/dev/sda1"]], "");
1863     (* We can't predict what UUIDs will be, so just check the commands run. *)
1864     InitBasicFS, Always, TestRun (
1865       [["set_e2uuid"; "/dev/sda1"; "random"]]);
1866     InitBasicFS, Always, TestRun (
1867       [["set_e2uuid"; "/dev/sda1"; "time"]])],
1868    "set the ext2/3/4 filesystem UUID",
1869    "\
1870 This sets the ext2/3/4 filesystem UUID of the filesystem on
1871 C<device> to C<uuid>.  The format of the UUID and alternatives
1872 such as C<clear>, C<random> and C<time> are described in the
1873 L<tune2fs(8)> manpage.
1874
1875 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
1876 to return the existing UUID of a filesystem.");
1877
1878   ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
1879    [],
1880    "get the ext2/3/4 filesystem UUID",
1881    "\
1882 This returns the ext2/3/4 filesystem UUID of the filesystem on
1883 C<device>.");
1884
1885   ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
1886    [InitBasicFS, Always, TestOutputInt (
1887       [["umount"; "/dev/sda1"];
1888        ["fsck"; "ext2"; "/dev/sda1"]], 0);
1889     InitBasicFS, Always, TestOutputInt (
1890       [["umount"; "/dev/sda1"];
1891        ["zero"; "/dev/sda1"];
1892        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
1893    "run the filesystem checker",
1894    "\
1895 This runs the filesystem checker (fsck) on C<device> which
1896 should have filesystem type C<fstype>.
1897
1898 The returned integer is the status.  See L<fsck(8)> for the
1899 list of status codes from C<fsck>.
1900
1901 Notes:
1902
1903 =over 4
1904
1905 =item *
1906
1907 Multiple status codes can be summed together.
1908
1909 =item *
1910
1911 A non-zero return code can mean \"success\", for example if
1912 errors have been corrected on the filesystem.
1913
1914 =item *
1915
1916 Checking or repairing NTFS volumes is not supported
1917 (by linux-ntfs).
1918
1919 =back
1920
1921 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
1922
1923   ("zero", (RErr, [String "device"]), 85, [],
1924    [InitBasicFS, Always, TestOutput (
1925       [["umount"; "/dev/sda1"];
1926        ["zero"; "/dev/sda1"];
1927        ["file"; "/dev/sda1"]], "data")],
1928    "write zeroes to the device",
1929    "\
1930 This command writes zeroes over the first few blocks of C<device>.
1931
1932 How many blocks are zeroed isn't specified (but it's I<not> enough
1933 to securely wipe the device).  It should be sufficient to remove
1934 any partition tables, filesystem superblocks and so on.");
1935
1936   ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
1937    [InitBasicFS, Always, TestOutputTrue (
1938       [["grub_install"; "/"; "/dev/sda1"];
1939        ["is_dir"; "/boot"]])],
1940    "install GRUB",
1941    "\
1942 This command installs GRUB (the Grand Unified Bootloader) on
1943 C<device>, with the root directory being C<root>.");
1944
1945   ("cp", (RErr, [String "src"; String "dest"]), 87, [],
1946    [InitBasicFS, Always, TestOutput (
1947       [["write_file"; "/old"; "file content"; "0"];
1948        ["cp"; "/old"; "/new"];
1949        ["cat"; "/new"]], "file content");
1950     InitBasicFS, Always, TestOutputTrue (
1951       [["write_file"; "/old"; "file content"; "0"];
1952        ["cp"; "/old"; "/new"];
1953        ["is_file"; "/old"]]);
1954     InitBasicFS, Always, TestOutput (
1955       [["write_file"; "/old"; "file content"; "0"];
1956        ["mkdir"; "/dir"];
1957        ["cp"; "/old"; "/dir/new"];
1958        ["cat"; "/dir/new"]], "file content")],
1959    "copy a file",
1960    "\
1961 This copies a file from C<src> to C<dest> where C<dest> is
1962 either a destination filename or destination directory.");
1963
1964   ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
1965    [InitBasicFS, Always, TestOutput (
1966       [["mkdir"; "/olddir"];
1967        ["mkdir"; "/newdir"];
1968        ["write_file"; "/olddir/file"; "file content"; "0"];
1969        ["cp_a"; "/olddir"; "/newdir"];
1970        ["cat"; "/newdir/olddir/file"]], "file content")],
1971    "copy a file or directory recursively",
1972    "\
1973 This copies a file or directory from C<src> to C<dest>
1974 recursively using the C<cp -a> command.");
1975
1976   ("mv", (RErr, [String "src"; String "dest"]), 89, [],
1977    [InitBasicFS, Always, TestOutput (
1978       [["write_file"; "/old"; "file content"; "0"];
1979        ["mv"; "/old"; "/new"];
1980        ["cat"; "/new"]], "file content");
1981     InitBasicFS, Always, TestOutputFalse (
1982       [["write_file"; "/old"; "file content"; "0"];
1983        ["mv"; "/old"; "/new"];
1984        ["is_file"; "/old"]])],
1985    "move a file",
1986    "\
1987 This moves a file from C<src> to C<dest> where C<dest> is
1988 either a destination filename or destination directory.");
1989
1990   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
1991    [InitEmpty, Always, TestRun (
1992       [["drop_caches"; "3"]])],
1993    "drop kernel page cache, dentries and inodes",
1994    "\
1995 This instructs the guest kernel to drop its page cache,
1996 and/or dentries and inode caches.  The parameter C<whattodrop>
1997 tells the kernel what precisely to drop, see
1998 L<http://linux-mm.org/Drop_Caches>
1999
2000 Setting C<whattodrop> to 3 should drop everything.
2001
2002 This automatically calls L<sync(2)> before the operation,
2003 so that the maximum guest memory is freed.");
2004
2005   ("dmesg", (RString "kmsgs", []), 91, [],
2006    [InitEmpty, Always, TestRun (
2007       [["dmesg"]])],
2008    "return kernel messages",
2009    "\
2010 This returns the kernel messages (C<dmesg> output) from
2011 the guest kernel.  This is sometimes useful for extended
2012 debugging of problems.
2013
2014 Another way to get the same information is to enable
2015 verbose messages with C<guestfs_set_verbose> or by setting
2016 the environment variable C<LIBGUESTFS_DEBUG=1> before
2017 running the program.");
2018
2019   ("ping_daemon", (RErr, []), 92, [],
2020    [InitEmpty, Always, TestRun (
2021       [["ping_daemon"]])],
2022    "ping the guest daemon",
2023    "\
2024 This is a test probe into the guestfs daemon running inside
2025 the qemu subprocess.  Calling this function checks that the
2026 daemon responds to the ping message, without affecting the daemon
2027 or attached block device(s) in any other way.");
2028
2029   ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2030    [InitBasicFS, Always, TestOutputTrue (
2031       [["write_file"; "/file1"; "contents of a file"; "0"];
2032        ["cp"; "/file1"; "/file2"];
2033        ["equal"; "/file1"; "/file2"]]);
2034     InitBasicFS, Always, TestOutputFalse (
2035       [["write_file"; "/file1"; "contents of a file"; "0"];
2036        ["write_file"; "/file2"; "contents of another file"; "0"];
2037        ["equal"; "/file1"; "/file2"]]);
2038     InitBasicFS, Always, TestLastFail (
2039       [["equal"; "/file1"; "/file2"]])],
2040    "test if two files have equal contents",
2041    "\
2042 This compares the two files C<file1> and C<file2> and returns
2043 true if their content is exactly equal, or false otherwise.
2044
2045 The external L<cmp(1)> program is used for the comparison.");
2046
2047   ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2048    [InitBasicFS, Always, TestOutputList (
2049       [["write_file"; "/new"; "hello\nworld\n"; "0"];
2050        ["strings"; "/new"]], ["hello"; "world"]);
2051     InitBasicFS, Always, TestOutputList (
2052       [["touch"; "/new"];
2053        ["strings"; "/new"]], [])],
2054    "print the printable strings in a file",
2055    "\
2056 This runs the L<strings(1)> command on a file and returns
2057 the list of printable strings found.");
2058
2059   ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2060    [InitBasicFS, Always, TestOutputList (
2061       [["write_file"; "/new"; "hello\nworld\n"; "0"];
2062        ["strings_e"; "b"; "/new"]], []);
2063     InitBasicFS, Disabled, TestOutputList (
2064       [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2065        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2066    "print the printable strings in a file",
2067    "\
2068 This is like the C<guestfs_strings> command, but allows you to
2069 specify the encoding.
2070
2071 See the L<strings(1)> manpage for the full list of encodings.
2072
2073 Commonly useful encodings are C<l> (lower case L) which will
2074 show strings inside Windows/x86 files.
2075
2076 The returned strings are transcoded to UTF-8.");
2077
2078   ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2079    [InitBasicFS, Always, TestOutput (
2080       [["write_file"; "/new"; "hello\nworld\n"; "12"];
2081        ["hexdump"; "/new"]], "00000000  68 65 6c 6c 6f 0a 77 6f  72 6c 64 0a              |hello.world.|\n0000000c\n")],
2082    "dump a file in hexadecimal",
2083    "\
2084 This runs C<hexdump -C> on the given C<path>.  The result is
2085 the human-readable, canonical hex dump of the file.");
2086
2087   ("zerofree", (RErr, [String "device"]), 97, [],
2088    [InitNone, Always, TestOutput (
2089       [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
2090        ["mkfs"; "ext3"; "/dev/sda1"];
2091        ["mount"; "/dev/sda1"; "/"];
2092        ["write_file"; "/new"; "test file"; "0"];
2093        ["umount"; "/dev/sda1"];
2094        ["zerofree"; "/dev/sda1"];
2095        ["mount"; "/dev/sda1"; "/"];
2096        ["cat"; "/new"]], "test file")],
2097    "zero unused inodes and disk blocks on ext2/3 filesystem",
2098    "\
2099 This runs the I<zerofree> program on C<device>.  This program
2100 claims to zero unused inodes and disk blocks on an ext2/3
2101 filesystem, thus making it possible to compress the filesystem
2102 more effectively.
2103
2104 You should B<not> run this program if the filesystem is
2105 mounted.
2106
2107 It is possible that using this program can damage the filesystem
2108 or data on the filesystem.");
2109
2110   ("pvresize", (RErr, [String "device"]), 98, [],
2111    [],
2112    "resize an LVM physical volume",
2113    "\
2114 This resizes (expands or shrinks) an existing LVM physical
2115 volume to match the new size of the underlying device.");
2116
2117   ("sfdisk_N", (RErr, [String "device"; Int "n";
2118                        Int "cyls"; Int "heads"; Int "sectors";
2119                        String "line"]), 99, [DangerWillRobinson],
2120    [],
2121    "modify a single partition on a block device",
2122    "\
2123 This runs L<sfdisk(8)> option to modify just the single
2124 partition C<n> (note: C<n> counts from 1).
2125
2126 For other parameters, see C<guestfs_sfdisk>.  You should usually
2127 pass C<0> for the cyls/heads/sectors parameters.");
2128
2129   ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2130    [],
2131    "display the partition table",
2132    "\
2133 This displays the partition table on C<device>, in the
2134 human-readable output of the L<sfdisk(8)> command.  It is
2135 not intended to be parsed.");
2136
2137   ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2138    [],
2139    "display the kernel geometry",
2140    "\
2141 This displays the kernel's idea of the geometry of C<device>.
2142
2143 The result is in human-readable format, and not designed to
2144 be parsed.");
2145
2146   ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2147    [],
2148    "display the disk geometry from the partition table",
2149    "\
2150 This displays the disk geometry of C<device> read from the
2151 partition table.  Especially in the case where the underlying
2152 block device has been resized, this can be different from the
2153 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2154
2155 The result is in human-readable format, and not designed to
2156 be parsed.");
2157
2158   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2159    [],
2160    "activate or deactivate all volume groups",
2161    "\
2162 This command activates or (if C<activate> is false) deactivates
2163 all logical volumes in all volume groups.
2164 If activated, then they are made known to the
2165 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2166 then those devices disappear.
2167
2168 This command is the same as running C<vgchange -a y|n>");
2169
2170   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2171    [],
2172    "activate or deactivate some volume groups",
2173    "\
2174 This command activates or (if C<activate> is false) deactivates
2175 all logical volumes in the listed volume groups C<volgroups>.
2176 If activated, then they are made known to the
2177 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2178 then those devices disappear.
2179
2180 This command is the same as running C<vgchange -a y|n volgroups...>
2181
2182 Note that if C<volgroups> is an empty list then B<all> volume groups
2183 are activated or deactivated.");
2184
2185   ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2186    [InitNone, Always, TestOutput (
2187     [["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
2188      ["pvcreate"; "/dev/sda1"];
2189      ["vgcreate"; "VG"; "/dev/sda1"];
2190      ["lvcreate"; "LV"; "VG"; "10"];
2191      ["mkfs"; "ext2"; "/dev/VG/LV"];
2192      ["mount"; "/dev/VG/LV"; "/"];
2193      ["write_file"; "/new"; "test content"; "0"];
2194      ["umount"; "/"];
2195      ["lvresize"; "/dev/VG/LV"; "20"];
2196      ["e2fsck_f"; "/dev/VG/LV"];
2197      ["resize2fs"; "/dev/VG/LV"];
2198      ["mount"; "/dev/VG/LV"; "/"];
2199      ["cat"; "/new"]], "test content")],
2200    "resize an LVM logical volume",
2201    "\
2202 This resizes (expands or shrinks) an existing LVM logical
2203 volume to C<mbytes>.  When reducing, data in the reduced part
2204 is lost.");
2205
2206   ("resize2fs", (RErr, [String "device"]), 106, [],
2207    [], (* lvresize tests this *)
2208    "resize an ext2/ext3 filesystem",
2209    "\
2210 This resizes an ext2 or ext3 filesystem to match the size of
2211 the underlying device.
2212
2213 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2214 on the C<device> before calling this command.  For unknown reasons
2215 C<resize2fs> sometimes gives an error about this and sometimes not.
2216 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2217 calling this function.");
2218
2219   ("find", (RStringList "names", [String "directory"]), 107, [],
2220    [InitBasicFS, Always, TestOutputList (
2221       [["find"; "/"]], ["lost+found"]);
2222     InitBasicFS, Always, TestOutputList (
2223       [["touch"; "/a"];
2224        ["mkdir"; "/b"];
2225        ["touch"; "/b/c"];
2226        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2227     InitBasicFS, Always, TestOutputList (
2228       [["mkdir_p"; "/a/b/c"];
2229        ["touch"; "/a/b/c/d"];
2230        ["find"; "/a/b/"]], ["c"; "c/d"])],
2231    "find all files and directories",
2232    "\
2233 This command lists out all files and directories, recursively,
2234 starting at C<directory>.  It is essentially equivalent to
2235 running the shell command C<find directory -print> but some
2236 post-processing happens on the output, described below.
2237
2238 This returns a list of strings I<without any prefix>.  Thus
2239 if the directory structure was:
2240
2241  /tmp/a
2242  /tmp/b
2243  /tmp/c/d
2244
2245 then the returned list from C<guestfs_find> C</tmp> would be
2246 4 elements:
2247
2248  a
2249  b
2250  c
2251  c/d
2252
2253 If C<directory> is not a directory, then this command returns
2254 an error.
2255
2256 The returned list is sorted.");
2257
2258   ("e2fsck_f", (RErr, [String "device"]), 108, [],
2259    [], (* lvresize tests this *)
2260    "check an ext2/ext3 filesystem",
2261    "\
2262 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2263 filesystem checker on C<device>, noninteractively (C<-p>),
2264 even if the filesystem appears to be clean (C<-f>).
2265
2266 This command is only needed because of C<guestfs_resize2fs>
2267 (q.v.).  Normally you should use C<guestfs_fsck>.");
2268
2269 ]
2270
2271 let all_functions = non_daemon_functions @ daemon_functions
2272
2273 (* In some places we want the functions to be displayed sorted
2274  * alphabetically, so this is useful:
2275  *)
2276 let all_functions_sorted =
2277   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
2278                compare n1 n2) all_functions
2279
2280 (* Column names and types from LVM PVs/VGs/LVs. *)
2281 let pv_cols = [
2282   "pv_name", `String;
2283   "pv_uuid", `UUID;
2284   "pv_fmt", `String;
2285   "pv_size", `Bytes;
2286   "dev_size", `Bytes;
2287   "pv_free", `Bytes;
2288   "pv_used", `Bytes;
2289   "pv_attr", `String (* XXX *);
2290   "pv_pe_count", `Int;
2291   "pv_pe_alloc_count", `Int;
2292   "pv_tags", `String;
2293   "pe_start", `Bytes;
2294   "pv_mda_count", `Int;
2295   "pv_mda_free", `Bytes;
2296 (* Not in Fedora 10:
2297   "pv_mda_size", `Bytes;
2298 *)
2299 ]
2300 let vg_cols = [
2301   "vg_name", `String;
2302   "vg_uuid", `UUID;
2303   "vg_fmt", `String;
2304   "vg_attr", `String (* XXX *);
2305   "vg_size", `Bytes;
2306   "vg_free", `Bytes;
2307   "vg_sysid", `String;
2308   "vg_extent_size", `Bytes;
2309   "vg_extent_count", `Int;
2310   "vg_free_count", `Int;
2311   "max_lv", `Int;
2312   "max_pv", `Int;
2313   "pv_count", `Int;
2314   "lv_count", `Int;
2315   "snap_count", `Int;
2316   "vg_seqno", `Int;
2317   "vg_tags", `String;
2318   "vg_mda_count", `Int;
2319   "vg_mda_free", `Bytes;
2320 (* Not in Fedora 10:
2321   "vg_mda_size", `Bytes;
2322 *)
2323 ]
2324 let lv_cols = [
2325   "lv_name", `String;
2326   "lv_uuid", `UUID;
2327   "lv_attr", `String (* XXX *);
2328   "lv_major", `Int;
2329   "lv_minor", `Int;
2330   "lv_kernel_major", `Int;
2331   "lv_kernel_minor", `Int;
2332   "lv_size", `Bytes;
2333   "seg_count", `Int;
2334   "origin", `String;
2335   "snap_percent", `OptPercent;
2336   "copy_percent", `OptPercent;
2337   "move_pv", `String;
2338   "lv_tags", `String;
2339   "mirror_log", `String;
2340   "modules", `String;
2341 ]
2342
2343 (* Column names and types from stat structures.
2344  * NB. Can't use things like 'st_atime' because glibc header files
2345  * define some of these as macros.  Ugh.
2346  *)
2347 let stat_cols = [
2348   "dev", `Int;
2349   "ino", `Int;
2350   "mode", `Int;
2351   "nlink", `Int;
2352   "uid", `Int;
2353   "gid", `Int;
2354   "rdev", `Int;
2355   "size", `Int;
2356   "blksize", `Int;
2357   "blocks", `Int;
2358   "atime", `Int;
2359   "mtime", `Int;
2360   "ctime", `Int;
2361 ]
2362 let statvfs_cols = [
2363   "bsize", `Int;
2364   "frsize", `Int;
2365   "blocks", `Int;
2366   "bfree", `Int;
2367   "bavail", `Int;
2368   "files", `Int;
2369   "ffree", `Int;
2370   "favail", `Int;
2371   "fsid", `Int;
2372   "flag", `Int;
2373   "namemax", `Int;
2374 ]
2375
2376 (* Useful functions.
2377  * Note we don't want to use any external OCaml libraries which
2378  * makes this a bit harder than it should be.
2379  *)
2380 let failwithf fs = ksprintf failwith fs
2381
2382 let replace_char s c1 c2 =
2383   let s2 = String.copy s in
2384   let r = ref false in
2385   for i = 0 to String.length s2 - 1 do
2386     if String.unsafe_get s2 i = c1 then (
2387       String.unsafe_set s2 i c2;
2388       r := true
2389     )
2390   done;
2391   if not !r then s else s2
2392
2393 let isspace c =
2394   c = ' '
2395   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
2396
2397 let triml ?(test = isspace) str =
2398   let i = ref 0 in
2399   let n = ref (String.length str) in
2400   while !n > 0 && test str.[!i]; do
2401     decr n;
2402     incr i
2403   done;
2404   if !i = 0 then str
2405   else String.sub str !i !n
2406
2407 let trimr ?(test = isspace) str =
2408   let n = ref (String.length str) in
2409   while !n > 0 && test str.[!n-1]; do
2410     decr n
2411   done;
2412   if !n = String.length str then str
2413   else String.sub str 0 !n
2414
2415 let trim ?(test = isspace) str =
2416   trimr ~test (triml ~test str)
2417
2418 let rec find s sub =
2419   let len = String.length s in
2420   let sublen = String.length sub in
2421   let rec loop i =
2422     if i <= len-sublen then (
2423       let rec loop2 j =
2424         if j < sublen then (
2425           if s.[i+j] = sub.[j] then loop2 (j+1)
2426           else -1
2427         ) else
2428           i (* found *)
2429       in
2430       let r = loop2 0 in
2431       if r = -1 then loop (i+1) else r
2432     ) else
2433       -1 (* not found *)
2434   in
2435   loop 0
2436
2437 let rec replace_str s s1 s2 =
2438   let len = String.length s in
2439   let sublen = String.length s1 in
2440   let i = find s s1 in
2441   if i = -1 then s
2442   else (
2443     let s' = String.sub s 0 i in
2444     let s'' = String.sub s (i+sublen) (len-i-sublen) in
2445     s' ^ s2 ^ replace_str s'' s1 s2
2446   )
2447
2448 let rec string_split sep str =
2449   let len = String.length str in
2450   let seplen = String.length sep in
2451   let i = find str sep in
2452   if i = -1 then [str]
2453   else (
2454     let s' = String.sub str 0 i in
2455     let s'' = String.sub str (i+seplen) (len-i-seplen) in
2456     s' :: string_split sep s''
2457   )
2458
2459 let files_equal n1 n2 =
2460   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
2461   match Sys.command cmd with
2462   | 0 -> true
2463   | 1 -> false
2464   | i -> failwithf "%s: failed with error code %d" cmd i
2465
2466 let rec find_map f = function
2467   | [] -> raise Not_found
2468   | x :: xs ->
2469       match f x with
2470       | Some y -> y
2471       | None -> find_map f xs
2472
2473 let iteri f xs =
2474   let rec loop i = function
2475     | [] -> ()
2476     | x :: xs -> f i x; loop (i+1) xs
2477   in
2478   loop 0 xs
2479
2480 let mapi f xs =
2481   let rec loop i = function
2482     | [] -> []
2483     | x :: xs -> let r = f i x in r :: loop (i+1) xs
2484   in
2485   loop 0 xs
2486
2487 let name_of_argt = function
2488   | String n | OptString n | StringList n | Bool n | Int n
2489   | FileIn n | FileOut n -> n
2490
2491 let seq_of_test = function
2492   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
2493   | TestOutputInt (s, _) | TestOutputTrue s | TestOutputFalse s
2494   | TestOutputLength (s, _) | TestOutputStruct (s, _)
2495   | TestLastFail s -> s
2496
2497 (* Check function names etc. for consistency. *)
2498 let check_functions () =
2499   let contains_uppercase str =
2500     let len = String.length str in
2501     let rec loop i =
2502       if i >= len then false
2503       else (
2504         let c = str.[i] in
2505         if c >= 'A' && c <= 'Z' then true
2506         else loop (i+1)
2507       )
2508     in
2509     loop 0
2510   in
2511
2512   (* Check function names. *)
2513   List.iter (
2514     fun (name, _, _, _, _, _, _) ->
2515       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
2516         failwithf "function name %s does not need 'guestfs' prefix" name;
2517       if name = "" then
2518         failwithf "function name is empty";
2519       if name.[0] < 'a' || name.[0] > 'z' then
2520         failwithf "function name %s must start with lowercase a-z" name;
2521       if String.contains name '-' then
2522         failwithf "function name %s should not contain '-', use '_' instead."
2523           name
2524   ) all_functions;
2525
2526   (* Check function parameter/return names. *)
2527   List.iter (
2528     fun (name, style, _, _, _, _, _) ->
2529       let check_arg_ret_name n =
2530         if contains_uppercase n then
2531           failwithf "%s param/ret %s should not contain uppercase chars"
2532             name n;
2533         if String.contains n '-' || String.contains n '_' then
2534           failwithf "%s param/ret %s should not contain '-' or '_'"
2535             name n;
2536         if n = "value" then
2537           failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
2538         if n = "int" || n = "char" || n = "short" || n = "long" then
2539           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
2540         if n = "i" then
2541           failwithf "%s has a param/ret called 'i', which will cause some conflicts in the generated code" name;
2542         if n = "argv" || n = "args" then
2543           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
2544       in
2545
2546       (match fst style with
2547        | RErr -> ()
2548        | RInt n | RInt64 n | RBool n | RConstString n | RString n
2549        | RStringList n | RPVList n | RVGList n | RLVList n
2550        | RStat n | RStatVFS n
2551        | RHashtable n ->
2552            check_arg_ret_name n
2553        | RIntBool (n,m) ->
2554            check_arg_ret_name n;
2555            check_arg_ret_name m
2556       );
2557       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
2558   ) all_functions;
2559
2560   (* Check short descriptions. *)
2561   List.iter (
2562     fun (name, _, _, _, _, shortdesc, _) ->
2563       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
2564         failwithf "short description of %s should begin with lowercase." name;
2565       let c = shortdesc.[String.length shortdesc-1] in
2566       if c = '\n' || c = '.' then
2567         failwithf "short description of %s should not end with . or \\n." name
2568   ) all_functions;
2569
2570   (* Check long dscriptions. *)
2571   List.iter (
2572     fun (name, _, _, _, _, _, longdesc) ->
2573       if longdesc.[String.length longdesc-1] = '\n' then
2574         failwithf "long description of %s should not end with \\n." name
2575   ) all_functions;
2576
2577   (* Check proc_nrs. *)
2578   List.iter (
2579     fun (name, _, proc_nr, _, _, _, _) ->
2580       if proc_nr <= 0 then
2581         failwithf "daemon function %s should have proc_nr > 0" name
2582   ) daemon_functions;
2583
2584   List.iter (
2585     fun (name, _, proc_nr, _, _, _, _) ->
2586       if proc_nr <> -1 then
2587         failwithf "non-daemon function %s should have proc_nr -1" name
2588   ) non_daemon_functions;
2589
2590   let proc_nrs =
2591     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
2592       daemon_functions in
2593   let proc_nrs =
2594     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
2595   let rec loop = function
2596     | [] -> ()
2597     | [_] -> ()
2598     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
2599         loop rest
2600     | (name1,nr1) :: (name2,nr2) :: _ ->
2601         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
2602           name1 name2 nr1 nr2
2603   in
2604   loop proc_nrs;
2605
2606   (* Check tests. *)
2607   List.iter (
2608     function
2609       (* Ignore functions that have no tests.  We generate a
2610        * warning when the user does 'make check' instead.
2611        *)
2612     | name, _, _, _, [], _, _ -> ()
2613     | name, _, _, _, tests, _, _ ->
2614         let funcs =
2615           List.map (
2616             fun (_, _, test) ->
2617               match seq_of_test test with
2618               | [] ->
2619                   failwithf "%s has a test containing an empty sequence" name
2620               | cmds -> List.map List.hd cmds
2621           ) tests in
2622         let funcs = List.flatten funcs in
2623
2624         let tested = List.mem name funcs in
2625
2626         if not tested then
2627           failwithf "function %s has tests but does not test itself" name
2628   ) all_functions
2629
2630 (* 'pr' prints to the current output file. *)
2631 let chan = ref stdout
2632 let pr fs = ksprintf (output_string !chan) fs
2633
2634 (* Generate a header block in a number of standard styles. *)
2635 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
2636 type license = GPLv2 | LGPLv2
2637
2638 let generate_header comment license =
2639   let c = match comment with
2640     | CStyle ->     pr "/* "; " *"
2641     | HashStyle ->  pr "# ";  "#"
2642     | OCamlStyle -> pr "(* "; " *"
2643     | HaskellStyle -> pr "{- "; "  " in
2644   pr "libguestfs generated file\n";
2645   pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
2646   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
2647   pr "%s\n" c;
2648   pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
2649   pr "%s\n" c;
2650   (match license with
2651    | GPLv2 ->
2652        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
2653        pr "%s it under the terms of the GNU General Public License as published by\n" c;
2654        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
2655        pr "%s (at your option) any later version.\n" c;
2656        pr "%s\n" c;
2657        pr "%s This program is distributed in the hope that it will be useful,\n" c;
2658        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2659        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
2660        pr "%s GNU General Public License for more details.\n" c;
2661        pr "%s\n" c;
2662        pr "%s You should have received a copy of the GNU General Public License along\n" c;
2663        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
2664        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
2665
2666    | LGPLv2 ->
2667        pr "%s This library is free software; you can redistribute it and/or\n" c;
2668        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
2669        pr "%s License as published by the Free Software Foundation; either\n" c;
2670        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
2671        pr "%s\n" c;
2672        pr "%s This library is distributed in the hope that it will be useful,\n" c;
2673        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2674        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
2675        pr "%s Lesser General Public License for more details.\n" c;
2676        pr "%s\n" c;
2677        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
2678        pr "%s License along with this library; if not, write to the Free Software\n" c;
2679        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
2680   );
2681   (match comment with
2682    | CStyle -> pr " */\n"
2683    | HashStyle -> ()
2684    | OCamlStyle -> pr " *)\n"
2685    | HaskellStyle -> pr "-}\n"
2686   );
2687   pr "\n"
2688
2689 (* Start of main code generation functions below this line. *)
2690
2691 (* Generate the pod documentation for the C API. *)
2692 let rec generate_actions_pod () =
2693   List.iter (
2694     fun (shortname, style, _, flags, _, _, longdesc) ->
2695       if not (List.mem NotInDocs flags) then (
2696         let name = "guestfs_" ^ shortname in
2697         pr "=head2 %s\n\n" name;
2698         pr " ";
2699         generate_prototype ~extern:false ~handle:"handle" name style;
2700         pr "\n\n";
2701         pr "%s\n\n" longdesc;
2702         (match fst style with
2703          | RErr ->
2704              pr "This function returns 0 on success or -1 on error.\n\n"
2705          | RInt _ ->
2706              pr "On error this function returns -1.\n\n"
2707          | RInt64 _ ->
2708              pr "On error this function returns -1.\n\n"
2709          | RBool _ ->
2710              pr "This function returns a C truth value on success or -1 on error.\n\n"
2711          | RConstString _ ->
2712              pr "This function returns a string, or NULL on error.
2713 The string is owned by the guest handle and must I<not> be freed.\n\n"
2714          | RString _ ->
2715              pr "This function returns a string, or NULL on error.
2716 I<The caller must free the returned string after use>.\n\n"
2717          | RStringList _ ->
2718              pr "This function returns a NULL-terminated array of strings
2719 (like L<environ(3)>), or NULL if there was an error.
2720 I<The caller must free the strings and the array after use>.\n\n"
2721          | RIntBool _ ->
2722              pr "This function returns a C<struct guestfs_int_bool *>,
2723 or NULL if there was an error.
2724 I<The caller must call C<guestfs_free_int_bool> after use>.\n\n"
2725          | RPVList _ ->
2726              pr "This function returns a C<struct guestfs_lvm_pv_list *>
2727 (see E<lt>guestfs-structs.hE<gt>),
2728 or NULL if there was an error.
2729 I<The caller must call C<guestfs_free_lvm_pv_list> after use>.\n\n"
2730          | RVGList _ ->
2731              pr "This function returns a C<struct guestfs_lvm_vg_list *>
2732 (see E<lt>guestfs-structs.hE<gt>),
2733 or NULL if there was an error.
2734 I<The caller must call C<guestfs_free_lvm_vg_list> after use>.\n\n"
2735          | RLVList _ ->
2736              pr "This function returns a C<struct guestfs_lvm_lv_list *>
2737 (see E<lt>guestfs-structs.hE<gt>),
2738 or NULL if there was an error.
2739 I<The caller must call C<guestfs_free_lvm_lv_list> after use>.\n\n"
2740          | RStat _ ->
2741              pr "This function returns a C<struct guestfs_stat *>
2742 (see L<stat(2)> and E<lt>guestfs-structs.hE<gt>),
2743 or NULL if there was an error.
2744 I<The caller must call C<free> after use>.\n\n"
2745          | RStatVFS _ ->
2746              pr "This function returns a C<struct guestfs_statvfs *>
2747 (see L<statvfs(2)> and E<lt>guestfs-structs.hE<gt>),
2748 or NULL if there was an error.
2749 I<The caller must call C<free> after use>.\n\n"
2750          | RHashtable _ ->
2751              pr "This function returns a NULL-terminated array of
2752 strings, or NULL if there was an error.
2753 The array of strings will always have length C<2n+1>, where
2754 C<n> keys and values alternate, followed by the trailing NULL entry.
2755 I<The caller must free the strings and the array after use>.\n\n"
2756         );
2757         if List.mem ProtocolLimitWarning flags then
2758           pr "%s\n\n" protocol_limit_warning;
2759         if List.mem DangerWillRobinson flags then
2760           pr "%s\n\n" danger_will_robinson
2761       )
2762   ) all_functions_sorted
2763
2764 and generate_structs_pod () =
2765   (* LVM structs documentation. *)
2766   List.iter (
2767     fun (typ, cols) ->
2768       pr "=head2 guestfs_lvm_%s\n" typ;
2769       pr "\n";
2770       pr " struct guestfs_lvm_%s {\n" typ;
2771       List.iter (
2772         function
2773         | name, `String -> pr "  char *%s;\n" name
2774         | name, `UUID ->
2775             pr "  /* The next field is NOT nul-terminated, be careful when printing it: */\n";
2776             pr "  char %s[32];\n" name
2777         | name, `Bytes -> pr "  uint64_t %s;\n" name
2778         | name, `Int -> pr "  int64_t %s;\n" name
2779         | name, `OptPercent ->
2780             pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
2781             pr "  float %s;\n" name
2782       ) cols;
2783       pr " \n";
2784       pr " struct guestfs_lvm_%s_list {\n" typ;
2785       pr "   uint32_t len; /* Number of elements in list. */\n";
2786       pr "   struct guestfs_lvm_%s *val; /* Elements. */\n" typ;
2787       pr " };\n";
2788       pr " \n";
2789       pr " void guestfs_free_lvm_%s_list (struct guestfs_free_lvm_%s_list *);\n"
2790         typ typ;
2791       pr "\n"
2792   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
2793
2794 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
2795  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
2796  *
2797  * We have to use an underscore instead of a dash because otherwise
2798  * rpcgen generates incorrect code.
2799  *
2800  * This header is NOT exported to clients, but see also generate_structs_h.
2801  *)
2802 and generate_xdr () =
2803   generate_header CStyle LGPLv2;
2804
2805   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
2806   pr "typedef string str<>;\n";
2807   pr "\n";
2808
2809   (* LVM internal structures. *)
2810   List.iter (
2811     function
2812     | typ, cols ->
2813         pr "struct guestfs_lvm_int_%s {\n" typ;
2814         List.iter (function
2815                    | name, `String -> pr "  string %s<>;\n" name
2816                    | name, `UUID -> pr "  opaque %s[32];\n" name
2817                    | name, `Bytes -> pr "  hyper %s;\n" name
2818                    | name, `Int -> pr "  hyper %s;\n" name
2819                    | name, `OptPercent -> pr "  float %s;\n" name
2820                   ) cols;
2821         pr "};\n";
2822         pr "\n";
2823         pr "typedef struct guestfs_lvm_int_%s guestfs_lvm_int_%s_list<>;\n" typ typ;
2824         pr "\n";
2825   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
2826
2827   (* Stat internal structures. *)
2828   List.iter (
2829     function
2830     | typ, cols ->
2831         pr "struct guestfs_int_%s {\n" typ;
2832         List.iter (function
2833                    | name, `Int -> pr "  hyper %s;\n" name
2834                   ) cols;
2835         pr "};\n";
2836         pr "\n";
2837   ) ["stat", stat_cols; "statvfs", statvfs_cols];
2838
2839   List.iter (
2840     fun (shortname, style, _, _, _, _, _) ->
2841       let name = "guestfs_" ^ shortname in
2842
2843       (match snd style with
2844        | [] -> ()
2845        | args ->
2846            pr "struct %s_args {\n" name;
2847            List.iter (
2848              function
2849              | String n -> pr "  string %s<>;\n" n
2850              | OptString n -> pr "  str *%s;\n" n
2851              | StringList n -> pr "  str %s<>;\n" n
2852              | Bool n -> pr "  bool %s;\n" n
2853              | Int n -> pr "  int %s;\n" n
2854              | FileIn _ | FileOut _ -> ()
2855            ) args;
2856            pr "};\n\n"
2857       );
2858       (match fst style with
2859        | RErr -> ()
2860        | RInt n ->
2861            pr "struct %s_ret {\n" name;
2862            pr "  int %s;\n" n;
2863            pr "};\n\n"
2864        | RInt64 n ->
2865            pr "struct %s_ret {\n" name;
2866            pr "  hyper %s;\n" n;
2867            pr "};\n\n"
2868        | RBool n ->
2869            pr "struct %s_ret {\n" name;
2870            pr "  bool %s;\n" n;
2871            pr "};\n\n"
2872        | RConstString _ ->
2873            failwithf "RConstString cannot be returned from a daemon function"
2874        | RString n ->
2875            pr "struct %s_ret {\n" name;
2876            pr "  string %s<>;\n" n;
2877            pr "};\n\n"
2878        | RStringList n ->
2879            pr "struct %s_ret {\n" name;
2880            pr "  str %s<>;\n" n;
2881            pr "};\n\n"
2882        | RIntBool (n,m) ->
2883            pr "struct %s_ret {\n" name;
2884            pr "  int %s;\n" n;
2885            pr "  bool %s;\n" m;
2886            pr "};\n\n"
2887        | RPVList n ->
2888            pr "struct %s_ret {\n" name;
2889            pr "  guestfs_lvm_int_pv_list %s;\n" n;
2890            pr "};\n\n"
2891        | RVGList n ->
2892            pr "struct %s_ret {\n" name;
2893            pr "  guestfs_lvm_int_vg_list %s;\n" n;
2894            pr "};\n\n"
2895        | RLVList n ->
2896            pr "struct %s_ret {\n" name;
2897            pr "  guestfs_lvm_int_lv_list %s;\n" n;
2898            pr "};\n\n"
2899        | RStat n ->
2900            pr "struct %s_ret {\n" name;
2901            pr "  guestfs_int_stat %s;\n" n;
2902            pr "};\n\n"
2903        | RStatVFS n ->
2904            pr "struct %s_ret {\n" name;
2905            pr "  guestfs_int_statvfs %s;\n" n;
2906            pr "};\n\n"
2907        | RHashtable n ->
2908            pr "struct %s_ret {\n" name;
2909            pr "  str %s<>;\n" n;
2910            pr "};\n\n"
2911       );
2912   ) daemon_functions;
2913
2914   (* Table of procedure numbers. *)
2915   pr "enum guestfs_procedure {\n";
2916   List.iter (
2917     fun (shortname, _, proc_nr, _, _, _, _) ->
2918       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
2919   ) daemon_functions;
2920   pr "  GUESTFS_PROC_NR_PROCS\n";
2921   pr "};\n";
2922   pr "\n";
2923
2924   (* Having to choose a maximum message size is annoying for several
2925    * reasons (it limits what we can do in the API), but it (a) makes
2926    * the protocol a lot simpler, and (b) provides a bound on the size
2927    * of the daemon which operates in limited memory space.  For large
2928    * file transfers you should use FTP.
2929    *)
2930   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
2931   pr "\n";
2932
2933   (* Message header, etc. *)
2934   pr "\
2935 /* The communication protocol is now documented in the guestfs(3)
2936  * manpage.
2937  */
2938
2939 const GUESTFS_PROGRAM = 0x2000F5F5;
2940 const GUESTFS_PROTOCOL_VERSION = 1;
2941
2942 /* These constants must be larger than any possible message length. */
2943 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
2944 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
2945
2946 enum guestfs_message_direction {
2947   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
2948   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
2949 };
2950
2951 enum guestfs_message_status {
2952   GUESTFS_STATUS_OK = 0,
2953   GUESTFS_STATUS_ERROR = 1
2954 };
2955
2956 const GUESTFS_ERROR_LEN = 256;
2957
2958 struct guestfs_message_error {
2959   string error_message<GUESTFS_ERROR_LEN>;
2960 };
2961
2962 struct guestfs_message_header {
2963   unsigned prog;                     /* GUESTFS_PROGRAM */
2964   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
2965   guestfs_procedure proc;            /* GUESTFS_PROC_x */
2966   guestfs_message_direction direction;
2967   unsigned serial;                   /* message serial number */
2968   guestfs_message_status status;
2969 };
2970
2971 const GUESTFS_MAX_CHUNK_SIZE = 8192;
2972
2973 struct guestfs_chunk {
2974   int cancel;                        /* if non-zero, transfer is cancelled */
2975   /* data size is 0 bytes if the transfer has finished successfully */
2976   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
2977 };
2978 "
2979
2980 (* Generate the guestfs-structs.h file. *)
2981 and generate_structs_h () =
2982   generate_header CStyle LGPLv2;
2983
2984   (* This is a public exported header file containing various
2985    * structures.  The structures are carefully written to have
2986    * exactly the same in-memory format as the XDR structures that
2987    * we use on the wire to the daemon.  The reason for creating
2988    * copies of these structures here is just so we don't have to
2989    * export the whole of guestfs_protocol.h (which includes much
2990    * unrelated and XDR-dependent stuff that we don't want to be
2991    * public, or required by clients).
2992    *
2993    * To reiterate, we will pass these structures to and from the
2994    * client with a simple assignment or memcpy, so the format
2995    * must be identical to what rpcgen / the RFC defines.
2996    *)
2997
2998   (* guestfs_int_bool structure. *)
2999   pr "struct guestfs_int_bool {\n";
3000   pr "  int32_t i;\n";
3001   pr "  int32_t b;\n";
3002   pr "};\n";
3003   pr "\n";
3004
3005   (* LVM public structures. *)
3006   List.iter (
3007     function
3008     | typ, cols ->
3009         pr "struct guestfs_lvm_%s {\n" typ;
3010         List.iter (
3011           function
3012           | name, `String -> pr "  char *%s;\n" name
3013           | name, `UUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3014           | name, `Bytes -> pr "  uint64_t %s;\n" name
3015           | name, `Int -> pr "  int64_t %s;\n" name
3016           | name, `OptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
3017         ) cols;
3018         pr "};\n";
3019         pr "\n";
3020         pr "struct guestfs_lvm_%s_list {\n" typ;
3021         pr "  uint32_t len;\n";
3022         pr "  struct guestfs_lvm_%s *val;\n" typ;
3023         pr "};\n";
3024         pr "\n"
3025   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
3026
3027   (* Stat structures. *)
3028   List.iter (
3029     function
3030     | typ, cols ->
3031         pr "struct guestfs_%s {\n" typ;
3032         List.iter (
3033           function
3034           | name, `Int -> pr "  int64_t %s;\n" name
3035         ) cols;
3036         pr "};\n";
3037         pr "\n"
3038   ) ["stat", stat_cols; "statvfs", statvfs_cols]
3039
3040 (* Generate the guestfs-actions.h file. *)
3041 and generate_actions_h () =
3042   generate_header CStyle LGPLv2;
3043   List.iter (
3044     fun (shortname, style, _, _, _, _, _) ->
3045       let name = "guestfs_" ^ shortname in
3046       generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3047         name style
3048   ) all_functions
3049
3050 (* Generate the client-side dispatch stubs. *)
3051 and generate_client_actions () =
3052   generate_header CStyle LGPLv2;
3053
3054   pr "\
3055 #include <stdio.h>
3056 #include <stdlib.h>
3057
3058 #include \"guestfs.h\"
3059 #include \"guestfs_protocol.h\"
3060
3061 #define error guestfs_error
3062 #define perrorf guestfs_perrorf
3063 #define safe_malloc guestfs_safe_malloc
3064 #define safe_realloc guestfs_safe_realloc
3065 #define safe_strdup guestfs_safe_strdup
3066 #define safe_memdup guestfs_safe_memdup
3067
3068 /* Check the return message from a call for validity. */
3069 static int
3070 check_reply_header (guestfs_h *g,
3071                     const struct guestfs_message_header *hdr,
3072                     int proc_nr, int serial)
3073 {
3074   if (hdr->prog != GUESTFS_PROGRAM) {
3075     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3076     return -1;
3077   }
3078   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3079     error (g, \"wrong protocol version (%%d/%%d)\",
3080            hdr->vers, GUESTFS_PROTOCOL_VERSION);
3081     return -1;
3082   }
3083   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3084     error (g, \"unexpected message direction (%%d/%%d)\",
3085            hdr->direction, GUESTFS_DIRECTION_REPLY);
3086     return -1;
3087   }
3088   if (hdr->proc != proc_nr) {
3089     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3090     return -1;
3091   }
3092   if (hdr->serial != serial) {
3093     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3094     return -1;
3095   }
3096
3097   return 0;
3098 }
3099
3100 /* Check we are in the right state to run a high-level action. */
3101 static int
3102 check_state (guestfs_h *g, const char *caller)
3103 {
3104   if (!guestfs_is_ready (g)) {
3105     if (guestfs_is_config (g))
3106       error (g, \"%%s: call launch() before using this function\",
3107         caller);
3108     else if (guestfs_is_launching (g))
3109       error (g, \"%%s: call wait_ready() before using this function\",
3110         caller);
3111     else
3112       error (g, \"%%s called from the wrong state, %%d != READY\",
3113         caller, guestfs_get_state (g));
3114     return -1;
3115   }
3116   return 0;
3117 }
3118
3119 ";
3120
3121   (* Client-side stubs for each function. *)
3122   List.iter (
3123     fun (shortname, style, _, _, _, _, _) ->
3124       let name = "guestfs_" ^ shortname in
3125
3126       (* Generate the context struct which stores the high-level
3127        * state between callback functions.
3128        *)
3129       pr "struct %s_ctx {\n" shortname;
3130       pr "  /* This flag is set by the callbacks, so we know we've done\n";
3131       pr "   * the callbacks as expected, and in the right sequence.\n";
3132       pr "   * 0 = not called, 1 = reply_cb called.\n";
3133       pr "   */\n";
3134       pr "  int cb_sequence;\n";
3135       pr "  struct guestfs_message_header hdr;\n";
3136       pr "  struct guestfs_message_error err;\n";
3137       (match fst style with
3138        | RErr -> ()
3139        | RConstString _ ->
3140            failwithf "RConstString cannot be returned from a daemon function"
3141        | RInt _ | RInt64 _
3142        | RBool _ | RString _ | RStringList _
3143        | RIntBool _
3144        | RPVList _ | RVGList _ | RLVList _
3145        | RStat _ | RStatVFS _
3146        | RHashtable _ ->
3147            pr "  struct %s_ret ret;\n" name
3148       );
3149       pr "};\n";
3150       pr "\n";
3151
3152       (* Generate the reply callback function. *)
3153       pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
3154       pr "{\n";
3155       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3156       pr "  struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
3157       pr "\n";
3158       pr "  /* This should definitely not happen. */\n";
3159       pr "  if (ctx->cb_sequence != 0) {\n";
3160       pr "    ctx->cb_sequence = 9999;\n";
3161       pr "    error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
3162       pr "    return;\n";
3163       pr "  }\n";
3164       pr "\n";
3165       pr "  ml->main_loop_quit (ml, g);\n";
3166       pr "\n";
3167       pr "  if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
3168       pr "    error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
3169       pr "    return;\n";
3170       pr "  }\n";
3171       pr "  if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
3172       pr "    if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
3173       pr "      error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
3174         name;
3175       pr "      return;\n";
3176       pr "    }\n";
3177       pr "    goto done;\n";
3178       pr "  }\n";
3179
3180       (match fst style with
3181        | RErr -> ()
3182        | RConstString _ ->
3183            failwithf "RConstString cannot be returned from a daemon function"
3184        | RInt _ | RInt64 _
3185        | RBool _ | RString _ | RStringList _
3186        | RIntBool _
3187        | RPVList _ | RVGList _ | RLVList _
3188        | RStat _ | RStatVFS _
3189        | RHashtable _ ->
3190             pr "  if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
3191             pr "    error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
3192             pr "    return;\n";
3193             pr "  }\n";
3194       );
3195
3196       pr " done:\n";
3197       pr "  ctx->cb_sequence = 1;\n";
3198       pr "}\n\n";
3199
3200       (* Generate the action stub. *)
3201       generate_prototype ~extern:false ~semicolon:false ~newline:true
3202         ~handle:"g" name style;
3203
3204       let error_code =
3205         match fst style with
3206         | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
3207         | RConstString _ ->
3208             failwithf "RConstString cannot be returned from a daemon function"
3209         | RString _ | RStringList _ | RIntBool _
3210         | RPVList _ | RVGList _ | RLVList _
3211         | RStat _ | RStatVFS _
3212         | RHashtable _ ->
3213             "NULL" in
3214
3215       pr "{\n";
3216
3217       (match snd style with
3218        | [] -> ()
3219        | _ -> pr "  struct %s_args args;\n" name
3220       );
3221
3222       pr "  struct %s_ctx ctx;\n" shortname;
3223       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3224       pr "  int serial;\n";
3225       pr "\n";
3226       pr "  if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
3227       pr "  guestfs_set_busy (g);\n";
3228       pr "\n";
3229       pr "  memset (&ctx, 0, sizeof ctx);\n";
3230       pr "\n";
3231
3232       (* Send the main header and arguments. *)
3233       (match snd style with
3234        | [] ->
3235            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
3236              (String.uppercase shortname)
3237        | args ->
3238            List.iter (
3239              function
3240              | String n ->
3241                  pr "  args.%s = (char *) %s;\n" n n
3242              | OptString n ->
3243                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
3244              | StringList n ->
3245                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
3246                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
3247              | Bool n ->
3248                  pr "  args.%s = %s;\n" n n
3249              | Int n ->
3250                  pr "  args.%s = %s;\n" n n
3251              | FileIn _ | FileOut _ -> ()
3252            ) args;
3253            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
3254              (String.uppercase shortname);
3255            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
3256              name;
3257       );
3258       pr "  if (serial == -1) {\n";
3259       pr "    guestfs_end_busy (g);\n";
3260       pr "    return %s;\n" error_code;
3261       pr "  }\n";
3262       pr "\n";
3263
3264       (* Send any additional files (FileIn) requested. *)
3265       let need_read_reply_label = ref false in
3266       List.iter (
3267         function
3268         | FileIn n ->
3269             pr "  {\n";
3270             pr "    int r;\n";
3271             pr "\n";
3272             pr "    r = guestfs__send_file_sync (g, %s);\n" n;
3273             pr "    if (r == -1) {\n";
3274             pr "      guestfs_end_busy (g);\n";
3275             pr "      return %s;\n" error_code;
3276             pr "    }\n";
3277             pr "    if (r == -2) /* daemon cancelled */\n";
3278             pr "      goto read_reply;\n";
3279             need_read_reply_label := true;
3280             pr "  }\n";
3281             pr "\n";
3282         | _ -> ()
3283       ) (snd style);
3284
3285       (* Wait for the reply from the remote end. *)
3286       if !need_read_reply_label then pr " read_reply:\n";
3287       pr "  guestfs__switch_to_receiving (g);\n";
3288       pr "  ctx.cb_sequence = 0;\n";
3289       pr "  guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
3290       pr "  (void) ml->main_loop_run (ml, g);\n";
3291       pr "  guestfs_set_reply_callback (g, NULL, NULL);\n";
3292       pr "  if (ctx.cb_sequence != 1) {\n";
3293       pr "    error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
3294       pr "    guestfs_end_busy (g);\n";
3295       pr "    return %s;\n" error_code;
3296       pr "  }\n";
3297       pr "\n";
3298
3299       pr "  if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
3300         (String.uppercase shortname);
3301       pr "    guestfs_end_busy (g);\n";
3302       pr "    return %s;\n" error_code;
3303       pr "  }\n";
3304       pr "\n";
3305
3306       pr "  if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
3307       pr "    error (g, \"%%s\", ctx.err.error_message);\n";
3308       pr "    free (ctx.err.error_message);\n";
3309       pr "    guestfs_end_busy (g);\n";
3310       pr "    return %s;\n" error_code;
3311       pr "  }\n";
3312       pr "\n";
3313
3314       (* Expecting to receive further files (FileOut)? *)
3315       List.iter (
3316         function
3317         | FileOut n ->
3318             pr "  if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
3319             pr "    guestfs_end_busy (g);\n";
3320             pr "    return %s;\n" error_code;
3321             pr "  }\n";
3322             pr "\n";
3323         | _ -> ()
3324       ) (snd style);
3325
3326       pr "  guestfs_end_busy (g);\n";
3327
3328       (match fst style with
3329        | RErr -> pr "  return 0;\n"
3330        | RInt n | RInt64 n | RBool n ->
3331            pr "  return ctx.ret.%s;\n" n
3332        | RConstString _ ->
3333            failwithf "RConstString cannot be returned from a daemon function"
3334        | RString n ->
3335            pr "  return ctx.ret.%s; /* caller will free */\n" n
3336        | RStringList n | RHashtable n ->
3337            pr "  /* caller will free this, but we need to add a NULL entry */\n";
3338            pr "  ctx.ret.%s.%s_val =\n" n n;
3339            pr "    safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
3340            pr "                  sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
3341              n n;
3342            pr "  ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
3343            pr "  return ctx.ret.%s.%s_val;\n" n n
3344        | RIntBool _ ->
3345            pr "  /* caller with free this */\n";
3346            pr "  return safe_memdup (g, &ctx.ret, sizeof (ctx.ret));\n"
3347        | RPVList n | RVGList n | RLVList n
3348        | RStat n | RStatVFS n ->
3349            pr "  /* caller will free this */\n";
3350            pr "  return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
3351       );
3352
3353       pr "}\n\n"
3354   ) daemon_functions
3355
3356 (* Generate daemon/actions.h. *)
3357 and generate_daemon_actions_h () =
3358   generate_header CStyle GPLv2;
3359
3360   pr "#include \"../src/guestfs_protocol.h\"\n";
3361   pr "\n";
3362
3363   List.iter (
3364     fun (name, style, _, _, _, _, _) ->
3365         generate_prototype
3366           ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
3367           name style;
3368   ) daemon_functions
3369
3370 (* Generate the server-side stubs. *)
3371 and generate_daemon_actions () =
3372   generate_header CStyle GPLv2;
3373
3374   pr "#include <config.h>\n";
3375   pr "\n";
3376   pr "#include <stdio.h>\n";
3377   pr "#include <stdlib.h>\n";
3378   pr "#include <string.h>\n";
3379   pr "#include <inttypes.h>\n";
3380   pr "#include <ctype.h>\n";
3381   pr "#include <rpc/types.h>\n";
3382   pr "#include <rpc/xdr.h>\n";
3383   pr "\n";
3384   pr "#include \"daemon.h\"\n";
3385   pr "#include \"../src/guestfs_protocol.h\"\n";
3386   pr "#include \"actions.h\"\n";
3387   pr "\n";
3388
3389   List.iter (
3390     fun (name, style, _, _, _, _, _) ->
3391       (* Generate server-side stubs. *)
3392       pr "static void %s_stub (XDR *xdr_in)\n" name;
3393       pr "{\n";
3394       let error_code =
3395         match fst style with
3396         | RErr | RInt _ -> pr "  int r;\n"; "-1"
3397         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
3398         | RBool _ -> pr "  int r;\n"; "-1"
3399         | RConstString _ ->
3400             failwithf "RConstString cannot be returned from a daemon function"
3401         | RString _ -> pr "  char *r;\n"; "NULL"
3402         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
3403         | RIntBool _ -> pr "  guestfs_%s_ret *r;\n" name; "NULL"
3404         | RPVList _ -> pr "  guestfs_lvm_int_pv_list *r;\n"; "NULL"
3405         | RVGList _ -> pr "  guestfs_lvm_int_vg_list *r;\n"; "NULL"
3406         | RLVList _ -> pr "  guestfs_lvm_int_lv_list *r;\n"; "NULL"
3407         | RStat _ -> pr "  guestfs_int_stat *r;\n"; "NULL"
3408         | RStatVFS _ -> pr "  guestfs_int_statvfs *r;\n"; "NULL" in
3409
3410       (match snd style with
3411        | [] -> ()
3412        | args ->
3413            pr "  struct guestfs_%s_args args;\n" name;
3414            List.iter (
3415              function
3416              | String n
3417              | OptString n -> pr "  const char *%s;\n" n
3418              | StringList n -> pr "  char **%s;\n" n
3419              | Bool n -> pr "  int %s;\n" n
3420              | Int n -> pr "  int %s;\n" n
3421              | FileIn _ | FileOut _ -> ()
3422            ) args
3423       );
3424       pr "\n";
3425
3426       (match snd style with
3427        | [] -> ()
3428        | args ->
3429            pr "  memset (&args, 0, sizeof args);\n";
3430            pr "\n";
3431            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
3432            pr "    reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
3433            pr "    return;\n";
3434            pr "  }\n";
3435            List.iter (
3436              function
3437              | String n -> pr "  %s = args.%s;\n" n n
3438              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
3439              | StringList n ->
3440                  pr "  %s = realloc (args.%s.%s_val,\n" n n n;
3441                  pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
3442                  pr "  if (%s == NULL) {\n" n;
3443                  pr "    reply_with_perror (\"realloc\");\n";
3444                  pr "    goto done;\n";
3445                  pr "  }\n";
3446                  pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
3447                  pr "  args.%s.%s_val = %s;\n" n n n;
3448              | Bool n -> pr "  %s = args.%s;\n" n n
3449              | Int n -> pr "  %s = args.%s;\n" n n
3450              | FileIn _ | FileOut _ -> ()
3451            ) args;
3452            pr "\n"
3453       );
3454
3455       (* Don't want to call the impl with any FileIn or FileOut
3456        * parameters, since these go "outside" the RPC protocol.
3457        *)
3458       let argsnofile =
3459         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
3460           (snd style) in
3461       pr "  r = do_%s " name;
3462       generate_call_args argsnofile;
3463       pr ";\n";
3464
3465       pr "  if (r == %s)\n" error_code;
3466       pr "    /* do_%s has already called reply_with_error */\n" name;
3467       pr "    goto done;\n";
3468       pr "\n";
3469
3470       (* If there are any FileOut parameters, then the impl must
3471        * send its own reply.
3472        *)
3473       let no_reply =
3474         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
3475       if no_reply then
3476         pr "  /* do_%s has already sent a reply */\n" name
3477       else (
3478         match fst style with
3479         | RErr -> pr "  reply (NULL, NULL);\n"
3480         | RInt n | RInt64 n | RBool n ->
3481             pr "  struct guestfs_%s_ret ret;\n" name;
3482             pr "  ret.%s = r;\n" n;
3483             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3484               name
3485         | RConstString _ ->
3486             failwithf "RConstString cannot be returned from a daemon function"
3487         | RString n ->
3488             pr "  struct guestfs_%s_ret ret;\n" name;
3489             pr "  ret.%s = r;\n" n;
3490             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3491               name;
3492             pr "  free (r);\n"
3493         | RStringList n | RHashtable n ->
3494             pr "  struct guestfs_%s_ret ret;\n" name;
3495             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
3496             pr "  ret.%s.%s_val = r;\n" n n;
3497             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3498               name;
3499             pr "  free_strings (r);\n"
3500         | RIntBool _ ->
3501             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n"
3502               name;
3503             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n" name
3504         | RPVList n | RVGList n | RLVList n
3505         | RStat n | RStatVFS n ->
3506             pr "  struct guestfs_%s_ret ret;\n" name;
3507             pr "  ret.%s = *r;\n" n;
3508             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3509               name;
3510             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3511               name
3512       );
3513
3514       (* Free the args. *)
3515       (match snd style with
3516        | [] ->
3517            pr "done: ;\n";
3518        | _ ->
3519            pr "done:\n";
3520            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
3521              name
3522       );
3523
3524       pr "}\n\n";
3525   ) daemon_functions;
3526
3527   (* Dispatch function. *)
3528   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
3529   pr "{\n";
3530   pr "  switch (proc_nr) {\n";
3531
3532   List.iter (
3533     fun (name, style, _, _, _, _, _) ->
3534         pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
3535         pr "      %s_stub (xdr_in);\n" name;
3536         pr "      break;\n"
3537   ) daemon_functions;
3538
3539   pr "    default:\n";
3540   pr "      reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d\", proc_nr);\n";
3541   pr "  }\n";
3542   pr "}\n";
3543   pr "\n";
3544
3545   (* LVM columns and tokenization functions. *)
3546   (* XXX This generates crap code.  We should rethink how we
3547    * do this parsing.
3548    *)
3549   List.iter (
3550     function
3551     | typ, cols ->
3552         pr "static const char *lvm_%s_cols = \"%s\";\n"
3553           typ (String.concat "," (List.map fst cols));
3554         pr "\n";
3555
3556         pr "static int lvm_tokenize_%s (char *str, struct guestfs_lvm_int_%s *r)\n" typ typ;
3557         pr "{\n";
3558         pr "  char *tok, *p, *next;\n";
3559         pr "  int i, j;\n";
3560         pr "\n";
3561         (*
3562         pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
3563         pr "\n";
3564         *)
3565         pr "  if (!str) {\n";
3566         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
3567         pr "    return -1;\n";
3568         pr "  }\n";
3569         pr "  if (!*str || isspace (*str)) {\n";
3570         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
3571         pr "    return -1;\n";
3572         pr "  }\n";
3573         pr "  tok = str;\n";
3574         List.iter (
3575           fun (name, coltype) ->
3576             pr "  if (!tok) {\n";
3577             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
3578             pr "    return -1;\n";
3579             pr "  }\n";
3580             pr "  p = strchrnul (tok, ',');\n";
3581             pr "  if (*p) next = p+1; else next = NULL;\n";
3582             pr "  *p = '\\0';\n";
3583             (match coltype with
3584              | `String ->
3585                  pr "  r->%s = strdup (tok);\n" name;
3586                  pr "  if (r->%s == NULL) {\n" name;
3587                  pr "    perror (\"strdup\");\n";
3588                  pr "    return -1;\n";
3589                  pr "  }\n"
3590              | `UUID ->
3591                  pr "  for (i = j = 0; i < 32; ++j) {\n";
3592                  pr "    if (tok[j] == '\\0') {\n";
3593                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
3594                  pr "      return -1;\n";
3595                  pr "    } else if (tok[j] != '-')\n";
3596                  pr "      r->%s[i++] = tok[j];\n" name;
3597                  pr "  }\n";
3598              | `Bytes ->
3599                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
3600                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3601                  pr "    return -1;\n";
3602                  pr "  }\n";
3603              | `Int ->
3604                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
3605                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3606                  pr "    return -1;\n";
3607                  pr "  }\n";
3608              | `OptPercent ->
3609                  pr "  if (tok[0] == '\\0')\n";
3610                  pr "    r->%s = -1;\n" name;
3611                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
3612                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3613                  pr "    return -1;\n";
3614                  pr "  }\n";
3615             );
3616             pr "  tok = next;\n";
3617         ) cols;
3618
3619         pr "  if (tok != NULL) {\n";
3620         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
3621         pr "    return -1;\n";
3622         pr "  }\n";
3623         pr "  return 0;\n";
3624         pr "}\n";
3625         pr "\n";
3626
3627         pr "guestfs_lvm_int_%s_list *\n" typ;
3628         pr "parse_command_line_%ss (void)\n" typ;
3629         pr "{\n";
3630         pr "  char *out, *err;\n";
3631         pr "  char *p, *pend;\n";
3632         pr "  int r, i;\n";
3633         pr "  guestfs_lvm_int_%s_list *ret;\n" typ;
3634         pr "  void *newp;\n";
3635         pr "\n";
3636         pr "  ret = malloc (sizeof *ret);\n";
3637         pr "  if (!ret) {\n";
3638         pr "    reply_with_perror (\"malloc\");\n";
3639         pr "    return NULL;\n";
3640         pr "  }\n";
3641         pr "\n";
3642         pr "  ret->guestfs_lvm_int_%s_list_len = 0;\n" typ;
3643         pr "  ret->guestfs_lvm_int_%s_list_val = NULL;\n" typ;
3644         pr "\n";
3645         pr "  r = command (&out, &err,\n";
3646         pr "           \"/sbin/lvm\", \"%ss\",\n" typ;
3647         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
3648         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
3649         pr "  if (r == -1) {\n";
3650         pr "    reply_with_error (\"%%s\", err);\n";
3651         pr "    free (out);\n";
3652         pr "    free (err);\n";
3653         pr "    free (ret);\n";
3654         pr "    return NULL;\n";
3655         pr "  }\n";
3656         pr "\n";
3657         pr "  free (err);\n";
3658         pr "\n";
3659         pr "  /* Tokenize each line of the output. */\n";
3660         pr "  p = out;\n";
3661         pr "  i = 0;\n";
3662         pr "  while (p) {\n";
3663         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
3664         pr "    if (pend) {\n";
3665         pr "      *pend = '\\0';\n";
3666         pr "      pend++;\n";
3667         pr "    }\n";
3668         pr "\n";
3669         pr "    while (*p && isspace (*p))      /* Skip any leading whitespace. */\n";
3670         pr "      p++;\n";
3671         pr "\n";
3672         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
3673         pr "      p = pend;\n";
3674         pr "      continue;\n";
3675         pr "    }\n";
3676         pr "\n";
3677         pr "    /* Allocate some space to store this next entry. */\n";
3678         pr "    newp = realloc (ret->guestfs_lvm_int_%s_list_val,\n" typ;
3679         pr "                sizeof (guestfs_lvm_int_%s) * (i+1));\n" typ;
3680         pr "    if (newp == NULL) {\n";
3681         pr "      reply_with_perror (\"realloc\");\n";
3682         pr "      free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3683         pr "      free (ret);\n";
3684         pr "      free (out);\n";
3685         pr "      return NULL;\n";
3686         pr "    }\n";
3687         pr "    ret->guestfs_lvm_int_%s_list_val = newp;\n" typ;
3688         pr "\n";
3689         pr "    /* Tokenize the next entry. */\n";
3690         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_lvm_int_%s_list_val[i]);\n" typ typ;
3691         pr "    if (r == -1) {\n";
3692         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
3693         pr "      free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3694         pr "      free (ret);\n";
3695         pr "      free (out);\n";
3696         pr "      return NULL;\n";
3697         pr "    }\n";
3698         pr "\n";
3699         pr "    ++i;\n";
3700         pr "    p = pend;\n";
3701         pr "  }\n";
3702         pr "\n";
3703         pr "  ret->guestfs_lvm_int_%s_list_len = i;\n" typ;
3704         pr "\n";
3705         pr "  free (out);\n";
3706         pr "  return ret;\n";
3707         pr "}\n"
3708
3709   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
3710
3711 (* Generate the tests. *)
3712 and generate_tests () =
3713   generate_header CStyle GPLv2;
3714
3715   pr "\
3716 #include <stdio.h>
3717 #include <stdlib.h>
3718 #include <string.h>
3719 #include <unistd.h>
3720 #include <sys/types.h>
3721 #include <fcntl.h>
3722
3723 #include \"guestfs.h\"
3724
3725 static guestfs_h *g;
3726 static int suppress_error = 0;
3727
3728 /* This will be 's' or 'h' depending on whether the guest kernel
3729  * names IDE devices /dev/sd* or /dev/hd*.
3730  */
3731 static char devchar = 's';
3732
3733 static void print_error (guestfs_h *g, void *data, const char *msg)
3734 {
3735   if (!suppress_error)
3736     fprintf (stderr, \"%%s\\n\", msg);
3737 }
3738
3739 static void print_strings (char * const * const argv)
3740 {
3741   int argc;
3742
3743   for (argc = 0; argv[argc] != NULL; ++argc)
3744     printf (\"\\t%%s\\n\", argv[argc]);
3745 }
3746
3747 /*
3748 static void print_table (char * const * const argv)
3749 {
3750   int i;
3751
3752   for (i = 0; argv[i] != NULL; i += 2)
3753     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
3754 }
3755 */
3756
3757 static void no_test_warnings (void)
3758 {
3759 ";
3760
3761   List.iter (
3762     function
3763     | name, _, _, _, [], _, _ ->
3764         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
3765     | name, _, _, _, tests, _, _ -> ()
3766   ) all_functions;
3767
3768   pr "}\n";
3769   pr "\n";
3770
3771   (* Generate the actual tests.  Note that we generate the tests
3772    * in reverse order, deliberately, so that (in general) the
3773    * newest tests run first.  This makes it quicker and easier to
3774    * debug them.
3775    *)
3776   let test_names =
3777     List.map (
3778       fun (name, _, _, _, tests, _, _) ->
3779         mapi (generate_one_test name) tests
3780     ) (List.rev all_functions) in
3781   let test_names = List.concat test_names in
3782   let nr_tests = List.length test_names in
3783
3784   pr "\
3785 int main (int argc, char *argv[])
3786 {
3787   char c = 0;
3788   int failed = 0;
3789   const char *srcdir;
3790   const char *filename;
3791   int fd, i;
3792   int nr_tests, test_num = 0;
3793   char **devs;
3794
3795   no_test_warnings ();
3796
3797   g = guestfs_create ();
3798   if (g == NULL) {
3799     printf (\"guestfs_create FAILED\\n\");
3800     exit (1);
3801   }
3802
3803   guestfs_set_error_handler (g, print_error, NULL);
3804
3805   guestfs_set_path (g, \"../appliance\");
3806
3807   filename = \"test1.img\";
3808   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3809   if (fd == -1) {
3810     perror (filename);
3811     exit (1);
3812   }
3813   if (lseek (fd, %d, SEEK_SET) == -1) {
3814     perror (\"lseek\");
3815     close (fd);
3816     unlink (filename);
3817     exit (1);
3818   }
3819   if (write (fd, &c, 1) == -1) {
3820     perror (\"write\");
3821     close (fd);
3822     unlink (filename);
3823     exit (1);
3824   }
3825   if (close (fd) == -1) {
3826     perror (filename);
3827     unlink (filename);
3828     exit (1);
3829   }
3830   if (guestfs_add_drive (g, filename) == -1) {
3831     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3832     exit (1);
3833   }
3834
3835   filename = \"test2.img\";
3836   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3837   if (fd == -1) {
3838     perror (filename);
3839     exit (1);
3840   }
3841   if (lseek (fd, %d, SEEK_SET) == -1) {
3842     perror (\"lseek\");
3843     close (fd);
3844     unlink (filename);
3845     exit (1);
3846   }
3847   if (write (fd, &c, 1) == -1) {
3848     perror (\"write\");
3849     close (fd);
3850     unlink (filename);
3851     exit (1);
3852   }
3853   if (close (fd) == -1) {
3854     perror (filename);
3855     unlink (filename);
3856     exit (1);
3857   }
3858   if (guestfs_add_drive (g, filename) == -1) {
3859     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3860     exit (1);
3861   }
3862
3863   filename = \"test3.img\";
3864   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3865   if (fd == -1) {
3866     perror (filename);
3867     exit (1);
3868   }
3869   if (lseek (fd, %d, SEEK_SET) == -1) {
3870     perror (\"lseek\");
3871     close (fd);
3872     unlink (filename);
3873     exit (1);
3874   }
3875   if (write (fd, &c, 1) == -1) {
3876     perror (\"write\");
3877     close (fd);
3878     unlink (filename);
3879     exit (1);
3880   }
3881   if (close (fd) == -1) {
3882     perror (filename);
3883     unlink (filename);
3884     exit (1);
3885   }
3886   if (guestfs_add_drive (g, filename) == -1) {
3887     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3888     exit (1);
3889   }
3890
3891   if (guestfs_launch (g) == -1) {
3892     printf (\"guestfs_launch FAILED\\n\");
3893     exit (1);
3894   }
3895   if (guestfs_wait_ready (g) == -1) {
3896     printf (\"guestfs_wait_ready FAILED\\n\");
3897     exit (1);
3898   }
3899
3900   /* Detect if the appliance uses /dev/sd* or /dev/hd* in device
3901    * names.  This changed between RHEL 5 and RHEL 6 so we have to
3902    * support both.
3903    */
3904   devs = guestfs_list_devices (g);
3905   if (devs == NULL || devs[0] == NULL) {
3906     printf (\"guestfs_list_devices FAILED\\n\");
3907     exit (1);
3908   }
3909   if (strncmp (devs[0], \"/dev/sd\", 7) == 0)
3910     devchar = 's';
3911   else if (strncmp (devs[0], \"/dev/hd\", 7) == 0)
3912     devchar = 'h';
3913   else {
3914     printf (\"guestfs_list_devices returned unexpected string '%%s'\\n\",
3915             devs[0]);
3916     exit (1);
3917   }
3918   for (i = 0; devs[i] != NULL; ++i)
3919     free (devs[i]);
3920   free (devs);
3921
3922   nr_tests = %d;
3923
3924 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
3925
3926   iteri (
3927     fun i test_name ->
3928       pr "  test_num++;\n";
3929       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
3930       pr "  if (%s () == -1) {\n" test_name;
3931       pr "    printf (\"%s FAILED\\n\");\n" test_name;
3932       pr "    failed++;\n";
3933       pr "  }\n";
3934   ) test_names;
3935   pr "\n";
3936
3937   pr "  guestfs_close (g);\n";
3938   pr "  unlink (\"test1.img\");\n";
3939   pr "  unlink (\"test2.img\");\n";
3940   pr "  unlink (\"test3.img\");\n";
3941   pr "\n";
3942
3943   pr "  if (failed > 0) {\n";
3944   pr "    printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
3945   pr "    exit (1);\n";
3946   pr "  }\n";
3947   pr "\n";
3948
3949   pr "  exit (0);\n";
3950   pr "}\n"
3951
3952 and generate_one_test name i (init, prereq, test) =
3953   let test_name = sprintf "test_%s_%d" name i in
3954
3955   pr "\
3956 static int %s_skip (void)
3957 {
3958   const char *str;
3959
3960   str = getenv (\"SKIP_%s\");
3961   if (str && strcmp (str, \"1\") == 0) return 1;
3962   str = getenv (\"SKIP_TEST_%s\");
3963   if (str && strcmp (str, \"1\") == 0) return 1;
3964   return 0;
3965 }
3966
3967 " test_name (String.uppercase test_name) (String.uppercase name);
3968
3969   (match prereq with
3970    | Disabled | Always -> ()
3971    | If code | Unless code ->
3972        pr "static int %s_prereq (void)\n" test_name;
3973        pr "{\n";
3974        pr "  %s\n" code;
3975        pr "}\n";
3976        pr "\n";
3977   );
3978
3979   pr "\
3980 static int %s (void)
3981 {
3982   if (%s_skip ()) {
3983     printf (\"%%s skipped (reason: SKIP_TEST_* variable set)\\n\", \"%s\");
3984     return 0;
3985   }
3986
3987 " test_name test_name test_name;
3988
3989   (match prereq with
3990    | Disabled ->
3991        pr "  printf (\"%%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
3992    | If _ ->
3993        pr "  if (! %s_prereq ()) {\n" test_name;
3994        pr "    printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
3995        pr "    return 0;\n";
3996        pr "  }\n";
3997        pr "\n";
3998        generate_one_test_body name i test_name init test;
3999    | Unless _ ->
4000        pr "  if (%s_prereq ()) {\n" test_name;
4001        pr "    printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4002        pr "    return 0;\n";
4003        pr "  }\n";
4004        pr "\n";
4005        generate_one_test_body name i test_name init test;
4006    | Always ->
4007        generate_one_test_body name i test_name init test
4008   );
4009
4010   pr "  return 0;\n";
4011   pr "}\n";
4012   pr "\n";
4013   test_name
4014
4015 and generate_one_test_body name i test_name init test =
4016   (match init with
4017    | InitNone
4018    | InitEmpty ->
4019        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
4020        List.iter (generate_test_command_call test_name)
4021          [["blockdev_setrw"; "/dev/sda"];
4022           ["umount_all"];
4023           ["lvm_remove_all"]]
4024    | InitBasicFS ->
4025        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
4026        List.iter (generate_test_command_call test_name)
4027          [["blockdev_setrw"; "/dev/sda"];
4028           ["umount_all"];
4029           ["lvm_remove_all"];
4030           ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4031           ["mkfs"; "ext2"; "/dev/sda1"];
4032           ["mount"; "/dev/sda1"; "/"]]
4033    | InitBasicFSonLVM ->
4034        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
4035          test_name;
4036        List.iter (generate_test_command_call test_name)
4037          [["blockdev_setrw"; "/dev/sda"];
4038           ["umount_all"];
4039           ["lvm_remove_all"];
4040           ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4041           ["pvcreate"; "/dev/sda1"];
4042           ["vgcreate"; "VG"; "/dev/sda1"];
4043           ["lvcreate"; "LV"; "VG"; "8"];
4044           ["mkfs"; "ext2"; "/dev/VG/LV"];
4045           ["mount"; "/dev/VG/LV"; "/"]]
4046   );
4047
4048   let get_seq_last = function
4049     | [] ->
4050         failwithf "%s: you cannot use [] (empty list) when expecting a command"
4051           test_name
4052     | seq ->
4053         let seq = List.rev seq in
4054         List.rev (List.tl seq), List.hd seq
4055   in
4056
4057   match test with
4058   | TestRun seq ->
4059       pr "  /* TestRun for %s (%d) */\n" name i;
4060       List.iter (generate_test_command_call test_name) seq
4061   | TestOutput (seq, expected) ->
4062       pr "  /* TestOutput for %s (%d) */\n" name i;
4063       pr "  char expected[] = \"%s\";\n" (c_quote expected);
4064       if String.length expected > 7 &&
4065         String.sub expected 0 7 = "/dev/sd" then
4066           pr "  expected[5] = devchar;\n";
4067       let seq, last = get_seq_last seq in
4068       let test () =
4069         pr "    if (strcmp (r, expected) != 0) {\n";
4070         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
4071         pr "      return -1;\n";
4072         pr "    }\n"
4073       in
4074       List.iter (generate_test_command_call test_name) seq;
4075       generate_test_command_call ~test test_name last
4076   | TestOutputList (seq, expected) ->
4077       pr "  /* TestOutputList for %s (%d) */\n" name i;
4078       let seq, last = get_seq_last seq in
4079       let test () =
4080         iteri (
4081           fun i str ->
4082             pr "    if (!r[%d]) {\n" i;
4083             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4084             pr "      print_strings (r);\n";
4085             pr "      return -1;\n";
4086             pr "    }\n";
4087             pr "    {\n";
4088             pr "      char expected[] = \"%s\";\n" (c_quote str);
4089             if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4090               pr "      expected[5] = devchar;\n";
4091             pr "      if (strcmp (r[%d], expected) != 0) {\n" i;
4092             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4093             pr "        return -1;\n";
4094             pr "      }\n";
4095             pr "    }\n"
4096         ) expected;
4097         pr "    if (r[%d] != NULL) {\n" (List.length expected);
4098         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4099           test_name;
4100         pr "      print_strings (r);\n";
4101         pr "      return -1;\n";
4102         pr "    }\n"
4103       in
4104       List.iter (generate_test_command_call test_name) seq;
4105       generate_test_command_call ~test test_name last
4106   | TestOutputInt (seq, expected) ->
4107       pr "  /* TestOutputInt for %s (%d) */\n" name i;
4108       let seq, last = get_seq_last seq in
4109       let test () =
4110         pr "    if (r != %d) {\n" expected;
4111         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
4112           test_name expected;
4113         pr "               (int) r);\n";
4114         pr "      return -1;\n";
4115         pr "    }\n"
4116       in
4117       List.iter (generate_test_command_call test_name) seq;
4118       generate_test_command_call ~test test_name last
4119   | TestOutputTrue seq ->
4120       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
4121       let seq, last = get_seq_last seq in
4122       let test () =
4123         pr "    if (!r) {\n";
4124         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
4125           test_name;
4126         pr "      return -1;\n";
4127         pr "    }\n"
4128       in
4129       List.iter (generate_test_command_call test_name) seq;
4130       generate_test_command_call ~test test_name last
4131   | TestOutputFalse seq ->
4132       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
4133       let seq, last = get_seq_last seq in
4134       let test () =
4135         pr "    if (r) {\n";
4136         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
4137           test_name;
4138         pr "      return -1;\n";
4139         pr "    }\n"
4140       in
4141       List.iter (generate_test_command_call test_name) seq;
4142       generate_test_command_call ~test test_name last
4143   | TestOutputLength (seq, expected) ->
4144       pr "  /* TestOutputLength for %s (%d) */\n" name i;
4145       let seq, last = get_seq_last seq in
4146       let test () =
4147         pr "    int j;\n";
4148         pr "    for (j = 0; j < %d; ++j)\n" expected;
4149         pr "      if (r[j] == NULL) {\n";
4150         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
4151           test_name;
4152         pr "        print_strings (r);\n";
4153         pr "        return -1;\n";
4154         pr "      }\n";
4155         pr "    if (r[j] != NULL) {\n";
4156         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
4157           test_name;
4158         pr "      print_strings (r);\n";
4159         pr "      return -1;\n";
4160         pr "    }\n"
4161       in
4162       List.iter (generate_test_command_call test_name) seq;
4163       generate_test_command_call ~test test_name last
4164   | TestOutputStruct (seq, checks) ->
4165       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
4166       let seq, last = get_seq_last seq in
4167       let test () =
4168         List.iter (
4169           function
4170           | CompareWithInt (field, expected) ->
4171               pr "    if (r->%s != %d) {\n" field expected;
4172               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
4173                 test_name field expected;
4174               pr "               (int) r->%s);\n" field;
4175               pr "      return -1;\n";
4176               pr "    }\n"
4177           | CompareWithString (field, expected) ->
4178               pr "    if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
4179               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
4180                 test_name field expected;
4181               pr "               r->%s);\n" field;
4182               pr "      return -1;\n";
4183               pr "    }\n"
4184           | CompareFieldsIntEq (field1, field2) ->
4185               pr "    if (r->%s != r->%s) {\n" field1 field2;
4186               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
4187                 test_name field1 field2;
4188               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
4189               pr "      return -1;\n";
4190               pr "    }\n"
4191           | CompareFieldsStrEq (field1, field2) ->
4192               pr "    if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
4193               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
4194                 test_name field1 field2;
4195               pr "               r->%s, r->%s);\n" field1 field2;
4196               pr "      return -1;\n";
4197               pr "    }\n"
4198         ) checks
4199       in
4200       List.iter (generate_test_command_call test_name) seq;
4201       generate_test_command_call ~test test_name last
4202   | TestLastFail seq ->
4203       pr "  /* TestLastFail for %s (%d) */\n" name i;
4204       let seq, last = get_seq_last seq in
4205       List.iter (generate_test_command_call test_name) seq;
4206       generate_test_command_call test_name ~expect_error:true last
4207
4208 (* Generate the code to run a command, leaving the result in 'r'.
4209  * If you expect to get an error then you should set expect_error:true.
4210  *)
4211 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
4212   match cmd with
4213   | [] -> assert false
4214   | name :: args ->
4215       (* Look up the command to find out what args/ret it has. *)
4216       let style =
4217         try
4218           let _, style, _, _, _, _, _ =
4219             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
4220           style
4221         with Not_found ->
4222           failwithf "%s: in test, command %s was not found" test_name name in
4223
4224       if List.length (snd style) <> List.length args then
4225         failwithf "%s: in test, wrong number of args given to %s"
4226           test_name name;
4227
4228       pr "  {\n";
4229
4230       List.iter (
4231         function
4232         | OptString n, "NULL" -> ()
4233         | String n, arg
4234         | OptString n, arg ->
4235             pr "    char %s[] = \"%s\";\n" n (c_quote arg);
4236             if String.length arg > 7 && String.sub arg 0 7 = "/dev/sd" then
4237               pr "    %s[5] = devchar;\n" n
4238         | Int _, _
4239         | Bool _, _
4240         | FileIn _, _ | FileOut _, _ -> ()
4241         | StringList n, arg ->
4242             let strs = string_split " " arg in
4243             iteri (
4244               fun i str ->
4245                 pr "    char %s_%d[] = \"%s\";\n" n i (c_quote str);
4246                 if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4247                   pr "    %s_%d[5] = devchar;\n" n i
4248             ) strs;
4249             pr "    char *%s[] = {\n" n;
4250             iteri (
4251               fun i _ -> pr "      %s_%d,\n" n i
4252             ) strs;
4253             pr "      NULL\n";
4254             pr "    };\n";
4255       ) (List.combine (snd style) args);
4256
4257       let error_code =
4258         match fst style with
4259         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
4260         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
4261         | RConstString _ -> pr "    const char *r;\n"; "NULL"
4262         | RString _ -> pr "    char *r;\n"; "NULL"
4263         | RStringList _ | RHashtable _ ->
4264             pr "    char **r;\n";
4265             pr "    int i;\n";
4266             "NULL"
4267         | RIntBool _ ->
4268             pr "    struct guestfs_int_bool *r;\n"; "NULL"
4269         | RPVList _ ->
4270             pr "    struct guestfs_lvm_pv_list *r;\n"; "NULL"
4271         | RVGList _ ->
4272             pr "    struct guestfs_lvm_vg_list *r;\n"; "NULL"
4273         | RLVList _ ->
4274             pr "    struct guestfs_lvm_lv_list *r;\n"; "NULL"
4275         | RStat _ ->
4276             pr "    struct guestfs_stat *r;\n"; "NULL"
4277         | RStatVFS _ ->
4278             pr "    struct guestfs_statvfs *r;\n"; "NULL" in
4279
4280       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
4281       pr "    r = guestfs_%s (g" name;
4282
4283       (* Generate the parameters. *)
4284       List.iter (
4285         function
4286         | OptString _, "NULL" -> pr ", NULL"
4287         | String n, _
4288         | OptString n, _ ->
4289             pr ", %s" n
4290         | FileIn _, arg | FileOut _, arg ->
4291             pr ", \"%s\"" (c_quote arg)
4292         | StringList n, _ ->
4293             pr ", %s" n
4294         | Int _, arg ->
4295             let i =
4296               try int_of_string arg
4297               with Failure "int_of_string" ->
4298                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
4299             pr ", %d" i
4300         | Bool _, arg ->
4301             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
4302       ) (List.combine (snd style) args);
4303
4304       pr ");\n";
4305       if not expect_error then
4306         pr "    if (r == %s)\n" error_code
4307       else
4308         pr "    if (r != %s)\n" error_code;
4309       pr "      return -1;\n";
4310
4311       (* Insert the test code. *)
4312       (match test with
4313        | None -> ()
4314        | Some f -> f ()
4315       );
4316
4317       (match fst style with
4318        | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _ -> ()
4319        | RString _ -> pr "    free (r);\n"
4320        | RStringList _ | RHashtable _ ->
4321            pr "    for (i = 0; r[i] != NULL; ++i)\n";
4322            pr "      free (r[i]);\n";
4323            pr "    free (r);\n"
4324        | RIntBool _ ->
4325            pr "    guestfs_free_int_bool (r);\n"
4326        | RPVList _ ->
4327            pr "    guestfs_free_lvm_pv_list (r);\n"
4328        | RVGList _ ->
4329            pr "    guestfs_free_lvm_vg_list (r);\n"
4330        | RLVList _ ->
4331            pr "    guestfs_free_lvm_lv_list (r);\n"
4332        | RStat _ | RStatVFS _ ->
4333            pr "    free (r);\n"
4334       );
4335
4336       pr "  }\n"
4337
4338 and c_quote str =
4339   let str = replace_str str "\r" "\\r" in
4340   let str = replace_str str "\n" "\\n" in
4341   let str = replace_str str "\t" "\\t" in
4342   let str = replace_str str "\000" "\\0" in
4343   str
4344
4345 (* Generate a lot of different functions for guestfish. *)
4346 and generate_fish_cmds () =
4347   generate_header CStyle GPLv2;
4348
4349   let all_functions =
4350     List.filter (
4351       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4352     ) all_functions in
4353   let all_functions_sorted =
4354     List.filter (
4355       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4356     ) all_functions_sorted in
4357
4358   pr "#include <stdio.h>\n";
4359   pr "#include <stdlib.h>\n";
4360   pr "#include <string.h>\n";
4361   pr "#include <inttypes.h>\n";
4362   pr "\n";
4363   pr "#include <guestfs.h>\n";
4364   pr "#include \"fish.h\"\n";
4365   pr "\n";
4366
4367   (* list_commands function, which implements guestfish -h *)
4368   pr "void list_commands (void)\n";
4369   pr "{\n";
4370   pr "  printf (\"    %%-16s     %%s\\n\", \"Command\", \"Description\");\n";
4371   pr "  list_builtin_commands ();\n";
4372   List.iter (
4373     fun (name, _, _, flags, _, shortdesc, _) ->
4374       let name = replace_char name '_' '-' in
4375       pr "  printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
4376         name shortdesc
4377   ) all_functions_sorted;
4378   pr "  printf (\"    Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
4379   pr "}\n";
4380   pr "\n";
4381
4382   (* display_command function, which implements guestfish -h cmd *)
4383   pr "void display_command (const char *cmd)\n";
4384   pr "{\n";
4385   List.iter (
4386     fun (name, style, _, flags, _, shortdesc, longdesc) ->
4387       let name2 = replace_char name '_' '-' in
4388       let alias =
4389         try find_map (function FishAlias n -> Some n | _ -> None) flags
4390         with Not_found -> name in
4391       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
4392       let synopsis =
4393         match snd style with
4394         | [] -> name2
4395         | args ->
4396             sprintf "%s <%s>"
4397               name2 (String.concat "> <" (List.map name_of_argt args)) in
4398
4399       let warnings =
4400         if List.mem ProtocolLimitWarning flags then
4401           ("\n\n" ^ protocol_limit_warning)
4402         else "" in
4403
4404       (* For DangerWillRobinson commands, we should probably have
4405        * guestfish prompt before allowing you to use them (especially
4406        * in interactive mode). XXX
4407        *)
4408       let warnings =
4409         warnings ^
4410           if List.mem DangerWillRobinson flags then
4411             ("\n\n" ^ danger_will_robinson)
4412           else "" in
4413
4414       let describe_alias =
4415         if name <> alias then
4416           sprintf "\n\nYou can use '%s' as an alias for this command." alias
4417         else "" in
4418
4419       pr "  if (";
4420       pr "strcasecmp (cmd, \"%s\") == 0" name;
4421       if name <> name2 then
4422         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4423       if name <> alias then
4424         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4425       pr ")\n";
4426       pr "    pod2text (\"%s - %s\", %S);\n"
4427         name2 shortdesc
4428         (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
4429       pr "  else\n"
4430   ) all_functions;
4431   pr "    display_builtin_command (cmd);\n";
4432   pr "}\n";
4433   pr "\n";
4434
4435   (* print_{pv,vg,lv}_list functions *)
4436   List.iter (
4437     function
4438     | typ, cols ->
4439         pr "static void print_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
4440         pr "{\n";
4441         pr "  int i;\n";
4442         pr "\n";
4443         List.iter (
4444           function
4445           | name, `String ->
4446               pr "  printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
4447           | name, `UUID ->
4448               pr "  printf (\"%s: \");\n" name;
4449               pr "  for (i = 0; i < 32; ++i)\n";
4450               pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
4451               pr "  printf (\"\\n\");\n"
4452           | name, `Bytes ->
4453               pr "  printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
4454           | name, `Int ->
4455               pr "  printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4456           | name, `OptPercent ->
4457               pr "  if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
4458                 typ name name typ name;
4459               pr "  else printf (\"%s: \\n\");\n" name
4460         ) cols;
4461         pr "}\n";
4462         pr "\n";
4463         pr "static void print_%s_list (struct guestfs_lvm_%s_list *%ss)\n"
4464           typ typ typ;
4465         pr "{\n";
4466         pr "  int i;\n";
4467         pr "\n";
4468         pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
4469         pr "    print_%s (&%ss->val[i]);\n" typ typ;
4470         pr "}\n";
4471         pr "\n";
4472   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
4473
4474   (* print_{stat,statvfs} functions *)
4475   List.iter (
4476     function
4477     | typ, cols ->
4478         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
4479         pr "{\n";
4480         List.iter (
4481           function
4482           | name, `Int ->
4483               pr "  printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4484         ) cols;
4485         pr "}\n";
4486         pr "\n";
4487   ) ["stat", stat_cols; "statvfs", statvfs_cols];
4488
4489   (* run_<action> actions *)
4490   List.iter (
4491     fun (name, style, _, flags, _, _, _) ->
4492       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
4493       pr "{\n";
4494       (match fst style with
4495        | RErr
4496        | RInt _
4497        | RBool _ -> pr "  int r;\n"
4498        | RInt64 _ -> pr "  int64_t r;\n"
4499        | RConstString _ -> pr "  const char *r;\n"
4500        | RString _ -> pr "  char *r;\n"
4501        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
4502        | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"
4503        | RPVList _ -> pr "  struct guestfs_lvm_pv_list *r;\n"
4504        | RVGList _ -> pr "  struct guestfs_lvm_vg_list *r;\n"
4505        | RLVList _ -> pr "  struct guestfs_lvm_lv_list *r;\n"
4506        | RStat _ -> pr "  struct guestfs_stat *r;\n"
4507        | RStatVFS _ -> pr "  struct guestfs_statvfs *r;\n"
4508       );
4509       List.iter (
4510         function
4511         | String n
4512         | OptString n
4513         | FileIn n
4514         | FileOut n -> pr "  const char *%s;\n" n
4515         | StringList n -> pr "  char **%s;\n" n
4516         | Bool n -> pr "  int %s;\n" n
4517         | Int n -> pr "  int %s;\n" n
4518       ) (snd style);
4519
4520       (* Check and convert parameters. *)
4521       let argc_expected = List.length (snd style) in
4522       pr "  if (argc != %d) {\n" argc_expected;
4523       pr "    fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
4524         argc_expected;
4525       pr "    fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
4526       pr "    return -1;\n";
4527       pr "  }\n";
4528       iteri (
4529         fun i ->
4530           function
4531           | String name -> pr "  %s = argv[%d];\n" name i
4532           | OptString name ->
4533               pr "  %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
4534                 name i i
4535           | FileIn name ->
4536               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
4537                 name i i
4538           | FileOut name ->
4539               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
4540                 name i i
4541           | StringList name ->
4542               pr "  %s = parse_string_list (argv[%d]);\n" name i
4543           | Bool name ->
4544               pr "  %s = is_true (argv[%d]) ? 1 : 0;\n" name i
4545           | Int name ->
4546               pr "  %s = atoi (argv[%d]);\n" name i
4547       ) (snd style);
4548
4549       (* Call C API function. *)
4550       let fn =
4551         try find_map (function FishAction n -> Some n | _ -> None) flags
4552         with Not_found -> sprintf "guestfs_%s" name in
4553       pr "  r = %s " fn;
4554       generate_call_args ~handle:"g" (snd style);
4555       pr ";\n";
4556
4557       (* Check return value for errors and display command results. *)
4558       (match fst style with
4559        | RErr -> pr "  return r;\n"
4560        | RInt _ ->
4561            pr "  if (r == -1) return -1;\n";
4562            pr "  printf (\"%%d\\n\", r);\n";
4563            pr "  return 0;\n"
4564        | RInt64 _ ->
4565            pr "  if (r == -1) return -1;\n";
4566            pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
4567            pr "  return 0;\n"
4568        | RBool _ ->
4569            pr "  if (r == -1) return -1;\n";
4570            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
4571            pr "  return 0;\n"
4572        | RConstString _ ->
4573            pr "  if (r == NULL) return -1;\n";
4574            pr "  printf (\"%%s\\n\", r);\n";
4575            pr "  return 0;\n"
4576        | RString _ ->
4577            pr "  if (r == NULL) return -1;\n";
4578            pr "  printf (\"%%s\\n\", r);\n";
4579            pr "  free (r);\n";
4580            pr "  return 0;\n"
4581        | RStringList _ ->
4582            pr "  if (r == NULL) return -1;\n";
4583            pr "  print_strings (r);\n";
4584            pr "  free_strings (r);\n";
4585            pr "  return 0;\n"
4586        | RIntBool _ ->
4587            pr "  if (r == NULL) return -1;\n";
4588            pr "  printf (\"%%d, %%s\\n\", r->i,\n";
4589            pr "    r->b ? \"true\" : \"false\");\n";
4590            pr "  guestfs_free_int_bool (r);\n";
4591            pr "  return 0;\n"
4592        | RPVList _ ->
4593            pr "  if (r == NULL) return -1;\n";
4594            pr "  print_pv_list (r);\n";
4595            pr "  guestfs_free_lvm_pv_list (r);\n";
4596            pr "  return 0;\n"
4597        | RVGList _ ->
4598            pr "  if (r == NULL) return -1;\n";
4599            pr "  print_vg_list (r);\n";
4600            pr "  guestfs_free_lvm_vg_list (r);\n";
4601            pr "  return 0;\n"
4602        | RLVList _ ->
4603            pr "  if (r == NULL) return -1;\n";
4604            pr "  print_lv_list (r);\n";
4605            pr "  guestfs_free_lvm_lv_list (r);\n";
4606            pr "  return 0;\n"
4607        | RStat _ ->
4608            pr "  if (r == NULL) return -1;\n";
4609            pr "  print_stat (r);\n";
4610            pr "  free (r);\n";
4611            pr "  return 0;\n"
4612        | RStatVFS _ ->
4613            pr "  if (r == NULL) return -1;\n";
4614            pr "  print_statvfs (r);\n";
4615            pr "  free (r);\n";
4616            pr "  return 0;\n"
4617        | RHashtable _ ->
4618            pr "  if (r == NULL) return -1;\n";
4619            pr "  print_table (r);\n";
4620            pr "  free_strings (r);\n";
4621            pr "  return 0;\n"
4622       );
4623       pr "}\n";
4624       pr "\n"
4625   ) all_functions;
4626
4627   (* run_action function *)
4628   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
4629   pr "{\n";
4630   List.iter (
4631     fun (name, _, _, flags, _, _, _) ->
4632       let name2 = replace_char name '_' '-' in
4633       let alias =
4634         try find_map (function FishAlias n -> Some n | _ -> None) flags
4635         with Not_found -> name in
4636       pr "  if (";
4637       pr "strcasecmp (cmd, \"%s\") == 0" name;
4638       if name <> name2 then
4639         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4640       if name <> alias then
4641         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4642       pr ")\n";
4643       pr "    return run_%s (cmd, argc, argv);\n" name;
4644       pr "  else\n";
4645   ) all_functions;
4646   pr "    {\n";
4647   pr "      fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
4648   pr "      return -1;\n";
4649   pr "    }\n";
4650   pr "  return 0;\n";
4651   pr "}\n";
4652   pr "\n"
4653
4654 (* Readline completion for guestfish. *)
4655 and generate_fish_completion () =
4656   generate_header CStyle GPLv2;
4657
4658   let all_functions =
4659     List.filter (
4660       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4661     ) all_functions in
4662
4663   pr "\
4664 #include <config.h>
4665
4666 #include <stdio.h>
4667 #include <stdlib.h>
4668 #include <string.h>
4669
4670 #ifdef HAVE_LIBREADLINE
4671 #include <readline/readline.h>
4672 #endif
4673
4674 #include \"fish.h\"
4675
4676 #ifdef HAVE_LIBREADLINE
4677
4678 static const char *const commands[] = {
4679   BUILTIN_COMMANDS_FOR_COMPLETION,
4680 ";
4681
4682   (* Get the commands, including the aliases.  They don't need to be
4683    * sorted - the generator() function just does a dumb linear search.
4684    *)
4685   let commands =
4686     List.map (
4687       fun (name, _, _, flags, _, _, _) ->
4688         let name2 = replace_char name '_' '-' in
4689         let alias =
4690           try find_map (function FishAlias n -> Some n | _ -> None) flags
4691           with Not_found -> name in
4692
4693         if name <> alias then [name2; alias] else [name2]
4694     ) all_functions in
4695   let commands = List.flatten commands in
4696
4697   List.iter (pr "  \"%s\",\n") commands;
4698
4699   pr "  NULL
4700 };
4701
4702 static char *
4703 generator (const char *text, int state)
4704 {
4705   static int index, len;
4706   const char *name;
4707
4708   if (!state) {
4709     index = 0;
4710     len = strlen (text);
4711   }
4712
4713   while ((name = commands[index]) != NULL) {
4714     index++;
4715     if (strncasecmp (name, text, len) == 0)
4716       return strdup (name);
4717   }
4718
4719   return NULL;
4720 }
4721
4722 #endif /* HAVE_LIBREADLINE */
4723
4724 char **do_completion (const char *text, int start, int end)
4725 {
4726   char **matches = NULL;
4727
4728 #ifdef HAVE_LIBREADLINE
4729   if (start == 0)
4730     matches = rl_completion_matches (text, generator);
4731 #endif
4732
4733   return matches;
4734 }
4735 ";
4736
4737 (* Generate the POD documentation for guestfish. *)
4738 and generate_fish_actions_pod () =
4739   let all_functions_sorted =
4740     List.filter (
4741       fun (_, _, _, flags, _, _, _) ->
4742         not (List.mem NotInFish flags || List.mem NotInDocs flags)
4743     ) all_functions_sorted in
4744
4745   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
4746
4747   List.iter (
4748     fun (name, style, _, flags, _, _, longdesc) ->
4749       let longdesc =
4750         Str.global_substitute rex (
4751           fun s ->
4752             let sub =
4753               try Str.matched_group 1 s
4754               with Not_found ->
4755                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
4756             "C<" ^ replace_char sub '_' '-' ^ ">"
4757         ) longdesc in
4758       let name = replace_char name '_' '-' in
4759       let alias =
4760         try find_map (function FishAlias n -> Some n | _ -> None) flags
4761         with Not_found -> name in
4762
4763       pr "=head2 %s" name;
4764       if name <> alias then
4765         pr " | %s" alias;
4766       pr "\n";
4767       pr "\n";
4768       pr " %s" name;
4769       List.iter (
4770         function
4771         | String n -> pr " %s" n
4772         | OptString n -> pr " %s" n
4773         | StringList n -> pr " '%s ...'" n
4774         | Bool _ -> pr " true|false"
4775         | Int n -> pr " %s" n
4776         | FileIn n | FileOut n -> pr " (%s|-)" n
4777       ) (snd style);
4778       pr "\n";
4779       pr "\n";
4780       pr "%s\n\n" longdesc;
4781
4782       if List.exists (function FileIn _ | FileOut _ -> true
4783                       | _ -> false) (snd style) then
4784         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
4785
4786       if List.mem ProtocolLimitWarning flags then
4787         pr "%s\n\n" protocol_limit_warning;
4788
4789       if List.mem DangerWillRobinson flags then
4790         pr "%s\n\n" danger_will_robinson
4791   ) all_functions_sorted
4792
4793 (* Generate a C function prototype. *)
4794 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
4795     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
4796     ?(prefix = "")
4797     ?handle name style =
4798   if extern then pr "extern ";
4799   if static then pr "static ";
4800   (match fst style with
4801    | RErr -> pr "int "
4802    | RInt _ -> pr "int "
4803    | RInt64 _ -> pr "int64_t "
4804    | RBool _ -> pr "int "
4805    | RConstString _ -> pr "const char *"
4806    | RString _ -> pr "char *"
4807    | RStringList _ | RHashtable _ -> pr "char **"
4808    | RIntBool _ ->
4809        if not in_daemon then pr "struct guestfs_int_bool *"
4810        else pr "guestfs_%s_ret *" name
4811    | RPVList _ ->
4812        if not in_daemon then pr "struct guestfs_lvm_pv_list *"
4813        else pr "guestfs_lvm_int_pv_list *"
4814    | RVGList _ ->
4815        if not in_daemon then pr "struct guestfs_lvm_vg_list *"
4816        else pr "guestfs_lvm_int_vg_list *"
4817    | RLVList _ ->
4818        if not in_daemon then pr "struct guestfs_lvm_lv_list *"
4819        else pr "guestfs_lvm_int_lv_list *"
4820    | RStat _ ->
4821        if not in_daemon then pr "struct guestfs_stat *"
4822        else pr "guestfs_int_stat *"
4823    | RStatVFS _ ->
4824        if not in_daemon then pr "struct guestfs_statvfs *"
4825        else pr "guestfs_int_statvfs *"
4826   );
4827   pr "%s%s (" prefix name;
4828   if handle = None && List.length (snd style) = 0 then
4829     pr "void"
4830   else (
4831     let comma = ref false in
4832     (match handle with
4833      | None -> ()
4834      | Some handle -> pr "guestfs_h *%s" handle; comma := true
4835     );
4836     let next () =
4837       if !comma then (
4838         if single_line then pr ", " else pr ",\n\t\t"
4839       );
4840       comma := true
4841     in
4842     List.iter (
4843       function
4844       | String n
4845       | OptString n -> next (); pr "const char *%s" n
4846       | StringList n -> next (); pr "char * const* const %s" n
4847       | Bool n -> next (); pr "int %s" n
4848       | Int n -> next (); pr "int %s" n
4849       | FileIn n
4850       | FileOut n ->
4851           if not in_daemon then (next (); pr "const char *%s" n)
4852     ) (snd style);
4853   );
4854   pr ")";
4855   if semicolon then pr ";";
4856   if newline then pr "\n"
4857
4858 (* Generate C call arguments, eg "(handle, foo, bar)" *)
4859 and generate_call_args ?handle args =
4860   pr "(";
4861   let comma = ref false in
4862   (match handle with
4863    | None -> ()
4864    | Some handle -> pr "%s" handle; comma := true
4865   );
4866   List.iter (
4867     fun arg ->
4868       if !comma then pr ", ";
4869       comma := true;
4870       pr "%s" (name_of_argt arg)
4871   ) args;
4872   pr ")"
4873
4874 (* Generate the OCaml bindings interface. *)
4875 and generate_ocaml_mli () =
4876   generate_header OCamlStyle LGPLv2;
4877
4878   pr "\
4879 (** For API documentation you should refer to the C API
4880     in the guestfs(3) manual page.  The OCaml API uses almost
4881     exactly the same calls. *)
4882
4883 type t
4884 (** A [guestfs_h] handle. *)
4885
4886 exception Error of string
4887 (** This exception is raised when there is an error. *)
4888
4889 val create : unit -> t
4890
4891 val close : t -> unit
4892 (** Handles are closed by the garbage collector when they become
4893     unreferenced, but callers can also call this in order to
4894     provide predictable cleanup. *)
4895
4896 ";
4897   generate_ocaml_lvm_structure_decls ();
4898
4899   generate_ocaml_stat_structure_decls ();
4900
4901   (* The actions. *)
4902   List.iter (
4903     fun (name, style, _, _, _, shortdesc, _) ->
4904       generate_ocaml_prototype name style;
4905       pr "(** %s *)\n" shortdesc;
4906       pr "\n"
4907   ) all_functions
4908
4909 (* Generate the OCaml bindings implementation. *)
4910 and generate_ocaml_ml () =
4911   generate_header OCamlStyle LGPLv2;
4912
4913   pr "\
4914 type t
4915 exception Error of string
4916 external create : unit -> t = \"ocaml_guestfs_create\"
4917 external close : t -> unit = \"ocaml_guestfs_close\"
4918
4919 let () =
4920   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
4921
4922 ";
4923
4924   generate_ocaml_lvm_structure_decls ();
4925
4926   generate_ocaml_stat_structure_decls ();
4927
4928   (* The actions. *)
4929   List.iter (
4930     fun (name, style, _, _, _, shortdesc, _) ->
4931       generate_ocaml_prototype ~is_external:true name style;
4932   ) all_functions
4933
4934 (* Generate the OCaml bindings C implementation. *)
4935 and generate_ocaml_c () =
4936   generate_header CStyle LGPLv2;
4937
4938   pr "\
4939 #include <stdio.h>
4940 #include <stdlib.h>
4941 #include <string.h>
4942
4943 #include <caml/config.h>
4944 #include <caml/alloc.h>
4945 #include <caml/callback.h>
4946 #include <caml/fail.h>
4947 #include <caml/memory.h>
4948 #include <caml/mlvalues.h>
4949 #include <caml/signals.h>
4950
4951 #include <guestfs.h>
4952
4953 #include \"guestfs_c.h\"
4954
4955 /* Copy a hashtable of string pairs into an assoc-list.  We return
4956  * the list in reverse order, but hashtables aren't supposed to be
4957  * ordered anyway.
4958  */
4959 static CAMLprim value
4960 copy_table (char * const * argv)
4961 {
4962   CAMLparam0 ();
4963   CAMLlocal5 (rv, pairv, kv, vv, cons);
4964   int i;
4965
4966   rv = Val_int (0);
4967   for (i = 0; argv[i] != NULL; i += 2) {
4968     kv = caml_copy_string (argv[i]);
4969     vv = caml_copy_string (argv[i+1]);
4970     pairv = caml_alloc (2, 0);
4971     Store_field (pairv, 0, kv);
4972     Store_field (pairv, 1, vv);
4973     cons = caml_alloc (2, 0);
4974     Store_field (cons, 1, rv);
4975     rv = cons;
4976     Store_field (cons, 0, pairv);
4977   }
4978
4979   CAMLreturn (rv);
4980 }
4981
4982 ";
4983
4984   (* LVM struct copy functions. *)
4985   List.iter (
4986     fun (typ, cols) ->
4987       let has_optpercent_col =
4988         List.exists (function (_, `OptPercent) -> true | _ -> false) cols in
4989
4990       pr "static CAMLprim value\n";
4991       pr "copy_lvm_%s (const struct guestfs_lvm_%s *%s)\n" typ typ typ;
4992       pr "{\n";
4993       pr "  CAMLparam0 ();\n";
4994       if has_optpercent_col then
4995         pr "  CAMLlocal3 (rv, v, v2);\n"
4996       else
4997         pr "  CAMLlocal2 (rv, v);\n";
4998       pr "\n";
4999       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
5000       iteri (
5001         fun i col ->
5002           (match col with
5003            | name, `String ->
5004                pr "  v = caml_copy_string (%s->%s);\n" typ name
5005            | name, `UUID ->
5006                pr "  v = caml_alloc_string (32);\n";
5007                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
5008            | name, `Bytes
5009            | name, `Int ->
5010                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
5011            | name, `OptPercent ->
5012                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
5013                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
5014                pr "    v = caml_alloc (1, 0);\n";
5015                pr "    Store_field (v, 0, v2);\n";
5016                pr "  } else /* None */\n";
5017                pr "    v = Val_int (0);\n";
5018           );
5019           pr "  Store_field (rv, %d, v);\n" i
5020       ) cols;
5021       pr "  CAMLreturn (rv);\n";
5022       pr "}\n";
5023       pr "\n";
5024
5025       pr "static CAMLprim value\n";
5026       pr "copy_lvm_%s_list (const struct guestfs_lvm_%s_list *%ss)\n"
5027         typ typ typ;
5028       pr "{\n";
5029       pr "  CAMLparam0 ();\n";
5030       pr "  CAMLlocal2 (rv, v);\n";
5031       pr "  int i;\n";
5032       pr "\n";
5033       pr "  if (%ss->len == 0)\n" typ;
5034       pr "    CAMLreturn (Atom (0));\n";
5035       pr "  else {\n";
5036       pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
5037       pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
5038       pr "      v = copy_lvm_%s (&%ss->val[i]);\n" typ typ;
5039       pr "      caml_modify (&Field (rv, i), v);\n";
5040       pr "    }\n";
5041       pr "    CAMLreturn (rv);\n";
5042       pr "  }\n";
5043       pr "}\n";
5044       pr "\n";
5045   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5046
5047   (* Stat copy functions. *)
5048   List.iter (
5049     fun (typ, cols) ->
5050       pr "static CAMLprim value\n";
5051       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5052       pr "{\n";
5053       pr "  CAMLparam0 ();\n";
5054       pr "  CAMLlocal2 (rv, v);\n";
5055       pr "\n";
5056       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
5057       iteri (
5058         fun i col ->
5059           (match col with
5060            | name, `Int ->
5061                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
5062           );
5063           pr "  Store_field (rv, %d, v);\n" i
5064       ) cols;
5065       pr "  CAMLreturn (rv);\n";
5066       pr "}\n";
5067       pr "\n";
5068   ) ["stat", stat_cols; "statvfs", statvfs_cols];
5069
5070   (* The wrappers. *)
5071   List.iter (
5072     fun (name, style, _, _, _, _, _) ->
5073       let params =
5074         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
5075
5076       pr "CAMLprim value\n";
5077       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
5078       List.iter (pr ", value %s") (List.tl params);
5079       pr ")\n";
5080       pr "{\n";
5081
5082       (match params with
5083        | [p1; p2; p3; p4; p5] ->
5084            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
5085        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
5086            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
5087            pr "  CAMLxparam%d (%s);\n"
5088              (List.length rest) (String.concat ", " rest)
5089        | ps ->
5090            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
5091       );
5092       pr "  CAMLlocal1 (rv);\n";
5093       pr "\n";
5094
5095       pr "  guestfs_h *g = Guestfs_val (gv);\n";
5096       pr "  if (g == NULL)\n";
5097       pr "    caml_failwith (\"%s: used handle after closing it\");\n" name;
5098       pr "\n";
5099
5100       List.iter (
5101         function
5102         | String n
5103         | FileIn n
5104         | FileOut n ->
5105             pr "  const char *%s = String_val (%sv);\n" n n
5106         | OptString n ->
5107             pr "  const char *%s =\n" n;
5108             pr "    %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
5109               n n
5110         | StringList n ->
5111             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
5112         | Bool n ->
5113             pr "  int %s = Bool_val (%sv);\n" n n
5114         | Int n ->
5115             pr "  int %s = Int_val (%sv);\n" n n
5116       ) (snd style);
5117       let error_code =
5118         match fst style with
5119         | RErr -> pr "  int r;\n"; "-1"
5120         | RInt _ -> pr "  int r;\n"; "-1"
5121         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
5122         | RBool _ -> pr "  int r;\n"; "-1"
5123         | RConstString _ -> pr "  const char *r;\n"; "NULL"
5124         | RString _ -> pr "  char *r;\n"; "NULL"
5125         | RStringList _ ->
5126             pr "  int i;\n";
5127             pr "  char **r;\n";
5128             "NULL"
5129         | RIntBool _ ->
5130             pr "  struct guestfs_int_bool *r;\n"; "NULL"
5131         | RPVList _ ->
5132             pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
5133         | RVGList _ ->
5134             pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
5135         | RLVList _ ->
5136             pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
5137         | RStat _ ->
5138             pr "  struct guestfs_stat *r;\n"; "NULL"
5139         | RStatVFS _ ->
5140             pr "  struct guestfs_statvfs *r;\n"; "NULL"
5141         | RHashtable _ ->
5142             pr "  int i;\n";
5143             pr "  char **r;\n";
5144             "NULL" in
5145       pr "\n";
5146
5147       pr "  caml_enter_blocking_section ();\n";
5148       pr "  r = guestfs_%s " name;
5149       generate_call_args ~handle:"g" (snd style);
5150       pr ";\n";
5151       pr "  caml_leave_blocking_section ();\n";
5152
5153       List.iter (
5154         function
5155         | StringList n ->
5156             pr "  ocaml_guestfs_free_strings (%s);\n" n;
5157         | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
5158       ) (snd style);
5159
5160       pr "  if (r == %s)\n" error_code;
5161       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
5162       pr "\n";
5163
5164       (match fst style with
5165        | RErr -> pr "  rv = Val_unit;\n"
5166        | RInt _ -> pr "  rv = Val_int (r);\n"
5167        | RInt64 _ ->
5168            pr "  rv = caml_copy_int64 (r);\n"
5169        | RBool _ -> pr "  rv = Val_bool (r);\n"
5170        | RConstString _ -> pr "  rv = caml_copy_string (r);\n"
5171        | RString _ ->
5172            pr "  rv = caml_copy_string (r);\n";
5173            pr "  free (r);\n"
5174        | RStringList _ ->
5175            pr "  rv = caml_copy_string_array ((const char **) r);\n";
5176            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5177            pr "  free (r);\n"
5178        | RIntBool _ ->
5179            pr "  rv = caml_alloc (2, 0);\n";
5180            pr "  Store_field (rv, 0, Val_int (r->i));\n";
5181            pr "  Store_field (rv, 1, Val_bool (r->b));\n";
5182            pr "  guestfs_free_int_bool (r);\n";
5183        | RPVList _ ->
5184            pr "  rv = copy_lvm_pv_list (r);\n";
5185            pr "  guestfs_free_lvm_pv_list (r);\n";
5186        | RVGList _ ->
5187            pr "  rv = copy_lvm_vg_list (r);\n";
5188            pr "  guestfs_free_lvm_vg_list (r);\n";
5189        | RLVList _ ->
5190            pr "  rv = copy_lvm_lv_list (r);\n";
5191            pr "  guestfs_free_lvm_lv_list (r);\n";
5192        | RStat _ ->
5193            pr "  rv = copy_stat (r);\n";
5194            pr "  free (r);\n";
5195        | RStatVFS _ ->
5196            pr "  rv = copy_statvfs (r);\n";
5197            pr "  free (r);\n";
5198        | RHashtable _ ->
5199            pr "  rv = copy_table (r);\n";
5200            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5201            pr "  free (r);\n";
5202       );
5203
5204       pr "  CAMLreturn (rv);\n";
5205       pr "}\n";
5206       pr "\n";
5207
5208       if List.length params > 5 then (
5209         pr "CAMLprim value\n";
5210         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
5211         pr "{\n";
5212         pr "  return ocaml_guestfs_%s (argv[0]" name;
5213         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
5214         pr ");\n";
5215         pr "}\n";
5216         pr "\n"
5217       )
5218   ) all_functions
5219
5220 and generate_ocaml_lvm_structure_decls () =
5221   List.iter (
5222     fun (typ, cols) ->
5223       pr "type lvm_%s = {\n" typ;
5224       List.iter (
5225         function
5226         | name, `String -> pr "  %s : string;\n" name
5227         | name, `UUID -> pr "  %s : string;\n" name
5228         | name, `Bytes -> pr "  %s : int64;\n" name
5229         | name, `Int -> pr "  %s : int64;\n" name
5230         | name, `OptPercent -> pr "  %s : float option;\n" name
5231       ) cols;
5232       pr "}\n";
5233       pr "\n"
5234   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
5235
5236 and generate_ocaml_stat_structure_decls () =
5237   List.iter (
5238     fun (typ, cols) ->
5239       pr "type %s = {\n" typ;
5240       List.iter (
5241         function
5242         | name, `Int -> pr "  %s : int64;\n" name
5243       ) cols;
5244       pr "}\n";
5245       pr "\n"
5246   ) ["stat", stat_cols; "statvfs", statvfs_cols]
5247
5248 and generate_ocaml_prototype ?(is_external = false) name style =
5249   if is_external then pr "external " else pr "val ";
5250   pr "%s : t -> " name;
5251   List.iter (
5252     function
5253     | String _ | FileIn _ | FileOut _ -> pr "string -> "
5254     | OptString _ -> pr "string option -> "
5255     | StringList _ -> pr "string array -> "
5256     | Bool _ -> pr "bool -> "
5257     | Int _ -> pr "int -> "
5258   ) (snd style);
5259   (match fst style with
5260    | RErr -> pr "unit" (* all errors are turned into exceptions *)
5261    | RInt _ -> pr "int"
5262    | RInt64 _ -> pr "int64"
5263    | RBool _ -> pr "bool"
5264    | RConstString _ -> pr "string"
5265    | RString _ -> pr "string"
5266    | RStringList _ -> pr "string array"
5267    | RIntBool _ -> pr "int * bool"
5268    | RPVList _ -> pr "lvm_pv array"
5269    | RVGList _ -> pr "lvm_vg array"
5270    | RLVList _ -> pr "lvm_lv array"
5271    | RStat _ -> pr "stat"
5272    | RStatVFS _ -> pr "statvfs"
5273    | RHashtable _ -> pr "(string * string) list"
5274   );
5275   if is_external then (
5276     pr " = ";
5277     if List.length (snd style) + 1 > 5 then
5278       pr "\"ocaml_guestfs_%s_byte\" " name;
5279     pr "\"ocaml_guestfs_%s\"" name
5280   );
5281   pr "\n"
5282
5283 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
5284 and generate_perl_xs () =
5285   generate_header CStyle LGPLv2;
5286
5287   pr "\
5288 #include \"EXTERN.h\"
5289 #include \"perl.h\"
5290 #include \"XSUB.h\"
5291
5292 #include <guestfs.h>
5293
5294 #ifndef PRId64
5295 #define PRId64 \"lld\"
5296 #endif
5297
5298 static SV *
5299 my_newSVll(long long val) {
5300 #ifdef USE_64_BIT_ALL
5301   return newSViv(val);
5302 #else
5303   char buf[100];
5304   int len;
5305   len = snprintf(buf, 100, \"%%\" PRId64, val);
5306   return newSVpv(buf, len);
5307 #endif
5308 }
5309
5310 #ifndef PRIu64
5311 #define PRIu64 \"llu\"
5312 #endif
5313
5314 static SV *
5315 my_newSVull(unsigned long long val) {
5316 #ifdef USE_64_BIT_ALL
5317   return newSVuv(val);
5318 #else
5319   char buf[100];
5320   int len;
5321   len = snprintf(buf, 100, \"%%\" PRIu64, val);
5322   return newSVpv(buf, len);
5323 #endif
5324 }
5325
5326 /* http://www.perlmonks.org/?node_id=680842 */
5327 static char **
5328 XS_unpack_charPtrPtr (SV *arg) {
5329   char **ret;
5330   AV *av;
5331   I32 i;
5332
5333   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
5334     croak (\"array reference expected\");
5335
5336   av = (AV *)SvRV (arg);
5337   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
5338   if (!ret)
5339     croak (\"malloc failed\");
5340
5341   for (i = 0; i <= av_len (av); i++) {
5342     SV **elem = av_fetch (av, i, 0);
5343
5344     if (!elem || !*elem)
5345       croak (\"missing element in list\");
5346
5347     ret[i] = SvPV_nolen (*elem);
5348   }
5349
5350   ret[i] = NULL;
5351
5352   return ret;
5353 }
5354
5355 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
5356
5357 PROTOTYPES: ENABLE
5358
5359 guestfs_h *
5360 _create ()
5361    CODE:
5362       RETVAL = guestfs_create ();
5363       if (!RETVAL)
5364         croak (\"could not create guestfs handle\");
5365       guestfs_set_error_handler (RETVAL, NULL, NULL);
5366  OUTPUT:
5367       RETVAL
5368
5369 void
5370 DESTROY (g)
5371       guestfs_h *g;
5372  PPCODE:
5373       guestfs_close (g);
5374
5375 ";
5376
5377   List.iter (
5378     fun (name, style, _, _, _, _, _) ->
5379       (match fst style with
5380        | RErr -> pr "void\n"
5381        | RInt _ -> pr "SV *\n"
5382        | RInt64 _ -> pr "SV *\n"
5383        | RBool _ -> pr "SV *\n"
5384        | RConstString _ -> pr "SV *\n"
5385        | RString _ -> pr "SV *\n"
5386        | RStringList _
5387        | RIntBool _
5388        | RPVList _ | RVGList _ | RLVList _
5389        | RStat _ | RStatVFS _
5390        | RHashtable _ ->
5391            pr "void\n" (* all lists returned implictly on the stack *)
5392       );
5393       (* Call and arguments. *)
5394       pr "%s " name;
5395       generate_call_args ~handle:"g" (snd style);
5396       pr "\n";
5397       pr "      guestfs_h *g;\n";
5398       List.iter (
5399         function
5400         | String n | FileIn n | FileOut n -> pr "      char *%s;\n" n
5401         | OptString n -> pr "      char *%s;\n" n
5402         | StringList n -> pr "      char **%s;\n" n
5403         | Bool n -> pr "      int %s;\n" n
5404         | Int n -> pr "      int %s;\n" n
5405       ) (snd style);
5406
5407       let do_cleanups () =
5408         List.iter (
5409           function
5410           | String _ | OptString _ | Bool _ | Int _
5411           | FileIn _ | FileOut _ -> ()
5412           | StringList n -> pr "      free (%s);\n" n
5413         ) (snd style)
5414       in
5415
5416       (* Code. *)
5417       (match fst style with
5418        | RErr ->
5419            pr "PREINIT:\n";
5420            pr "      int r;\n";
5421            pr " PPCODE:\n";
5422            pr "      r = guestfs_%s " name;
5423            generate_call_args ~handle:"g" (snd style);
5424            pr ";\n";
5425            do_cleanups ();
5426            pr "      if (r == -1)\n";
5427            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5428        | RInt n
5429        | RBool n ->
5430            pr "PREINIT:\n";
5431            pr "      int %s;\n" n;
5432            pr "   CODE:\n";
5433            pr "      %s = guestfs_%s " n name;
5434            generate_call_args ~handle:"g" (snd style);
5435            pr ";\n";
5436            do_cleanups ();
5437            pr "      if (%s == -1)\n" n;
5438            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5439            pr "      RETVAL = newSViv (%s);\n" n;
5440            pr " OUTPUT:\n";
5441            pr "      RETVAL\n"
5442        | RInt64 n ->
5443            pr "PREINIT:\n";
5444            pr "      int64_t %s;\n" n;
5445            pr "   CODE:\n";
5446            pr "      %s = guestfs_%s " n name;
5447            generate_call_args ~handle:"g" (snd style);
5448            pr ";\n";
5449            do_cleanups ();
5450            pr "      if (%s == -1)\n" n;
5451            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5452            pr "      RETVAL = my_newSVll (%s);\n" n;
5453            pr " OUTPUT:\n";
5454            pr "      RETVAL\n"
5455        | RConstString n ->
5456            pr "PREINIT:\n";
5457            pr "      const char *%s;\n" n;
5458            pr "   CODE:\n";
5459            pr "      %s = guestfs_%s " n name;
5460            generate_call_args ~handle:"g" (snd style);
5461            pr ";\n";
5462            do_cleanups ();
5463            pr "      if (%s == NULL)\n" n;
5464            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5465            pr "      RETVAL = newSVpv (%s, 0);\n" n;
5466            pr " OUTPUT:\n";
5467            pr "      RETVAL\n"
5468        | RString n ->
5469            pr "PREINIT:\n";
5470            pr "      char *%s;\n" n;
5471            pr "   CODE:\n";
5472            pr "      %s = guestfs_%s " n name;
5473            generate_call_args ~handle:"g" (snd style);
5474            pr ";\n";
5475            do_cleanups ();
5476            pr "      if (%s == NULL)\n" n;
5477            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5478            pr "      RETVAL = newSVpv (%s, 0);\n" n;
5479            pr "      free (%s);\n" n;
5480            pr " OUTPUT:\n";
5481            pr "      RETVAL\n"
5482        | RStringList n | RHashtable n ->
5483            pr "PREINIT:\n";
5484            pr "      char **%s;\n" n;
5485            pr "      int i, n;\n";
5486            pr " PPCODE:\n";
5487            pr "      %s = guestfs_%s " n name;
5488            generate_call_args ~handle:"g" (snd style);
5489            pr ";\n";
5490            do_cleanups ();
5491            pr "      if (%s == NULL)\n" n;
5492            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5493            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
5494            pr "      EXTEND (SP, n);\n";
5495            pr "      for (i = 0; i < n; ++i) {\n";
5496            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
5497            pr "        free (%s[i]);\n" n;
5498            pr "      }\n";
5499            pr "      free (%s);\n" n;
5500        | RIntBool _ ->
5501            pr "PREINIT:\n";
5502            pr "      struct guestfs_int_bool *r;\n";
5503            pr " PPCODE:\n";
5504            pr "      r = guestfs_%s " name;
5505            generate_call_args ~handle:"g" (snd style);
5506            pr ";\n";
5507            do_cleanups ();
5508            pr "      if (r == NULL)\n";
5509            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5510            pr "      EXTEND (SP, 2);\n";
5511            pr "      PUSHs (sv_2mortal (newSViv (r->i)));\n";
5512            pr "      PUSHs (sv_2mortal (newSViv (r->b)));\n";
5513            pr "      guestfs_free_int_bool (r);\n";
5514        | RPVList n ->
5515            generate_perl_lvm_code "pv" pv_cols name style n do_cleanups
5516        | RVGList n ->
5517            generate_perl_lvm_code "vg" vg_cols name style n do_cleanups
5518        | RLVList n ->
5519            generate_perl_lvm_code "lv" lv_cols name style n do_cleanups
5520        | RStat n ->
5521            generate_perl_stat_code "stat" stat_cols name style n do_cleanups
5522        | RStatVFS n ->
5523            generate_perl_stat_code
5524              "statvfs" statvfs_cols name style n do_cleanups
5525       );
5526
5527       pr "\n"
5528   ) all_functions
5529
5530 and generate_perl_lvm_code typ cols name style n do_cleanups =
5531   pr "PREINIT:\n";
5532   pr "      struct guestfs_lvm_%s_list *%s;\n" typ n;
5533   pr "      int i;\n";
5534   pr "      HV *hv;\n";
5535   pr " PPCODE:\n";
5536   pr "      %s = guestfs_%s " n name;
5537   generate_call_args ~handle:"g" (snd style);
5538   pr ";\n";
5539   do_cleanups ();
5540   pr "      if (%s == NULL)\n" n;
5541   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5542   pr "      EXTEND (SP, %s->len);\n" n;
5543   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
5544   pr "        hv = newHV ();\n";
5545   List.iter (
5546     function
5547     | name, `String ->
5548         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
5549           name (String.length name) n name
5550     | name, `UUID ->
5551         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
5552           name (String.length name) n name
5553     | name, `Bytes ->
5554         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
5555           name (String.length name) n name
5556     | name, `Int ->
5557         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
5558           name (String.length name) n name
5559     | name, `OptPercent ->
5560         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
5561           name (String.length name) n name
5562   ) cols;
5563   pr "        PUSHs (sv_2mortal ((SV *) hv));\n";
5564   pr "      }\n";
5565   pr "      guestfs_free_lvm_%s_list (%s);\n" typ n
5566
5567 and generate_perl_stat_code typ cols name style n do_cleanups =
5568   pr "PREINIT:\n";
5569   pr "      struct guestfs_%s *%s;\n" typ n;
5570   pr " PPCODE:\n";
5571   pr "      %s = guestfs_%s " n name;
5572   generate_call_args ~handle:"g" (snd style);
5573   pr ";\n";
5574   do_cleanups ();
5575   pr "      if (%s == NULL)\n" n;
5576   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5577   pr "      EXTEND (SP, %d);\n" (List.length cols);
5578   List.iter (
5579     function
5580     | name, `Int ->
5581         pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n" n name
5582   ) cols;
5583   pr "      free (%s);\n" n
5584
5585 (* Generate Sys/Guestfs.pm. *)
5586 and generate_perl_pm () =
5587   generate_header HashStyle LGPLv2;
5588
5589   pr "\
5590 =pod
5591
5592 =head1 NAME
5593
5594 Sys::Guestfs - Perl bindings for libguestfs
5595
5596 =head1 SYNOPSIS
5597
5598  use Sys::Guestfs;
5599  
5600  my $h = Sys::Guestfs->new ();
5601  $h->add_drive ('guest.img');
5602  $h->launch ();
5603  $h->wait_ready ();
5604  $h->mount ('/dev/sda1', '/');
5605  $h->touch ('/hello');
5606  $h->sync ();
5607
5608 =head1 DESCRIPTION
5609
5610 The C<Sys::Guestfs> module provides a Perl XS binding to the
5611 libguestfs API for examining and modifying virtual machine
5612 disk images.
5613
5614 Amongst the things this is good for: making batch configuration
5615 changes to guests, getting disk used/free statistics (see also:
5616 virt-df), migrating between virtualization systems (see also:
5617 virt-p2v), performing partial backups, performing partial guest
5618 clones, cloning guests and changing registry/UUID/hostname info, and
5619 much else besides.
5620
5621 Libguestfs uses Linux kernel and qemu code, and can access any type of
5622 guest filesystem that Linux and qemu can, including but not limited
5623 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
5624 schemes, qcow, qcow2, vmdk.
5625
5626 Libguestfs provides ways to enumerate guest storage (eg. partitions,
5627 LVs, what filesystem is in each LV, etc.).  It can also run commands
5628 in the context of the guest.  Also you can access filesystems over FTP.
5629
5630 =head1 ERRORS
5631
5632 All errors turn into calls to C<croak> (see L<Carp(3)>).
5633
5634 =head1 METHODS
5635
5636 =over 4
5637
5638 =cut
5639
5640 package Sys::Guestfs;
5641
5642 use strict;
5643 use warnings;
5644
5645 require XSLoader;
5646 XSLoader::load ('Sys::Guestfs');
5647
5648 =item $h = Sys::Guestfs->new ();
5649
5650 Create a new guestfs handle.
5651
5652 =cut
5653
5654 sub new {
5655   my $proto = shift;
5656   my $class = ref ($proto) || $proto;
5657
5658   my $self = Sys::Guestfs::_create ();
5659   bless $self, $class;
5660   return $self;
5661 }
5662
5663 ";
5664
5665   (* Actions.  We only need to print documentation for these as
5666    * they are pulled in from the XS code automatically.
5667    *)
5668   List.iter (
5669     fun (name, style, _, flags, _, _, longdesc) ->
5670       if not (List.mem NotInDocs flags) then (
5671         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
5672         pr "=item ";
5673         generate_perl_prototype name style;
5674         pr "\n\n";
5675         pr "%s\n\n" longdesc;
5676         if List.mem ProtocolLimitWarning flags then
5677           pr "%s\n\n" protocol_limit_warning;
5678         if List.mem DangerWillRobinson flags then
5679           pr "%s\n\n" danger_will_robinson
5680       )
5681   ) all_functions_sorted;
5682
5683   (* End of file. *)
5684   pr "\
5685 =cut
5686
5687 1;
5688
5689 =back
5690
5691 =head1 COPYRIGHT
5692
5693 Copyright (C) 2009 Red Hat Inc.
5694
5695 =head1 LICENSE
5696
5697 Please see the file COPYING.LIB for the full license.
5698
5699 =head1 SEE ALSO
5700
5701 L<guestfs(3)>, L<guestfish(1)>.
5702
5703 =cut
5704 "
5705
5706 and generate_perl_prototype name style =
5707   (match fst style with
5708    | RErr -> ()
5709    | RBool n
5710    | RInt n
5711    | RInt64 n
5712    | RConstString n
5713    | RString n -> pr "$%s = " n
5714    | RIntBool (n, m) -> pr "($%s, $%s) = " n m
5715    | RStringList n
5716    | RPVList n
5717    | RVGList n
5718    | RLVList n -> pr "@%s = " n
5719    | RStat n
5720    | RStatVFS n
5721    | RHashtable n -> pr "%%%s = " n
5722   );
5723   pr "$h->%s (" name;
5724   let comma = ref false in
5725   List.iter (
5726     fun arg ->
5727       if !comma then pr ", ";
5728       comma := true;
5729       match arg with
5730       | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
5731           pr "$%s" n
5732       | StringList n ->
5733           pr "\\@%s" n
5734   ) (snd style);
5735   pr ");"
5736
5737 (* Generate Python C module. *)
5738 and generate_python_c () =
5739   generate_header CStyle LGPLv2;
5740
5741   pr "\
5742 #include <stdio.h>
5743 #include <stdlib.h>
5744 #include <assert.h>
5745
5746 #include <Python.h>
5747
5748 #include \"guestfs.h\"
5749
5750 typedef struct {
5751   PyObject_HEAD
5752   guestfs_h *g;
5753 } Pyguestfs_Object;
5754
5755 static guestfs_h *
5756 get_handle (PyObject *obj)
5757 {
5758   assert (obj);
5759   assert (obj != Py_None);
5760   return ((Pyguestfs_Object *) obj)->g;
5761 }
5762
5763 static PyObject *
5764 put_handle (guestfs_h *g)
5765 {
5766   assert (g);
5767   return
5768     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
5769 }
5770
5771 /* This list should be freed (but not the strings) after use. */
5772 static const char **
5773 get_string_list (PyObject *obj)
5774 {
5775   int i, len;
5776   const char **r;
5777
5778   assert (obj);
5779
5780   if (!PyList_Check (obj)) {
5781     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
5782     return NULL;
5783   }
5784
5785   len = PyList_Size (obj);
5786   r = malloc (sizeof (char *) * (len+1));
5787   if (r == NULL) {
5788     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
5789     return NULL;
5790   }
5791
5792   for (i = 0; i < len; ++i)
5793     r[i] = PyString_AsString (PyList_GetItem (obj, i));
5794   r[len] = NULL;
5795
5796   return r;
5797 }
5798
5799 static PyObject *
5800 put_string_list (char * const * const argv)
5801 {
5802   PyObject *list;
5803   int argc, i;
5804
5805   for (argc = 0; argv[argc] != NULL; ++argc)
5806     ;
5807
5808   list = PyList_New (argc);
5809   for (i = 0; i < argc; ++i)
5810     PyList_SetItem (list, i, PyString_FromString (argv[i]));
5811
5812   return list;
5813 }
5814
5815 static PyObject *
5816 put_table (char * const * const argv)
5817 {
5818   PyObject *list, *item;
5819   int argc, i;
5820
5821   for (argc = 0; argv[argc] != NULL; ++argc)
5822     ;
5823
5824   list = PyList_New (argc >> 1);
5825   for (i = 0; i < argc; i += 2) {
5826     item = PyTuple_New (2);
5827     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
5828     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
5829     PyList_SetItem (list, i >> 1, item);
5830   }
5831
5832   return list;
5833 }
5834
5835 static void
5836 free_strings (char **argv)
5837 {
5838   int argc;
5839
5840   for (argc = 0; argv[argc] != NULL; ++argc)
5841     free (argv[argc]);
5842   free (argv);
5843 }
5844
5845 static PyObject *
5846 py_guestfs_create (PyObject *self, PyObject *args)
5847 {
5848   guestfs_h *g;
5849
5850   g = guestfs_create ();
5851   if (g == NULL) {
5852     PyErr_SetString (PyExc_RuntimeError,
5853                      \"guestfs.create: failed to allocate handle\");
5854     return NULL;
5855   }
5856   guestfs_set_error_handler (g, NULL, NULL);
5857   return put_handle (g);
5858 }
5859
5860 static PyObject *
5861 py_guestfs_close (PyObject *self, PyObject *args)
5862 {
5863   PyObject *py_g;
5864   guestfs_h *g;
5865
5866   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
5867     return NULL;
5868   g = get_handle (py_g);
5869
5870   guestfs_close (g);
5871
5872   Py_INCREF (Py_None);
5873   return Py_None;
5874 }
5875
5876 ";
5877
5878   (* LVM structures, turned into Python dictionaries. *)
5879   List.iter (
5880     fun (typ, cols) ->
5881       pr "static PyObject *\n";
5882       pr "put_lvm_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
5883       pr "{\n";
5884       pr "  PyObject *dict;\n";
5885       pr "\n";
5886       pr "  dict = PyDict_New ();\n";
5887       List.iter (
5888         function
5889         | name, `String ->
5890             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5891             pr "                        PyString_FromString (%s->%s));\n"
5892               typ name
5893         | name, `UUID ->
5894             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5895             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
5896               typ name
5897         | name, `Bytes ->
5898             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5899             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
5900               typ name
5901         | name, `Int ->
5902             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5903             pr "                        PyLong_FromLongLong (%s->%s));\n"
5904               typ name
5905         | name, `OptPercent ->
5906             pr "  if (%s->%s >= 0)\n" typ name;
5907             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
5908             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
5909               typ name;
5910             pr "  else {\n";
5911             pr "    Py_INCREF (Py_None);\n";
5912             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);" name;
5913             pr "  }\n"
5914       ) cols;
5915       pr "  return dict;\n";
5916       pr "};\n";
5917       pr "\n";
5918
5919       pr "static PyObject *\n";
5920       pr "put_lvm_%s_list (struct guestfs_lvm_%s_list *%ss)\n" typ typ typ;
5921       pr "{\n";
5922       pr "  PyObject *list;\n";
5923       pr "  int i;\n";
5924       pr "\n";
5925       pr "  list = PyList_New (%ss->len);\n" typ;
5926       pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
5927       pr "    PyList_SetItem (list, i, put_lvm_%s (&%ss->val[i]));\n" typ typ;
5928       pr "  return list;\n";
5929       pr "};\n";
5930       pr "\n"
5931   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5932
5933   (* Stat structures, turned into Python dictionaries. *)
5934   List.iter (
5935     fun (typ, cols) ->
5936       pr "static PyObject *\n";
5937       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
5938       pr "{\n";
5939       pr "  PyObject *dict;\n";
5940       pr "\n";
5941       pr "  dict = PyDict_New ();\n";
5942       List.iter (
5943         function
5944         | name, `Int ->
5945             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5946             pr "                        PyLong_FromLongLong (%s->%s));\n"
5947               typ name
5948       ) cols;
5949       pr "  return dict;\n";
5950       pr "};\n";
5951       pr "\n";
5952   ) ["stat", stat_cols; "statvfs", statvfs_cols];
5953
5954   (* Python wrapper functions. *)
5955   List.iter (
5956     fun (name, style, _, _, _, _, _) ->
5957       pr "static PyObject *\n";
5958       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
5959       pr "{\n";
5960
5961       pr "  PyObject *py_g;\n";
5962       pr "  guestfs_h *g;\n";
5963       pr "  PyObject *py_r;\n";
5964
5965       let error_code =
5966         match fst style with
5967         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
5968         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
5969         | RConstString _ -> pr "  const char *r;\n"; "NULL"
5970         | RString _ -> pr "  char *r;\n"; "NULL"
5971         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
5972         | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"; "NULL"
5973         | RPVList n -> pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
5974         | RVGList n -> pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
5975         | RLVList n -> pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
5976         | RStat n -> pr "  struct guestfs_stat *r;\n"; "NULL"
5977         | RStatVFS n -> pr "  struct guestfs_statvfs *r;\n"; "NULL" in
5978
5979       List.iter (
5980         function
5981         | String n | FileIn n | FileOut n -> pr "  const char *%s;\n" n
5982         | OptString n -> pr "  const char *%s;\n" n
5983         | StringList n ->
5984             pr "  PyObject *py_%s;\n" n;
5985             pr "  const char **%s;\n" n
5986         | Bool n -> pr "  int %s;\n" n
5987         | Int n -> pr "  int %s;\n" n
5988       ) (snd style);
5989
5990       pr "\n";
5991
5992       (* Convert the parameters. *)
5993       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
5994       List.iter (
5995         function
5996         | String _ | FileIn _ | FileOut _ -> pr "s"
5997         | OptString _ -> pr "z"
5998         | StringList _ -> pr "O"
5999         | Bool _ -> pr "i" (* XXX Python has booleans? *)
6000         | Int _ -> pr "i"
6001       ) (snd style);
6002       pr ":guestfs_%s\",\n" name;
6003       pr "                         &py_g";
6004       List.iter (
6005         function
6006         | String n | FileIn n | FileOut n -> pr ", &%s" n
6007         | OptString n -> pr ", &%s" n
6008         | StringList n -> pr ", &py_%s" n
6009         | Bool n -> pr ", &%s" n
6010         | Int n -> pr ", &%s" n
6011       ) (snd style);
6012
6013       pr "))\n";
6014       pr "    return NULL;\n";
6015
6016       pr "  g = get_handle (py_g);\n";
6017       List.iter (
6018         function
6019         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6020         | StringList n ->
6021             pr "  %s = get_string_list (py_%s);\n" n n;
6022             pr "  if (!%s) return NULL;\n" n
6023       ) (snd style);
6024
6025       pr "\n";
6026
6027       pr "  r = guestfs_%s " name;
6028       generate_call_args ~handle:"g" (snd style);
6029       pr ";\n";
6030
6031       List.iter (
6032         function
6033         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6034         | StringList n ->
6035             pr "  free (%s);\n" n
6036       ) (snd style);
6037
6038       pr "  if (r == %s) {\n" error_code;
6039       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6040       pr "    return NULL;\n";
6041       pr "  }\n";
6042       pr "\n";
6043
6044       (match fst style with
6045        | RErr ->
6046            pr "  Py_INCREF (Py_None);\n";
6047            pr "  py_r = Py_None;\n"
6048        | RInt _
6049        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
6050        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
6051        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
6052        | RString _ ->
6053            pr "  py_r = PyString_FromString (r);\n";
6054            pr "  free (r);\n"
6055        | RStringList _ ->
6056            pr "  py_r = put_string_list (r);\n";
6057            pr "  free_strings (r);\n"
6058        | RIntBool _ ->
6059            pr "  py_r = PyTuple_New (2);\n";
6060            pr "  PyTuple_SetItem (py_r, 0, PyInt_FromLong ((long) r->i));\n";
6061            pr "  PyTuple_SetItem (py_r, 1, PyInt_FromLong ((long) r->b));\n";
6062            pr "  guestfs_free_int_bool (r);\n"
6063        | RPVList n ->
6064            pr "  py_r = put_lvm_pv_list (r);\n";
6065            pr "  guestfs_free_lvm_pv_list (r);\n"
6066        | RVGList n ->
6067            pr "  py_r = put_lvm_vg_list (r);\n";
6068            pr "  guestfs_free_lvm_vg_list (r);\n"
6069        | RLVList n ->
6070            pr "  py_r = put_lvm_lv_list (r);\n";
6071            pr "  guestfs_free_lvm_lv_list (r);\n"
6072        | RStat n ->
6073            pr "  py_r = put_stat (r);\n";
6074            pr "  free (r);\n"
6075        | RStatVFS n ->
6076            pr "  py_r = put_statvfs (r);\n";
6077            pr "  free (r);\n"
6078        | RHashtable n ->
6079            pr "  py_r = put_table (r);\n";
6080            pr "  free_strings (r);\n"
6081       );
6082
6083       pr "  return py_r;\n";
6084       pr "}\n";
6085       pr "\n"
6086   ) all_functions;
6087
6088   (* Table of functions. *)
6089   pr "static PyMethodDef methods[] = {\n";
6090   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
6091   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
6092   List.iter (
6093     fun (name, _, _, _, _, _, _) ->
6094       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
6095         name name
6096   ) all_functions;
6097   pr "  { NULL, NULL, 0, NULL }\n";
6098   pr "};\n";
6099   pr "\n";
6100
6101   (* Init function. *)
6102   pr "\
6103 void
6104 initlibguestfsmod (void)
6105 {
6106   static int initialized = 0;
6107
6108   if (initialized) return;
6109   Py_InitModule ((char *) \"libguestfsmod\", methods);
6110   initialized = 1;
6111 }
6112 "
6113
6114 (* Generate Python module. *)
6115 and generate_python_py () =
6116   generate_header HashStyle LGPLv2;
6117
6118   pr "\
6119 u\"\"\"Python bindings for libguestfs
6120
6121 import guestfs
6122 g = guestfs.GuestFS ()
6123 g.add_drive (\"guest.img\")
6124 g.launch ()
6125 g.wait_ready ()
6126 parts = g.list_partitions ()
6127
6128 The guestfs module provides a Python binding to the libguestfs API
6129 for examining and modifying virtual machine disk images.
6130
6131 Amongst the things this is good for: making batch configuration
6132 changes to guests, getting disk used/free statistics (see also:
6133 virt-df), migrating between virtualization systems (see also:
6134 virt-p2v), performing partial backups, performing partial guest
6135 clones, cloning guests and changing registry/UUID/hostname info, and
6136 much else besides.
6137
6138 Libguestfs uses Linux kernel and qemu code, and can access any type of
6139 guest filesystem that Linux and qemu can, including but not limited
6140 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6141 schemes, qcow, qcow2, vmdk.
6142
6143 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6144 LVs, what filesystem is in each LV, etc.).  It can also run commands
6145 in the context of the guest.  Also you can access filesystems over FTP.
6146
6147 Errors which happen while using the API are turned into Python
6148 RuntimeError exceptions.
6149
6150 To create a guestfs handle you usually have to perform the following
6151 sequence of calls:
6152
6153 # Create the handle, call add_drive at least once, and possibly
6154 # several times if the guest has multiple block devices:
6155 g = guestfs.GuestFS ()
6156 g.add_drive (\"guest.img\")
6157
6158 # Launch the qemu subprocess and wait for it to become ready:
6159 g.launch ()
6160 g.wait_ready ()
6161
6162 # Now you can issue commands, for example:
6163 logvols = g.lvs ()
6164
6165 \"\"\"
6166
6167 import libguestfsmod
6168
6169 class GuestFS:
6170     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
6171
6172     def __init__ (self):
6173         \"\"\"Create a new libguestfs handle.\"\"\"
6174         self._o = libguestfsmod.create ()
6175
6176     def __del__ (self):
6177         libguestfsmod.close (self._o)
6178
6179 ";
6180
6181   List.iter (
6182     fun (name, style, _, flags, _, _, longdesc) ->
6183       pr "    def %s " name;
6184       generate_call_args ~handle:"self" (snd style);
6185       pr ":\n";
6186
6187       if not (List.mem NotInDocs flags) then (
6188         let doc = replace_str longdesc "C<guestfs_" "C<g." in
6189         let doc =
6190           match fst style with
6191           | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _
6192           | RString _ -> doc
6193           | RStringList _ ->
6194               doc ^ "\n\nThis function returns a list of strings."
6195           | RIntBool _ ->
6196               doc ^ "\n\nThis function returns a tuple (int, bool).\n"
6197           | RPVList _ ->
6198               doc ^ "\n\nThis function returns a list of PVs.  Each PV is represented as a dictionary."
6199           | RVGList _ ->
6200               doc ^ "\n\nThis function returns a list of VGs.  Each VG is represented as a dictionary."
6201           | RLVList _ ->
6202               doc ^ "\n\nThis function returns a list of LVs.  Each LV is represented as a dictionary."
6203           | RStat _ ->
6204               doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the stat structure."
6205           | RStatVFS _ ->
6206               doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the statvfs structure."
6207           | RHashtable _ ->
6208               doc ^ "\n\nThis function returns a dictionary." in
6209         let doc =
6210           if List.mem ProtocolLimitWarning flags then
6211             doc ^ "\n\n" ^ protocol_limit_warning
6212           else doc in
6213         let doc =
6214           if List.mem DangerWillRobinson flags then
6215             doc ^ "\n\n" ^ danger_will_robinson
6216           else doc in
6217         let doc = pod2text ~width:60 name doc in
6218         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
6219         let doc = String.concat "\n        " doc in
6220         pr "        u\"\"\"%s\"\"\"\n" doc;
6221       );
6222       pr "        return libguestfsmod.%s " name;
6223       generate_call_args ~handle:"self._o" (snd style);
6224       pr "\n";
6225       pr "\n";
6226   ) all_functions
6227
6228 (* Useful if you need the longdesc POD text as plain text.  Returns a
6229  * list of lines.
6230  *
6231  * This is the slowest thing about autogeneration.
6232  *)
6233 and pod2text ~width name longdesc =
6234   let filename, chan = Filename.open_temp_file "gen" ".tmp" in
6235   fprintf chan "=head1 %s\n\n%s\n" name longdesc;
6236   close_out chan;
6237   let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
6238   let chan = Unix.open_process_in cmd in
6239   let lines = ref [] in
6240   let rec loop i =
6241     let line = input_line chan in
6242     if i = 1 then               (* discard the first line of output *)
6243       loop (i+1)
6244     else (
6245       let line = triml line in
6246       lines := line :: !lines;
6247       loop (i+1)
6248     ) in
6249   let lines = try loop 1 with End_of_file -> List.rev !lines in
6250   Unix.unlink filename;
6251   match Unix.close_process_in chan with
6252   | Unix.WEXITED 0 -> lines
6253   | Unix.WEXITED i ->
6254       failwithf "pod2text: process exited with non-zero status (%d)" i
6255   | Unix.WSIGNALED i | Unix.WSTOPPED i ->
6256       failwithf "pod2text: process signalled or stopped by signal %d" i
6257
6258 (* Generate ruby bindings. *)
6259 and generate_ruby_c () =
6260   generate_header CStyle LGPLv2;
6261
6262   pr "\
6263 #include <stdio.h>
6264 #include <stdlib.h>
6265
6266 #include <ruby.h>
6267
6268 #include \"guestfs.h\"
6269
6270 #include \"extconf.h\"
6271
6272 /* For Ruby < 1.9 */
6273 #ifndef RARRAY_LEN
6274 #define RARRAY_LEN(r) (RARRAY((r))->len)
6275 #endif
6276
6277 static VALUE m_guestfs;                 /* guestfs module */
6278 static VALUE c_guestfs;                 /* guestfs_h handle */
6279 static VALUE e_Error;                   /* used for all errors */
6280
6281 static void ruby_guestfs_free (void *p)
6282 {
6283   if (!p) return;
6284   guestfs_close ((guestfs_h *) p);
6285 }
6286
6287 static VALUE ruby_guestfs_create (VALUE m)
6288 {
6289   guestfs_h *g;
6290
6291   g = guestfs_create ();
6292   if (!g)
6293     rb_raise (e_Error, \"failed to create guestfs handle\");
6294
6295   /* Don't print error messages to stderr by default. */
6296   guestfs_set_error_handler (g, NULL, NULL);
6297
6298   /* Wrap it, and make sure the close function is called when the
6299    * handle goes away.
6300    */
6301   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
6302 }
6303
6304 static VALUE ruby_guestfs_close (VALUE gv)
6305 {
6306   guestfs_h *g;
6307   Data_Get_Struct (gv, guestfs_h, g);
6308
6309   ruby_guestfs_free (g);
6310   DATA_PTR (gv) = NULL;
6311
6312   return Qnil;
6313 }
6314
6315 ";
6316
6317   List.iter (
6318     fun (name, style, _, _, _, _, _) ->
6319       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
6320       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
6321       pr ")\n";
6322       pr "{\n";
6323       pr "  guestfs_h *g;\n";
6324       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
6325       pr "  if (!g)\n";
6326       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
6327         name;
6328       pr "\n";
6329
6330       List.iter (
6331         function
6332         | String n | FileIn n | FileOut n ->
6333             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
6334             pr "  if (!%s)\n" n;
6335             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
6336             pr "              \"%s\", \"%s\");\n" n name
6337         | OptString n ->
6338             pr "  const char *%s = StringValueCStr (%sv);\n" n n
6339         | StringList n ->
6340             pr "  char **%s;" n;
6341             pr "  {\n";
6342             pr "    int i, len;\n";
6343             pr "    len = RARRAY_LEN (%sv);\n" n;
6344             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
6345               n;
6346             pr "    for (i = 0; i < len; ++i) {\n";
6347             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
6348             pr "      %s[i] = StringValueCStr (v);\n" n;
6349             pr "    }\n";
6350             pr "    %s[len] = NULL;\n" n;
6351             pr "  }\n";
6352         | Bool n
6353         | Int n ->
6354             pr "  int %s = NUM2INT (%sv);\n" n n
6355       ) (snd style);
6356       pr "\n";
6357
6358       let error_code =
6359         match fst style with
6360         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
6361         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
6362         | RConstString _ -> pr "  const char *r;\n"; "NULL"
6363         | RString _ -> pr "  char *r;\n"; "NULL"
6364         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
6365         | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"; "NULL"
6366         | RPVList n -> pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
6367         | RVGList n -> pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
6368         | RLVList n -> pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
6369         | RStat n -> pr "  struct guestfs_stat *r;\n"; "NULL"
6370         | RStatVFS n -> pr "  struct guestfs_statvfs *r;\n"; "NULL" in
6371       pr "\n";
6372
6373       pr "  r = guestfs_%s " name;
6374       generate_call_args ~handle:"g" (snd style);
6375       pr ";\n";
6376
6377       List.iter (
6378         function
6379         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6380         | StringList n ->
6381             pr "  free (%s);\n" n
6382       ) (snd style);
6383
6384       pr "  if (r == %s)\n" error_code;
6385       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
6386       pr "\n";
6387
6388       (match fst style with
6389        | RErr ->
6390            pr "  return Qnil;\n"
6391        | RInt _ | RBool _ ->
6392            pr "  return INT2NUM (r);\n"
6393        | RInt64 _ ->
6394            pr "  return ULL2NUM (r);\n"
6395        | RConstString _ ->
6396            pr "  return rb_str_new2 (r);\n";
6397        | RString _ ->
6398            pr "  VALUE rv = rb_str_new2 (r);\n";
6399            pr "  free (r);\n";
6400            pr "  return rv;\n";
6401        | RStringList _ ->
6402            pr "  int i, len = 0;\n";
6403            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
6404            pr "  VALUE rv = rb_ary_new2 (len);\n";
6405            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
6406            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
6407            pr "    free (r[i]);\n";
6408            pr "  }\n";
6409            pr "  free (r);\n";
6410            pr "  return rv;\n"
6411        | RIntBool _ ->
6412            pr "  VALUE rv = rb_ary_new2 (2);\n";
6413            pr "  rb_ary_push (rv, INT2NUM (r->i));\n";
6414            pr "  rb_ary_push (rv, INT2NUM (r->b));\n";
6415            pr "  guestfs_free_int_bool (r);\n";
6416            pr "  return rv;\n"
6417        | RPVList n ->
6418            generate_ruby_lvm_code "pv" pv_cols
6419        | RVGList n ->
6420            generate_ruby_lvm_code "vg" vg_cols
6421        | RLVList n ->
6422            generate_ruby_lvm_code "lv" lv_cols
6423        | RStat n ->
6424            pr "  VALUE rv = rb_hash_new ();\n";
6425            List.iter (
6426              function
6427              | name, `Int ->
6428                  pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6429            ) stat_cols;
6430            pr "  free (r);\n";
6431            pr "  return rv;\n"
6432        | RStatVFS n ->
6433            pr "  VALUE rv = rb_hash_new ();\n";
6434            List.iter (
6435              function
6436              | name, `Int ->
6437                  pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6438            ) statvfs_cols;
6439            pr "  free (r);\n";
6440            pr "  return rv;\n"
6441        | RHashtable _ ->
6442            pr "  VALUE rv = rb_hash_new ();\n";
6443            pr "  int i;\n";
6444            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
6445            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
6446            pr "    free (r[i]);\n";
6447            pr "    free (r[i+1]);\n";
6448            pr "  }\n";
6449            pr "  free (r);\n";
6450            pr "  return rv;\n"
6451       );
6452
6453       pr "}\n";
6454       pr "\n"
6455   ) all_functions;
6456
6457   pr "\
6458 /* Initialize the module. */
6459 void Init__guestfs ()
6460 {
6461   m_guestfs = rb_define_module (\"Guestfs\");
6462   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
6463   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
6464
6465   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
6466   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
6467
6468 ";
6469   (* Define the rest of the methods. *)
6470   List.iter (
6471     fun (name, style, _, _, _, _, _) ->
6472       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
6473       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
6474   ) all_functions;
6475
6476   pr "}\n"
6477
6478 (* Ruby code to return an LVM struct list. *)
6479 and generate_ruby_lvm_code typ cols =
6480   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
6481   pr "  int i;\n";
6482   pr "  for (i = 0; i < r->len; ++i) {\n";
6483   pr "    VALUE hv = rb_hash_new ();\n";
6484   List.iter (
6485     function
6486     | name, `String ->
6487         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
6488     | name, `UUID ->
6489         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
6490     | name, `Bytes
6491     | name, `Int ->
6492         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
6493     | name, `OptPercent ->
6494         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
6495   ) cols;
6496   pr "    rb_ary_push (rv, hv);\n";
6497   pr "  }\n";
6498   pr "  guestfs_free_lvm_%s_list (r);\n" typ;
6499   pr "  return rv;\n"
6500
6501 (* Generate Java bindings GuestFS.java file. *)
6502 and generate_java_java () =
6503   generate_header CStyle LGPLv2;
6504
6505   pr "\
6506 package com.redhat.et.libguestfs;
6507
6508 import java.util.HashMap;
6509 import com.redhat.et.libguestfs.LibGuestFSException;
6510 import com.redhat.et.libguestfs.PV;
6511 import com.redhat.et.libguestfs.VG;
6512 import com.redhat.et.libguestfs.LV;
6513 import com.redhat.et.libguestfs.Stat;
6514 import com.redhat.et.libguestfs.StatVFS;
6515 import com.redhat.et.libguestfs.IntBool;
6516
6517 /**
6518  * The GuestFS object is a libguestfs handle.
6519  *
6520  * @author rjones
6521  */
6522 public class GuestFS {
6523   // Load the native code.
6524   static {
6525     System.loadLibrary (\"guestfs_jni\");
6526   }
6527
6528   /**
6529    * The native guestfs_h pointer.
6530    */
6531   long g;
6532
6533   /**
6534    * Create a libguestfs handle.
6535    *
6536    * @throws LibGuestFSException
6537    */
6538   public GuestFS () throws LibGuestFSException
6539   {
6540     g = _create ();
6541   }
6542   private native long _create () throws LibGuestFSException;
6543
6544   /**
6545    * Close a libguestfs handle.
6546    *
6547    * You can also leave handles to be collected by the garbage
6548    * collector, but this method ensures that the resources used
6549    * by the handle are freed up immediately.  If you call any
6550    * other methods after closing the handle, you will get an
6551    * exception.
6552    *
6553    * @throws LibGuestFSException
6554    */
6555   public void close () throws LibGuestFSException
6556   {
6557     if (g != 0)
6558       _close (g);
6559     g = 0;
6560   }
6561   private native void _close (long g) throws LibGuestFSException;
6562
6563   public void finalize () throws LibGuestFSException
6564   {
6565     close ();
6566   }
6567
6568 ";
6569
6570   List.iter (
6571     fun (name, style, _, flags, _, shortdesc, longdesc) ->
6572       if not (List.mem NotInDocs flags); then (
6573         let doc = replace_str longdesc "C<guestfs_" "C<g." in
6574         let doc =
6575           if List.mem ProtocolLimitWarning flags then
6576             doc ^ "\n\n" ^ protocol_limit_warning
6577           else doc in
6578         let doc =
6579           if List.mem DangerWillRobinson flags then
6580             doc ^ "\n\n" ^ danger_will_robinson
6581           else doc in
6582         let doc = pod2text ~width:60 name doc in
6583         let doc = List.map (            (* RHBZ#501883 *)
6584           function
6585           | "" -> "<p>"
6586           | nonempty -> nonempty
6587         ) doc in
6588         let doc = String.concat "\n   * " doc in
6589
6590         pr "  /**\n";
6591         pr "   * %s\n" shortdesc;
6592         pr "   * <p>\n";
6593         pr "   * %s\n" doc;
6594         pr "   * @throws LibGuestFSException\n";
6595         pr "   */\n";
6596         pr "  ";
6597       );
6598       generate_java_prototype ~public:true ~semicolon:false name style;
6599       pr "\n";
6600       pr "  {\n";
6601       pr "    if (g == 0)\n";
6602       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
6603         name;
6604       pr "    ";
6605       if fst style <> RErr then pr "return ";
6606       pr "_%s " name;
6607       generate_call_args ~handle:"g" (snd style);
6608       pr ";\n";
6609       pr "  }\n";
6610       pr "  ";
6611       generate_java_prototype ~privat:true ~native:true name style;
6612       pr "\n";
6613       pr "\n";
6614   ) all_functions;
6615
6616   pr "}\n"
6617
6618 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
6619     ?(semicolon=true) name style =
6620   if privat then pr "private ";
6621   if public then pr "public ";
6622   if native then pr "native ";
6623
6624   (* return type *)
6625   (match fst style with
6626    | RErr -> pr "void ";
6627    | RInt _ -> pr "int ";
6628    | RInt64 _ -> pr "long ";
6629    | RBool _ -> pr "boolean ";
6630    | RConstString _ | RString _ -> pr "String ";
6631    | RStringList _ -> pr "String[] ";
6632    | RIntBool _ -> pr "IntBool ";
6633    | RPVList _ -> pr "PV[] ";
6634    | RVGList _ -> pr "VG[] ";
6635    | RLVList _ -> pr "LV[] ";
6636    | RStat _ -> pr "Stat ";
6637    | RStatVFS _ -> pr "StatVFS ";
6638    | RHashtable _ -> pr "HashMap<String,String> ";
6639   );
6640
6641   if native then pr "_%s " name else pr "%s " name;
6642   pr "(";
6643   let needs_comma = ref false in
6644   if native then (
6645     pr "long g";
6646     needs_comma := true
6647   );
6648
6649   (* args *)
6650   List.iter (
6651     fun arg ->
6652       if !needs_comma then pr ", ";
6653       needs_comma := true;
6654
6655       match arg with
6656       | String n
6657       | OptString n
6658       | FileIn n
6659       | FileOut n ->
6660           pr "String %s" n
6661       | StringList n ->
6662           pr "String[] %s" n
6663       | Bool n ->
6664           pr "boolean %s" n
6665       | Int n ->
6666           pr "int %s" n
6667   ) (snd style);
6668
6669   pr ")\n";
6670   pr "    throws LibGuestFSException";
6671   if semicolon then pr ";"
6672
6673 and generate_java_struct typ cols =
6674   generate_header CStyle LGPLv2;
6675
6676   pr "\
6677 package com.redhat.et.libguestfs;
6678
6679 /**
6680  * Libguestfs %s structure.
6681  *
6682  * @author rjones
6683  * @see GuestFS
6684  */
6685 public class %s {
6686 " typ typ;
6687
6688   List.iter (
6689     function
6690     | name, `String
6691     | name, `UUID -> pr "  public String %s;\n" name
6692     | name, `Bytes
6693     | name, `Int -> pr "  public long %s;\n" name
6694     | name, `OptPercent ->
6695         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
6696         pr "  public float %s;\n" name
6697   ) cols;
6698
6699   pr "}\n"
6700
6701 and generate_java_c () =
6702   generate_header CStyle LGPLv2;
6703
6704   pr "\
6705 #include <stdio.h>
6706 #include <stdlib.h>
6707 #include <string.h>
6708
6709 #include \"com_redhat_et_libguestfs_GuestFS.h\"
6710 #include \"guestfs.h\"
6711
6712 /* Note that this function returns.  The exception is not thrown
6713  * until after the wrapper function returns.
6714  */
6715 static void
6716 throw_exception (JNIEnv *env, const char *msg)
6717 {
6718   jclass cl;
6719   cl = (*env)->FindClass (env,
6720                           \"com/redhat/et/libguestfs/LibGuestFSException\");
6721   (*env)->ThrowNew (env, cl, msg);
6722 }
6723
6724 JNIEXPORT jlong JNICALL
6725 Java_com_redhat_et_libguestfs_GuestFS__1create
6726   (JNIEnv *env, jobject obj)
6727 {
6728   guestfs_h *g;
6729
6730   g = guestfs_create ();
6731   if (g == NULL) {
6732     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
6733     return 0;
6734   }
6735   guestfs_set_error_handler (g, NULL, NULL);
6736   return (jlong) (long) g;
6737 }
6738
6739 JNIEXPORT void JNICALL
6740 Java_com_redhat_et_libguestfs_GuestFS__1close
6741   (JNIEnv *env, jobject obj, jlong jg)
6742 {
6743   guestfs_h *g = (guestfs_h *) (long) jg;
6744   guestfs_close (g);
6745 }
6746
6747 ";
6748
6749   List.iter (
6750     fun (name, style, _, _, _, _, _) ->
6751       pr "JNIEXPORT ";
6752       (match fst style with
6753        | RErr -> pr "void ";
6754        | RInt _ -> pr "jint ";
6755        | RInt64 _ -> pr "jlong ";
6756        | RBool _ -> pr "jboolean ";
6757        | RConstString _ | RString _ -> pr "jstring ";
6758        | RIntBool _ | RStat _ | RStatVFS _ | RHashtable _ ->
6759            pr "jobject ";
6760        | RStringList _ | RPVList _ | RVGList _ | RLVList _ ->
6761            pr "jobjectArray ";
6762       );
6763       pr "JNICALL\n";
6764       pr "Java_com_redhat_et_libguestfs_GuestFS_";
6765       pr "%s" (replace_str ("_" ^ name) "_" "_1");
6766       pr "\n";
6767       pr "  (JNIEnv *env, jobject obj, jlong jg";
6768       List.iter (
6769         function
6770         | String n
6771         | OptString n
6772         | FileIn n
6773         | FileOut n ->
6774             pr ", jstring j%s" n
6775         | StringList n ->
6776             pr ", jobjectArray j%s" n
6777         | Bool n ->
6778             pr ", jboolean j%s" n
6779         | Int n ->
6780             pr ", jint j%s" n
6781       ) (snd style);
6782       pr ")\n";
6783       pr "{\n";
6784       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
6785       let error_code, no_ret =
6786         match fst style with
6787         | RErr -> pr "  int r;\n"; "-1", ""
6788         | RBool _
6789         | RInt _ -> pr "  int r;\n"; "-1", "0"
6790         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
6791         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
6792         | RString _ ->
6793             pr "  jstring jr;\n";
6794             pr "  char *r;\n"; "NULL", "NULL"
6795         | RStringList _ ->
6796             pr "  jobjectArray jr;\n";
6797             pr "  int r_len;\n";
6798             pr "  jclass cl;\n";
6799             pr "  jstring jstr;\n";
6800             pr "  char **r;\n"; "NULL", "NULL"
6801         | RIntBool _ ->
6802             pr "  jobject jr;\n";
6803             pr "  jclass cl;\n";
6804             pr "  jfieldID fl;\n";
6805             pr "  struct guestfs_int_bool *r;\n"; "NULL", "NULL"
6806         | RStat _ ->
6807             pr "  jobject jr;\n";
6808             pr "  jclass cl;\n";
6809             pr "  jfieldID fl;\n";
6810             pr "  struct guestfs_stat *r;\n"; "NULL", "NULL"
6811         | RStatVFS _ ->
6812             pr "  jobject jr;\n";
6813             pr "  jclass cl;\n";
6814             pr "  jfieldID fl;\n";
6815             pr "  struct guestfs_statvfs *r;\n"; "NULL", "NULL"
6816         | RPVList _ ->
6817             pr "  jobjectArray jr;\n";
6818             pr "  jclass cl;\n";
6819             pr "  jfieldID fl;\n";
6820             pr "  jobject jfl;\n";
6821             pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL", "NULL"
6822         | RVGList _ ->
6823             pr "  jobjectArray jr;\n";
6824             pr "  jclass cl;\n";
6825             pr "  jfieldID fl;\n";
6826             pr "  jobject jfl;\n";
6827             pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL", "NULL"
6828         | RLVList _ ->
6829             pr "  jobjectArray jr;\n";
6830             pr "  jclass cl;\n";
6831             pr "  jfieldID fl;\n";
6832             pr "  jobject jfl;\n";
6833             pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL", "NULL"
6834         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL" in
6835       List.iter (
6836         function
6837         | String n
6838         | OptString n
6839         | FileIn n
6840         | FileOut n ->
6841             pr "  const char *%s;\n" n
6842         | StringList n ->
6843             pr "  int %s_len;\n" n;
6844             pr "  const char **%s;\n" n
6845         | Bool n
6846         | Int n ->
6847             pr "  int %s;\n" n
6848       ) (snd style);
6849
6850       let needs_i =
6851         (match fst style with
6852          | RStringList _ | RPVList _ | RVGList _ | RLVList _ -> true
6853          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
6854          | RString _ | RIntBool _ | RStat _ | RStatVFS _
6855          | RHashtable _ -> false) ||
6856         List.exists (function StringList _ -> true | _ -> false) (snd style) in
6857       if needs_i then
6858         pr "  int i;\n";
6859
6860       pr "\n";
6861
6862       (* Get the parameters. *)
6863       List.iter (
6864         function
6865         | String n
6866         | OptString n
6867         | FileIn n
6868         | FileOut n ->
6869             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
6870         | StringList n ->
6871             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
6872             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
6873             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
6874             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6875               n;
6876             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
6877             pr "  }\n";
6878             pr "  %s[%s_len] = NULL;\n" n n;
6879         | Bool n
6880         | Int n ->
6881             pr "  %s = j%s;\n" n n
6882       ) (snd style);
6883
6884       (* Make the call. *)
6885       pr "  r = guestfs_%s " name;
6886       generate_call_args ~handle:"g" (snd style);
6887       pr ";\n";
6888
6889       (* Release the parameters. *)
6890       List.iter (
6891         function
6892         | String n
6893         | OptString n
6894         | FileIn n
6895         | FileOut n ->
6896             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6897         | StringList n ->
6898             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
6899             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6900               n;
6901             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
6902             pr "  }\n";
6903             pr "  free (%s);\n" n
6904         | Bool n
6905         | Int n -> ()
6906       ) (snd style);
6907
6908       (* Check for errors. *)
6909       pr "  if (r == %s) {\n" error_code;
6910       pr "    throw_exception (env, guestfs_last_error (g));\n";
6911       pr "    return %s;\n" no_ret;
6912       pr "  }\n";
6913
6914       (* Return value. *)
6915       (match fst style with
6916        | RErr -> ()
6917        | RInt _ -> pr "  return (jint) r;\n"
6918        | RBool _ -> pr "  return (jboolean) r;\n"
6919        | RInt64 _ -> pr "  return (jlong) r;\n"
6920        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
6921        | RString _ ->
6922            pr "  jr = (*env)->NewStringUTF (env, r);\n";
6923            pr "  free (r);\n";
6924            pr "  return jr;\n"
6925        | RStringList _ ->
6926            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
6927            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
6928            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
6929            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
6930            pr "  for (i = 0; i < r_len; ++i) {\n";
6931            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
6932            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
6933            pr "    free (r[i]);\n";
6934            pr "  }\n";
6935            pr "  free (r);\n";
6936            pr "  return jr;\n"
6937        | RIntBool _ ->
6938            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/IntBool\");\n";
6939            pr "  jr = (*env)->AllocObject (env, cl);\n";
6940            pr "  fl = (*env)->GetFieldID (env, cl, \"i\", \"I\");\n";
6941            pr "  (*env)->SetIntField (env, jr, fl, r->i);\n";
6942            pr "  fl = (*env)->GetFieldID (env, cl, \"i\", \"Z\");\n";
6943            pr "  (*env)->SetBooleanField (env, jr, fl, r->b);\n";
6944            pr "  guestfs_free_int_bool (r);\n";
6945            pr "  return jr;\n"
6946        | RStat _ ->
6947            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/Stat\");\n";
6948            pr "  jr = (*env)->AllocObject (env, cl);\n";
6949            List.iter (
6950              function
6951              | name, `Int ->
6952                  pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6953                    name;
6954                  pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6955            ) stat_cols;
6956            pr "  free (r);\n";
6957            pr "  return jr;\n"
6958        | RStatVFS _ ->
6959            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/StatVFS\");\n";
6960            pr "  jr = (*env)->AllocObject (env, cl);\n";
6961            List.iter (
6962              function
6963              | name, `Int ->
6964                  pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6965                    name;
6966                  pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6967            ) statvfs_cols;
6968            pr "  free (r);\n";
6969            pr "  return jr;\n"
6970        | RPVList _ ->
6971            generate_java_lvm_return "pv" "PV" pv_cols
6972        | RVGList _ ->
6973            generate_java_lvm_return "vg" "VG" vg_cols
6974        | RLVList _ ->
6975            generate_java_lvm_return "lv" "LV" lv_cols
6976        | RHashtable _ ->
6977            (* XXX *)
6978            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
6979            pr "  return NULL;\n"
6980       );
6981
6982       pr "}\n";
6983       pr "\n"
6984   ) all_functions
6985
6986 and generate_java_lvm_return typ jtyp cols =
6987   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
6988   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
6989   pr "  for (i = 0; i < r->len; ++i) {\n";
6990   pr "    jfl = (*env)->AllocObject (env, cl);\n";
6991   List.iter (
6992     function
6993     | name, `String ->
6994         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
6995         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
6996     | name, `UUID ->
6997         pr "    {\n";
6998         pr "      char s[33];\n";
6999         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
7000         pr "      s[32] = 0;\n";
7001         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7002         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
7003         pr "    }\n";
7004     | name, (`Bytes|`Int) ->
7005         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7006         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7007     | name, `OptPercent ->
7008         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7009         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
7010   ) cols;
7011   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
7012   pr "  }\n";
7013   pr "  guestfs_free_lvm_%s_list (r);\n" typ;
7014   pr "  return jr;\n"
7015
7016 and generate_haskell_hs () =
7017   generate_header HaskellStyle LGPLv2;
7018
7019   (* XXX We only know how to generate partial FFI for Haskell
7020    * at the moment.  Please help out!
7021    *)
7022   let can_generate style =
7023     let check_no_bad_args =
7024       List.for_all (function Bool _ | Int _ -> false | _ -> true)
7025     in
7026     match style with
7027     | RErr, args -> check_no_bad_args args
7028     | RBool _, _
7029     | RInt _, _
7030     | RInt64 _, _
7031     | RConstString _, _
7032     | RString _, _
7033     | RStringList _, _
7034     | RIntBool _, _
7035     | RPVList _, _
7036     | RVGList _, _
7037     | RLVList _, _
7038     | RStat _, _
7039     | RStatVFS _, _
7040     | RHashtable _, _ -> false in
7041
7042   pr "\
7043 {-# INCLUDE <guestfs.h> #-}
7044 {-# LANGUAGE ForeignFunctionInterface #-}
7045
7046 module Guestfs (
7047   create";
7048
7049   (* List out the names of the actions we want to export. *)
7050   List.iter (
7051     fun (name, style, _, _, _, _, _) ->
7052       if can_generate style then pr ",\n  %s" name
7053   ) all_functions;
7054
7055   pr "
7056   ) where
7057 import Foreign
7058 import Foreign.C
7059 import IO
7060 import Control.Exception
7061 import Data.Typeable
7062
7063 data GuestfsS = GuestfsS            -- represents the opaque C struct
7064 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
7065 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
7066
7067 -- XXX define properly later XXX
7068 data PV = PV
7069 data VG = VG
7070 data LV = LV
7071 data IntBool = IntBool
7072 data Stat = Stat
7073 data StatVFS = StatVFS
7074 data Hashtable = Hashtable
7075
7076 foreign import ccall unsafe \"guestfs_create\" c_create
7077   :: IO GuestfsP
7078 foreign import ccall unsafe \"&guestfs_close\" c_close
7079   :: FunPtr (GuestfsP -> IO ())
7080 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
7081   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
7082
7083 create :: IO GuestfsH
7084 create = do
7085   p <- c_create
7086   c_set_error_handler p nullPtr nullPtr
7087   h <- newForeignPtr c_close p
7088   return h
7089
7090 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
7091   :: GuestfsP -> IO CString
7092
7093 -- last_error :: GuestfsH -> IO (Maybe String)
7094 -- last_error h = do
7095 --   str <- withForeignPtr h (\\p -> c_last_error p)
7096 --   maybePeek peekCString str
7097
7098 last_error :: GuestfsH -> IO (String)
7099 last_error h = do
7100   str <- withForeignPtr h (\\p -> c_last_error p)
7101   if (str == nullPtr)
7102     then return \"no error\"
7103     else peekCString str
7104
7105 ";
7106
7107   (* Generate wrappers for each foreign function. *)
7108   List.iter (
7109     fun (name, style, _, _, _, _, _) ->
7110       if can_generate style then (
7111         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
7112         pr "  :: ";
7113         generate_haskell_prototype ~handle:"GuestfsP" style;
7114         pr "\n";
7115         pr "\n";
7116         pr "%s :: " name;
7117         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
7118         pr "\n";
7119         pr "%s %s = do\n" name
7120           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
7121         pr "  r <- ";
7122         List.iter (
7123           function
7124           | FileIn n
7125           | FileOut n
7126           | String n -> pr "withCString %s $ \\%s -> " n n
7127           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
7128           | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
7129           | Bool n ->
7130               (* XXX this doesn't work *)
7131               pr "      let\n";
7132               pr "        %s = case %s of\n" n n;
7133               pr "          False -> 0\n";
7134               pr "          True -> 1\n";
7135               pr "      in fromIntegral %s $ \\%s ->\n" n n
7136           | Int n -> pr "fromIntegral %s $ \\%s -> " n n
7137         ) (snd style);
7138         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
7139           (String.concat " " ("p" :: List.map name_of_argt (snd style)));
7140         (match fst style with
7141          | RErr | RInt _ | RInt64 _ | RBool _ ->
7142              pr "  if (r == -1)\n";
7143              pr "    then do\n";
7144              pr "      err <- last_error h\n";
7145              pr "      fail err\n";
7146          | RConstString _ | RString _ | RStringList _ | RIntBool _
7147          | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7148          | RHashtable _ ->
7149              pr "  if (r == nullPtr)\n";
7150              pr "    then do\n";
7151              pr "      err <- last_error h\n";
7152              pr "      fail err\n";
7153         );
7154         (match fst style with
7155          | RErr ->
7156              pr "    else return ()\n"
7157          | RInt _ ->
7158              pr "    else return (fromIntegral r)\n"
7159          | RInt64 _ ->
7160              pr "    else return (fromIntegral r)\n"
7161          | RBool _ ->
7162              pr "    else return (toBool r)\n"
7163          | RConstString _
7164          | RString _
7165          | RStringList _
7166          | RIntBool _
7167          | RPVList _
7168          | RVGList _
7169          | RLVList _
7170          | RStat _
7171          | RStatVFS _
7172          | RHashtable _ ->
7173              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
7174         );
7175         pr "\n";
7176       )
7177   ) all_functions
7178
7179 and generate_haskell_prototype ~handle ?(hs = false) style =
7180   pr "%s -> " handle;
7181   let string = if hs then "String" else "CString" in
7182   let int = if hs then "Int" else "CInt" in
7183   let bool = if hs then "Bool" else "CInt" in
7184   let int64 = if hs then "Integer" else "Int64" in
7185   List.iter (
7186     fun arg ->
7187       (match arg with
7188        | String _ -> pr "%s" string
7189        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
7190        | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
7191        | Bool _ -> pr "%s" bool
7192        | Int _ -> pr "%s" int
7193        | FileIn _ -> pr "%s" string
7194        | FileOut _ -> pr "%s" string
7195       );
7196       pr " -> ";
7197   ) (snd style);
7198   pr "IO (";
7199   (match fst style with
7200    | RErr -> if not hs then pr "CInt"
7201    | RInt _ -> pr "%s" int
7202    | RInt64 _ -> pr "%s" int64
7203    | RBool _ -> pr "%s" bool
7204    | RConstString _ -> pr "%s" string
7205    | RString _ -> pr "%s" string
7206    | RStringList _ -> pr "[%s]" string
7207    | RIntBool _ -> pr "IntBool"
7208    | RPVList _ -> pr "[PV]"
7209    | RVGList _ -> pr "[VG]"
7210    | RLVList _ -> pr "[LV]"
7211    | RStat _ -> pr "Stat"
7212    | RStatVFS _ -> pr "StatVFS"
7213    | RHashtable _ -> pr "Hashtable"
7214   );
7215   pr ")"
7216
7217 and generate_bindtests () =
7218   generate_header CStyle LGPLv2;
7219
7220   pr "\
7221 #include <stdio.h>
7222 #include <stdlib.h>
7223 #include <inttypes.h>
7224 #include <string.h>
7225
7226 #include \"guestfs.h\"
7227 #include \"guestfs_protocol.h\"
7228
7229 #define error guestfs_error
7230
7231 static void
7232 print_strings (char * const* const argv)
7233 {
7234   int argc;
7235
7236   printf (\"[\");
7237   for (argc = 0; argv[argc] != NULL; ++argc) {
7238     if (argc > 0) printf (\", \");
7239     printf (\"\\\"%%s\\\"\", argv[argc]);
7240   }
7241   printf (\"]\\n\");
7242 }
7243
7244 /* The test0 function prints its parameters to stdout. */
7245 ";
7246
7247   let test0, tests =
7248     match test_functions with
7249     | [] -> assert false
7250     | test0 :: tests -> test0, tests in
7251
7252   let () =
7253     let (name, style, _, _, _, _, _) = test0 in
7254     generate_prototype ~extern:false ~semicolon:false ~newline:true
7255       ~handle:"g" ~prefix:"guestfs_" name style;
7256     pr "{\n";
7257     List.iter (
7258       function
7259       | String n
7260       | FileIn n
7261       | FileOut n -> pr "  printf (\"%%s\\n\", %s);\n" n
7262       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
7263       | StringList n -> pr "  print_strings (%s);\n" n
7264       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
7265       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
7266     ) (snd style);
7267     pr "  return 0;\n";
7268     pr "}\n";
7269     pr "\n" in
7270
7271   List.iter (
7272     fun (name, style, _, _, _, _, _) ->
7273       if String.sub name (String.length name - 3) 3 <> "err" then (
7274         pr "/* Test normal return. */\n";
7275         generate_prototype ~extern:false ~semicolon:false ~newline:true
7276           ~handle:"g" ~prefix:"guestfs_" name style;
7277         pr "{\n";
7278         (match fst style with
7279          | RErr ->
7280              pr "  return 0;\n"
7281          | RInt _ ->
7282              pr "  int r;\n";
7283              pr "  sscanf (val, \"%%d\", &r);\n";
7284              pr "  return r;\n"
7285          | RInt64 _ ->
7286              pr "  int64_t r;\n";
7287              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
7288              pr "  return r;\n"
7289          | RBool _ ->
7290              pr "  return strcmp (val, \"true\") == 0;\n"
7291          | RConstString _ ->
7292              (* Can't return the input string here.  Return a static
7293               * string so we ensure we get a segfault if the caller
7294               * tries to free it.
7295               *)
7296              pr "  return \"static string\";\n"
7297          | RString _ ->
7298              pr "  return strdup (val);\n"
7299          | RStringList _ ->
7300              pr "  char **strs;\n";
7301              pr "  int n, i;\n";
7302              pr "  sscanf (val, \"%%d\", &n);\n";
7303              pr "  strs = malloc ((n+1) * sizeof (char *));\n";
7304              pr "  for (i = 0; i < n; ++i) {\n";
7305              pr "    strs[i] = malloc (16);\n";
7306              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
7307              pr "  }\n";
7308              pr "  strs[n] = NULL;\n";
7309              pr "  return strs;\n"
7310          | RIntBool _ ->
7311              pr "  struct guestfs_int_bool *r;\n";
7312              pr "  r = malloc (sizeof (struct guestfs_int_bool));\n";
7313              pr "  sscanf (val, \"%%\" SCNi32, &r->i);\n";
7314              pr "  r->b = 0;\n";
7315              pr "  return r;\n"
7316          | RPVList _ ->
7317              pr "  struct guestfs_lvm_pv_list *r;\n";
7318              pr "  int i;\n";
7319              pr "  r = malloc (sizeof (struct guestfs_lvm_pv_list));\n";
7320              pr "  sscanf (val, \"%%d\", &r->len);\n";
7321              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_pv));\n";
7322              pr "  for (i = 0; i < r->len; ++i) {\n";
7323              pr "    r->val[i].pv_name = malloc (16);\n";
7324              pr "    snprintf (r->val[i].pv_name, 16, \"%%d\", i);\n";
7325              pr "  }\n";
7326              pr "  return r;\n"
7327          | RVGList _ ->
7328              pr "  struct guestfs_lvm_vg_list *r;\n";
7329              pr "  int i;\n";
7330              pr "  r = malloc (sizeof (struct guestfs_lvm_vg_list));\n";
7331              pr "  sscanf (val, \"%%d\", &r->len);\n";
7332              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_vg));\n";
7333              pr "  for (i = 0; i < r->len; ++i) {\n";
7334              pr "    r->val[i].vg_name = malloc (16);\n";
7335              pr "    snprintf (r->val[i].vg_name, 16, \"%%d\", i);\n";
7336              pr "  }\n";
7337              pr "  return r;\n"
7338          | RLVList _ ->
7339              pr "  struct guestfs_lvm_lv_list *r;\n";
7340              pr "  int i;\n";
7341              pr "  r = malloc (sizeof (struct guestfs_lvm_lv_list));\n";
7342              pr "  sscanf (val, \"%%d\", &r->len);\n";
7343              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_lv));\n";
7344              pr "  for (i = 0; i < r->len; ++i) {\n";
7345              pr "    r->val[i].lv_name = malloc (16);\n";
7346              pr "    snprintf (r->val[i].lv_name, 16, \"%%d\", i);\n";
7347              pr "  }\n";
7348              pr "  return r;\n"
7349          | RStat _ ->
7350              pr "  struct guestfs_stat *r;\n";
7351              pr "  r = calloc (1, sizeof (*r));\n";
7352              pr "  sscanf (val, \"%%\" SCNi64, &r->dev);\n";
7353              pr "  return r;\n"
7354          | RStatVFS _ ->
7355              pr "  struct guestfs_statvfs *r;\n";
7356              pr "  r = calloc (1, sizeof (*r));\n";
7357              pr "  sscanf (val, \"%%\" SCNi64, &r->bsize);\n";
7358              pr "  return r;\n"
7359          | RHashtable _ ->
7360              pr "  char **strs;\n";
7361              pr "  int n, i;\n";
7362              pr "  sscanf (val, \"%%d\", &n);\n";
7363              pr "  strs = malloc ((n*2+1) * sizeof (char *));\n";
7364              pr "  for (i = 0; i < n; ++i) {\n";
7365              pr "    strs[i*2] = malloc (16);\n";
7366              pr "    strs[i*2+1] = malloc (16);\n";
7367              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
7368              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
7369              pr "  }\n";
7370              pr "  strs[n*2] = NULL;\n";
7371              pr "  return strs;\n"
7372         );
7373         pr "}\n";
7374         pr "\n"
7375       ) else (
7376         pr "/* Test error return. */\n";
7377         generate_prototype ~extern:false ~semicolon:false ~newline:true
7378           ~handle:"g" ~prefix:"guestfs_" name style;
7379         pr "{\n";
7380         pr "  error (g, \"error\");\n";
7381         (match fst style with
7382          | RErr | RInt _ | RInt64 _ | RBool _ ->
7383              pr "  return -1;\n"
7384          | RConstString _
7385          | RString _ | RStringList _ | RIntBool _
7386          | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7387          | RHashtable _ ->
7388              pr "  return NULL;\n"
7389         );
7390         pr "}\n";
7391         pr "\n"
7392       )
7393   ) tests
7394
7395 let output_to filename =
7396   let filename_new = filename ^ ".new" in
7397   chan := open_out filename_new;
7398   let close () =
7399     close_out !chan;
7400     chan := stdout;
7401
7402     (* Is the new file different from the current file? *)
7403     if Sys.file_exists filename && files_equal filename filename_new then
7404       Unix.unlink filename_new          (* same, so skip it *)
7405     else (
7406       (* different, overwrite old one *)
7407       (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
7408       Unix.rename filename_new filename;
7409       Unix.chmod filename 0o444;
7410       printf "written %s\n%!" filename;
7411     )
7412   in
7413   close
7414
7415 (* Main program. *)
7416 let () =
7417   check_functions ();
7418
7419   if not (Sys.file_exists "configure.ac") then (
7420     eprintf "\
7421 You are probably running this from the wrong directory.
7422 Run it from the top source directory using the command
7423   src/generator.ml
7424 ";
7425     exit 1
7426   );
7427
7428   let close = output_to "src/guestfs_protocol.x" in
7429   generate_xdr ();
7430   close ();
7431
7432   let close = output_to "src/guestfs-structs.h" in
7433   generate_structs_h ();
7434   close ();
7435
7436   let close = output_to "src/guestfs-actions.h" in
7437   generate_actions_h ();
7438   close ();
7439
7440   let close = output_to "src/guestfs-actions.c" in
7441   generate_client_actions ();
7442   close ();
7443
7444   let close = output_to "daemon/actions.h" in
7445   generate_daemon_actions_h ();
7446   close ();
7447
7448   let close = output_to "daemon/stubs.c" in
7449   generate_daemon_actions ();
7450   close ();
7451
7452   let close = output_to "capitests/tests.c" in
7453   generate_tests ();
7454   close ();
7455
7456   let close = output_to "src/guestfs-bindtests.c" in
7457   generate_bindtests ();
7458   close ();
7459
7460   let close = output_to "fish/cmds.c" in
7461   generate_fish_cmds ();
7462   close ();
7463
7464   let close = output_to "fish/completion.c" in
7465   generate_fish_completion ();
7466   close ();
7467
7468   let close = output_to "guestfs-structs.pod" in
7469   generate_structs_pod ();
7470   close ();
7471
7472   let close = output_to "guestfs-actions.pod" in
7473   generate_actions_pod ();
7474   close ();
7475
7476   let close = output_to "guestfish-actions.pod" in
7477   generate_fish_actions_pod ();
7478   close ();
7479
7480   let close = output_to "ocaml/guestfs.mli" in
7481   generate_ocaml_mli ();
7482   close ();
7483
7484   let close = output_to "ocaml/guestfs.ml" in
7485   generate_ocaml_ml ();
7486   close ();
7487
7488   let close = output_to "ocaml/guestfs_c_actions.c" in
7489   generate_ocaml_c ();
7490   close ();
7491
7492   let close = output_to "perl/Guestfs.xs" in
7493   generate_perl_xs ();
7494   close ();
7495
7496   let close = output_to "perl/lib/Sys/Guestfs.pm" in
7497   generate_perl_pm ();
7498   close ();
7499
7500   let close = output_to "python/guestfs-py.c" in
7501   generate_python_c ();
7502   close ();
7503
7504   let close = output_to "python/guestfs.py" in
7505   generate_python_py ();
7506   close ();
7507
7508   let close = output_to "ruby/ext/guestfs/_guestfs.c" in
7509   generate_ruby_c ();
7510   close ();
7511
7512   let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
7513   generate_java_java ();
7514   close ();
7515
7516   let close = output_to "java/com/redhat/et/libguestfs/PV.java" in
7517   generate_java_struct "PV" pv_cols;
7518   close ();
7519
7520   let close = output_to "java/com/redhat/et/libguestfs/VG.java" in
7521   generate_java_struct "VG" vg_cols;
7522   close ();
7523
7524   let close = output_to "java/com/redhat/et/libguestfs/LV.java" in
7525   generate_java_struct "LV" lv_cols;
7526   close ();
7527
7528   let close = output_to "java/com/redhat/et/libguestfs/Stat.java" in
7529   generate_java_struct "Stat" stat_cols;
7530   close ();
7531
7532   let close = output_to "java/com/redhat/et/libguestfs/StatVFS.java" in
7533   generate_java_struct "StatVFS" statvfs_cols;
7534   close ();
7535
7536   let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
7537   generate_java_c ();
7538   close ();
7539
7540   let close = output_to "haskell/Guestfs.hs" in
7541   generate_haskell_hs ();
7542   close ();