f30d7798adc42c3f1e54a8647d2e9c20bdd00712
[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 (* Used for testing language bindings. *)
2377 type callt =
2378   | CallString of string
2379   | CallOptString of string option
2380   | CallStringList of string list
2381   | CallInt of int
2382   | CallBool of bool
2383
2384 (* Useful functions.
2385  * Note we don't want to use any external OCaml libraries which
2386  * makes this a bit harder than it should be.
2387  *)
2388 let failwithf fs = ksprintf failwith fs
2389
2390 let replace_char s c1 c2 =
2391   let s2 = String.copy s in
2392   let r = ref false in
2393   for i = 0 to String.length s2 - 1 do
2394     if String.unsafe_get s2 i = c1 then (
2395       String.unsafe_set s2 i c2;
2396       r := true
2397     )
2398   done;
2399   if not !r then s else s2
2400
2401 let isspace c =
2402   c = ' '
2403   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
2404
2405 let triml ?(test = isspace) str =
2406   let i = ref 0 in
2407   let n = ref (String.length str) in
2408   while !n > 0 && test str.[!i]; do
2409     decr n;
2410     incr i
2411   done;
2412   if !i = 0 then str
2413   else String.sub str !i !n
2414
2415 let trimr ?(test = isspace) str =
2416   let n = ref (String.length str) in
2417   while !n > 0 && test str.[!n-1]; do
2418     decr n
2419   done;
2420   if !n = String.length str then str
2421   else String.sub str 0 !n
2422
2423 let trim ?(test = isspace) str =
2424   trimr ~test (triml ~test str)
2425
2426 let rec find s sub =
2427   let len = String.length s in
2428   let sublen = String.length sub in
2429   let rec loop i =
2430     if i <= len-sublen then (
2431       let rec loop2 j =
2432         if j < sublen then (
2433           if s.[i+j] = sub.[j] then loop2 (j+1)
2434           else -1
2435         ) else
2436           i (* found *)
2437       in
2438       let r = loop2 0 in
2439       if r = -1 then loop (i+1) else r
2440     ) else
2441       -1 (* not found *)
2442   in
2443   loop 0
2444
2445 let rec replace_str s s1 s2 =
2446   let len = String.length s in
2447   let sublen = String.length s1 in
2448   let i = find s s1 in
2449   if i = -1 then s
2450   else (
2451     let s' = String.sub s 0 i in
2452     let s'' = String.sub s (i+sublen) (len-i-sublen) in
2453     s' ^ s2 ^ replace_str s'' s1 s2
2454   )
2455
2456 let rec string_split sep str =
2457   let len = String.length str in
2458   let seplen = String.length sep in
2459   let i = find str sep in
2460   if i = -1 then [str]
2461   else (
2462     let s' = String.sub str 0 i in
2463     let s'' = String.sub str (i+seplen) (len-i-seplen) in
2464     s' :: string_split sep s''
2465   )
2466
2467 let files_equal n1 n2 =
2468   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
2469   match Sys.command cmd with
2470   | 0 -> true
2471   | 1 -> false
2472   | i -> failwithf "%s: failed with error code %d" cmd i
2473
2474 let rec find_map f = function
2475   | [] -> raise Not_found
2476   | x :: xs ->
2477       match f x with
2478       | Some y -> y
2479       | None -> find_map f xs
2480
2481 let iteri f xs =
2482   let rec loop i = function
2483     | [] -> ()
2484     | x :: xs -> f i x; loop (i+1) xs
2485   in
2486   loop 0 xs
2487
2488 let mapi f xs =
2489   let rec loop i = function
2490     | [] -> []
2491     | x :: xs -> let r = f i x in r :: loop (i+1) xs
2492   in
2493   loop 0 xs
2494
2495 let name_of_argt = function
2496   | String n | OptString n | StringList n | Bool n | Int n
2497   | FileIn n | FileOut n -> n
2498
2499 let seq_of_test = function
2500   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
2501   | TestOutputInt (s, _) | TestOutputTrue s | TestOutputFalse s
2502   | TestOutputLength (s, _) | TestOutputStruct (s, _)
2503   | TestLastFail s -> s
2504
2505 (* Check function names etc. for consistency. *)
2506 let check_functions () =
2507   let contains_uppercase str =
2508     let len = String.length str in
2509     let rec loop i =
2510       if i >= len then false
2511       else (
2512         let c = str.[i] in
2513         if c >= 'A' && c <= 'Z' then true
2514         else loop (i+1)
2515       )
2516     in
2517     loop 0
2518   in
2519
2520   (* Check function names. *)
2521   List.iter (
2522     fun (name, _, _, _, _, _, _) ->
2523       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
2524         failwithf "function name %s does not need 'guestfs' prefix" name;
2525       if name = "" then
2526         failwithf "function name is empty";
2527       if name.[0] < 'a' || name.[0] > 'z' then
2528         failwithf "function name %s must start with lowercase a-z" name;
2529       if String.contains name '-' then
2530         failwithf "function name %s should not contain '-', use '_' instead."
2531           name
2532   ) all_functions;
2533
2534   (* Check function parameter/return names. *)
2535   List.iter (
2536     fun (name, style, _, _, _, _, _) ->
2537       let check_arg_ret_name n =
2538         if contains_uppercase n then
2539           failwithf "%s param/ret %s should not contain uppercase chars"
2540             name n;
2541         if String.contains n '-' || String.contains n '_' then
2542           failwithf "%s param/ret %s should not contain '-' or '_'"
2543             name n;
2544         if n = "value" then
2545           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;
2546         if n = "int" || n = "char" || n = "short" || n = "long" then
2547           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
2548         if n = "i" then
2549           failwithf "%s has a param/ret called 'i', which will cause some conflicts in the generated code" name;
2550         if n = "argv" || n = "args" then
2551           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
2552       in
2553
2554       (match fst style with
2555        | RErr -> ()
2556        | RInt n | RInt64 n | RBool n | RConstString n | RString n
2557        | RStringList n | RPVList n | RVGList n | RLVList n
2558        | RStat n | RStatVFS n
2559        | RHashtable n ->
2560            check_arg_ret_name n
2561        | RIntBool (n,m) ->
2562            check_arg_ret_name n;
2563            check_arg_ret_name m
2564       );
2565       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
2566   ) all_functions;
2567
2568   (* Check short descriptions. *)
2569   List.iter (
2570     fun (name, _, _, _, _, shortdesc, _) ->
2571       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
2572         failwithf "short description of %s should begin with lowercase." name;
2573       let c = shortdesc.[String.length shortdesc-1] in
2574       if c = '\n' || c = '.' then
2575         failwithf "short description of %s should not end with . or \\n." name
2576   ) all_functions;
2577
2578   (* Check long dscriptions. *)
2579   List.iter (
2580     fun (name, _, _, _, _, _, longdesc) ->
2581       if longdesc.[String.length longdesc-1] = '\n' then
2582         failwithf "long description of %s should not end with \\n." name
2583   ) all_functions;
2584
2585   (* Check proc_nrs. *)
2586   List.iter (
2587     fun (name, _, proc_nr, _, _, _, _) ->
2588       if proc_nr <= 0 then
2589         failwithf "daemon function %s should have proc_nr > 0" name
2590   ) daemon_functions;
2591
2592   List.iter (
2593     fun (name, _, proc_nr, _, _, _, _) ->
2594       if proc_nr <> -1 then
2595         failwithf "non-daemon function %s should have proc_nr -1" name
2596   ) non_daemon_functions;
2597
2598   let proc_nrs =
2599     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
2600       daemon_functions in
2601   let proc_nrs =
2602     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
2603   let rec loop = function
2604     | [] -> ()
2605     | [_] -> ()
2606     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
2607         loop rest
2608     | (name1,nr1) :: (name2,nr2) :: _ ->
2609         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
2610           name1 name2 nr1 nr2
2611   in
2612   loop proc_nrs;
2613
2614   (* Check tests. *)
2615   List.iter (
2616     function
2617       (* Ignore functions that have no tests.  We generate a
2618        * warning when the user does 'make check' instead.
2619        *)
2620     | name, _, _, _, [], _, _ -> ()
2621     | name, _, _, _, tests, _, _ ->
2622         let funcs =
2623           List.map (
2624             fun (_, _, test) ->
2625               match seq_of_test test with
2626               | [] ->
2627                   failwithf "%s has a test containing an empty sequence" name
2628               | cmds -> List.map List.hd cmds
2629           ) tests in
2630         let funcs = List.flatten funcs in
2631
2632         let tested = List.mem name funcs in
2633
2634         if not tested then
2635           failwithf "function %s has tests but does not test itself" name
2636   ) all_functions
2637
2638 (* 'pr' prints to the current output file. *)
2639 let chan = ref stdout
2640 let pr fs = ksprintf (output_string !chan) fs
2641
2642 (* Generate a header block in a number of standard styles. *)
2643 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
2644 type license = GPLv2 | LGPLv2
2645
2646 let generate_header comment license =
2647   let c = match comment with
2648     | CStyle ->     pr "/* "; " *"
2649     | HashStyle ->  pr "# ";  "#"
2650     | OCamlStyle -> pr "(* "; " *"
2651     | HaskellStyle -> pr "{- "; "  " in
2652   pr "libguestfs generated file\n";
2653   pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
2654   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
2655   pr "%s\n" c;
2656   pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
2657   pr "%s\n" c;
2658   (match license with
2659    | GPLv2 ->
2660        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
2661        pr "%s it under the terms of the GNU General Public License as published by\n" c;
2662        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
2663        pr "%s (at your option) any later version.\n" c;
2664        pr "%s\n" c;
2665        pr "%s This program is distributed in the hope that it will be useful,\n" c;
2666        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2667        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
2668        pr "%s GNU General Public License for more details.\n" c;
2669        pr "%s\n" c;
2670        pr "%s You should have received a copy of the GNU General Public License along\n" c;
2671        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
2672        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
2673
2674    | LGPLv2 ->
2675        pr "%s This library is free software; you can redistribute it and/or\n" c;
2676        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
2677        pr "%s License as published by the Free Software Foundation; either\n" c;
2678        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
2679        pr "%s\n" c;
2680        pr "%s This library is distributed in the hope that it will be useful,\n" c;
2681        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
2682        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
2683        pr "%s Lesser General Public License for more details.\n" c;
2684        pr "%s\n" c;
2685        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
2686        pr "%s License along with this library; if not, write to the Free Software\n" c;
2687        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
2688   );
2689   (match comment with
2690    | CStyle -> pr " */\n"
2691    | HashStyle -> ()
2692    | OCamlStyle -> pr " *)\n"
2693    | HaskellStyle -> pr "-}\n"
2694   );
2695   pr "\n"
2696
2697 (* Start of main code generation functions below this line. *)
2698
2699 (* Generate the pod documentation for the C API. *)
2700 let rec generate_actions_pod () =
2701   List.iter (
2702     fun (shortname, style, _, flags, _, _, longdesc) ->
2703       if not (List.mem NotInDocs flags) then (
2704         let name = "guestfs_" ^ shortname in
2705         pr "=head2 %s\n\n" name;
2706         pr " ";
2707         generate_prototype ~extern:false ~handle:"handle" name style;
2708         pr "\n\n";
2709         pr "%s\n\n" longdesc;
2710         (match fst style with
2711          | RErr ->
2712              pr "This function returns 0 on success or -1 on error.\n\n"
2713          | RInt _ ->
2714              pr "On error this function returns -1.\n\n"
2715          | RInt64 _ ->
2716              pr "On error this function returns -1.\n\n"
2717          | RBool _ ->
2718              pr "This function returns a C truth value on success or -1 on error.\n\n"
2719          | RConstString _ ->
2720              pr "This function returns a string, or NULL on error.
2721 The string is owned by the guest handle and must I<not> be freed.\n\n"
2722          | RString _ ->
2723              pr "This function returns a string, or NULL on error.
2724 I<The caller must free the returned string after use>.\n\n"
2725          | RStringList _ ->
2726              pr "This function returns a NULL-terminated array of strings
2727 (like L<environ(3)>), or NULL if there was an error.
2728 I<The caller must free the strings and the array after use>.\n\n"
2729          | RIntBool _ ->
2730              pr "This function returns a C<struct guestfs_int_bool *>,
2731 or NULL if there was an error.
2732 I<The caller must call C<guestfs_free_int_bool> after use>.\n\n"
2733          | RPVList _ ->
2734              pr "This function returns a C<struct guestfs_lvm_pv_list *>
2735 (see E<lt>guestfs-structs.hE<gt>),
2736 or NULL if there was an error.
2737 I<The caller must call C<guestfs_free_lvm_pv_list> after use>.\n\n"
2738          | RVGList _ ->
2739              pr "This function returns a C<struct guestfs_lvm_vg_list *>
2740 (see E<lt>guestfs-structs.hE<gt>),
2741 or NULL if there was an error.
2742 I<The caller must call C<guestfs_free_lvm_vg_list> after use>.\n\n"
2743          | RLVList _ ->
2744              pr "This function returns a C<struct guestfs_lvm_lv_list *>
2745 (see E<lt>guestfs-structs.hE<gt>),
2746 or NULL if there was an error.
2747 I<The caller must call C<guestfs_free_lvm_lv_list> after use>.\n\n"
2748          | RStat _ ->
2749              pr "This function returns a C<struct guestfs_stat *>
2750 (see L<stat(2)> and E<lt>guestfs-structs.hE<gt>),
2751 or NULL if there was an error.
2752 I<The caller must call C<free> after use>.\n\n"
2753          | RStatVFS _ ->
2754              pr "This function returns a C<struct guestfs_statvfs *>
2755 (see L<statvfs(2)> and E<lt>guestfs-structs.hE<gt>),
2756 or NULL if there was an error.
2757 I<The caller must call C<free> after use>.\n\n"
2758          | RHashtable _ ->
2759              pr "This function returns a NULL-terminated array of
2760 strings, or NULL if there was an error.
2761 The array of strings will always have length C<2n+1>, where
2762 C<n> keys and values alternate, followed by the trailing NULL entry.
2763 I<The caller must free the strings and the array after use>.\n\n"
2764         );
2765         if List.mem ProtocolLimitWarning flags then
2766           pr "%s\n\n" protocol_limit_warning;
2767         if List.mem DangerWillRobinson flags then
2768           pr "%s\n\n" danger_will_robinson
2769       )
2770   ) all_functions_sorted
2771
2772 and generate_structs_pod () =
2773   (* LVM structs documentation. *)
2774   List.iter (
2775     fun (typ, cols) ->
2776       pr "=head2 guestfs_lvm_%s\n" typ;
2777       pr "\n";
2778       pr " struct guestfs_lvm_%s {\n" typ;
2779       List.iter (
2780         function
2781         | name, `String -> pr "  char *%s;\n" name
2782         | name, `UUID ->
2783             pr "  /* The next field is NOT nul-terminated, be careful when printing it: */\n";
2784             pr "  char %s[32];\n" name
2785         | name, `Bytes -> pr "  uint64_t %s;\n" name
2786         | name, `Int -> pr "  int64_t %s;\n" name
2787         | name, `OptPercent ->
2788             pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
2789             pr "  float %s;\n" name
2790       ) cols;
2791       pr " \n";
2792       pr " struct guestfs_lvm_%s_list {\n" typ;
2793       pr "   uint32_t len; /* Number of elements in list. */\n";
2794       pr "   struct guestfs_lvm_%s *val; /* Elements. */\n" typ;
2795       pr " };\n";
2796       pr " \n";
2797       pr " void guestfs_free_lvm_%s_list (struct guestfs_free_lvm_%s_list *);\n"
2798         typ typ;
2799       pr "\n"
2800   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
2801
2802 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
2803  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
2804  *
2805  * We have to use an underscore instead of a dash because otherwise
2806  * rpcgen generates incorrect code.
2807  *
2808  * This header is NOT exported to clients, but see also generate_structs_h.
2809  *)
2810 and generate_xdr () =
2811   generate_header CStyle LGPLv2;
2812
2813   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
2814   pr "typedef string str<>;\n";
2815   pr "\n";
2816
2817   (* LVM internal structures. *)
2818   List.iter (
2819     function
2820     | typ, cols ->
2821         pr "struct guestfs_lvm_int_%s {\n" typ;
2822         List.iter (function
2823                    | name, `String -> pr "  string %s<>;\n" name
2824                    | name, `UUID -> pr "  opaque %s[32];\n" name
2825                    | name, `Bytes -> pr "  hyper %s;\n" name
2826                    | name, `Int -> pr "  hyper %s;\n" name
2827                    | name, `OptPercent -> pr "  float %s;\n" name
2828                   ) cols;
2829         pr "};\n";
2830         pr "\n";
2831         pr "typedef struct guestfs_lvm_int_%s guestfs_lvm_int_%s_list<>;\n" typ typ;
2832         pr "\n";
2833   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
2834
2835   (* Stat internal structures. *)
2836   List.iter (
2837     function
2838     | typ, cols ->
2839         pr "struct guestfs_int_%s {\n" typ;
2840         List.iter (function
2841                    | name, `Int -> pr "  hyper %s;\n" name
2842                   ) cols;
2843         pr "};\n";
2844         pr "\n";
2845   ) ["stat", stat_cols; "statvfs", statvfs_cols];
2846
2847   List.iter (
2848     fun (shortname, style, _, _, _, _, _) ->
2849       let name = "guestfs_" ^ shortname in
2850
2851       (match snd style with
2852        | [] -> ()
2853        | args ->
2854            pr "struct %s_args {\n" name;
2855            List.iter (
2856              function
2857              | String n -> pr "  string %s<>;\n" n
2858              | OptString n -> pr "  str *%s;\n" n
2859              | StringList n -> pr "  str %s<>;\n" n
2860              | Bool n -> pr "  bool %s;\n" n
2861              | Int n -> pr "  int %s;\n" n
2862              | FileIn _ | FileOut _ -> ()
2863            ) args;
2864            pr "};\n\n"
2865       );
2866       (match fst style with
2867        | RErr -> ()
2868        | RInt n ->
2869            pr "struct %s_ret {\n" name;
2870            pr "  int %s;\n" n;
2871            pr "};\n\n"
2872        | RInt64 n ->
2873            pr "struct %s_ret {\n" name;
2874            pr "  hyper %s;\n" n;
2875            pr "};\n\n"
2876        | RBool n ->
2877            pr "struct %s_ret {\n" name;
2878            pr "  bool %s;\n" n;
2879            pr "};\n\n"
2880        | RConstString _ ->
2881            failwithf "RConstString cannot be returned from a daemon function"
2882        | RString n ->
2883            pr "struct %s_ret {\n" name;
2884            pr "  string %s<>;\n" n;
2885            pr "};\n\n"
2886        | RStringList n ->
2887            pr "struct %s_ret {\n" name;
2888            pr "  str %s<>;\n" n;
2889            pr "};\n\n"
2890        | RIntBool (n,m) ->
2891            pr "struct %s_ret {\n" name;
2892            pr "  int %s;\n" n;
2893            pr "  bool %s;\n" m;
2894            pr "};\n\n"
2895        | RPVList n ->
2896            pr "struct %s_ret {\n" name;
2897            pr "  guestfs_lvm_int_pv_list %s;\n" n;
2898            pr "};\n\n"
2899        | RVGList n ->
2900            pr "struct %s_ret {\n" name;
2901            pr "  guestfs_lvm_int_vg_list %s;\n" n;
2902            pr "};\n\n"
2903        | RLVList n ->
2904            pr "struct %s_ret {\n" name;
2905            pr "  guestfs_lvm_int_lv_list %s;\n" n;
2906            pr "};\n\n"
2907        | RStat n ->
2908            pr "struct %s_ret {\n" name;
2909            pr "  guestfs_int_stat %s;\n" n;
2910            pr "};\n\n"
2911        | RStatVFS n ->
2912            pr "struct %s_ret {\n" name;
2913            pr "  guestfs_int_statvfs %s;\n" n;
2914            pr "};\n\n"
2915        | RHashtable n ->
2916            pr "struct %s_ret {\n" name;
2917            pr "  str %s<>;\n" n;
2918            pr "};\n\n"
2919       );
2920   ) daemon_functions;
2921
2922   (* Table of procedure numbers. *)
2923   pr "enum guestfs_procedure {\n";
2924   List.iter (
2925     fun (shortname, _, proc_nr, _, _, _, _) ->
2926       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
2927   ) daemon_functions;
2928   pr "  GUESTFS_PROC_NR_PROCS\n";
2929   pr "};\n";
2930   pr "\n";
2931
2932   (* Having to choose a maximum message size is annoying for several
2933    * reasons (it limits what we can do in the API), but it (a) makes
2934    * the protocol a lot simpler, and (b) provides a bound on the size
2935    * of the daemon which operates in limited memory space.  For large
2936    * file transfers you should use FTP.
2937    *)
2938   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
2939   pr "\n";
2940
2941   (* Message header, etc. *)
2942   pr "\
2943 /* The communication protocol is now documented in the guestfs(3)
2944  * manpage.
2945  */
2946
2947 const GUESTFS_PROGRAM = 0x2000F5F5;
2948 const GUESTFS_PROTOCOL_VERSION = 1;
2949
2950 /* These constants must be larger than any possible message length. */
2951 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
2952 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
2953
2954 enum guestfs_message_direction {
2955   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
2956   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
2957 };
2958
2959 enum guestfs_message_status {
2960   GUESTFS_STATUS_OK = 0,
2961   GUESTFS_STATUS_ERROR = 1
2962 };
2963
2964 const GUESTFS_ERROR_LEN = 256;
2965
2966 struct guestfs_message_error {
2967   string error_message<GUESTFS_ERROR_LEN>;
2968 };
2969
2970 struct guestfs_message_header {
2971   unsigned prog;                     /* GUESTFS_PROGRAM */
2972   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
2973   guestfs_procedure proc;            /* GUESTFS_PROC_x */
2974   guestfs_message_direction direction;
2975   unsigned serial;                   /* message serial number */
2976   guestfs_message_status status;
2977 };
2978
2979 const GUESTFS_MAX_CHUNK_SIZE = 8192;
2980
2981 struct guestfs_chunk {
2982   int cancel;                        /* if non-zero, transfer is cancelled */
2983   /* data size is 0 bytes if the transfer has finished successfully */
2984   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
2985 };
2986 "
2987
2988 (* Generate the guestfs-structs.h file. *)
2989 and generate_structs_h () =
2990   generate_header CStyle LGPLv2;
2991
2992   (* This is a public exported header file containing various
2993    * structures.  The structures are carefully written to have
2994    * exactly the same in-memory format as the XDR structures that
2995    * we use on the wire to the daemon.  The reason for creating
2996    * copies of these structures here is just so we don't have to
2997    * export the whole of guestfs_protocol.h (which includes much
2998    * unrelated and XDR-dependent stuff that we don't want to be
2999    * public, or required by clients).
3000    *
3001    * To reiterate, we will pass these structures to and from the
3002    * client with a simple assignment or memcpy, so the format
3003    * must be identical to what rpcgen / the RFC defines.
3004    *)
3005
3006   (* guestfs_int_bool structure. *)
3007   pr "struct guestfs_int_bool {\n";
3008   pr "  int32_t i;\n";
3009   pr "  int32_t b;\n";
3010   pr "};\n";
3011   pr "\n";
3012
3013   (* LVM public structures. *)
3014   List.iter (
3015     function
3016     | typ, cols ->
3017         pr "struct guestfs_lvm_%s {\n" typ;
3018         List.iter (
3019           function
3020           | name, `String -> pr "  char *%s;\n" name
3021           | name, `UUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3022           | name, `Bytes -> pr "  uint64_t %s;\n" name
3023           | name, `Int -> pr "  int64_t %s;\n" name
3024           | name, `OptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
3025         ) cols;
3026         pr "};\n";
3027         pr "\n";
3028         pr "struct guestfs_lvm_%s_list {\n" typ;
3029         pr "  uint32_t len;\n";
3030         pr "  struct guestfs_lvm_%s *val;\n" typ;
3031         pr "};\n";
3032         pr "\n"
3033   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
3034
3035   (* Stat structures. *)
3036   List.iter (
3037     function
3038     | typ, cols ->
3039         pr "struct guestfs_%s {\n" typ;
3040         List.iter (
3041           function
3042           | name, `Int -> pr "  int64_t %s;\n" name
3043         ) cols;
3044         pr "};\n";
3045         pr "\n"
3046   ) ["stat", stat_cols; "statvfs", statvfs_cols]
3047
3048 (* Generate the guestfs-actions.h file. *)
3049 and generate_actions_h () =
3050   generate_header CStyle LGPLv2;
3051   List.iter (
3052     fun (shortname, style, _, _, _, _, _) ->
3053       let name = "guestfs_" ^ shortname in
3054       generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3055         name style
3056   ) all_functions
3057
3058 (* Generate the client-side dispatch stubs. *)
3059 and generate_client_actions () =
3060   generate_header CStyle LGPLv2;
3061
3062   pr "\
3063 #include <stdio.h>
3064 #include <stdlib.h>
3065
3066 #include \"guestfs.h\"
3067 #include \"guestfs_protocol.h\"
3068
3069 #define error guestfs_error
3070 #define perrorf guestfs_perrorf
3071 #define safe_malloc guestfs_safe_malloc
3072 #define safe_realloc guestfs_safe_realloc
3073 #define safe_strdup guestfs_safe_strdup
3074 #define safe_memdup guestfs_safe_memdup
3075
3076 /* Check the return message from a call for validity. */
3077 static int
3078 check_reply_header (guestfs_h *g,
3079                     const struct guestfs_message_header *hdr,
3080                     int proc_nr, int serial)
3081 {
3082   if (hdr->prog != GUESTFS_PROGRAM) {
3083     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3084     return -1;
3085   }
3086   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3087     error (g, \"wrong protocol version (%%d/%%d)\",
3088            hdr->vers, GUESTFS_PROTOCOL_VERSION);
3089     return -1;
3090   }
3091   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3092     error (g, \"unexpected message direction (%%d/%%d)\",
3093            hdr->direction, GUESTFS_DIRECTION_REPLY);
3094     return -1;
3095   }
3096   if (hdr->proc != proc_nr) {
3097     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3098     return -1;
3099   }
3100   if (hdr->serial != serial) {
3101     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3102     return -1;
3103   }
3104
3105   return 0;
3106 }
3107
3108 /* Check we are in the right state to run a high-level action. */
3109 static int
3110 check_state (guestfs_h *g, const char *caller)
3111 {
3112   if (!guestfs_is_ready (g)) {
3113     if (guestfs_is_config (g))
3114       error (g, \"%%s: call launch() before using this function\",
3115         caller);
3116     else if (guestfs_is_launching (g))
3117       error (g, \"%%s: call wait_ready() before using this function\",
3118         caller);
3119     else
3120       error (g, \"%%s called from the wrong state, %%d != READY\",
3121         caller, guestfs_get_state (g));
3122     return -1;
3123   }
3124   return 0;
3125 }
3126
3127 ";
3128
3129   (* Client-side stubs for each function. *)
3130   List.iter (
3131     fun (shortname, style, _, _, _, _, _) ->
3132       let name = "guestfs_" ^ shortname in
3133
3134       (* Generate the context struct which stores the high-level
3135        * state between callback functions.
3136        *)
3137       pr "struct %s_ctx {\n" shortname;
3138       pr "  /* This flag is set by the callbacks, so we know we've done\n";
3139       pr "   * the callbacks as expected, and in the right sequence.\n";
3140       pr "   * 0 = not called, 1 = reply_cb called.\n";
3141       pr "   */\n";
3142       pr "  int cb_sequence;\n";
3143       pr "  struct guestfs_message_header hdr;\n";
3144       pr "  struct guestfs_message_error err;\n";
3145       (match fst style with
3146        | RErr -> ()
3147        | RConstString _ ->
3148            failwithf "RConstString cannot be returned from a daemon function"
3149        | RInt _ | RInt64 _
3150        | RBool _ | RString _ | RStringList _
3151        | RIntBool _
3152        | RPVList _ | RVGList _ | RLVList _
3153        | RStat _ | RStatVFS _
3154        | RHashtable _ ->
3155            pr "  struct %s_ret ret;\n" name
3156       );
3157       pr "};\n";
3158       pr "\n";
3159
3160       (* Generate the reply callback function. *)
3161       pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
3162       pr "{\n";
3163       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3164       pr "  struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
3165       pr "\n";
3166       pr "  /* This should definitely not happen. */\n";
3167       pr "  if (ctx->cb_sequence != 0) {\n";
3168       pr "    ctx->cb_sequence = 9999;\n";
3169       pr "    error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
3170       pr "    return;\n";
3171       pr "  }\n";
3172       pr "\n";
3173       pr "  ml->main_loop_quit (ml, g);\n";
3174       pr "\n";
3175       pr "  if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
3176       pr "    error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
3177       pr "    return;\n";
3178       pr "  }\n";
3179       pr "  if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
3180       pr "    if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
3181       pr "      error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
3182         name;
3183       pr "      return;\n";
3184       pr "    }\n";
3185       pr "    goto done;\n";
3186       pr "  }\n";
3187
3188       (match fst style with
3189        | RErr -> ()
3190        | RConstString _ ->
3191            failwithf "RConstString cannot be returned from a daemon function"
3192        | RInt _ | RInt64 _
3193        | RBool _ | RString _ | RStringList _
3194        | RIntBool _
3195        | RPVList _ | RVGList _ | RLVList _
3196        | RStat _ | RStatVFS _
3197        | RHashtable _ ->
3198             pr "  if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
3199             pr "    error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
3200             pr "    return;\n";
3201             pr "  }\n";
3202       );
3203
3204       pr " done:\n";
3205       pr "  ctx->cb_sequence = 1;\n";
3206       pr "}\n\n";
3207
3208       (* Generate the action stub. *)
3209       generate_prototype ~extern:false ~semicolon:false ~newline:true
3210         ~handle:"g" name style;
3211
3212       let error_code =
3213         match fst style with
3214         | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
3215         | RConstString _ ->
3216             failwithf "RConstString cannot be returned from a daemon function"
3217         | RString _ | RStringList _ | RIntBool _
3218         | RPVList _ | RVGList _ | RLVList _
3219         | RStat _ | RStatVFS _
3220         | RHashtable _ ->
3221             "NULL" in
3222
3223       pr "{\n";
3224
3225       (match snd style with
3226        | [] -> ()
3227        | _ -> pr "  struct %s_args args;\n" name
3228       );
3229
3230       pr "  struct %s_ctx ctx;\n" shortname;
3231       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3232       pr "  int serial;\n";
3233       pr "\n";
3234       pr "  if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
3235       pr "  guestfs_set_busy (g);\n";
3236       pr "\n";
3237       pr "  memset (&ctx, 0, sizeof ctx);\n";
3238       pr "\n";
3239
3240       (* Send the main header and arguments. *)
3241       (match snd style with
3242        | [] ->
3243            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
3244              (String.uppercase shortname)
3245        | args ->
3246            List.iter (
3247              function
3248              | String n ->
3249                  pr "  args.%s = (char *) %s;\n" n n
3250              | OptString n ->
3251                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
3252              | StringList n ->
3253                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
3254                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
3255              | Bool n ->
3256                  pr "  args.%s = %s;\n" n n
3257              | Int n ->
3258                  pr "  args.%s = %s;\n" n n
3259              | FileIn _ | FileOut _ -> ()
3260            ) args;
3261            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
3262              (String.uppercase shortname);
3263            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
3264              name;
3265       );
3266       pr "  if (serial == -1) {\n";
3267       pr "    guestfs_end_busy (g);\n";
3268       pr "    return %s;\n" error_code;
3269       pr "  }\n";
3270       pr "\n";
3271
3272       (* Send any additional files (FileIn) requested. *)
3273       let need_read_reply_label = ref false in
3274       List.iter (
3275         function
3276         | FileIn n ->
3277             pr "  {\n";
3278             pr "    int r;\n";
3279             pr "\n";
3280             pr "    r = guestfs__send_file_sync (g, %s);\n" n;
3281             pr "    if (r == -1) {\n";
3282             pr "      guestfs_end_busy (g);\n";
3283             pr "      return %s;\n" error_code;
3284             pr "    }\n";
3285             pr "    if (r == -2) /* daemon cancelled */\n";
3286             pr "      goto read_reply;\n";
3287             need_read_reply_label := true;
3288             pr "  }\n";
3289             pr "\n";
3290         | _ -> ()
3291       ) (snd style);
3292
3293       (* Wait for the reply from the remote end. *)
3294       if !need_read_reply_label then pr " read_reply:\n";
3295       pr "  guestfs__switch_to_receiving (g);\n";
3296       pr "  ctx.cb_sequence = 0;\n";
3297       pr "  guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
3298       pr "  (void) ml->main_loop_run (ml, g);\n";
3299       pr "  guestfs_set_reply_callback (g, NULL, NULL);\n";
3300       pr "  if (ctx.cb_sequence != 1) {\n";
3301       pr "    error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
3302       pr "    guestfs_end_busy (g);\n";
3303       pr "    return %s;\n" error_code;
3304       pr "  }\n";
3305       pr "\n";
3306
3307       pr "  if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
3308         (String.uppercase shortname);
3309       pr "    guestfs_end_busy (g);\n";
3310       pr "    return %s;\n" error_code;
3311       pr "  }\n";
3312       pr "\n";
3313
3314       pr "  if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
3315       pr "    error (g, \"%%s\", ctx.err.error_message);\n";
3316       pr "    free (ctx.err.error_message);\n";
3317       pr "    guestfs_end_busy (g);\n";
3318       pr "    return %s;\n" error_code;
3319       pr "  }\n";
3320       pr "\n";
3321
3322       (* Expecting to receive further files (FileOut)? *)
3323       List.iter (
3324         function
3325         | FileOut n ->
3326             pr "  if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
3327             pr "    guestfs_end_busy (g);\n";
3328             pr "    return %s;\n" error_code;
3329             pr "  }\n";
3330             pr "\n";
3331         | _ -> ()
3332       ) (snd style);
3333
3334       pr "  guestfs_end_busy (g);\n";
3335
3336       (match fst style with
3337        | RErr -> pr "  return 0;\n"
3338        | RInt n | RInt64 n | RBool n ->
3339            pr "  return ctx.ret.%s;\n" n
3340        | RConstString _ ->
3341            failwithf "RConstString cannot be returned from a daemon function"
3342        | RString n ->
3343            pr "  return ctx.ret.%s; /* caller will free */\n" n
3344        | RStringList n | RHashtable n ->
3345            pr "  /* caller will free this, but we need to add a NULL entry */\n";
3346            pr "  ctx.ret.%s.%s_val =\n" n n;
3347            pr "    safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
3348            pr "                  sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
3349              n n;
3350            pr "  ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
3351            pr "  return ctx.ret.%s.%s_val;\n" n n
3352        | RIntBool _ ->
3353            pr "  /* caller with free this */\n";
3354            pr "  return safe_memdup (g, &ctx.ret, sizeof (ctx.ret));\n"
3355        | RPVList n | RVGList n | RLVList n
3356        | RStat n | RStatVFS n ->
3357            pr "  /* caller will free this */\n";
3358            pr "  return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
3359       );
3360
3361       pr "}\n\n"
3362   ) daemon_functions
3363
3364 (* Generate daemon/actions.h. *)
3365 and generate_daemon_actions_h () =
3366   generate_header CStyle GPLv2;
3367
3368   pr "#include \"../src/guestfs_protocol.h\"\n";
3369   pr "\n";
3370
3371   List.iter (
3372     fun (name, style, _, _, _, _, _) ->
3373         generate_prototype
3374           ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
3375           name style;
3376   ) daemon_functions
3377
3378 (* Generate the server-side stubs. *)
3379 and generate_daemon_actions () =
3380   generate_header CStyle GPLv2;
3381
3382   pr "#include <config.h>\n";
3383   pr "\n";
3384   pr "#include <stdio.h>\n";
3385   pr "#include <stdlib.h>\n";
3386   pr "#include <string.h>\n";
3387   pr "#include <inttypes.h>\n";
3388   pr "#include <ctype.h>\n";
3389   pr "#include <rpc/types.h>\n";
3390   pr "#include <rpc/xdr.h>\n";
3391   pr "\n";
3392   pr "#include \"daemon.h\"\n";
3393   pr "#include \"../src/guestfs_protocol.h\"\n";
3394   pr "#include \"actions.h\"\n";
3395   pr "\n";
3396
3397   List.iter (
3398     fun (name, style, _, _, _, _, _) ->
3399       (* Generate server-side stubs. *)
3400       pr "static void %s_stub (XDR *xdr_in)\n" name;
3401       pr "{\n";
3402       let error_code =
3403         match fst style with
3404         | RErr | RInt _ -> pr "  int r;\n"; "-1"
3405         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
3406         | RBool _ -> pr "  int r;\n"; "-1"
3407         | RConstString _ ->
3408             failwithf "RConstString cannot be returned from a daemon function"
3409         | RString _ -> pr "  char *r;\n"; "NULL"
3410         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
3411         | RIntBool _ -> pr "  guestfs_%s_ret *r;\n" name; "NULL"
3412         | RPVList _ -> pr "  guestfs_lvm_int_pv_list *r;\n"; "NULL"
3413         | RVGList _ -> pr "  guestfs_lvm_int_vg_list *r;\n"; "NULL"
3414         | RLVList _ -> pr "  guestfs_lvm_int_lv_list *r;\n"; "NULL"
3415         | RStat _ -> pr "  guestfs_int_stat *r;\n"; "NULL"
3416         | RStatVFS _ -> pr "  guestfs_int_statvfs *r;\n"; "NULL" in
3417
3418       (match snd style with
3419        | [] -> ()
3420        | args ->
3421            pr "  struct guestfs_%s_args args;\n" name;
3422            List.iter (
3423              function
3424              | String n
3425              | OptString n -> pr "  const char *%s;\n" n
3426              | StringList n -> pr "  char **%s;\n" n
3427              | Bool n -> pr "  int %s;\n" n
3428              | Int n -> pr "  int %s;\n" n
3429              | FileIn _ | FileOut _ -> ()
3430            ) args
3431       );
3432       pr "\n";
3433
3434       (match snd style with
3435        | [] -> ()
3436        | args ->
3437            pr "  memset (&args, 0, sizeof args);\n";
3438            pr "\n";
3439            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
3440            pr "    reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
3441            pr "    return;\n";
3442            pr "  }\n";
3443            List.iter (
3444              function
3445              | String n -> pr "  %s = args.%s;\n" n n
3446              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
3447              | StringList n ->
3448                  pr "  %s = realloc (args.%s.%s_val,\n" n n n;
3449                  pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
3450                  pr "  if (%s == NULL) {\n" n;
3451                  pr "    reply_with_perror (\"realloc\");\n";
3452                  pr "    goto done;\n";
3453                  pr "  }\n";
3454                  pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
3455                  pr "  args.%s.%s_val = %s;\n" n n n;
3456              | Bool n -> pr "  %s = args.%s;\n" n n
3457              | Int n -> pr "  %s = args.%s;\n" n n
3458              | FileIn _ | FileOut _ -> ()
3459            ) args;
3460            pr "\n"
3461       );
3462
3463       (* Don't want to call the impl with any FileIn or FileOut
3464        * parameters, since these go "outside" the RPC protocol.
3465        *)
3466       let argsnofile =
3467         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
3468           (snd style) in
3469       pr "  r = do_%s " name;
3470       generate_call_args argsnofile;
3471       pr ";\n";
3472
3473       pr "  if (r == %s)\n" error_code;
3474       pr "    /* do_%s has already called reply_with_error */\n" name;
3475       pr "    goto done;\n";
3476       pr "\n";
3477
3478       (* If there are any FileOut parameters, then the impl must
3479        * send its own reply.
3480        *)
3481       let no_reply =
3482         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
3483       if no_reply then
3484         pr "  /* do_%s has already sent a reply */\n" name
3485       else (
3486         match fst style with
3487         | RErr -> pr "  reply (NULL, NULL);\n"
3488         | RInt n | RInt64 n | RBool n ->
3489             pr "  struct guestfs_%s_ret ret;\n" name;
3490             pr "  ret.%s = r;\n" n;
3491             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3492               name
3493         | RConstString _ ->
3494             failwithf "RConstString cannot be returned from a daemon function"
3495         | RString n ->
3496             pr "  struct guestfs_%s_ret ret;\n" name;
3497             pr "  ret.%s = r;\n" n;
3498             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3499               name;
3500             pr "  free (r);\n"
3501         | RStringList n | RHashtable n ->
3502             pr "  struct guestfs_%s_ret ret;\n" name;
3503             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
3504             pr "  ret.%s.%s_val = r;\n" n n;
3505             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
3506               name;
3507             pr "  free_strings (r);\n"
3508         | RIntBool _ ->
3509             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n"
3510               name;
3511             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n" name
3512         | RPVList n | RVGList n | RLVList n
3513         | RStat n | RStatVFS n ->
3514             pr "  struct guestfs_%s_ret ret;\n" name;
3515             pr "  ret.%s = *r;\n" n;
3516             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3517               name;
3518             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3519               name
3520       );
3521
3522       (* Free the args. *)
3523       (match snd style with
3524        | [] ->
3525            pr "done: ;\n";
3526        | _ ->
3527            pr "done:\n";
3528            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
3529              name
3530       );
3531
3532       pr "}\n\n";
3533   ) daemon_functions;
3534
3535   (* Dispatch function. *)
3536   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
3537   pr "{\n";
3538   pr "  switch (proc_nr) {\n";
3539
3540   List.iter (
3541     fun (name, style, _, _, _, _, _) ->
3542         pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
3543         pr "      %s_stub (xdr_in);\n" name;
3544         pr "      break;\n"
3545   ) daemon_functions;
3546
3547   pr "    default:\n";
3548   pr "      reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d\", proc_nr);\n";
3549   pr "  }\n";
3550   pr "}\n";
3551   pr "\n";
3552
3553   (* LVM columns and tokenization functions. *)
3554   (* XXX This generates crap code.  We should rethink how we
3555    * do this parsing.
3556    *)
3557   List.iter (
3558     function
3559     | typ, cols ->
3560         pr "static const char *lvm_%s_cols = \"%s\";\n"
3561           typ (String.concat "," (List.map fst cols));
3562         pr "\n";
3563
3564         pr "static int lvm_tokenize_%s (char *str, struct guestfs_lvm_int_%s *r)\n" typ typ;
3565         pr "{\n";
3566         pr "  char *tok, *p, *next;\n";
3567         pr "  int i, j;\n";
3568         pr "\n";
3569         (*
3570         pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
3571         pr "\n";
3572         *)
3573         pr "  if (!str) {\n";
3574         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
3575         pr "    return -1;\n";
3576         pr "  }\n";
3577         pr "  if (!*str || isspace (*str)) {\n";
3578         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
3579         pr "    return -1;\n";
3580         pr "  }\n";
3581         pr "  tok = str;\n";
3582         List.iter (
3583           fun (name, coltype) ->
3584             pr "  if (!tok) {\n";
3585             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
3586             pr "    return -1;\n";
3587             pr "  }\n";
3588             pr "  p = strchrnul (tok, ',');\n";
3589             pr "  if (*p) next = p+1; else next = NULL;\n";
3590             pr "  *p = '\\0';\n";
3591             (match coltype with
3592              | `String ->
3593                  pr "  r->%s = strdup (tok);\n" name;
3594                  pr "  if (r->%s == NULL) {\n" name;
3595                  pr "    perror (\"strdup\");\n";
3596                  pr "    return -1;\n";
3597                  pr "  }\n"
3598              | `UUID ->
3599                  pr "  for (i = j = 0; i < 32; ++j) {\n";
3600                  pr "    if (tok[j] == '\\0') {\n";
3601                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
3602                  pr "      return -1;\n";
3603                  pr "    } else if (tok[j] != '-')\n";
3604                  pr "      r->%s[i++] = tok[j];\n" name;
3605                  pr "  }\n";
3606              | `Bytes ->
3607                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
3608                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3609                  pr "    return -1;\n";
3610                  pr "  }\n";
3611              | `Int ->
3612                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
3613                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3614                  pr "    return -1;\n";
3615                  pr "  }\n";
3616              | `OptPercent ->
3617                  pr "  if (tok[0] == '\\0')\n";
3618                  pr "    r->%s = -1;\n" name;
3619                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
3620                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
3621                  pr "    return -1;\n";
3622                  pr "  }\n";
3623             );
3624             pr "  tok = next;\n";
3625         ) cols;
3626
3627         pr "  if (tok != NULL) {\n";
3628         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
3629         pr "    return -1;\n";
3630         pr "  }\n";
3631         pr "  return 0;\n";
3632         pr "}\n";
3633         pr "\n";
3634
3635         pr "guestfs_lvm_int_%s_list *\n" typ;
3636         pr "parse_command_line_%ss (void)\n" typ;
3637         pr "{\n";
3638         pr "  char *out, *err;\n";
3639         pr "  char *p, *pend;\n";
3640         pr "  int r, i;\n";
3641         pr "  guestfs_lvm_int_%s_list *ret;\n" typ;
3642         pr "  void *newp;\n";
3643         pr "\n";
3644         pr "  ret = malloc (sizeof *ret);\n";
3645         pr "  if (!ret) {\n";
3646         pr "    reply_with_perror (\"malloc\");\n";
3647         pr "    return NULL;\n";
3648         pr "  }\n";
3649         pr "\n";
3650         pr "  ret->guestfs_lvm_int_%s_list_len = 0;\n" typ;
3651         pr "  ret->guestfs_lvm_int_%s_list_val = NULL;\n" typ;
3652         pr "\n";
3653         pr "  r = command (&out, &err,\n";
3654         pr "           \"/sbin/lvm\", \"%ss\",\n" typ;
3655         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
3656         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
3657         pr "  if (r == -1) {\n";
3658         pr "    reply_with_error (\"%%s\", err);\n";
3659         pr "    free (out);\n";
3660         pr "    free (err);\n";
3661         pr "    free (ret);\n";
3662         pr "    return NULL;\n";
3663         pr "  }\n";
3664         pr "\n";
3665         pr "  free (err);\n";
3666         pr "\n";
3667         pr "  /* Tokenize each line of the output. */\n";
3668         pr "  p = out;\n";
3669         pr "  i = 0;\n";
3670         pr "  while (p) {\n";
3671         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
3672         pr "    if (pend) {\n";
3673         pr "      *pend = '\\0';\n";
3674         pr "      pend++;\n";
3675         pr "    }\n";
3676         pr "\n";
3677         pr "    while (*p && isspace (*p))      /* Skip any leading whitespace. */\n";
3678         pr "      p++;\n";
3679         pr "\n";
3680         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
3681         pr "      p = pend;\n";
3682         pr "      continue;\n";
3683         pr "    }\n";
3684         pr "\n";
3685         pr "    /* Allocate some space to store this next entry. */\n";
3686         pr "    newp = realloc (ret->guestfs_lvm_int_%s_list_val,\n" typ;
3687         pr "                sizeof (guestfs_lvm_int_%s) * (i+1));\n" typ;
3688         pr "    if (newp == NULL) {\n";
3689         pr "      reply_with_perror (\"realloc\");\n";
3690         pr "      free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3691         pr "      free (ret);\n";
3692         pr "      free (out);\n";
3693         pr "      return NULL;\n";
3694         pr "    }\n";
3695         pr "    ret->guestfs_lvm_int_%s_list_val = newp;\n" typ;
3696         pr "\n";
3697         pr "    /* Tokenize the next entry. */\n";
3698         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_lvm_int_%s_list_val[i]);\n" typ typ;
3699         pr "    if (r == -1) {\n";
3700         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
3701         pr "      free (ret->guestfs_lvm_int_%s_list_val);\n" typ;
3702         pr "      free (ret);\n";
3703         pr "      free (out);\n";
3704         pr "      return NULL;\n";
3705         pr "    }\n";
3706         pr "\n";
3707         pr "    ++i;\n";
3708         pr "    p = pend;\n";
3709         pr "  }\n";
3710         pr "\n";
3711         pr "  ret->guestfs_lvm_int_%s_list_len = i;\n" typ;
3712         pr "\n";
3713         pr "  free (out);\n";
3714         pr "  return ret;\n";
3715         pr "}\n"
3716
3717   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
3718
3719 (* Generate the tests. *)
3720 and generate_tests () =
3721   generate_header CStyle GPLv2;
3722
3723   pr "\
3724 #include <stdio.h>
3725 #include <stdlib.h>
3726 #include <string.h>
3727 #include <unistd.h>
3728 #include <sys/types.h>
3729 #include <fcntl.h>
3730
3731 #include \"guestfs.h\"
3732
3733 static guestfs_h *g;
3734 static int suppress_error = 0;
3735
3736 /* This will be 's' or 'h' depending on whether the guest kernel
3737  * names IDE devices /dev/sd* or /dev/hd*.
3738  */
3739 static char devchar = 's';
3740
3741 static void print_error (guestfs_h *g, void *data, const char *msg)
3742 {
3743   if (!suppress_error)
3744     fprintf (stderr, \"%%s\\n\", msg);
3745 }
3746
3747 static void print_strings (char * const * const argv)
3748 {
3749   int argc;
3750
3751   for (argc = 0; argv[argc] != NULL; ++argc)
3752     printf (\"\\t%%s\\n\", argv[argc]);
3753 }
3754
3755 /*
3756 static void print_table (char * const * const argv)
3757 {
3758   int i;
3759
3760   for (i = 0; argv[i] != NULL; i += 2)
3761     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
3762 }
3763 */
3764
3765 static void no_test_warnings (void)
3766 {
3767 ";
3768
3769   List.iter (
3770     function
3771     | name, _, _, _, [], _, _ ->
3772         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
3773     | name, _, _, _, tests, _, _ -> ()
3774   ) all_functions;
3775
3776   pr "}\n";
3777   pr "\n";
3778
3779   (* Generate the actual tests.  Note that we generate the tests
3780    * in reverse order, deliberately, so that (in general) the
3781    * newest tests run first.  This makes it quicker and easier to
3782    * debug them.
3783    *)
3784   let test_names =
3785     List.map (
3786       fun (name, _, _, _, tests, _, _) ->
3787         mapi (generate_one_test name) tests
3788     ) (List.rev all_functions) in
3789   let test_names = List.concat test_names in
3790   let nr_tests = List.length test_names in
3791
3792   pr "\
3793 int main (int argc, char *argv[])
3794 {
3795   char c = 0;
3796   int failed = 0;
3797   const char *srcdir;
3798   const char *filename;
3799   int fd, i;
3800   int nr_tests, test_num = 0;
3801   char **devs;
3802
3803   no_test_warnings ();
3804
3805   g = guestfs_create ();
3806   if (g == NULL) {
3807     printf (\"guestfs_create FAILED\\n\");
3808     exit (1);
3809   }
3810
3811   guestfs_set_error_handler (g, print_error, NULL);
3812
3813   guestfs_set_path (g, \"../appliance\");
3814
3815   filename = \"test1.img\";
3816   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3817   if (fd == -1) {
3818     perror (filename);
3819     exit (1);
3820   }
3821   if (lseek (fd, %d, SEEK_SET) == -1) {
3822     perror (\"lseek\");
3823     close (fd);
3824     unlink (filename);
3825     exit (1);
3826   }
3827   if (write (fd, &c, 1) == -1) {
3828     perror (\"write\");
3829     close (fd);
3830     unlink (filename);
3831     exit (1);
3832   }
3833   if (close (fd) == -1) {
3834     perror (filename);
3835     unlink (filename);
3836     exit (1);
3837   }
3838   if (guestfs_add_drive (g, filename) == -1) {
3839     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3840     exit (1);
3841   }
3842
3843   filename = \"test2.img\";
3844   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3845   if (fd == -1) {
3846     perror (filename);
3847     exit (1);
3848   }
3849   if (lseek (fd, %d, SEEK_SET) == -1) {
3850     perror (\"lseek\");
3851     close (fd);
3852     unlink (filename);
3853     exit (1);
3854   }
3855   if (write (fd, &c, 1) == -1) {
3856     perror (\"write\");
3857     close (fd);
3858     unlink (filename);
3859     exit (1);
3860   }
3861   if (close (fd) == -1) {
3862     perror (filename);
3863     unlink (filename);
3864     exit (1);
3865   }
3866   if (guestfs_add_drive (g, filename) == -1) {
3867     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3868     exit (1);
3869   }
3870
3871   filename = \"test3.img\";
3872   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3873   if (fd == -1) {
3874     perror (filename);
3875     exit (1);
3876   }
3877   if (lseek (fd, %d, SEEK_SET) == -1) {
3878     perror (\"lseek\");
3879     close (fd);
3880     unlink (filename);
3881     exit (1);
3882   }
3883   if (write (fd, &c, 1) == -1) {
3884     perror (\"write\");
3885     close (fd);
3886     unlink (filename);
3887     exit (1);
3888   }
3889   if (close (fd) == -1) {
3890     perror (filename);
3891     unlink (filename);
3892     exit (1);
3893   }
3894   if (guestfs_add_drive (g, filename) == -1) {
3895     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3896     exit (1);
3897   }
3898
3899   if (guestfs_launch (g) == -1) {
3900     printf (\"guestfs_launch FAILED\\n\");
3901     exit (1);
3902   }
3903   if (guestfs_wait_ready (g) == -1) {
3904     printf (\"guestfs_wait_ready FAILED\\n\");
3905     exit (1);
3906   }
3907
3908   /* Detect if the appliance uses /dev/sd* or /dev/hd* in device
3909    * names.  This changed between RHEL 5 and RHEL 6 so we have to
3910    * support both.
3911    */
3912   devs = guestfs_list_devices (g);
3913   if (devs == NULL || devs[0] == NULL) {
3914     printf (\"guestfs_list_devices FAILED\\n\");
3915     exit (1);
3916   }
3917   if (strncmp (devs[0], \"/dev/sd\", 7) == 0)
3918     devchar = 's';
3919   else if (strncmp (devs[0], \"/dev/hd\", 7) == 0)
3920     devchar = 'h';
3921   else {
3922     printf (\"guestfs_list_devices returned unexpected string '%%s'\\n\",
3923             devs[0]);
3924     exit (1);
3925   }
3926   for (i = 0; devs[i] != NULL; ++i)
3927     free (devs[i]);
3928   free (devs);
3929
3930   nr_tests = %d;
3931
3932 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
3933
3934   iteri (
3935     fun i test_name ->
3936       pr "  test_num++;\n";
3937       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
3938       pr "  if (%s () == -1) {\n" test_name;
3939       pr "    printf (\"%s FAILED\\n\");\n" test_name;
3940       pr "    failed++;\n";
3941       pr "  }\n";
3942   ) test_names;
3943   pr "\n";
3944
3945   pr "  guestfs_close (g);\n";
3946   pr "  unlink (\"test1.img\");\n";
3947   pr "  unlink (\"test2.img\");\n";
3948   pr "  unlink (\"test3.img\");\n";
3949   pr "\n";
3950
3951   pr "  if (failed > 0) {\n";
3952   pr "    printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
3953   pr "    exit (1);\n";
3954   pr "  }\n";
3955   pr "\n";
3956
3957   pr "  exit (0);\n";
3958   pr "}\n"
3959
3960 and generate_one_test name i (init, prereq, test) =
3961   let test_name = sprintf "test_%s_%d" name i in
3962
3963   pr "\
3964 static int %s_skip (void)
3965 {
3966   const char *str;
3967
3968   str = getenv (\"SKIP_%s\");
3969   if (str && strcmp (str, \"1\") == 0) return 1;
3970   str = getenv (\"SKIP_TEST_%s\");
3971   if (str && strcmp (str, \"1\") == 0) return 1;
3972   return 0;
3973 }
3974
3975 " test_name (String.uppercase test_name) (String.uppercase name);
3976
3977   (match prereq with
3978    | Disabled | Always -> ()
3979    | If code | Unless code ->
3980        pr "static int %s_prereq (void)\n" test_name;
3981        pr "{\n";
3982        pr "  %s\n" code;
3983        pr "}\n";
3984        pr "\n";
3985   );
3986
3987   pr "\
3988 static int %s (void)
3989 {
3990   if (%s_skip ()) {
3991     printf (\"%%s skipped (reason: SKIP_TEST_* variable set)\\n\", \"%s\");
3992     return 0;
3993   }
3994
3995 " test_name test_name test_name;
3996
3997   (match prereq with
3998    | Disabled ->
3999        pr "  printf (\"%%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4000    | If _ ->
4001        pr "  if (! %s_prereq ()) {\n" test_name;
4002        pr "    printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4003        pr "    return 0;\n";
4004        pr "  }\n";
4005        pr "\n";
4006        generate_one_test_body name i test_name init test;
4007    | Unless _ ->
4008        pr "  if (%s_prereq ()) {\n" test_name;
4009        pr "    printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4010        pr "    return 0;\n";
4011        pr "  }\n";
4012        pr "\n";
4013        generate_one_test_body name i test_name init test;
4014    | Always ->
4015        generate_one_test_body name i test_name init test
4016   );
4017
4018   pr "  return 0;\n";
4019   pr "}\n";
4020   pr "\n";
4021   test_name
4022
4023 and generate_one_test_body name i test_name init test =
4024   (match init with
4025    | InitNone
4026    | InitEmpty ->
4027        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
4028        List.iter (generate_test_command_call test_name)
4029          [["blockdev_setrw"; "/dev/sda"];
4030           ["umount_all"];
4031           ["lvm_remove_all"]]
4032    | InitBasicFS ->
4033        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
4034        List.iter (generate_test_command_call test_name)
4035          [["blockdev_setrw"; "/dev/sda"];
4036           ["umount_all"];
4037           ["lvm_remove_all"];
4038           ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4039           ["mkfs"; "ext2"; "/dev/sda1"];
4040           ["mount"; "/dev/sda1"; "/"]]
4041    | InitBasicFSonLVM ->
4042        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
4043          test_name;
4044        List.iter (generate_test_command_call test_name)
4045          [["blockdev_setrw"; "/dev/sda"];
4046           ["umount_all"];
4047           ["lvm_remove_all"];
4048           ["sfdisk"; "/dev/sda"; "0"; "0"; "0"; ","];
4049           ["pvcreate"; "/dev/sda1"];
4050           ["vgcreate"; "VG"; "/dev/sda1"];
4051           ["lvcreate"; "LV"; "VG"; "8"];
4052           ["mkfs"; "ext2"; "/dev/VG/LV"];
4053           ["mount"; "/dev/VG/LV"; "/"]]
4054   );
4055
4056   let get_seq_last = function
4057     | [] ->
4058         failwithf "%s: you cannot use [] (empty list) when expecting a command"
4059           test_name
4060     | seq ->
4061         let seq = List.rev seq in
4062         List.rev (List.tl seq), List.hd seq
4063   in
4064
4065   match test with
4066   | TestRun seq ->
4067       pr "  /* TestRun for %s (%d) */\n" name i;
4068       List.iter (generate_test_command_call test_name) seq
4069   | TestOutput (seq, expected) ->
4070       pr "  /* TestOutput for %s (%d) */\n" name i;
4071       pr "  char expected[] = \"%s\";\n" (c_quote expected);
4072       if String.length expected > 7 &&
4073         String.sub expected 0 7 = "/dev/sd" then
4074           pr "  expected[5] = devchar;\n";
4075       let seq, last = get_seq_last seq in
4076       let test () =
4077         pr "    if (strcmp (r, expected) != 0) {\n";
4078         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
4079         pr "      return -1;\n";
4080         pr "    }\n"
4081       in
4082       List.iter (generate_test_command_call test_name) seq;
4083       generate_test_command_call ~test test_name last
4084   | TestOutputList (seq, expected) ->
4085       pr "  /* TestOutputList for %s (%d) */\n" name i;
4086       let seq, last = get_seq_last seq in
4087       let test () =
4088         iteri (
4089           fun i str ->
4090             pr "    if (!r[%d]) {\n" i;
4091             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4092             pr "      print_strings (r);\n";
4093             pr "      return -1;\n";
4094             pr "    }\n";
4095             pr "    {\n";
4096             pr "      char expected[] = \"%s\";\n" (c_quote str);
4097             if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4098               pr "      expected[5] = devchar;\n";
4099             pr "      if (strcmp (r[%d], expected) != 0) {\n" i;
4100             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4101             pr "        return -1;\n";
4102             pr "      }\n";
4103             pr "    }\n"
4104         ) expected;
4105         pr "    if (r[%d] != NULL) {\n" (List.length expected);
4106         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4107           test_name;
4108         pr "      print_strings (r);\n";
4109         pr "      return -1;\n";
4110         pr "    }\n"
4111       in
4112       List.iter (generate_test_command_call test_name) seq;
4113       generate_test_command_call ~test test_name last
4114   | TestOutputInt (seq, expected) ->
4115       pr "  /* TestOutputInt for %s (%d) */\n" name i;
4116       let seq, last = get_seq_last seq in
4117       let test () =
4118         pr "    if (r != %d) {\n" expected;
4119         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
4120           test_name expected;
4121         pr "               (int) r);\n";
4122         pr "      return -1;\n";
4123         pr "    }\n"
4124       in
4125       List.iter (generate_test_command_call test_name) seq;
4126       generate_test_command_call ~test test_name last
4127   | TestOutputTrue seq ->
4128       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
4129       let seq, last = get_seq_last seq in
4130       let test () =
4131         pr "    if (!r) {\n";
4132         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
4133           test_name;
4134         pr "      return -1;\n";
4135         pr "    }\n"
4136       in
4137       List.iter (generate_test_command_call test_name) seq;
4138       generate_test_command_call ~test test_name last
4139   | TestOutputFalse seq ->
4140       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
4141       let seq, last = get_seq_last seq in
4142       let test () =
4143         pr "    if (r) {\n";
4144         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
4145           test_name;
4146         pr "      return -1;\n";
4147         pr "    }\n"
4148       in
4149       List.iter (generate_test_command_call test_name) seq;
4150       generate_test_command_call ~test test_name last
4151   | TestOutputLength (seq, expected) ->
4152       pr "  /* TestOutputLength for %s (%d) */\n" name i;
4153       let seq, last = get_seq_last seq in
4154       let test () =
4155         pr "    int j;\n";
4156         pr "    for (j = 0; j < %d; ++j)\n" expected;
4157         pr "      if (r[j] == NULL) {\n";
4158         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
4159           test_name;
4160         pr "        print_strings (r);\n";
4161         pr "        return -1;\n";
4162         pr "      }\n";
4163         pr "    if (r[j] != NULL) {\n";
4164         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
4165           test_name;
4166         pr "      print_strings (r);\n";
4167         pr "      return -1;\n";
4168         pr "    }\n"
4169       in
4170       List.iter (generate_test_command_call test_name) seq;
4171       generate_test_command_call ~test test_name last
4172   | TestOutputStruct (seq, checks) ->
4173       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
4174       let seq, last = get_seq_last seq in
4175       let test () =
4176         List.iter (
4177           function
4178           | CompareWithInt (field, expected) ->
4179               pr "    if (r->%s != %d) {\n" field expected;
4180               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
4181                 test_name field expected;
4182               pr "               (int) r->%s);\n" field;
4183               pr "      return -1;\n";
4184               pr "    }\n"
4185           | CompareWithString (field, expected) ->
4186               pr "    if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
4187               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
4188                 test_name field expected;
4189               pr "               r->%s);\n" field;
4190               pr "      return -1;\n";
4191               pr "    }\n"
4192           | CompareFieldsIntEq (field1, field2) ->
4193               pr "    if (r->%s != r->%s) {\n" field1 field2;
4194               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
4195                 test_name field1 field2;
4196               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
4197               pr "      return -1;\n";
4198               pr "    }\n"
4199           | CompareFieldsStrEq (field1, field2) ->
4200               pr "    if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
4201               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
4202                 test_name field1 field2;
4203               pr "               r->%s, r->%s);\n" field1 field2;
4204               pr "      return -1;\n";
4205               pr "    }\n"
4206         ) checks
4207       in
4208       List.iter (generate_test_command_call test_name) seq;
4209       generate_test_command_call ~test test_name last
4210   | TestLastFail seq ->
4211       pr "  /* TestLastFail for %s (%d) */\n" name i;
4212       let seq, last = get_seq_last seq in
4213       List.iter (generate_test_command_call test_name) seq;
4214       generate_test_command_call test_name ~expect_error:true last
4215
4216 (* Generate the code to run a command, leaving the result in 'r'.
4217  * If you expect to get an error then you should set expect_error:true.
4218  *)
4219 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
4220   match cmd with
4221   | [] -> assert false
4222   | name :: args ->
4223       (* Look up the command to find out what args/ret it has. *)
4224       let style =
4225         try
4226           let _, style, _, _, _, _, _ =
4227             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
4228           style
4229         with Not_found ->
4230           failwithf "%s: in test, command %s was not found" test_name name in
4231
4232       if List.length (snd style) <> List.length args then
4233         failwithf "%s: in test, wrong number of args given to %s"
4234           test_name name;
4235
4236       pr "  {\n";
4237
4238       List.iter (
4239         function
4240         | OptString n, "NULL" -> ()
4241         | String n, arg
4242         | OptString n, arg ->
4243             pr "    char %s[] = \"%s\";\n" n (c_quote arg);
4244             if String.length arg > 7 && String.sub arg 0 7 = "/dev/sd" then
4245               pr "    %s[5] = devchar;\n" n
4246         | Int _, _
4247         | Bool _, _
4248         | FileIn _, _ | FileOut _, _ -> ()
4249         | StringList n, arg ->
4250             let strs = string_split " " arg in
4251             iteri (
4252               fun i str ->
4253                 pr "    char %s_%d[] = \"%s\";\n" n i (c_quote str);
4254                 if String.length str > 7 && String.sub str 0 7 = "/dev/sd" then
4255                   pr "    %s_%d[5] = devchar;\n" n i
4256             ) strs;
4257             pr "    char *%s[] = {\n" n;
4258             iteri (
4259               fun i _ -> pr "      %s_%d,\n" n i
4260             ) strs;
4261             pr "      NULL\n";
4262             pr "    };\n";
4263       ) (List.combine (snd style) args);
4264
4265       let error_code =
4266         match fst style with
4267         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
4268         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
4269         | RConstString _ -> pr "    const char *r;\n"; "NULL"
4270         | RString _ -> pr "    char *r;\n"; "NULL"
4271         | RStringList _ | RHashtable _ ->
4272             pr "    char **r;\n";
4273             pr "    int i;\n";
4274             "NULL"
4275         | RIntBool _ ->
4276             pr "    struct guestfs_int_bool *r;\n"; "NULL"
4277         | RPVList _ ->
4278             pr "    struct guestfs_lvm_pv_list *r;\n"; "NULL"
4279         | RVGList _ ->
4280             pr "    struct guestfs_lvm_vg_list *r;\n"; "NULL"
4281         | RLVList _ ->
4282             pr "    struct guestfs_lvm_lv_list *r;\n"; "NULL"
4283         | RStat _ ->
4284             pr "    struct guestfs_stat *r;\n"; "NULL"
4285         | RStatVFS _ ->
4286             pr "    struct guestfs_statvfs *r;\n"; "NULL" in
4287
4288       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
4289       pr "    r = guestfs_%s (g" name;
4290
4291       (* Generate the parameters. *)
4292       List.iter (
4293         function
4294         | OptString _, "NULL" -> pr ", NULL"
4295         | String n, _
4296         | OptString n, _ ->
4297             pr ", %s" n
4298         | FileIn _, arg | FileOut _, arg ->
4299             pr ", \"%s\"" (c_quote arg)
4300         | StringList n, _ ->
4301             pr ", %s" n
4302         | Int _, arg ->
4303             let i =
4304               try int_of_string arg
4305               with Failure "int_of_string" ->
4306                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
4307             pr ", %d" i
4308         | Bool _, arg ->
4309             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
4310       ) (List.combine (snd style) args);
4311
4312       pr ");\n";
4313       if not expect_error then
4314         pr "    if (r == %s)\n" error_code
4315       else
4316         pr "    if (r != %s)\n" error_code;
4317       pr "      return -1;\n";
4318
4319       (* Insert the test code. *)
4320       (match test with
4321        | None -> ()
4322        | Some f -> f ()
4323       );
4324
4325       (match fst style with
4326        | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _ -> ()
4327        | RString _ -> pr "    free (r);\n"
4328        | RStringList _ | RHashtable _ ->
4329            pr "    for (i = 0; r[i] != NULL; ++i)\n";
4330            pr "      free (r[i]);\n";
4331            pr "    free (r);\n"
4332        | RIntBool _ ->
4333            pr "    guestfs_free_int_bool (r);\n"
4334        | RPVList _ ->
4335            pr "    guestfs_free_lvm_pv_list (r);\n"
4336        | RVGList _ ->
4337            pr "    guestfs_free_lvm_vg_list (r);\n"
4338        | RLVList _ ->
4339            pr "    guestfs_free_lvm_lv_list (r);\n"
4340        | RStat _ | RStatVFS _ ->
4341            pr "    free (r);\n"
4342       );
4343
4344       pr "  }\n"
4345
4346 and c_quote str =
4347   let str = replace_str str "\r" "\\r" in
4348   let str = replace_str str "\n" "\\n" in
4349   let str = replace_str str "\t" "\\t" in
4350   let str = replace_str str "\000" "\\0" in
4351   str
4352
4353 (* Generate a lot of different functions for guestfish. *)
4354 and generate_fish_cmds () =
4355   generate_header CStyle GPLv2;
4356
4357   let all_functions =
4358     List.filter (
4359       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4360     ) all_functions in
4361   let all_functions_sorted =
4362     List.filter (
4363       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4364     ) all_functions_sorted in
4365
4366   pr "#include <stdio.h>\n";
4367   pr "#include <stdlib.h>\n";
4368   pr "#include <string.h>\n";
4369   pr "#include <inttypes.h>\n";
4370   pr "\n";
4371   pr "#include <guestfs.h>\n";
4372   pr "#include \"fish.h\"\n";
4373   pr "\n";
4374
4375   (* list_commands function, which implements guestfish -h *)
4376   pr "void list_commands (void)\n";
4377   pr "{\n";
4378   pr "  printf (\"    %%-16s     %%s\\n\", \"Command\", \"Description\");\n";
4379   pr "  list_builtin_commands ();\n";
4380   List.iter (
4381     fun (name, _, _, flags, _, shortdesc, _) ->
4382       let name = replace_char name '_' '-' in
4383       pr "  printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
4384         name shortdesc
4385   ) all_functions_sorted;
4386   pr "  printf (\"    Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
4387   pr "}\n";
4388   pr "\n";
4389
4390   (* display_command function, which implements guestfish -h cmd *)
4391   pr "void display_command (const char *cmd)\n";
4392   pr "{\n";
4393   List.iter (
4394     fun (name, style, _, flags, _, shortdesc, longdesc) ->
4395       let name2 = replace_char name '_' '-' in
4396       let alias =
4397         try find_map (function FishAlias n -> Some n | _ -> None) flags
4398         with Not_found -> name in
4399       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
4400       let synopsis =
4401         match snd style with
4402         | [] -> name2
4403         | args ->
4404             sprintf "%s <%s>"
4405               name2 (String.concat "> <" (List.map name_of_argt args)) in
4406
4407       let warnings =
4408         if List.mem ProtocolLimitWarning flags then
4409           ("\n\n" ^ protocol_limit_warning)
4410         else "" in
4411
4412       (* For DangerWillRobinson commands, we should probably have
4413        * guestfish prompt before allowing you to use them (especially
4414        * in interactive mode). XXX
4415        *)
4416       let warnings =
4417         warnings ^
4418           if List.mem DangerWillRobinson flags then
4419             ("\n\n" ^ danger_will_robinson)
4420           else "" in
4421
4422       let describe_alias =
4423         if name <> alias then
4424           sprintf "\n\nYou can use '%s' as an alias for this command." alias
4425         else "" in
4426
4427       pr "  if (";
4428       pr "strcasecmp (cmd, \"%s\") == 0" name;
4429       if name <> name2 then
4430         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4431       if name <> alias then
4432         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4433       pr ")\n";
4434       pr "    pod2text (\"%s - %s\", %S);\n"
4435         name2 shortdesc
4436         (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
4437       pr "  else\n"
4438   ) all_functions;
4439   pr "    display_builtin_command (cmd);\n";
4440   pr "}\n";
4441   pr "\n";
4442
4443   (* print_{pv,vg,lv}_list functions *)
4444   List.iter (
4445     function
4446     | typ, cols ->
4447         pr "static void print_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
4448         pr "{\n";
4449         pr "  int i;\n";
4450         pr "\n";
4451         List.iter (
4452           function
4453           | name, `String ->
4454               pr "  printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
4455           | name, `UUID ->
4456               pr "  printf (\"%s: \");\n" name;
4457               pr "  for (i = 0; i < 32; ++i)\n";
4458               pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
4459               pr "  printf (\"\\n\");\n"
4460           | name, `Bytes ->
4461               pr "  printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
4462           | name, `Int ->
4463               pr "  printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4464           | name, `OptPercent ->
4465               pr "  if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
4466                 typ name name typ name;
4467               pr "  else printf (\"%s: \\n\");\n" name
4468         ) cols;
4469         pr "}\n";
4470         pr "\n";
4471         pr "static void print_%s_list (struct guestfs_lvm_%s_list *%ss)\n"
4472           typ typ typ;
4473         pr "{\n";
4474         pr "  int i;\n";
4475         pr "\n";
4476         pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
4477         pr "    print_%s (&%ss->val[i]);\n" typ typ;
4478         pr "}\n";
4479         pr "\n";
4480   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
4481
4482   (* print_{stat,statvfs} functions *)
4483   List.iter (
4484     function
4485     | typ, cols ->
4486         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
4487         pr "{\n";
4488         List.iter (
4489           function
4490           | name, `Int ->
4491               pr "  printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4492         ) cols;
4493         pr "}\n";
4494         pr "\n";
4495   ) ["stat", stat_cols; "statvfs", statvfs_cols];
4496
4497   (* run_<action> actions *)
4498   List.iter (
4499     fun (name, style, _, flags, _, _, _) ->
4500       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
4501       pr "{\n";
4502       (match fst style with
4503        | RErr
4504        | RInt _
4505        | RBool _ -> pr "  int r;\n"
4506        | RInt64 _ -> pr "  int64_t r;\n"
4507        | RConstString _ -> pr "  const char *r;\n"
4508        | RString _ -> pr "  char *r;\n"
4509        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
4510        | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"
4511        | RPVList _ -> pr "  struct guestfs_lvm_pv_list *r;\n"
4512        | RVGList _ -> pr "  struct guestfs_lvm_vg_list *r;\n"
4513        | RLVList _ -> pr "  struct guestfs_lvm_lv_list *r;\n"
4514        | RStat _ -> pr "  struct guestfs_stat *r;\n"
4515        | RStatVFS _ -> pr "  struct guestfs_statvfs *r;\n"
4516       );
4517       List.iter (
4518         function
4519         | String n
4520         | OptString n
4521         | FileIn n
4522         | FileOut n -> pr "  const char *%s;\n" n
4523         | StringList n -> pr "  char **%s;\n" n
4524         | Bool n -> pr "  int %s;\n" n
4525         | Int n -> pr "  int %s;\n" n
4526       ) (snd style);
4527
4528       (* Check and convert parameters. *)
4529       let argc_expected = List.length (snd style) in
4530       pr "  if (argc != %d) {\n" argc_expected;
4531       pr "    fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
4532         argc_expected;
4533       pr "    fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
4534       pr "    return -1;\n";
4535       pr "  }\n";
4536       iteri (
4537         fun i ->
4538           function
4539           | String name -> pr "  %s = argv[%d];\n" name i
4540           | OptString name ->
4541               pr "  %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
4542                 name i i
4543           | FileIn name ->
4544               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
4545                 name i i
4546           | FileOut name ->
4547               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
4548                 name i i
4549           | StringList name ->
4550               pr "  %s = parse_string_list (argv[%d]);\n" name i
4551           | Bool name ->
4552               pr "  %s = is_true (argv[%d]) ? 1 : 0;\n" name i
4553           | Int name ->
4554               pr "  %s = atoi (argv[%d]);\n" name i
4555       ) (snd style);
4556
4557       (* Call C API function. *)
4558       let fn =
4559         try find_map (function FishAction n -> Some n | _ -> None) flags
4560         with Not_found -> sprintf "guestfs_%s" name in
4561       pr "  r = %s " fn;
4562       generate_call_args ~handle:"g" (snd style);
4563       pr ";\n";
4564
4565       (* Check return value for errors and display command results. *)
4566       (match fst style with
4567        | RErr -> pr "  return r;\n"
4568        | RInt _ ->
4569            pr "  if (r == -1) return -1;\n";
4570            pr "  printf (\"%%d\\n\", r);\n";
4571            pr "  return 0;\n"
4572        | RInt64 _ ->
4573            pr "  if (r == -1) return -1;\n";
4574            pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
4575            pr "  return 0;\n"
4576        | RBool _ ->
4577            pr "  if (r == -1) return -1;\n";
4578            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
4579            pr "  return 0;\n"
4580        | RConstString _ ->
4581            pr "  if (r == NULL) return -1;\n";
4582            pr "  printf (\"%%s\\n\", r);\n";
4583            pr "  return 0;\n"
4584        | RString _ ->
4585            pr "  if (r == NULL) return -1;\n";
4586            pr "  printf (\"%%s\\n\", r);\n";
4587            pr "  free (r);\n";
4588            pr "  return 0;\n"
4589        | RStringList _ ->
4590            pr "  if (r == NULL) return -1;\n";
4591            pr "  print_strings (r);\n";
4592            pr "  free_strings (r);\n";
4593            pr "  return 0;\n"
4594        | RIntBool _ ->
4595            pr "  if (r == NULL) return -1;\n";
4596            pr "  printf (\"%%d, %%s\\n\", r->i,\n";
4597            pr "    r->b ? \"true\" : \"false\");\n";
4598            pr "  guestfs_free_int_bool (r);\n";
4599            pr "  return 0;\n"
4600        | RPVList _ ->
4601            pr "  if (r == NULL) return -1;\n";
4602            pr "  print_pv_list (r);\n";
4603            pr "  guestfs_free_lvm_pv_list (r);\n";
4604            pr "  return 0;\n"
4605        | RVGList _ ->
4606            pr "  if (r == NULL) return -1;\n";
4607            pr "  print_vg_list (r);\n";
4608            pr "  guestfs_free_lvm_vg_list (r);\n";
4609            pr "  return 0;\n"
4610        | RLVList _ ->
4611            pr "  if (r == NULL) return -1;\n";
4612            pr "  print_lv_list (r);\n";
4613            pr "  guestfs_free_lvm_lv_list (r);\n";
4614            pr "  return 0;\n"
4615        | RStat _ ->
4616            pr "  if (r == NULL) return -1;\n";
4617            pr "  print_stat (r);\n";
4618            pr "  free (r);\n";
4619            pr "  return 0;\n"
4620        | RStatVFS _ ->
4621            pr "  if (r == NULL) return -1;\n";
4622            pr "  print_statvfs (r);\n";
4623            pr "  free (r);\n";
4624            pr "  return 0;\n"
4625        | RHashtable _ ->
4626            pr "  if (r == NULL) return -1;\n";
4627            pr "  print_table (r);\n";
4628            pr "  free_strings (r);\n";
4629            pr "  return 0;\n"
4630       );
4631       pr "}\n";
4632       pr "\n"
4633   ) all_functions;
4634
4635   (* run_action function *)
4636   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
4637   pr "{\n";
4638   List.iter (
4639     fun (name, _, _, flags, _, _, _) ->
4640       let name2 = replace_char name '_' '-' in
4641       let alias =
4642         try find_map (function FishAlias n -> Some n | _ -> None) flags
4643         with Not_found -> name in
4644       pr "  if (";
4645       pr "strcasecmp (cmd, \"%s\") == 0" name;
4646       if name <> name2 then
4647         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4648       if name <> alias then
4649         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
4650       pr ")\n";
4651       pr "    return run_%s (cmd, argc, argv);\n" name;
4652       pr "  else\n";
4653   ) all_functions;
4654   pr "    {\n";
4655   pr "      fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
4656   pr "      return -1;\n";
4657   pr "    }\n";
4658   pr "  return 0;\n";
4659   pr "}\n";
4660   pr "\n"
4661
4662 (* Readline completion for guestfish. *)
4663 and generate_fish_completion () =
4664   generate_header CStyle GPLv2;
4665
4666   let all_functions =
4667     List.filter (
4668       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4669     ) all_functions in
4670
4671   pr "\
4672 #include <config.h>
4673
4674 #include <stdio.h>
4675 #include <stdlib.h>
4676 #include <string.h>
4677
4678 #ifdef HAVE_LIBREADLINE
4679 #include <readline/readline.h>
4680 #endif
4681
4682 #include \"fish.h\"
4683
4684 #ifdef HAVE_LIBREADLINE
4685
4686 static const char *const commands[] = {
4687   BUILTIN_COMMANDS_FOR_COMPLETION,
4688 ";
4689
4690   (* Get the commands, including the aliases.  They don't need to be
4691    * sorted - the generator() function just does a dumb linear search.
4692    *)
4693   let commands =
4694     List.map (
4695       fun (name, _, _, flags, _, _, _) ->
4696         let name2 = replace_char name '_' '-' in
4697         let alias =
4698           try find_map (function FishAlias n -> Some n | _ -> None) flags
4699           with Not_found -> name in
4700
4701         if name <> alias then [name2; alias] else [name2]
4702     ) all_functions in
4703   let commands = List.flatten commands in
4704
4705   List.iter (pr "  \"%s\",\n") commands;
4706
4707   pr "  NULL
4708 };
4709
4710 static char *
4711 generator (const char *text, int state)
4712 {
4713   static int index, len;
4714   const char *name;
4715
4716   if (!state) {
4717     index = 0;
4718     len = strlen (text);
4719   }
4720
4721   while ((name = commands[index]) != NULL) {
4722     index++;
4723     if (strncasecmp (name, text, len) == 0)
4724       return strdup (name);
4725   }
4726
4727   return NULL;
4728 }
4729
4730 #endif /* HAVE_LIBREADLINE */
4731
4732 char **do_completion (const char *text, int start, int end)
4733 {
4734   char **matches = NULL;
4735
4736 #ifdef HAVE_LIBREADLINE
4737   if (start == 0)
4738     matches = rl_completion_matches (text, generator);
4739 #endif
4740
4741   return matches;
4742 }
4743 ";
4744
4745 (* Generate the POD documentation for guestfish. *)
4746 and generate_fish_actions_pod () =
4747   let all_functions_sorted =
4748     List.filter (
4749       fun (_, _, _, flags, _, _, _) ->
4750         not (List.mem NotInFish flags || List.mem NotInDocs flags)
4751     ) all_functions_sorted in
4752
4753   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
4754
4755   List.iter (
4756     fun (name, style, _, flags, _, _, longdesc) ->
4757       let longdesc =
4758         Str.global_substitute rex (
4759           fun s ->
4760             let sub =
4761               try Str.matched_group 1 s
4762               with Not_found ->
4763                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
4764             "C<" ^ replace_char sub '_' '-' ^ ">"
4765         ) longdesc in
4766       let name = replace_char name '_' '-' in
4767       let alias =
4768         try find_map (function FishAlias n -> Some n | _ -> None) flags
4769         with Not_found -> name in
4770
4771       pr "=head2 %s" name;
4772       if name <> alias then
4773         pr " | %s" alias;
4774       pr "\n";
4775       pr "\n";
4776       pr " %s" name;
4777       List.iter (
4778         function
4779         | String n -> pr " %s" n
4780         | OptString n -> pr " %s" n
4781         | StringList n -> pr " '%s ...'" n
4782         | Bool _ -> pr " true|false"
4783         | Int n -> pr " %s" n
4784         | FileIn n | FileOut n -> pr " (%s|-)" n
4785       ) (snd style);
4786       pr "\n";
4787       pr "\n";
4788       pr "%s\n\n" longdesc;
4789
4790       if List.exists (function FileIn _ | FileOut _ -> true
4791                       | _ -> false) (snd style) then
4792         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
4793
4794       if List.mem ProtocolLimitWarning flags then
4795         pr "%s\n\n" protocol_limit_warning;
4796
4797       if List.mem DangerWillRobinson flags then
4798         pr "%s\n\n" danger_will_robinson
4799   ) all_functions_sorted
4800
4801 (* Generate a C function prototype. *)
4802 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
4803     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
4804     ?(prefix = "")
4805     ?handle name style =
4806   if extern then pr "extern ";
4807   if static then pr "static ";
4808   (match fst style with
4809    | RErr -> pr "int "
4810    | RInt _ -> pr "int "
4811    | RInt64 _ -> pr "int64_t "
4812    | RBool _ -> pr "int "
4813    | RConstString _ -> pr "const char *"
4814    | RString _ -> pr "char *"
4815    | RStringList _ | RHashtable _ -> pr "char **"
4816    | RIntBool _ ->
4817        if not in_daemon then pr "struct guestfs_int_bool *"
4818        else pr "guestfs_%s_ret *" name
4819    | RPVList _ ->
4820        if not in_daemon then pr "struct guestfs_lvm_pv_list *"
4821        else pr "guestfs_lvm_int_pv_list *"
4822    | RVGList _ ->
4823        if not in_daemon then pr "struct guestfs_lvm_vg_list *"
4824        else pr "guestfs_lvm_int_vg_list *"
4825    | RLVList _ ->
4826        if not in_daemon then pr "struct guestfs_lvm_lv_list *"
4827        else pr "guestfs_lvm_int_lv_list *"
4828    | RStat _ ->
4829        if not in_daemon then pr "struct guestfs_stat *"
4830        else pr "guestfs_int_stat *"
4831    | RStatVFS _ ->
4832        if not in_daemon then pr "struct guestfs_statvfs *"
4833        else pr "guestfs_int_statvfs *"
4834   );
4835   pr "%s%s (" prefix name;
4836   if handle = None && List.length (snd style) = 0 then
4837     pr "void"
4838   else (
4839     let comma = ref false in
4840     (match handle with
4841      | None -> ()
4842      | Some handle -> pr "guestfs_h *%s" handle; comma := true
4843     );
4844     let next () =
4845       if !comma then (
4846         if single_line then pr ", " else pr ",\n\t\t"
4847       );
4848       comma := true
4849     in
4850     List.iter (
4851       function
4852       | String n
4853       | OptString n -> next (); pr "const char *%s" n
4854       | StringList n -> next (); pr "char * const* const %s" n
4855       | Bool n -> next (); pr "int %s" n
4856       | Int n -> next (); pr "int %s" n
4857       | FileIn n
4858       | FileOut n ->
4859           if not in_daemon then (next (); pr "const char *%s" n)
4860     ) (snd style);
4861   );
4862   pr ")";
4863   if semicolon then pr ";";
4864   if newline then pr "\n"
4865
4866 (* Generate C call arguments, eg "(handle, foo, bar)" *)
4867 and generate_call_args ?handle args =
4868   pr "(";
4869   let comma = ref false in
4870   (match handle with
4871    | None -> ()
4872    | Some handle -> pr "%s" handle; comma := true
4873   );
4874   List.iter (
4875     fun arg ->
4876       if !comma then pr ", ";
4877       comma := true;
4878       pr "%s" (name_of_argt arg)
4879   ) args;
4880   pr ")"
4881
4882 (* Generate the OCaml bindings interface. *)
4883 and generate_ocaml_mli () =
4884   generate_header OCamlStyle LGPLv2;
4885
4886   pr "\
4887 (** For API documentation you should refer to the C API
4888     in the guestfs(3) manual page.  The OCaml API uses almost
4889     exactly the same calls. *)
4890
4891 type t
4892 (** A [guestfs_h] handle. *)
4893
4894 exception Error of string
4895 (** This exception is raised when there is an error. *)
4896
4897 val create : unit -> t
4898
4899 val close : t -> unit
4900 (** Handles are closed by the garbage collector when they become
4901     unreferenced, but callers can also call this in order to
4902     provide predictable cleanup. *)
4903
4904 ";
4905   generate_ocaml_lvm_structure_decls ();
4906
4907   generate_ocaml_stat_structure_decls ();
4908
4909   (* The actions. *)
4910   List.iter (
4911     fun (name, style, _, _, _, shortdesc, _) ->
4912       generate_ocaml_prototype name style;
4913       pr "(** %s *)\n" shortdesc;
4914       pr "\n"
4915   ) all_functions
4916
4917 (* Generate the OCaml bindings implementation. *)
4918 and generate_ocaml_ml () =
4919   generate_header OCamlStyle LGPLv2;
4920
4921   pr "\
4922 type t
4923 exception Error of string
4924 external create : unit -> t = \"ocaml_guestfs_create\"
4925 external close : t -> unit = \"ocaml_guestfs_close\"
4926
4927 let () =
4928   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
4929
4930 ";
4931
4932   generate_ocaml_lvm_structure_decls ();
4933
4934   generate_ocaml_stat_structure_decls ();
4935
4936   (* The actions. *)
4937   List.iter (
4938     fun (name, style, _, _, _, shortdesc, _) ->
4939       generate_ocaml_prototype ~is_external:true name style;
4940   ) all_functions
4941
4942 (* Generate the OCaml bindings C implementation. *)
4943 and generate_ocaml_c () =
4944   generate_header CStyle LGPLv2;
4945
4946   pr "\
4947 #include <stdio.h>
4948 #include <stdlib.h>
4949 #include <string.h>
4950
4951 #include <caml/config.h>
4952 #include <caml/alloc.h>
4953 #include <caml/callback.h>
4954 #include <caml/fail.h>
4955 #include <caml/memory.h>
4956 #include <caml/mlvalues.h>
4957 #include <caml/signals.h>
4958
4959 #include <guestfs.h>
4960
4961 #include \"guestfs_c.h\"
4962
4963 /* Copy a hashtable of string pairs into an assoc-list.  We return
4964  * the list in reverse order, but hashtables aren't supposed to be
4965  * ordered anyway.
4966  */
4967 static CAMLprim value
4968 copy_table (char * const * argv)
4969 {
4970   CAMLparam0 ();
4971   CAMLlocal5 (rv, pairv, kv, vv, cons);
4972   int i;
4973
4974   rv = Val_int (0);
4975   for (i = 0; argv[i] != NULL; i += 2) {
4976     kv = caml_copy_string (argv[i]);
4977     vv = caml_copy_string (argv[i+1]);
4978     pairv = caml_alloc (2, 0);
4979     Store_field (pairv, 0, kv);
4980     Store_field (pairv, 1, vv);
4981     cons = caml_alloc (2, 0);
4982     Store_field (cons, 1, rv);
4983     rv = cons;
4984     Store_field (cons, 0, pairv);
4985   }
4986
4987   CAMLreturn (rv);
4988 }
4989
4990 ";
4991
4992   (* LVM struct copy functions. *)
4993   List.iter (
4994     fun (typ, cols) ->
4995       let has_optpercent_col =
4996         List.exists (function (_, `OptPercent) -> true | _ -> false) cols in
4997
4998       pr "static CAMLprim value\n";
4999       pr "copy_lvm_%s (const struct guestfs_lvm_%s *%s)\n" typ typ typ;
5000       pr "{\n";
5001       pr "  CAMLparam0 ();\n";
5002       if has_optpercent_col then
5003         pr "  CAMLlocal3 (rv, v, v2);\n"
5004       else
5005         pr "  CAMLlocal2 (rv, v);\n";
5006       pr "\n";
5007       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
5008       iteri (
5009         fun i col ->
5010           (match col with
5011            | name, `String ->
5012                pr "  v = caml_copy_string (%s->%s);\n" typ name
5013            | name, `UUID ->
5014                pr "  v = caml_alloc_string (32);\n";
5015                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
5016            | name, `Bytes
5017            | name, `Int ->
5018                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
5019            | name, `OptPercent ->
5020                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
5021                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
5022                pr "    v = caml_alloc (1, 0);\n";
5023                pr "    Store_field (v, 0, v2);\n";
5024                pr "  } else /* None */\n";
5025                pr "    v = Val_int (0);\n";
5026           );
5027           pr "  Store_field (rv, %d, v);\n" i
5028       ) cols;
5029       pr "  CAMLreturn (rv);\n";
5030       pr "}\n";
5031       pr "\n";
5032
5033       pr "static CAMLprim value\n";
5034       pr "copy_lvm_%s_list (const struct guestfs_lvm_%s_list *%ss)\n"
5035         typ typ typ;
5036       pr "{\n";
5037       pr "  CAMLparam0 ();\n";
5038       pr "  CAMLlocal2 (rv, v);\n";
5039       pr "  int i;\n";
5040       pr "\n";
5041       pr "  if (%ss->len == 0)\n" typ;
5042       pr "    CAMLreturn (Atom (0));\n";
5043       pr "  else {\n";
5044       pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
5045       pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
5046       pr "      v = copy_lvm_%s (&%ss->val[i]);\n" typ typ;
5047       pr "      caml_modify (&Field (rv, i), v);\n";
5048       pr "    }\n";
5049       pr "    CAMLreturn (rv);\n";
5050       pr "  }\n";
5051       pr "}\n";
5052       pr "\n";
5053   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5054
5055   (* Stat copy functions. *)
5056   List.iter (
5057     fun (typ, cols) ->
5058       pr "static CAMLprim value\n";
5059       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5060       pr "{\n";
5061       pr "  CAMLparam0 ();\n";
5062       pr "  CAMLlocal2 (rv, v);\n";
5063       pr "\n";
5064       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
5065       iteri (
5066         fun i col ->
5067           (match col with
5068            | name, `Int ->
5069                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
5070           );
5071           pr "  Store_field (rv, %d, v);\n" i
5072       ) cols;
5073       pr "  CAMLreturn (rv);\n";
5074       pr "}\n";
5075       pr "\n";
5076   ) ["stat", stat_cols; "statvfs", statvfs_cols];
5077
5078   (* The wrappers. *)
5079   List.iter (
5080     fun (name, style, _, _, _, _, _) ->
5081       let params =
5082         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
5083
5084       pr "CAMLprim value\n";
5085       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
5086       List.iter (pr ", value %s") (List.tl params);
5087       pr ")\n";
5088       pr "{\n";
5089
5090       (match params with
5091        | [p1; p2; p3; p4; p5] ->
5092            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
5093        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
5094            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
5095            pr "  CAMLxparam%d (%s);\n"
5096              (List.length rest) (String.concat ", " rest)
5097        | ps ->
5098            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
5099       );
5100       pr "  CAMLlocal1 (rv);\n";
5101       pr "\n";
5102
5103       pr "  guestfs_h *g = Guestfs_val (gv);\n";
5104       pr "  if (g == NULL)\n";
5105       pr "    caml_failwith (\"%s: used handle after closing it\");\n" name;
5106       pr "\n";
5107
5108       List.iter (
5109         function
5110         | String n
5111         | FileIn n
5112         | FileOut n ->
5113             pr "  const char *%s = String_val (%sv);\n" n n
5114         | OptString n ->
5115             pr "  const char *%s =\n" n;
5116             pr "    %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
5117               n n
5118         | StringList n ->
5119             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
5120         | Bool n ->
5121             pr "  int %s = Bool_val (%sv);\n" n n
5122         | Int n ->
5123             pr "  int %s = Int_val (%sv);\n" n n
5124       ) (snd style);
5125       let error_code =
5126         match fst style with
5127         | RErr -> pr "  int r;\n"; "-1"
5128         | RInt _ -> pr "  int r;\n"; "-1"
5129         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
5130         | RBool _ -> pr "  int r;\n"; "-1"
5131         | RConstString _ -> pr "  const char *r;\n"; "NULL"
5132         | RString _ -> pr "  char *r;\n"; "NULL"
5133         | RStringList _ ->
5134             pr "  int i;\n";
5135             pr "  char **r;\n";
5136             "NULL"
5137         | RIntBool _ ->
5138             pr "  struct guestfs_int_bool *r;\n"; "NULL"
5139         | RPVList _ ->
5140             pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
5141         | RVGList _ ->
5142             pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
5143         | RLVList _ ->
5144             pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
5145         | RStat _ ->
5146             pr "  struct guestfs_stat *r;\n"; "NULL"
5147         | RStatVFS _ ->
5148             pr "  struct guestfs_statvfs *r;\n"; "NULL"
5149         | RHashtable _ ->
5150             pr "  int i;\n";
5151             pr "  char **r;\n";
5152             "NULL" in
5153       pr "\n";
5154
5155       pr "  caml_enter_blocking_section ();\n";
5156       pr "  r = guestfs_%s " name;
5157       generate_call_args ~handle:"g" (snd style);
5158       pr ";\n";
5159       pr "  caml_leave_blocking_section ();\n";
5160
5161       List.iter (
5162         function
5163         | StringList n ->
5164             pr "  ocaml_guestfs_free_strings (%s);\n" n;
5165         | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
5166       ) (snd style);
5167
5168       pr "  if (r == %s)\n" error_code;
5169       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
5170       pr "\n";
5171
5172       (match fst style with
5173        | RErr -> pr "  rv = Val_unit;\n"
5174        | RInt _ -> pr "  rv = Val_int (r);\n"
5175        | RInt64 _ ->
5176            pr "  rv = caml_copy_int64 (r);\n"
5177        | RBool _ -> pr "  rv = Val_bool (r);\n"
5178        | RConstString _ -> pr "  rv = caml_copy_string (r);\n"
5179        | RString _ ->
5180            pr "  rv = caml_copy_string (r);\n";
5181            pr "  free (r);\n"
5182        | RStringList _ ->
5183            pr "  rv = caml_copy_string_array ((const char **) r);\n";
5184            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5185            pr "  free (r);\n"
5186        | RIntBool _ ->
5187            pr "  rv = caml_alloc (2, 0);\n";
5188            pr "  Store_field (rv, 0, Val_int (r->i));\n";
5189            pr "  Store_field (rv, 1, Val_bool (r->b));\n";
5190            pr "  guestfs_free_int_bool (r);\n";
5191        | RPVList _ ->
5192            pr "  rv = copy_lvm_pv_list (r);\n";
5193            pr "  guestfs_free_lvm_pv_list (r);\n";
5194        | RVGList _ ->
5195            pr "  rv = copy_lvm_vg_list (r);\n";
5196            pr "  guestfs_free_lvm_vg_list (r);\n";
5197        | RLVList _ ->
5198            pr "  rv = copy_lvm_lv_list (r);\n";
5199            pr "  guestfs_free_lvm_lv_list (r);\n";
5200        | RStat _ ->
5201            pr "  rv = copy_stat (r);\n";
5202            pr "  free (r);\n";
5203        | RStatVFS _ ->
5204            pr "  rv = copy_statvfs (r);\n";
5205            pr "  free (r);\n";
5206        | RHashtable _ ->
5207            pr "  rv = copy_table (r);\n";
5208            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5209            pr "  free (r);\n";
5210       );
5211
5212       pr "  CAMLreturn (rv);\n";
5213       pr "}\n";
5214       pr "\n";
5215
5216       if List.length params > 5 then (
5217         pr "CAMLprim value\n";
5218         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
5219         pr "{\n";
5220         pr "  return ocaml_guestfs_%s (argv[0]" name;
5221         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
5222         pr ");\n";
5223         pr "}\n";
5224         pr "\n"
5225       )
5226   ) all_functions
5227
5228 and generate_ocaml_lvm_structure_decls () =
5229   List.iter (
5230     fun (typ, cols) ->
5231       pr "type lvm_%s = {\n" typ;
5232       List.iter (
5233         function
5234         | name, `String -> pr "  %s : string;\n" name
5235         | name, `UUID -> pr "  %s : string;\n" name
5236         | name, `Bytes -> pr "  %s : int64;\n" name
5237         | name, `Int -> pr "  %s : int64;\n" name
5238         | name, `OptPercent -> pr "  %s : float option;\n" name
5239       ) cols;
5240       pr "}\n";
5241       pr "\n"
5242   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
5243
5244 and generate_ocaml_stat_structure_decls () =
5245   List.iter (
5246     fun (typ, cols) ->
5247       pr "type %s = {\n" typ;
5248       List.iter (
5249         function
5250         | name, `Int -> pr "  %s : int64;\n" name
5251       ) cols;
5252       pr "}\n";
5253       pr "\n"
5254   ) ["stat", stat_cols; "statvfs", statvfs_cols]
5255
5256 and generate_ocaml_prototype ?(is_external = false) name style =
5257   if is_external then pr "external " else pr "val ";
5258   pr "%s : t -> " name;
5259   List.iter (
5260     function
5261     | String _ | FileIn _ | FileOut _ -> pr "string -> "
5262     | OptString _ -> pr "string option -> "
5263     | StringList _ -> pr "string array -> "
5264     | Bool _ -> pr "bool -> "
5265     | Int _ -> pr "int -> "
5266   ) (snd style);
5267   (match fst style with
5268    | RErr -> pr "unit" (* all errors are turned into exceptions *)
5269    | RInt _ -> pr "int"
5270    | RInt64 _ -> pr "int64"
5271    | RBool _ -> pr "bool"
5272    | RConstString _ -> pr "string"
5273    | RString _ -> pr "string"
5274    | RStringList _ -> pr "string array"
5275    | RIntBool _ -> pr "int * bool"
5276    | RPVList _ -> pr "lvm_pv array"
5277    | RVGList _ -> pr "lvm_vg array"
5278    | RLVList _ -> pr "lvm_lv array"
5279    | RStat _ -> pr "stat"
5280    | RStatVFS _ -> pr "statvfs"
5281    | RHashtable _ -> pr "(string * string) list"
5282   );
5283   if is_external then (
5284     pr " = ";
5285     if List.length (snd style) + 1 > 5 then
5286       pr "\"ocaml_guestfs_%s_byte\" " name;
5287     pr "\"ocaml_guestfs_%s\"" name
5288   );
5289   pr "\n"
5290
5291 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
5292 and generate_perl_xs () =
5293   generate_header CStyle LGPLv2;
5294
5295   pr "\
5296 #include \"EXTERN.h\"
5297 #include \"perl.h\"
5298 #include \"XSUB.h\"
5299
5300 #include <guestfs.h>
5301
5302 #ifndef PRId64
5303 #define PRId64 \"lld\"
5304 #endif
5305
5306 static SV *
5307 my_newSVll(long long val) {
5308 #ifdef USE_64_BIT_ALL
5309   return newSViv(val);
5310 #else
5311   char buf[100];
5312   int len;
5313   len = snprintf(buf, 100, \"%%\" PRId64, val);
5314   return newSVpv(buf, len);
5315 #endif
5316 }
5317
5318 #ifndef PRIu64
5319 #define PRIu64 \"llu\"
5320 #endif
5321
5322 static SV *
5323 my_newSVull(unsigned long long val) {
5324 #ifdef USE_64_BIT_ALL
5325   return newSVuv(val);
5326 #else
5327   char buf[100];
5328   int len;
5329   len = snprintf(buf, 100, \"%%\" PRIu64, val);
5330   return newSVpv(buf, len);
5331 #endif
5332 }
5333
5334 /* http://www.perlmonks.org/?node_id=680842 */
5335 static char **
5336 XS_unpack_charPtrPtr (SV *arg) {
5337   char **ret;
5338   AV *av;
5339   I32 i;
5340
5341   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
5342     croak (\"array reference expected\");
5343
5344   av = (AV *)SvRV (arg);
5345   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
5346   if (!ret)
5347     croak (\"malloc failed\");
5348
5349   for (i = 0; i <= av_len (av); i++) {
5350     SV **elem = av_fetch (av, i, 0);
5351
5352     if (!elem || !*elem)
5353       croak (\"missing element in list\");
5354
5355     ret[i] = SvPV_nolen (*elem);
5356   }
5357
5358   ret[i] = NULL;
5359
5360   return ret;
5361 }
5362
5363 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
5364
5365 PROTOTYPES: ENABLE
5366
5367 guestfs_h *
5368 _create ()
5369    CODE:
5370       RETVAL = guestfs_create ();
5371       if (!RETVAL)
5372         croak (\"could not create guestfs handle\");
5373       guestfs_set_error_handler (RETVAL, NULL, NULL);
5374  OUTPUT:
5375       RETVAL
5376
5377 void
5378 DESTROY (g)
5379       guestfs_h *g;
5380  PPCODE:
5381       guestfs_close (g);
5382
5383 ";
5384
5385   List.iter (
5386     fun (name, style, _, _, _, _, _) ->
5387       (match fst style with
5388        | RErr -> pr "void\n"
5389        | RInt _ -> pr "SV *\n"
5390        | RInt64 _ -> pr "SV *\n"
5391        | RBool _ -> pr "SV *\n"
5392        | RConstString _ -> pr "SV *\n"
5393        | RString _ -> pr "SV *\n"
5394        | RStringList _
5395        | RIntBool _
5396        | RPVList _ | RVGList _ | RLVList _
5397        | RStat _ | RStatVFS _
5398        | RHashtable _ ->
5399            pr "void\n" (* all lists returned implictly on the stack *)
5400       );
5401       (* Call and arguments. *)
5402       pr "%s " name;
5403       generate_call_args ~handle:"g" (snd style);
5404       pr "\n";
5405       pr "      guestfs_h *g;\n";
5406       iteri (
5407         fun i ->
5408           function
5409           | String n | FileIn n | FileOut n -> pr "      char *%s;\n" n
5410           | OptString n ->
5411               (* http://www.perlmonks.org/?node_id=554277
5412                * Note that the implicit handle argument means we have
5413                * to add 1 to the ST(x) operator.
5414                *)
5415               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
5416           | StringList n -> pr "      char **%s;\n" n
5417           | Bool n -> pr "      int %s;\n" n
5418           | Int n -> pr "      int %s;\n" n
5419       ) (snd style);
5420
5421       let do_cleanups () =
5422         List.iter (
5423           function
5424           | String _ | OptString _ | Bool _ | Int _
5425           | FileIn _ | FileOut _ -> ()
5426           | StringList n -> pr "      free (%s);\n" n
5427         ) (snd style)
5428       in
5429
5430       (* Code. *)
5431       (match fst style with
5432        | RErr ->
5433            pr "PREINIT:\n";
5434            pr "      int r;\n";
5435            pr " PPCODE:\n";
5436            pr "      r = guestfs_%s " name;
5437            generate_call_args ~handle:"g" (snd style);
5438            pr ";\n";
5439            do_cleanups ();
5440            pr "      if (r == -1)\n";
5441            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5442        | RInt n
5443        | RBool n ->
5444            pr "PREINIT:\n";
5445            pr "      int %s;\n" n;
5446            pr "   CODE:\n";
5447            pr "      %s = guestfs_%s " n name;
5448            generate_call_args ~handle:"g" (snd style);
5449            pr ";\n";
5450            do_cleanups ();
5451            pr "      if (%s == -1)\n" n;
5452            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5453            pr "      RETVAL = newSViv (%s);\n" n;
5454            pr " OUTPUT:\n";
5455            pr "      RETVAL\n"
5456        | RInt64 n ->
5457            pr "PREINIT:\n";
5458            pr "      int64_t %s;\n" n;
5459            pr "   CODE:\n";
5460            pr "      %s = guestfs_%s " n name;
5461            generate_call_args ~handle:"g" (snd style);
5462            pr ";\n";
5463            do_cleanups ();
5464            pr "      if (%s == -1)\n" n;
5465            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5466            pr "      RETVAL = my_newSVll (%s);\n" n;
5467            pr " OUTPUT:\n";
5468            pr "      RETVAL\n"
5469        | RConstString n ->
5470            pr "PREINIT:\n";
5471            pr "      const char *%s;\n" n;
5472            pr "   CODE:\n";
5473            pr "      %s = guestfs_%s " n name;
5474            generate_call_args ~handle:"g" (snd style);
5475            pr ";\n";
5476            do_cleanups ();
5477            pr "      if (%s == NULL)\n" n;
5478            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5479            pr "      RETVAL = newSVpv (%s, 0);\n" n;
5480            pr " OUTPUT:\n";
5481            pr "      RETVAL\n"
5482        | RString n ->
5483            pr "PREINIT:\n";
5484            pr "      char *%s;\n" n;
5485            pr "   CODE:\n";
5486            pr "      %s = guestfs_%s " n name;
5487            generate_call_args ~handle:"g" (snd style);
5488            pr ";\n";
5489            do_cleanups ();
5490            pr "      if (%s == NULL)\n" n;
5491            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5492            pr "      RETVAL = newSVpv (%s, 0);\n" n;
5493            pr "      free (%s);\n" n;
5494            pr " OUTPUT:\n";
5495            pr "      RETVAL\n"
5496        | RStringList n | RHashtable n ->
5497            pr "PREINIT:\n";
5498            pr "      char **%s;\n" n;
5499            pr "      int i, n;\n";
5500            pr " PPCODE:\n";
5501            pr "      %s = guestfs_%s " n name;
5502            generate_call_args ~handle:"g" (snd style);
5503            pr ";\n";
5504            do_cleanups ();
5505            pr "      if (%s == NULL)\n" n;
5506            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5507            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
5508            pr "      EXTEND (SP, n);\n";
5509            pr "      for (i = 0; i < n; ++i) {\n";
5510            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
5511            pr "        free (%s[i]);\n" n;
5512            pr "      }\n";
5513            pr "      free (%s);\n" n;
5514        | RIntBool _ ->
5515            pr "PREINIT:\n";
5516            pr "      struct guestfs_int_bool *r;\n";
5517            pr " PPCODE:\n";
5518            pr "      r = guestfs_%s " name;
5519            generate_call_args ~handle:"g" (snd style);
5520            pr ";\n";
5521            do_cleanups ();
5522            pr "      if (r == NULL)\n";
5523            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5524            pr "      EXTEND (SP, 2);\n";
5525            pr "      PUSHs (sv_2mortal (newSViv (r->i)));\n";
5526            pr "      PUSHs (sv_2mortal (newSViv (r->b)));\n";
5527            pr "      guestfs_free_int_bool (r);\n";
5528        | RPVList n ->
5529            generate_perl_lvm_code "pv" pv_cols name style n do_cleanups
5530        | RVGList n ->
5531            generate_perl_lvm_code "vg" vg_cols name style n do_cleanups
5532        | RLVList n ->
5533            generate_perl_lvm_code "lv" lv_cols name style n do_cleanups
5534        | RStat n ->
5535            generate_perl_stat_code "stat" stat_cols name style n do_cleanups
5536        | RStatVFS n ->
5537            generate_perl_stat_code
5538              "statvfs" statvfs_cols name style n do_cleanups
5539       );
5540
5541       pr "\n"
5542   ) all_functions
5543
5544 and generate_perl_lvm_code typ cols name style n do_cleanups =
5545   pr "PREINIT:\n";
5546   pr "      struct guestfs_lvm_%s_list *%s;\n" typ n;
5547   pr "      int i;\n";
5548   pr "      HV *hv;\n";
5549   pr " PPCODE:\n";
5550   pr "      %s = guestfs_%s " n name;
5551   generate_call_args ~handle:"g" (snd style);
5552   pr ";\n";
5553   do_cleanups ();
5554   pr "      if (%s == NULL)\n" n;
5555   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5556   pr "      EXTEND (SP, %s->len);\n" n;
5557   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
5558   pr "        hv = newHV ();\n";
5559   List.iter (
5560     function
5561     | name, `String ->
5562         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
5563           name (String.length name) n name
5564     | name, `UUID ->
5565         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
5566           name (String.length name) n name
5567     | name, `Bytes ->
5568         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
5569           name (String.length name) n name
5570     | name, `Int ->
5571         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
5572           name (String.length name) n name
5573     | name, `OptPercent ->
5574         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
5575           name (String.length name) n name
5576   ) cols;
5577   pr "        PUSHs (sv_2mortal ((SV *) hv));\n";
5578   pr "      }\n";
5579   pr "      guestfs_free_lvm_%s_list (%s);\n" typ n
5580
5581 and generate_perl_stat_code typ cols name style n do_cleanups =
5582   pr "PREINIT:\n";
5583   pr "      struct guestfs_%s *%s;\n" typ n;
5584   pr " PPCODE:\n";
5585   pr "      %s = guestfs_%s " n name;
5586   generate_call_args ~handle:"g" (snd style);
5587   pr ";\n";
5588   do_cleanups ();
5589   pr "      if (%s == NULL)\n" n;
5590   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5591   pr "      EXTEND (SP, %d);\n" (List.length cols);
5592   List.iter (
5593     function
5594     | name, `Int ->
5595         pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n" n name
5596   ) cols;
5597   pr "      free (%s);\n" n
5598
5599 (* Generate Sys/Guestfs.pm. *)
5600 and generate_perl_pm () =
5601   generate_header HashStyle LGPLv2;
5602
5603   pr "\
5604 =pod
5605
5606 =head1 NAME
5607
5608 Sys::Guestfs - Perl bindings for libguestfs
5609
5610 =head1 SYNOPSIS
5611
5612  use Sys::Guestfs;
5613  
5614  my $h = Sys::Guestfs->new ();
5615  $h->add_drive ('guest.img');
5616  $h->launch ();
5617  $h->wait_ready ();
5618  $h->mount ('/dev/sda1', '/');
5619  $h->touch ('/hello');
5620  $h->sync ();
5621
5622 =head1 DESCRIPTION
5623
5624 The C<Sys::Guestfs> module provides a Perl XS binding to the
5625 libguestfs API for examining and modifying virtual machine
5626 disk images.
5627
5628 Amongst the things this is good for: making batch configuration
5629 changes to guests, getting disk used/free statistics (see also:
5630 virt-df), migrating between virtualization systems (see also:
5631 virt-p2v), performing partial backups, performing partial guest
5632 clones, cloning guests and changing registry/UUID/hostname info, and
5633 much else besides.
5634
5635 Libguestfs uses Linux kernel and qemu code, and can access any type of
5636 guest filesystem that Linux and qemu can, including but not limited
5637 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
5638 schemes, qcow, qcow2, vmdk.
5639
5640 Libguestfs provides ways to enumerate guest storage (eg. partitions,
5641 LVs, what filesystem is in each LV, etc.).  It can also run commands
5642 in the context of the guest.  Also you can access filesystems over FTP.
5643
5644 =head1 ERRORS
5645
5646 All errors turn into calls to C<croak> (see L<Carp(3)>).
5647
5648 =head1 METHODS
5649
5650 =over 4
5651
5652 =cut
5653
5654 package Sys::Guestfs;
5655
5656 use strict;
5657 use warnings;
5658
5659 require XSLoader;
5660 XSLoader::load ('Sys::Guestfs');
5661
5662 =item $h = Sys::Guestfs->new ();
5663
5664 Create a new guestfs handle.
5665
5666 =cut
5667
5668 sub new {
5669   my $proto = shift;
5670   my $class = ref ($proto) || $proto;
5671
5672   my $self = Sys::Guestfs::_create ();
5673   bless $self, $class;
5674   return $self;
5675 }
5676
5677 ";
5678
5679   (* Actions.  We only need to print documentation for these as
5680    * they are pulled in from the XS code automatically.
5681    *)
5682   List.iter (
5683     fun (name, style, _, flags, _, _, longdesc) ->
5684       if not (List.mem NotInDocs flags) then (
5685         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
5686         pr "=item ";
5687         generate_perl_prototype name style;
5688         pr "\n\n";
5689         pr "%s\n\n" longdesc;
5690         if List.mem ProtocolLimitWarning flags then
5691           pr "%s\n\n" protocol_limit_warning;
5692         if List.mem DangerWillRobinson flags then
5693           pr "%s\n\n" danger_will_robinson
5694       )
5695   ) all_functions_sorted;
5696
5697   (* End of file. *)
5698   pr "\
5699 =cut
5700
5701 1;
5702
5703 =back
5704
5705 =head1 COPYRIGHT
5706
5707 Copyright (C) 2009 Red Hat Inc.
5708
5709 =head1 LICENSE
5710
5711 Please see the file COPYING.LIB for the full license.
5712
5713 =head1 SEE ALSO
5714
5715 L<guestfs(3)>, L<guestfish(1)>.
5716
5717 =cut
5718 "
5719
5720 and generate_perl_prototype name style =
5721   (match fst style with
5722    | RErr -> ()
5723    | RBool n
5724    | RInt n
5725    | RInt64 n
5726    | RConstString n
5727    | RString n -> pr "$%s = " n
5728    | RIntBool (n, m) -> pr "($%s, $%s) = " n m
5729    | RStringList n
5730    | RPVList n
5731    | RVGList n
5732    | RLVList n -> pr "@%s = " n
5733    | RStat n
5734    | RStatVFS n
5735    | RHashtable n -> pr "%%%s = " n
5736   );
5737   pr "$h->%s (" name;
5738   let comma = ref false in
5739   List.iter (
5740     fun arg ->
5741       if !comma then pr ", ";
5742       comma := true;
5743       match arg with
5744       | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
5745           pr "$%s" n
5746       | StringList n ->
5747           pr "\\@%s" n
5748   ) (snd style);
5749   pr ");"
5750
5751 (* Generate Python C module. *)
5752 and generate_python_c () =
5753   generate_header CStyle LGPLv2;
5754
5755   pr "\
5756 #include <stdio.h>
5757 #include <stdlib.h>
5758 #include <assert.h>
5759
5760 #include <Python.h>
5761
5762 #include \"guestfs.h\"
5763
5764 typedef struct {
5765   PyObject_HEAD
5766   guestfs_h *g;
5767 } Pyguestfs_Object;
5768
5769 static guestfs_h *
5770 get_handle (PyObject *obj)
5771 {
5772   assert (obj);
5773   assert (obj != Py_None);
5774   return ((Pyguestfs_Object *) obj)->g;
5775 }
5776
5777 static PyObject *
5778 put_handle (guestfs_h *g)
5779 {
5780   assert (g);
5781   return
5782     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
5783 }
5784
5785 /* This list should be freed (but not the strings) after use. */
5786 static const char **
5787 get_string_list (PyObject *obj)
5788 {
5789   int i, len;
5790   const char **r;
5791
5792   assert (obj);
5793
5794   if (!PyList_Check (obj)) {
5795     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
5796     return NULL;
5797   }
5798
5799   len = PyList_Size (obj);
5800   r = malloc (sizeof (char *) * (len+1));
5801   if (r == NULL) {
5802     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
5803     return NULL;
5804   }
5805
5806   for (i = 0; i < len; ++i)
5807     r[i] = PyString_AsString (PyList_GetItem (obj, i));
5808   r[len] = NULL;
5809
5810   return r;
5811 }
5812
5813 static PyObject *
5814 put_string_list (char * const * const argv)
5815 {
5816   PyObject *list;
5817   int argc, i;
5818
5819   for (argc = 0; argv[argc] != NULL; ++argc)
5820     ;
5821
5822   list = PyList_New (argc);
5823   for (i = 0; i < argc; ++i)
5824     PyList_SetItem (list, i, PyString_FromString (argv[i]));
5825
5826   return list;
5827 }
5828
5829 static PyObject *
5830 put_table (char * const * const argv)
5831 {
5832   PyObject *list, *item;
5833   int argc, i;
5834
5835   for (argc = 0; argv[argc] != NULL; ++argc)
5836     ;
5837
5838   list = PyList_New (argc >> 1);
5839   for (i = 0; i < argc; i += 2) {
5840     item = PyTuple_New (2);
5841     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
5842     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
5843     PyList_SetItem (list, i >> 1, item);
5844   }
5845
5846   return list;
5847 }
5848
5849 static void
5850 free_strings (char **argv)
5851 {
5852   int argc;
5853
5854   for (argc = 0; argv[argc] != NULL; ++argc)
5855     free (argv[argc]);
5856   free (argv);
5857 }
5858
5859 static PyObject *
5860 py_guestfs_create (PyObject *self, PyObject *args)
5861 {
5862   guestfs_h *g;
5863
5864   g = guestfs_create ();
5865   if (g == NULL) {
5866     PyErr_SetString (PyExc_RuntimeError,
5867                      \"guestfs.create: failed to allocate handle\");
5868     return NULL;
5869   }
5870   guestfs_set_error_handler (g, NULL, NULL);
5871   return put_handle (g);
5872 }
5873
5874 static PyObject *
5875 py_guestfs_close (PyObject *self, PyObject *args)
5876 {
5877   PyObject *py_g;
5878   guestfs_h *g;
5879
5880   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
5881     return NULL;
5882   g = get_handle (py_g);
5883
5884   guestfs_close (g);
5885
5886   Py_INCREF (Py_None);
5887   return Py_None;
5888 }
5889
5890 ";
5891
5892   (* LVM structures, turned into Python dictionaries. *)
5893   List.iter (
5894     fun (typ, cols) ->
5895       pr "static PyObject *\n";
5896       pr "put_lvm_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
5897       pr "{\n";
5898       pr "  PyObject *dict;\n";
5899       pr "\n";
5900       pr "  dict = PyDict_New ();\n";
5901       List.iter (
5902         function
5903         | name, `String ->
5904             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5905             pr "                        PyString_FromString (%s->%s));\n"
5906               typ name
5907         | name, `UUID ->
5908             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5909             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
5910               typ name
5911         | name, `Bytes ->
5912             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5913             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
5914               typ name
5915         | name, `Int ->
5916             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5917             pr "                        PyLong_FromLongLong (%s->%s));\n"
5918               typ name
5919         | name, `OptPercent ->
5920             pr "  if (%s->%s >= 0)\n" typ name;
5921             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
5922             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
5923               typ name;
5924             pr "  else {\n";
5925             pr "    Py_INCREF (Py_None);\n";
5926             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);" name;
5927             pr "  }\n"
5928       ) cols;
5929       pr "  return dict;\n";
5930       pr "};\n";
5931       pr "\n";
5932
5933       pr "static PyObject *\n";
5934       pr "put_lvm_%s_list (struct guestfs_lvm_%s_list *%ss)\n" typ typ typ;
5935       pr "{\n";
5936       pr "  PyObject *list;\n";
5937       pr "  int i;\n";
5938       pr "\n";
5939       pr "  list = PyList_New (%ss->len);\n" typ;
5940       pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
5941       pr "    PyList_SetItem (list, i, put_lvm_%s (&%ss->val[i]));\n" typ typ;
5942       pr "  return list;\n";
5943       pr "};\n";
5944       pr "\n"
5945   ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5946
5947   (* Stat structures, turned into Python dictionaries. *)
5948   List.iter (
5949     fun (typ, cols) ->
5950       pr "static PyObject *\n";
5951       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
5952       pr "{\n";
5953       pr "  PyObject *dict;\n";
5954       pr "\n";
5955       pr "  dict = PyDict_New ();\n";
5956       List.iter (
5957         function
5958         | name, `Int ->
5959             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
5960             pr "                        PyLong_FromLongLong (%s->%s));\n"
5961               typ name
5962       ) cols;
5963       pr "  return dict;\n";
5964       pr "};\n";
5965       pr "\n";
5966   ) ["stat", stat_cols; "statvfs", statvfs_cols];
5967
5968   (* Python wrapper functions. *)
5969   List.iter (
5970     fun (name, style, _, _, _, _, _) ->
5971       pr "static PyObject *\n";
5972       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
5973       pr "{\n";
5974
5975       pr "  PyObject *py_g;\n";
5976       pr "  guestfs_h *g;\n";
5977       pr "  PyObject *py_r;\n";
5978
5979       let error_code =
5980         match fst style with
5981         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
5982         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
5983         | RConstString _ -> pr "  const char *r;\n"; "NULL"
5984         | RString _ -> pr "  char *r;\n"; "NULL"
5985         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
5986         | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"; "NULL"
5987         | RPVList n -> pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
5988         | RVGList n -> pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
5989         | RLVList n -> pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
5990         | RStat n -> pr "  struct guestfs_stat *r;\n"; "NULL"
5991         | RStatVFS n -> pr "  struct guestfs_statvfs *r;\n"; "NULL" in
5992
5993       List.iter (
5994         function
5995         | String n | FileIn n | FileOut n -> pr "  const char *%s;\n" n
5996         | OptString n -> pr "  const char *%s;\n" n
5997         | StringList n ->
5998             pr "  PyObject *py_%s;\n" n;
5999             pr "  const char **%s;\n" n
6000         | Bool n -> pr "  int %s;\n" n
6001         | Int n -> pr "  int %s;\n" n
6002       ) (snd style);
6003
6004       pr "\n";
6005
6006       (* Convert the parameters. *)
6007       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
6008       List.iter (
6009         function
6010         | String _ | FileIn _ | FileOut _ -> pr "s"
6011         | OptString _ -> pr "z"
6012         | StringList _ -> pr "O"
6013         | Bool _ -> pr "i" (* XXX Python has booleans? *)
6014         | Int _ -> pr "i"
6015       ) (snd style);
6016       pr ":guestfs_%s\",\n" name;
6017       pr "                         &py_g";
6018       List.iter (
6019         function
6020         | String n | FileIn n | FileOut n -> pr ", &%s" n
6021         | OptString n -> pr ", &%s" n
6022         | StringList n -> pr ", &py_%s" n
6023         | Bool n -> pr ", &%s" n
6024         | Int n -> pr ", &%s" n
6025       ) (snd style);
6026
6027       pr "))\n";
6028       pr "    return NULL;\n";
6029
6030       pr "  g = get_handle (py_g);\n";
6031       List.iter (
6032         function
6033         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6034         | StringList n ->
6035             pr "  %s = get_string_list (py_%s);\n" n n;
6036             pr "  if (!%s) return NULL;\n" n
6037       ) (snd style);
6038
6039       pr "\n";
6040
6041       pr "  r = guestfs_%s " name;
6042       generate_call_args ~handle:"g" (snd style);
6043       pr ";\n";
6044
6045       List.iter (
6046         function
6047         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6048         | StringList n ->
6049             pr "  free (%s);\n" n
6050       ) (snd style);
6051
6052       pr "  if (r == %s) {\n" error_code;
6053       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6054       pr "    return NULL;\n";
6055       pr "  }\n";
6056       pr "\n";
6057
6058       (match fst style with
6059        | RErr ->
6060            pr "  Py_INCREF (Py_None);\n";
6061            pr "  py_r = Py_None;\n"
6062        | RInt _
6063        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
6064        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
6065        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
6066        | RString _ ->
6067            pr "  py_r = PyString_FromString (r);\n";
6068            pr "  free (r);\n"
6069        | RStringList _ ->
6070            pr "  py_r = put_string_list (r);\n";
6071            pr "  free_strings (r);\n"
6072        | RIntBool _ ->
6073            pr "  py_r = PyTuple_New (2);\n";
6074            pr "  PyTuple_SetItem (py_r, 0, PyInt_FromLong ((long) r->i));\n";
6075            pr "  PyTuple_SetItem (py_r, 1, PyInt_FromLong ((long) r->b));\n";
6076            pr "  guestfs_free_int_bool (r);\n"
6077        | RPVList n ->
6078            pr "  py_r = put_lvm_pv_list (r);\n";
6079            pr "  guestfs_free_lvm_pv_list (r);\n"
6080        | RVGList n ->
6081            pr "  py_r = put_lvm_vg_list (r);\n";
6082            pr "  guestfs_free_lvm_vg_list (r);\n"
6083        | RLVList n ->
6084            pr "  py_r = put_lvm_lv_list (r);\n";
6085            pr "  guestfs_free_lvm_lv_list (r);\n"
6086        | RStat n ->
6087            pr "  py_r = put_stat (r);\n";
6088            pr "  free (r);\n"
6089        | RStatVFS n ->
6090            pr "  py_r = put_statvfs (r);\n";
6091            pr "  free (r);\n"
6092        | RHashtable n ->
6093            pr "  py_r = put_table (r);\n";
6094            pr "  free_strings (r);\n"
6095       );
6096
6097       pr "  return py_r;\n";
6098       pr "}\n";
6099       pr "\n"
6100   ) all_functions;
6101
6102   (* Table of functions. *)
6103   pr "static PyMethodDef methods[] = {\n";
6104   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
6105   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
6106   List.iter (
6107     fun (name, _, _, _, _, _, _) ->
6108       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
6109         name name
6110   ) all_functions;
6111   pr "  { NULL, NULL, 0, NULL }\n";
6112   pr "};\n";
6113   pr "\n";
6114
6115   (* Init function. *)
6116   pr "\
6117 void
6118 initlibguestfsmod (void)
6119 {
6120   static int initialized = 0;
6121
6122   if (initialized) return;
6123   Py_InitModule ((char *) \"libguestfsmod\", methods);
6124   initialized = 1;
6125 }
6126 "
6127
6128 (* Generate Python module. *)
6129 and generate_python_py () =
6130   generate_header HashStyle LGPLv2;
6131
6132   pr "\
6133 u\"\"\"Python bindings for libguestfs
6134
6135 import guestfs
6136 g = guestfs.GuestFS ()
6137 g.add_drive (\"guest.img\")
6138 g.launch ()
6139 g.wait_ready ()
6140 parts = g.list_partitions ()
6141
6142 The guestfs module provides a Python binding to the libguestfs API
6143 for examining and modifying virtual machine disk images.
6144
6145 Amongst the things this is good for: making batch configuration
6146 changes to guests, getting disk used/free statistics (see also:
6147 virt-df), migrating between virtualization systems (see also:
6148 virt-p2v), performing partial backups, performing partial guest
6149 clones, cloning guests and changing registry/UUID/hostname info, and
6150 much else besides.
6151
6152 Libguestfs uses Linux kernel and qemu code, and can access any type of
6153 guest filesystem that Linux and qemu can, including but not limited
6154 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6155 schemes, qcow, qcow2, vmdk.
6156
6157 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6158 LVs, what filesystem is in each LV, etc.).  It can also run commands
6159 in the context of the guest.  Also you can access filesystems over FTP.
6160
6161 Errors which happen while using the API are turned into Python
6162 RuntimeError exceptions.
6163
6164 To create a guestfs handle you usually have to perform the following
6165 sequence of calls:
6166
6167 # Create the handle, call add_drive at least once, and possibly
6168 # several times if the guest has multiple block devices:
6169 g = guestfs.GuestFS ()
6170 g.add_drive (\"guest.img\")
6171
6172 # Launch the qemu subprocess and wait for it to become ready:
6173 g.launch ()
6174 g.wait_ready ()
6175
6176 # Now you can issue commands, for example:
6177 logvols = g.lvs ()
6178
6179 \"\"\"
6180
6181 import libguestfsmod
6182
6183 class GuestFS:
6184     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
6185
6186     def __init__ (self):
6187         \"\"\"Create a new libguestfs handle.\"\"\"
6188         self._o = libguestfsmod.create ()
6189
6190     def __del__ (self):
6191         libguestfsmod.close (self._o)
6192
6193 ";
6194
6195   List.iter (
6196     fun (name, style, _, flags, _, _, longdesc) ->
6197       pr "    def %s " name;
6198       generate_call_args ~handle:"self" (snd style);
6199       pr ":\n";
6200
6201       if not (List.mem NotInDocs flags) then (
6202         let doc = replace_str longdesc "C<guestfs_" "C<g." in
6203         let doc =
6204           match fst style with
6205           | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _
6206           | RString _ -> doc
6207           | RStringList _ ->
6208               doc ^ "\n\nThis function returns a list of strings."
6209           | RIntBool _ ->
6210               doc ^ "\n\nThis function returns a tuple (int, bool).\n"
6211           | RPVList _ ->
6212               doc ^ "\n\nThis function returns a list of PVs.  Each PV is represented as a dictionary."
6213           | RVGList _ ->
6214               doc ^ "\n\nThis function returns a list of VGs.  Each VG is represented as a dictionary."
6215           | RLVList _ ->
6216               doc ^ "\n\nThis function returns a list of LVs.  Each LV is represented as a dictionary."
6217           | RStat _ ->
6218               doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the stat structure."
6219           | RStatVFS _ ->
6220               doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the statvfs structure."
6221           | RHashtable _ ->
6222               doc ^ "\n\nThis function returns a dictionary." in
6223         let doc =
6224           if List.mem ProtocolLimitWarning flags then
6225             doc ^ "\n\n" ^ protocol_limit_warning
6226           else doc in
6227         let doc =
6228           if List.mem DangerWillRobinson flags then
6229             doc ^ "\n\n" ^ danger_will_robinson
6230           else doc in
6231         let doc = pod2text ~width:60 name doc in
6232         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
6233         let doc = String.concat "\n        " doc in
6234         pr "        u\"\"\"%s\"\"\"\n" doc;
6235       );
6236       pr "        return libguestfsmod.%s " name;
6237       generate_call_args ~handle:"self._o" (snd style);
6238       pr "\n";
6239       pr "\n";
6240   ) all_functions
6241
6242 (* Useful if you need the longdesc POD text as plain text.  Returns a
6243  * list of lines.
6244  *
6245  * This is the slowest thing about autogeneration.
6246  *)
6247 and pod2text ~width name longdesc =
6248   let filename, chan = Filename.open_temp_file "gen" ".tmp" in
6249   fprintf chan "=head1 %s\n\n%s\n" name longdesc;
6250   close_out chan;
6251   let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
6252   let chan = Unix.open_process_in cmd in
6253   let lines = ref [] in
6254   let rec loop i =
6255     let line = input_line chan in
6256     if i = 1 then               (* discard the first line of output *)
6257       loop (i+1)
6258     else (
6259       let line = triml line in
6260       lines := line :: !lines;
6261       loop (i+1)
6262     ) in
6263   let lines = try loop 1 with End_of_file -> List.rev !lines in
6264   Unix.unlink filename;
6265   match Unix.close_process_in chan with
6266   | Unix.WEXITED 0 -> lines
6267   | Unix.WEXITED i ->
6268       failwithf "pod2text: process exited with non-zero status (%d)" i
6269   | Unix.WSIGNALED i | Unix.WSTOPPED i ->
6270       failwithf "pod2text: process signalled or stopped by signal %d" i
6271
6272 (* Generate ruby bindings. *)
6273 and generate_ruby_c () =
6274   generate_header CStyle LGPLv2;
6275
6276   pr "\
6277 #include <stdio.h>
6278 #include <stdlib.h>
6279
6280 #include <ruby.h>
6281
6282 #include \"guestfs.h\"
6283
6284 #include \"extconf.h\"
6285
6286 /* For Ruby < 1.9 */
6287 #ifndef RARRAY_LEN
6288 #define RARRAY_LEN(r) (RARRAY((r))->len)
6289 #endif
6290
6291 static VALUE m_guestfs;                 /* guestfs module */
6292 static VALUE c_guestfs;                 /* guestfs_h handle */
6293 static VALUE e_Error;                   /* used for all errors */
6294
6295 static void ruby_guestfs_free (void *p)
6296 {
6297   if (!p) return;
6298   guestfs_close ((guestfs_h *) p);
6299 }
6300
6301 static VALUE ruby_guestfs_create (VALUE m)
6302 {
6303   guestfs_h *g;
6304
6305   g = guestfs_create ();
6306   if (!g)
6307     rb_raise (e_Error, \"failed to create guestfs handle\");
6308
6309   /* Don't print error messages to stderr by default. */
6310   guestfs_set_error_handler (g, NULL, NULL);
6311
6312   /* Wrap it, and make sure the close function is called when the
6313    * handle goes away.
6314    */
6315   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
6316 }
6317
6318 static VALUE ruby_guestfs_close (VALUE gv)
6319 {
6320   guestfs_h *g;
6321   Data_Get_Struct (gv, guestfs_h, g);
6322
6323   ruby_guestfs_free (g);
6324   DATA_PTR (gv) = NULL;
6325
6326   return Qnil;
6327 }
6328
6329 ";
6330
6331   List.iter (
6332     fun (name, style, _, _, _, _, _) ->
6333       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
6334       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
6335       pr ")\n";
6336       pr "{\n";
6337       pr "  guestfs_h *g;\n";
6338       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
6339       pr "  if (!g)\n";
6340       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
6341         name;
6342       pr "\n";
6343
6344       List.iter (
6345         function
6346         | String n | FileIn n | FileOut n ->
6347             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
6348             pr "  if (!%s)\n" n;
6349             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
6350             pr "              \"%s\", \"%s\");\n" n name
6351         | OptString n ->
6352             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
6353         | StringList n ->
6354             pr "  char **%s;" n;
6355             pr "  {\n";
6356             pr "    int i, len;\n";
6357             pr "    len = RARRAY_LEN (%sv);\n" n;
6358             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
6359               n;
6360             pr "    for (i = 0; i < len; ++i) {\n";
6361             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
6362             pr "      %s[i] = StringValueCStr (v);\n" n;
6363             pr "    }\n";
6364             pr "    %s[len] = NULL;\n" n;
6365             pr "  }\n";
6366         | Bool n ->
6367             pr "  int %s = RTEST (%sv);\n" n n
6368         | Int n ->
6369             pr "  int %s = NUM2INT (%sv);\n" n n
6370       ) (snd style);
6371       pr "\n";
6372
6373       let error_code =
6374         match fst style with
6375         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
6376         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
6377         | RConstString _ -> pr "  const char *r;\n"; "NULL"
6378         | RString _ -> pr "  char *r;\n"; "NULL"
6379         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
6380         | RIntBool _ -> pr "  struct guestfs_int_bool *r;\n"; "NULL"
6381         | RPVList n -> pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL"
6382         | RVGList n -> pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL"
6383         | RLVList n -> pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL"
6384         | RStat n -> pr "  struct guestfs_stat *r;\n"; "NULL"
6385         | RStatVFS n -> pr "  struct guestfs_statvfs *r;\n"; "NULL" in
6386       pr "\n";
6387
6388       pr "  r = guestfs_%s " name;
6389       generate_call_args ~handle:"g" (snd style);
6390       pr ";\n";
6391
6392       List.iter (
6393         function
6394         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6395         | StringList n ->
6396             pr "  free (%s);\n" n
6397       ) (snd style);
6398
6399       pr "  if (r == %s)\n" error_code;
6400       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
6401       pr "\n";
6402
6403       (match fst style with
6404        | RErr ->
6405            pr "  return Qnil;\n"
6406        | RInt _ | RBool _ ->
6407            pr "  return INT2NUM (r);\n"
6408        | RInt64 _ ->
6409            pr "  return ULL2NUM (r);\n"
6410        | RConstString _ ->
6411            pr "  return rb_str_new2 (r);\n";
6412        | RString _ ->
6413            pr "  VALUE rv = rb_str_new2 (r);\n";
6414            pr "  free (r);\n";
6415            pr "  return rv;\n";
6416        | RStringList _ ->
6417            pr "  int i, len = 0;\n";
6418            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
6419            pr "  VALUE rv = rb_ary_new2 (len);\n";
6420            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
6421            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
6422            pr "    free (r[i]);\n";
6423            pr "  }\n";
6424            pr "  free (r);\n";
6425            pr "  return rv;\n"
6426        | RIntBool _ ->
6427            pr "  VALUE rv = rb_ary_new2 (2);\n";
6428            pr "  rb_ary_push (rv, INT2NUM (r->i));\n";
6429            pr "  rb_ary_push (rv, INT2NUM (r->b));\n";
6430            pr "  guestfs_free_int_bool (r);\n";
6431            pr "  return rv;\n"
6432        | RPVList n ->
6433            generate_ruby_lvm_code "pv" pv_cols
6434        | RVGList n ->
6435            generate_ruby_lvm_code "vg" vg_cols
6436        | RLVList n ->
6437            generate_ruby_lvm_code "lv" lv_cols
6438        | RStat n ->
6439            pr "  VALUE rv = rb_hash_new ();\n";
6440            List.iter (
6441              function
6442              | name, `Int ->
6443                  pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6444            ) stat_cols;
6445            pr "  free (r);\n";
6446            pr "  return rv;\n"
6447        | RStatVFS n ->
6448            pr "  VALUE rv = rb_hash_new ();\n";
6449            List.iter (
6450              function
6451              | name, `Int ->
6452                  pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6453            ) statvfs_cols;
6454            pr "  free (r);\n";
6455            pr "  return rv;\n"
6456        | RHashtable _ ->
6457            pr "  VALUE rv = rb_hash_new ();\n";
6458            pr "  int i;\n";
6459            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
6460            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
6461            pr "    free (r[i]);\n";
6462            pr "    free (r[i+1]);\n";
6463            pr "  }\n";
6464            pr "  free (r);\n";
6465            pr "  return rv;\n"
6466       );
6467
6468       pr "}\n";
6469       pr "\n"
6470   ) all_functions;
6471
6472   pr "\
6473 /* Initialize the module. */
6474 void Init__guestfs ()
6475 {
6476   m_guestfs = rb_define_module (\"Guestfs\");
6477   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
6478   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
6479
6480   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
6481   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
6482
6483 ";
6484   (* Define the rest of the methods. *)
6485   List.iter (
6486     fun (name, style, _, _, _, _, _) ->
6487       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
6488       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
6489   ) all_functions;
6490
6491   pr "}\n"
6492
6493 (* Ruby code to return an LVM struct list. *)
6494 and generate_ruby_lvm_code typ cols =
6495   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
6496   pr "  int i;\n";
6497   pr "  for (i = 0; i < r->len; ++i) {\n";
6498   pr "    VALUE hv = rb_hash_new ();\n";
6499   List.iter (
6500     function
6501     | name, `String ->
6502         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
6503     | name, `UUID ->
6504         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
6505     | name, `Bytes
6506     | name, `Int ->
6507         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
6508     | name, `OptPercent ->
6509         pr "    rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
6510   ) cols;
6511   pr "    rb_ary_push (rv, hv);\n";
6512   pr "  }\n";
6513   pr "  guestfs_free_lvm_%s_list (r);\n" typ;
6514   pr "  return rv;\n"
6515
6516 (* Generate Java bindings GuestFS.java file. *)
6517 and generate_java_java () =
6518   generate_header CStyle LGPLv2;
6519
6520   pr "\
6521 package com.redhat.et.libguestfs;
6522
6523 import java.util.HashMap;
6524 import com.redhat.et.libguestfs.LibGuestFSException;
6525 import com.redhat.et.libguestfs.PV;
6526 import com.redhat.et.libguestfs.VG;
6527 import com.redhat.et.libguestfs.LV;
6528 import com.redhat.et.libguestfs.Stat;
6529 import com.redhat.et.libguestfs.StatVFS;
6530 import com.redhat.et.libguestfs.IntBool;
6531
6532 /**
6533  * The GuestFS object is a libguestfs handle.
6534  *
6535  * @author rjones
6536  */
6537 public class GuestFS {
6538   // Load the native code.
6539   static {
6540     System.loadLibrary (\"guestfs_jni\");
6541   }
6542
6543   /**
6544    * The native guestfs_h pointer.
6545    */
6546   long g;
6547
6548   /**
6549    * Create a libguestfs handle.
6550    *
6551    * @throws LibGuestFSException
6552    */
6553   public GuestFS () throws LibGuestFSException
6554   {
6555     g = _create ();
6556   }
6557   private native long _create () throws LibGuestFSException;
6558
6559   /**
6560    * Close a libguestfs handle.
6561    *
6562    * You can also leave handles to be collected by the garbage
6563    * collector, but this method ensures that the resources used
6564    * by the handle are freed up immediately.  If you call any
6565    * other methods after closing the handle, you will get an
6566    * exception.
6567    *
6568    * @throws LibGuestFSException
6569    */
6570   public void close () throws LibGuestFSException
6571   {
6572     if (g != 0)
6573       _close (g);
6574     g = 0;
6575   }
6576   private native void _close (long g) throws LibGuestFSException;
6577
6578   public void finalize () throws LibGuestFSException
6579   {
6580     close ();
6581   }
6582
6583 ";
6584
6585   List.iter (
6586     fun (name, style, _, flags, _, shortdesc, longdesc) ->
6587       if not (List.mem NotInDocs flags); then (
6588         let doc = replace_str longdesc "C<guestfs_" "C<g." in
6589         let doc =
6590           if List.mem ProtocolLimitWarning flags then
6591             doc ^ "\n\n" ^ protocol_limit_warning
6592           else doc in
6593         let doc =
6594           if List.mem DangerWillRobinson flags then
6595             doc ^ "\n\n" ^ danger_will_robinson
6596           else doc in
6597         let doc = pod2text ~width:60 name doc in
6598         let doc = List.map (            (* RHBZ#501883 *)
6599           function
6600           | "" -> "<p>"
6601           | nonempty -> nonempty
6602         ) doc in
6603         let doc = String.concat "\n   * " doc in
6604
6605         pr "  /**\n";
6606         pr "   * %s\n" shortdesc;
6607         pr "   * <p>\n";
6608         pr "   * %s\n" doc;
6609         pr "   * @throws LibGuestFSException\n";
6610         pr "   */\n";
6611         pr "  ";
6612       );
6613       generate_java_prototype ~public:true ~semicolon:false name style;
6614       pr "\n";
6615       pr "  {\n";
6616       pr "    if (g == 0)\n";
6617       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
6618         name;
6619       pr "    ";
6620       if fst style <> RErr then pr "return ";
6621       pr "_%s " name;
6622       generate_call_args ~handle:"g" (snd style);
6623       pr ";\n";
6624       pr "  }\n";
6625       pr "  ";
6626       generate_java_prototype ~privat:true ~native:true name style;
6627       pr "\n";
6628       pr "\n";
6629   ) all_functions;
6630
6631   pr "}\n"
6632
6633 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
6634     ?(semicolon=true) name style =
6635   if privat then pr "private ";
6636   if public then pr "public ";
6637   if native then pr "native ";
6638
6639   (* return type *)
6640   (match fst style with
6641    | RErr -> pr "void ";
6642    | RInt _ -> pr "int ";
6643    | RInt64 _ -> pr "long ";
6644    | RBool _ -> pr "boolean ";
6645    | RConstString _ | RString _ -> pr "String ";
6646    | RStringList _ -> pr "String[] ";
6647    | RIntBool _ -> pr "IntBool ";
6648    | RPVList _ -> pr "PV[] ";
6649    | RVGList _ -> pr "VG[] ";
6650    | RLVList _ -> pr "LV[] ";
6651    | RStat _ -> pr "Stat ";
6652    | RStatVFS _ -> pr "StatVFS ";
6653    | RHashtable _ -> pr "HashMap<String,String> ";
6654   );
6655
6656   if native then pr "_%s " name else pr "%s " name;
6657   pr "(";
6658   let needs_comma = ref false in
6659   if native then (
6660     pr "long g";
6661     needs_comma := true
6662   );
6663
6664   (* args *)
6665   List.iter (
6666     fun arg ->
6667       if !needs_comma then pr ", ";
6668       needs_comma := true;
6669
6670       match arg with
6671       | String n
6672       | OptString n
6673       | FileIn n
6674       | FileOut n ->
6675           pr "String %s" n
6676       | StringList n ->
6677           pr "String[] %s" n
6678       | Bool n ->
6679           pr "boolean %s" n
6680       | Int n ->
6681           pr "int %s" n
6682   ) (snd style);
6683
6684   pr ")\n";
6685   pr "    throws LibGuestFSException";
6686   if semicolon then pr ";"
6687
6688 and generate_java_struct typ cols =
6689   generate_header CStyle LGPLv2;
6690
6691   pr "\
6692 package com.redhat.et.libguestfs;
6693
6694 /**
6695  * Libguestfs %s structure.
6696  *
6697  * @author rjones
6698  * @see GuestFS
6699  */
6700 public class %s {
6701 " typ typ;
6702
6703   List.iter (
6704     function
6705     | name, `String
6706     | name, `UUID -> pr "  public String %s;\n" name
6707     | name, `Bytes
6708     | name, `Int -> pr "  public long %s;\n" name
6709     | name, `OptPercent ->
6710         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
6711         pr "  public float %s;\n" name
6712   ) cols;
6713
6714   pr "}\n"
6715
6716 and generate_java_c () =
6717   generate_header CStyle LGPLv2;
6718
6719   pr "\
6720 #include <stdio.h>
6721 #include <stdlib.h>
6722 #include <string.h>
6723
6724 #include \"com_redhat_et_libguestfs_GuestFS.h\"
6725 #include \"guestfs.h\"
6726
6727 /* Note that this function returns.  The exception is not thrown
6728  * until after the wrapper function returns.
6729  */
6730 static void
6731 throw_exception (JNIEnv *env, const char *msg)
6732 {
6733   jclass cl;
6734   cl = (*env)->FindClass (env,
6735                           \"com/redhat/et/libguestfs/LibGuestFSException\");
6736   (*env)->ThrowNew (env, cl, msg);
6737 }
6738
6739 JNIEXPORT jlong JNICALL
6740 Java_com_redhat_et_libguestfs_GuestFS__1create
6741   (JNIEnv *env, jobject obj)
6742 {
6743   guestfs_h *g;
6744
6745   g = guestfs_create ();
6746   if (g == NULL) {
6747     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
6748     return 0;
6749   }
6750   guestfs_set_error_handler (g, NULL, NULL);
6751   return (jlong) (long) g;
6752 }
6753
6754 JNIEXPORT void JNICALL
6755 Java_com_redhat_et_libguestfs_GuestFS__1close
6756   (JNIEnv *env, jobject obj, jlong jg)
6757 {
6758   guestfs_h *g = (guestfs_h *) (long) jg;
6759   guestfs_close (g);
6760 }
6761
6762 ";
6763
6764   List.iter (
6765     fun (name, style, _, _, _, _, _) ->
6766       pr "JNIEXPORT ";
6767       (match fst style with
6768        | RErr -> pr "void ";
6769        | RInt _ -> pr "jint ";
6770        | RInt64 _ -> pr "jlong ";
6771        | RBool _ -> pr "jboolean ";
6772        | RConstString _ | RString _ -> pr "jstring ";
6773        | RIntBool _ | RStat _ | RStatVFS _ | RHashtable _ ->
6774            pr "jobject ";
6775        | RStringList _ | RPVList _ | RVGList _ | RLVList _ ->
6776            pr "jobjectArray ";
6777       );
6778       pr "JNICALL\n";
6779       pr "Java_com_redhat_et_libguestfs_GuestFS_";
6780       pr "%s" (replace_str ("_" ^ name) "_" "_1");
6781       pr "\n";
6782       pr "  (JNIEnv *env, jobject obj, jlong jg";
6783       List.iter (
6784         function
6785         | String n
6786         | OptString n
6787         | FileIn n
6788         | FileOut n ->
6789             pr ", jstring j%s" n
6790         | StringList n ->
6791             pr ", jobjectArray j%s" n
6792         | Bool n ->
6793             pr ", jboolean j%s" n
6794         | Int n ->
6795             pr ", jint j%s" n
6796       ) (snd style);
6797       pr ")\n";
6798       pr "{\n";
6799       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
6800       let error_code, no_ret =
6801         match fst style with
6802         | RErr -> pr "  int r;\n"; "-1", ""
6803         | RBool _
6804         | RInt _ -> pr "  int r;\n"; "-1", "0"
6805         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
6806         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
6807         | RString _ ->
6808             pr "  jstring jr;\n";
6809             pr "  char *r;\n"; "NULL", "NULL"
6810         | RStringList _ ->
6811             pr "  jobjectArray jr;\n";
6812             pr "  int r_len;\n";
6813             pr "  jclass cl;\n";
6814             pr "  jstring jstr;\n";
6815             pr "  char **r;\n"; "NULL", "NULL"
6816         | RIntBool _ ->
6817             pr "  jobject jr;\n";
6818             pr "  jclass cl;\n";
6819             pr "  jfieldID fl;\n";
6820             pr "  struct guestfs_int_bool *r;\n"; "NULL", "NULL"
6821         | RStat _ ->
6822             pr "  jobject jr;\n";
6823             pr "  jclass cl;\n";
6824             pr "  jfieldID fl;\n";
6825             pr "  struct guestfs_stat *r;\n"; "NULL", "NULL"
6826         | RStatVFS _ ->
6827             pr "  jobject jr;\n";
6828             pr "  jclass cl;\n";
6829             pr "  jfieldID fl;\n";
6830             pr "  struct guestfs_statvfs *r;\n"; "NULL", "NULL"
6831         | RPVList _ ->
6832             pr "  jobjectArray jr;\n";
6833             pr "  jclass cl;\n";
6834             pr "  jfieldID fl;\n";
6835             pr "  jobject jfl;\n";
6836             pr "  struct guestfs_lvm_pv_list *r;\n"; "NULL", "NULL"
6837         | RVGList _ ->
6838             pr "  jobjectArray jr;\n";
6839             pr "  jclass cl;\n";
6840             pr "  jfieldID fl;\n";
6841             pr "  jobject jfl;\n";
6842             pr "  struct guestfs_lvm_vg_list *r;\n"; "NULL", "NULL"
6843         | RLVList _ ->
6844             pr "  jobjectArray jr;\n";
6845             pr "  jclass cl;\n";
6846             pr "  jfieldID fl;\n";
6847             pr "  jobject jfl;\n";
6848             pr "  struct guestfs_lvm_lv_list *r;\n"; "NULL", "NULL"
6849         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL" in
6850       List.iter (
6851         function
6852         | String n
6853         | OptString n
6854         | FileIn n
6855         | FileOut n ->
6856             pr "  const char *%s;\n" n
6857         | StringList n ->
6858             pr "  int %s_len;\n" n;
6859             pr "  const char **%s;\n" n
6860         | Bool n
6861         | Int n ->
6862             pr "  int %s;\n" n
6863       ) (snd style);
6864
6865       let needs_i =
6866         (match fst style with
6867          | RStringList _ | RPVList _ | RVGList _ | RLVList _ -> true
6868          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
6869          | RString _ | RIntBool _ | RStat _ | RStatVFS _
6870          | RHashtable _ -> false) ||
6871         List.exists (function StringList _ -> true | _ -> false) (snd style) in
6872       if needs_i then
6873         pr "  int i;\n";
6874
6875       pr "\n";
6876
6877       (* Get the parameters. *)
6878       List.iter (
6879         function
6880         | String n
6881         | FileIn n
6882         | FileOut n ->
6883             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
6884         | OptString n ->
6885             (* This is completely undocumented, but Java null becomes
6886              * a NULL parameter.
6887              *)
6888             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
6889         | StringList n ->
6890             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
6891             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
6892             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
6893             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6894               n;
6895             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
6896             pr "  }\n";
6897             pr "  %s[%s_len] = NULL;\n" n n;
6898         | Bool n
6899         | Int n ->
6900             pr "  %s = j%s;\n" n n
6901       ) (snd style);
6902
6903       (* Make the call. *)
6904       pr "  r = guestfs_%s " name;
6905       generate_call_args ~handle:"g" (snd style);
6906       pr ";\n";
6907
6908       (* Release the parameters. *)
6909       List.iter (
6910         function
6911         | String n
6912         | FileIn n
6913         | FileOut n ->
6914             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6915         | OptString n ->
6916             pr "  if (j%s)\n" n;
6917             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6918         | StringList n ->
6919             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
6920             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6921               n;
6922             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
6923             pr "  }\n";
6924             pr "  free (%s);\n" n
6925         | Bool n
6926         | Int n -> ()
6927       ) (snd style);
6928
6929       (* Check for errors. *)
6930       pr "  if (r == %s) {\n" error_code;
6931       pr "    throw_exception (env, guestfs_last_error (g));\n";
6932       pr "    return %s;\n" no_ret;
6933       pr "  }\n";
6934
6935       (* Return value. *)
6936       (match fst style with
6937        | RErr -> ()
6938        | RInt _ -> pr "  return (jint) r;\n"
6939        | RBool _ -> pr "  return (jboolean) r;\n"
6940        | RInt64 _ -> pr "  return (jlong) r;\n"
6941        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
6942        | RString _ ->
6943            pr "  jr = (*env)->NewStringUTF (env, r);\n";
6944            pr "  free (r);\n";
6945            pr "  return jr;\n"
6946        | RStringList _ ->
6947            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
6948            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
6949            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
6950            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
6951            pr "  for (i = 0; i < r_len; ++i) {\n";
6952            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
6953            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
6954            pr "    free (r[i]);\n";
6955            pr "  }\n";
6956            pr "  free (r);\n";
6957            pr "  return jr;\n"
6958        | RIntBool _ ->
6959            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/IntBool\");\n";
6960            pr "  jr = (*env)->AllocObject (env, cl);\n";
6961            pr "  fl = (*env)->GetFieldID (env, cl, \"i\", \"I\");\n";
6962            pr "  (*env)->SetIntField (env, jr, fl, r->i);\n";
6963            pr "  fl = (*env)->GetFieldID (env, cl, \"i\", \"Z\");\n";
6964            pr "  (*env)->SetBooleanField (env, jr, fl, r->b);\n";
6965            pr "  guestfs_free_int_bool (r);\n";
6966            pr "  return jr;\n"
6967        | RStat _ ->
6968            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/Stat\");\n";
6969            pr "  jr = (*env)->AllocObject (env, cl);\n";
6970            List.iter (
6971              function
6972              | name, `Int ->
6973                  pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6974                    name;
6975                  pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6976            ) stat_cols;
6977            pr "  free (r);\n";
6978            pr "  return jr;\n"
6979        | RStatVFS _ ->
6980            pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/StatVFS\");\n";
6981            pr "  jr = (*env)->AllocObject (env, cl);\n";
6982            List.iter (
6983              function
6984              | name, `Int ->
6985                  pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6986                    name;
6987                  pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6988            ) statvfs_cols;
6989            pr "  free (r);\n";
6990            pr "  return jr;\n"
6991        | RPVList _ ->
6992            generate_java_lvm_return "pv" "PV" pv_cols
6993        | RVGList _ ->
6994            generate_java_lvm_return "vg" "VG" vg_cols
6995        | RLVList _ ->
6996            generate_java_lvm_return "lv" "LV" lv_cols
6997        | RHashtable _ ->
6998            (* XXX *)
6999            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
7000            pr "  return NULL;\n"
7001       );
7002
7003       pr "}\n";
7004       pr "\n"
7005   ) all_functions
7006
7007 and generate_java_lvm_return typ jtyp cols =
7008   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
7009   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
7010   pr "  for (i = 0; i < r->len; ++i) {\n";
7011   pr "    jfl = (*env)->AllocObject (env, cl);\n";
7012   List.iter (
7013     function
7014     | name, `String ->
7015         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7016         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
7017     | name, `UUID ->
7018         pr "    {\n";
7019         pr "      char s[33];\n";
7020         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
7021         pr "      s[32] = 0;\n";
7022         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7023         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
7024         pr "    }\n";
7025     | name, (`Bytes|`Int) ->
7026         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7027         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7028     | name, `OptPercent ->
7029         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7030         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
7031   ) cols;
7032   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
7033   pr "  }\n";
7034   pr "  guestfs_free_lvm_%s_list (r);\n" typ;
7035   pr "  return jr;\n"
7036
7037 and generate_haskell_hs () =
7038   generate_header HaskellStyle LGPLv2;
7039
7040   (* XXX We only know how to generate partial FFI for Haskell
7041    * at the moment.  Please help out!
7042    *)
7043   let can_generate style =
7044     let check_no_bad_args =
7045       List.for_all (function Bool _ | Int _ -> false | _ -> true)
7046     in
7047     match style with
7048     | RErr, args -> check_no_bad_args args
7049     | RBool _, _
7050     | RInt _, _
7051     | RInt64 _, _
7052     | RConstString _, _
7053     | RString _, _
7054     | RStringList _, _
7055     | RIntBool _, _
7056     | RPVList _, _
7057     | RVGList _, _
7058     | RLVList _, _
7059     | RStat _, _
7060     | RStatVFS _, _
7061     | RHashtable _, _ -> false in
7062
7063   pr "\
7064 {-# INCLUDE <guestfs.h> #-}
7065 {-# LANGUAGE ForeignFunctionInterface #-}
7066
7067 module Guestfs (
7068   create";
7069
7070   (* List out the names of the actions we want to export. *)
7071   List.iter (
7072     fun (name, style, _, _, _, _, _) ->
7073       if can_generate style then pr ",\n  %s" name
7074   ) all_functions;
7075
7076   pr "
7077   ) where
7078 import Foreign
7079 import Foreign.C
7080 import IO
7081 import Control.Exception
7082 import Data.Typeable
7083
7084 data GuestfsS = GuestfsS            -- represents the opaque C struct
7085 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
7086 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
7087
7088 -- XXX define properly later XXX
7089 data PV = PV
7090 data VG = VG
7091 data LV = LV
7092 data IntBool = IntBool
7093 data Stat = Stat
7094 data StatVFS = StatVFS
7095 data Hashtable = Hashtable
7096
7097 foreign import ccall unsafe \"guestfs_create\" c_create
7098   :: IO GuestfsP
7099 foreign import ccall unsafe \"&guestfs_close\" c_close
7100   :: FunPtr (GuestfsP -> IO ())
7101 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
7102   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
7103
7104 create :: IO GuestfsH
7105 create = do
7106   p <- c_create
7107   c_set_error_handler p nullPtr nullPtr
7108   h <- newForeignPtr c_close p
7109   return h
7110
7111 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
7112   :: GuestfsP -> IO CString
7113
7114 -- last_error :: GuestfsH -> IO (Maybe String)
7115 -- last_error h = do
7116 --   str <- withForeignPtr h (\\p -> c_last_error p)
7117 --   maybePeek peekCString str
7118
7119 last_error :: GuestfsH -> IO (String)
7120 last_error h = do
7121   str <- withForeignPtr h (\\p -> c_last_error p)
7122   if (str == nullPtr)
7123     then return \"no error\"
7124     else peekCString str
7125
7126 ";
7127
7128   (* Generate wrappers for each foreign function. *)
7129   List.iter (
7130     fun (name, style, _, _, _, _, _) ->
7131       if can_generate style then (
7132         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
7133         pr "  :: ";
7134         generate_haskell_prototype ~handle:"GuestfsP" style;
7135         pr "\n";
7136         pr "\n";
7137         pr "%s :: " name;
7138         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
7139         pr "\n";
7140         pr "%s %s = do\n" name
7141           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
7142         pr "  r <- ";
7143         List.iter (
7144           function
7145           | FileIn n
7146           | FileOut n
7147           | String n -> pr "withCString %s $ \\%s -> " n n
7148           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
7149           | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
7150           | Bool n ->
7151               (* XXX this doesn't work *)
7152               pr "      let\n";
7153               pr "        %s = case %s of\n" n n;
7154               pr "          False -> 0\n";
7155               pr "          True -> 1\n";
7156               pr "      in fromIntegral %s $ \\%s ->\n" n n
7157           | Int n -> pr "fromIntegral %s $ \\%s -> " n n
7158         ) (snd style);
7159         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
7160           (String.concat " " ("p" :: List.map name_of_argt (snd style)));
7161         (match fst style with
7162          | RErr | RInt _ | RInt64 _ | RBool _ ->
7163              pr "  if (r == -1)\n";
7164              pr "    then do\n";
7165              pr "      err <- last_error h\n";
7166              pr "      fail err\n";
7167          | RConstString _ | RString _ | RStringList _ | RIntBool _
7168          | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7169          | RHashtable _ ->
7170              pr "  if (r == nullPtr)\n";
7171              pr "    then do\n";
7172              pr "      err <- last_error h\n";
7173              pr "      fail err\n";
7174         );
7175         (match fst style with
7176          | RErr ->
7177              pr "    else return ()\n"
7178          | RInt _ ->
7179              pr "    else return (fromIntegral r)\n"
7180          | RInt64 _ ->
7181              pr "    else return (fromIntegral r)\n"
7182          | RBool _ ->
7183              pr "    else return (toBool r)\n"
7184          | RConstString _
7185          | RString _
7186          | RStringList _
7187          | RIntBool _
7188          | RPVList _
7189          | RVGList _
7190          | RLVList _
7191          | RStat _
7192          | RStatVFS _
7193          | RHashtable _ ->
7194              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
7195         );
7196         pr "\n";
7197       )
7198   ) all_functions
7199
7200 and generate_haskell_prototype ~handle ?(hs = false) style =
7201   pr "%s -> " handle;
7202   let string = if hs then "String" else "CString" in
7203   let int = if hs then "Int" else "CInt" in
7204   let bool = if hs then "Bool" else "CInt" in
7205   let int64 = if hs then "Integer" else "Int64" in
7206   List.iter (
7207     fun arg ->
7208       (match arg with
7209        | String _ -> pr "%s" string
7210        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
7211        | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
7212        | Bool _ -> pr "%s" bool
7213        | Int _ -> pr "%s" int
7214        | FileIn _ -> pr "%s" string
7215        | FileOut _ -> pr "%s" string
7216       );
7217       pr " -> ";
7218   ) (snd style);
7219   pr "IO (";
7220   (match fst style with
7221    | RErr -> if not hs then pr "CInt"
7222    | RInt _ -> pr "%s" int
7223    | RInt64 _ -> pr "%s" int64
7224    | RBool _ -> pr "%s" bool
7225    | RConstString _ -> pr "%s" string
7226    | RString _ -> pr "%s" string
7227    | RStringList _ -> pr "[%s]" string
7228    | RIntBool _ -> pr "IntBool"
7229    | RPVList _ -> pr "[PV]"
7230    | RVGList _ -> pr "[VG]"
7231    | RLVList _ -> pr "[LV]"
7232    | RStat _ -> pr "Stat"
7233    | RStatVFS _ -> pr "StatVFS"
7234    | RHashtable _ -> pr "Hashtable"
7235   );
7236   pr ")"
7237
7238 and generate_bindtests () =
7239   generate_header CStyle LGPLv2;
7240
7241   pr "\
7242 #include <stdio.h>
7243 #include <stdlib.h>
7244 #include <inttypes.h>
7245 #include <string.h>
7246
7247 #include \"guestfs.h\"
7248 #include \"guestfs_protocol.h\"
7249
7250 #define error guestfs_error
7251
7252 static void
7253 print_strings (char * const* const argv)
7254 {
7255   int argc;
7256
7257   printf (\"[\");
7258   for (argc = 0; argv[argc] != NULL; ++argc) {
7259     if (argc > 0) printf (\", \");
7260     printf (\"\\\"%%s\\\"\", argv[argc]);
7261   }
7262   printf (\"]\\n\");
7263 }
7264
7265 /* The test0 function prints its parameters to stdout. */
7266 ";
7267
7268   let test0, tests =
7269     match test_functions with
7270     | [] -> assert false
7271     | test0 :: tests -> test0, tests in
7272
7273   let () =
7274     let (name, style, _, _, _, _, _) = test0 in
7275     generate_prototype ~extern:false ~semicolon:false ~newline:true
7276       ~handle:"g" ~prefix:"guestfs_" name style;
7277     pr "{\n";
7278     List.iter (
7279       function
7280       | String n
7281       | FileIn n
7282       | FileOut n -> pr "  printf (\"%%s\\n\", %s);\n" n
7283       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
7284       | StringList n -> pr "  print_strings (%s);\n" n
7285       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
7286       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
7287     ) (snd style);
7288     pr "  /* Java changes stdout line buffering so we need this: */\n";
7289     pr "  fflush (stdout);\n";
7290     pr "  return 0;\n";
7291     pr "}\n";
7292     pr "\n" in
7293
7294   List.iter (
7295     fun (name, style, _, _, _, _, _) ->
7296       if String.sub name (String.length name - 3) 3 <> "err" then (
7297         pr "/* Test normal return. */\n";
7298         generate_prototype ~extern:false ~semicolon:false ~newline:true
7299           ~handle:"g" ~prefix:"guestfs_" name style;
7300         pr "{\n";
7301         (match fst style with
7302          | RErr ->
7303              pr "  return 0;\n"
7304          | RInt _ ->
7305              pr "  int r;\n";
7306              pr "  sscanf (val, \"%%d\", &r);\n";
7307              pr "  return r;\n"
7308          | RInt64 _ ->
7309              pr "  int64_t r;\n";
7310              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
7311              pr "  return r;\n"
7312          | RBool _ ->
7313              pr "  return strcmp (val, \"true\") == 0;\n"
7314          | RConstString _ ->
7315              (* Can't return the input string here.  Return a static
7316               * string so we ensure we get a segfault if the caller
7317               * tries to free it.
7318               *)
7319              pr "  return \"static string\";\n"
7320          | RString _ ->
7321              pr "  return strdup (val);\n"
7322          | RStringList _ ->
7323              pr "  char **strs;\n";
7324              pr "  int n, i;\n";
7325              pr "  sscanf (val, \"%%d\", &n);\n";
7326              pr "  strs = malloc ((n+1) * sizeof (char *));\n";
7327              pr "  for (i = 0; i < n; ++i) {\n";
7328              pr "    strs[i] = malloc (16);\n";
7329              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
7330              pr "  }\n";
7331              pr "  strs[n] = NULL;\n";
7332              pr "  return strs;\n"
7333          | RIntBool _ ->
7334              pr "  struct guestfs_int_bool *r;\n";
7335              pr "  r = malloc (sizeof (struct guestfs_int_bool));\n";
7336              pr "  sscanf (val, \"%%\" SCNi32, &r->i);\n";
7337              pr "  r->b = 0;\n";
7338              pr "  return r;\n"
7339          | RPVList _ ->
7340              pr "  struct guestfs_lvm_pv_list *r;\n";
7341              pr "  int i;\n";
7342              pr "  r = malloc (sizeof (struct guestfs_lvm_pv_list));\n";
7343              pr "  sscanf (val, \"%%d\", &r->len);\n";
7344              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_pv));\n";
7345              pr "  for (i = 0; i < r->len; ++i) {\n";
7346              pr "    r->val[i].pv_name = malloc (16);\n";
7347              pr "    snprintf (r->val[i].pv_name, 16, \"%%d\", i);\n";
7348              pr "  }\n";
7349              pr "  return r;\n"
7350          | RVGList _ ->
7351              pr "  struct guestfs_lvm_vg_list *r;\n";
7352              pr "  int i;\n";
7353              pr "  r = malloc (sizeof (struct guestfs_lvm_vg_list));\n";
7354              pr "  sscanf (val, \"%%d\", &r->len);\n";
7355              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_vg));\n";
7356              pr "  for (i = 0; i < r->len; ++i) {\n";
7357              pr "    r->val[i].vg_name = malloc (16);\n";
7358              pr "    snprintf (r->val[i].vg_name, 16, \"%%d\", i);\n";
7359              pr "  }\n";
7360              pr "  return r;\n"
7361          | RLVList _ ->
7362              pr "  struct guestfs_lvm_lv_list *r;\n";
7363              pr "  int i;\n";
7364              pr "  r = malloc (sizeof (struct guestfs_lvm_lv_list));\n";
7365              pr "  sscanf (val, \"%%d\", &r->len);\n";
7366              pr "  r->val = calloc (r->len, sizeof (struct guestfs_lvm_lv));\n";
7367              pr "  for (i = 0; i < r->len; ++i) {\n";
7368              pr "    r->val[i].lv_name = malloc (16);\n";
7369              pr "    snprintf (r->val[i].lv_name, 16, \"%%d\", i);\n";
7370              pr "  }\n";
7371              pr "  return r;\n"
7372          | RStat _ ->
7373              pr "  struct guestfs_stat *r;\n";
7374              pr "  r = calloc (1, sizeof (*r));\n";
7375              pr "  sscanf (val, \"%%\" SCNi64, &r->dev);\n";
7376              pr "  return r;\n"
7377          | RStatVFS _ ->
7378              pr "  struct guestfs_statvfs *r;\n";
7379              pr "  r = calloc (1, sizeof (*r));\n";
7380              pr "  sscanf (val, \"%%\" SCNi64, &r->bsize);\n";
7381              pr "  return r;\n"
7382          | RHashtable _ ->
7383              pr "  char **strs;\n";
7384              pr "  int n, i;\n";
7385              pr "  sscanf (val, \"%%d\", &n);\n";
7386              pr "  strs = malloc ((n*2+1) * sizeof (char *));\n";
7387              pr "  for (i = 0; i < n; ++i) {\n";
7388              pr "    strs[i*2] = malloc (16);\n";
7389              pr "    strs[i*2+1] = malloc (16);\n";
7390              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
7391              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
7392              pr "  }\n";
7393              pr "  strs[n*2] = NULL;\n";
7394              pr "  return strs;\n"
7395         );
7396         pr "}\n";
7397         pr "\n"
7398       ) else (
7399         pr "/* Test error return. */\n";
7400         generate_prototype ~extern:false ~semicolon:false ~newline:true
7401           ~handle:"g" ~prefix:"guestfs_" name style;
7402         pr "{\n";
7403         pr "  error (g, \"error\");\n";
7404         (match fst style with
7405          | RErr | RInt _ | RInt64 _ | RBool _ ->
7406              pr "  return -1;\n"
7407          | RConstString _
7408          | RString _ | RStringList _ | RIntBool _
7409          | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7410          | RHashtable _ ->
7411              pr "  return NULL;\n"
7412         );
7413         pr "}\n";
7414         pr "\n"
7415       )
7416   ) tests
7417
7418 and generate_ocaml_bindtests () =
7419   generate_header OCamlStyle GPLv2;
7420
7421   pr "\
7422 let () =
7423   let g = Guestfs.create () in
7424 ";
7425
7426   let mkargs args =
7427     String.concat " " (
7428       List.map (
7429         function
7430         | CallString s -> "\"" ^ s ^ "\""
7431         | CallOptString None -> "None"
7432         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
7433         | CallStringList xs ->
7434             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
7435         | CallInt i when i >= 0 -> string_of_int i
7436         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
7437         | CallBool b -> string_of_bool b
7438       ) args
7439     )
7440   in
7441
7442   generate_lang_bindtests (
7443     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
7444   );
7445
7446   pr "print_endline \"EOF\"\n"
7447
7448 and generate_perl_bindtests () =
7449   pr "#!/usr/bin/perl -w\n";
7450   generate_header HashStyle GPLv2;
7451
7452   pr "\
7453 use strict;
7454
7455 use Sys::Guestfs;
7456
7457 my $g = Sys::Guestfs->new ();
7458 ";
7459
7460   let mkargs args =
7461     String.concat ", " (
7462       List.map (
7463         function
7464         | CallString s -> "\"" ^ s ^ "\""
7465         | CallOptString None -> "undef"
7466         | CallOptString (Some s) -> sprintf "\"%s\"" s
7467         | CallStringList xs ->
7468             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7469         | CallInt i -> string_of_int i
7470         | CallBool b -> if b then "1" else "0"
7471       ) args
7472     )
7473   in
7474
7475   generate_lang_bindtests (
7476     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
7477   );
7478
7479   pr "print \"EOF\\n\"\n"
7480
7481 and generate_python_bindtests () =
7482   generate_header HashStyle GPLv2;
7483
7484   pr "\
7485 import guestfs
7486
7487 g = guestfs.GuestFS ()
7488 ";
7489
7490   let mkargs args =
7491     String.concat ", " (
7492       List.map (
7493         function
7494         | CallString s -> "\"" ^ s ^ "\""
7495         | CallOptString None -> "None"
7496         | CallOptString (Some s) -> sprintf "\"%s\"" s
7497         | CallStringList xs ->
7498             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7499         | CallInt i -> string_of_int i
7500         | CallBool b -> if b then "1" else "0"
7501       ) args
7502     )
7503   in
7504
7505   generate_lang_bindtests (
7506     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
7507   );
7508
7509   pr "print \"EOF\"\n"
7510
7511 and generate_ruby_bindtests () =
7512   generate_header HashStyle GPLv2;
7513
7514   pr "\
7515 require 'guestfs'
7516
7517 g = Guestfs::create()
7518 ";
7519
7520   let mkargs args =
7521     String.concat ", " (
7522       List.map (
7523         function
7524         | CallString s -> "\"" ^ s ^ "\""
7525         | CallOptString None -> "nil"
7526         | CallOptString (Some s) -> sprintf "\"%s\"" s
7527         | CallStringList xs ->
7528             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7529         | CallInt i -> string_of_int i
7530         | CallBool b -> string_of_bool b
7531       ) args
7532     )
7533   in
7534
7535   generate_lang_bindtests (
7536     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
7537   );
7538
7539   pr "print \"EOF\\n\"\n"
7540
7541 and generate_java_bindtests () =
7542   generate_header CStyle GPLv2;
7543
7544   pr "\
7545 import com.redhat.et.libguestfs.*;
7546
7547 public class Bindtests {
7548     public static void main (String[] argv)
7549     {
7550         try {
7551             GuestFS g = new GuestFS ();
7552 ";
7553
7554   let mkargs args =
7555     String.concat ", " (
7556       List.map (
7557         function
7558         | CallString s -> "\"" ^ s ^ "\""
7559         | CallOptString None -> "null"
7560         | CallOptString (Some s) -> sprintf "\"%s\"" s
7561         | CallStringList xs ->
7562             "new String[]{" ^
7563               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
7564         | CallInt i -> string_of_int i
7565         | CallBool b -> string_of_bool b
7566       ) args
7567     )
7568   in
7569
7570   generate_lang_bindtests (
7571     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
7572   );
7573
7574   pr "
7575             System.out.println (\"EOF\");
7576         }
7577         catch (Exception exn) {
7578             System.err.println (exn);
7579             System.exit (1);
7580         }
7581     }
7582 }
7583 "
7584
7585 and generate_haskell_bindtests () =
7586   () (* XXX Haskell bindings need to be fleshed out. *)
7587
7588 (* Language-independent bindings tests - we do it this way to
7589  * ensure there is parity in testing bindings across all languages.
7590  *)
7591 and generate_lang_bindtests call =
7592   call "test0" [CallString "abc"; CallOptString (Some "def");
7593                 CallStringList []; CallBool false;
7594                 CallInt 0; CallString "123"; CallString "456"];
7595   call "test0" [CallString "abc"; CallOptString None;
7596                 CallStringList []; CallBool false;
7597                 CallInt 0; CallString "123"; CallString "456"];
7598   call "test0" [CallString ""; CallOptString (Some "def");
7599                 CallStringList []; CallBool false;
7600                 CallInt 0; CallString "123"; CallString "456"];
7601   call "test0" [CallString ""; CallOptString (Some "");
7602                 CallStringList []; CallBool false;
7603                 CallInt 0; CallString "123"; CallString "456"];
7604   call "test0" [CallString "abc"; CallOptString (Some "def");
7605                 CallStringList ["1"]; CallBool false;
7606                 CallInt 0; CallString "123"; CallString "456"];
7607   call "test0" [CallString "abc"; CallOptString (Some "def");
7608                 CallStringList ["1"; "2"]; CallBool false;
7609                 CallInt 0; CallString "123"; CallString "456"];
7610   call "test0" [CallString "abc"; CallOptString (Some "def");
7611                 CallStringList ["1"]; CallBool true;
7612                 CallInt 0; CallString "123"; CallString "456"];
7613   call "test0" [CallString "abc"; CallOptString (Some "def");
7614                 CallStringList ["1"]; CallBool false;
7615                 CallInt (-1); CallString "123"; CallString "456"];
7616   call "test0" [CallString "abc"; CallOptString (Some "def");
7617                 CallStringList ["1"]; CallBool false;
7618                 CallInt (-2); CallString "123"; CallString "456"];
7619   call "test0" [CallString "abc"; CallOptString (Some "def");
7620                 CallStringList ["1"]; CallBool false;
7621                 CallInt 1; CallString "123"; CallString "456"];
7622   call "test0" [CallString "abc"; CallOptString (Some "def");
7623                 CallStringList ["1"]; CallBool false;
7624                 CallInt 2; CallString "123"; CallString "456"];
7625   call "test0" [CallString "abc"; CallOptString (Some "def");
7626                 CallStringList ["1"]; CallBool false;
7627                 CallInt 4095; CallString "123"; CallString "456"];
7628   call "test0" [CallString "abc"; CallOptString (Some "def");
7629                 CallStringList ["1"]; CallBool false;
7630                 CallInt 0; CallString ""; CallString ""]
7631
7632   (* XXX Add here tests of the return and error functions. *)
7633
7634 let output_to filename =
7635   let filename_new = filename ^ ".new" in
7636   chan := open_out filename_new;
7637   let close () =
7638     close_out !chan;
7639     chan := stdout;
7640
7641     (* Is the new file different from the current file? *)
7642     if Sys.file_exists filename && files_equal filename filename_new then
7643       Unix.unlink filename_new          (* same, so skip it *)
7644     else (
7645       (* different, overwrite old one *)
7646       (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
7647       Unix.rename filename_new filename;
7648       Unix.chmod filename 0o444;
7649       printf "written %s\n%!" filename;
7650     )
7651   in
7652   close
7653
7654 (* Main program. *)
7655 let () =
7656   check_functions ();
7657
7658   if not (Sys.file_exists "configure.ac") then (
7659     eprintf "\
7660 You are probably running this from the wrong directory.
7661 Run it from the top source directory using the command
7662   src/generator.ml
7663 ";
7664     exit 1
7665   );
7666
7667   let close = output_to "src/guestfs_protocol.x" in
7668   generate_xdr ();
7669   close ();
7670
7671   let close = output_to "src/guestfs-structs.h" in
7672   generate_structs_h ();
7673   close ();
7674
7675   let close = output_to "src/guestfs-actions.h" in
7676   generate_actions_h ();
7677   close ();
7678
7679   let close = output_to "src/guestfs-actions.c" in
7680   generate_client_actions ();
7681   close ();
7682
7683   let close = output_to "daemon/actions.h" in
7684   generate_daemon_actions_h ();
7685   close ();
7686
7687   let close = output_to "daemon/stubs.c" in
7688   generate_daemon_actions ();
7689   close ();
7690
7691   let close = output_to "capitests/tests.c" in
7692   generate_tests ();
7693   close ();
7694
7695   let close = output_to "src/guestfs-bindtests.c" in
7696   generate_bindtests ();
7697   close ();
7698
7699   let close = output_to "fish/cmds.c" in
7700   generate_fish_cmds ();
7701   close ();
7702
7703   let close = output_to "fish/completion.c" in
7704   generate_fish_completion ();
7705   close ();
7706
7707   let close = output_to "guestfs-structs.pod" in
7708   generate_structs_pod ();
7709   close ();
7710
7711   let close = output_to "guestfs-actions.pod" in
7712   generate_actions_pod ();
7713   close ();
7714
7715   let close = output_to "guestfish-actions.pod" in
7716   generate_fish_actions_pod ();
7717   close ();
7718
7719   let close = output_to "ocaml/guestfs.mli" in
7720   generate_ocaml_mli ();
7721   close ();
7722
7723   let close = output_to "ocaml/guestfs.ml" in
7724   generate_ocaml_ml ();
7725   close ();
7726
7727   let close = output_to "ocaml/guestfs_c_actions.c" in
7728   generate_ocaml_c ();
7729   close ();
7730
7731   let close = output_to "ocaml/bindtests.ml" in
7732   generate_ocaml_bindtests ();
7733   close ();
7734
7735   let close = output_to "perl/Guestfs.xs" in
7736   generate_perl_xs ();
7737   close ();
7738
7739   let close = output_to "perl/lib/Sys/Guestfs.pm" in
7740   generate_perl_pm ();
7741   close ();
7742
7743   let close = output_to "perl/bindtests.pl" in
7744   generate_perl_bindtests ();
7745   close ();
7746
7747   let close = output_to "python/guestfs-py.c" in
7748   generate_python_c ();
7749   close ();
7750
7751   let close = output_to "python/guestfs.py" in
7752   generate_python_py ();
7753   close ();
7754
7755   let close = output_to "python/bindtests.py" in
7756   generate_python_bindtests ();
7757   close ();
7758
7759   let close = output_to "ruby/ext/guestfs/_guestfs.c" in
7760   generate_ruby_c ();
7761   close ();
7762
7763   let close = output_to "ruby/bindtests.rb" in
7764   generate_ruby_bindtests ();
7765   close ();
7766
7767   let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
7768   generate_java_java ();
7769   close ();
7770
7771   let close = output_to "java/com/redhat/et/libguestfs/PV.java" in
7772   generate_java_struct "PV" pv_cols;
7773   close ();
7774
7775   let close = output_to "java/com/redhat/et/libguestfs/VG.java" in
7776   generate_java_struct "VG" vg_cols;
7777   close ();
7778
7779   let close = output_to "java/com/redhat/et/libguestfs/LV.java" in
7780   generate_java_struct "LV" lv_cols;
7781   close ();
7782
7783   let close = output_to "java/com/redhat/et/libguestfs/Stat.java" in
7784   generate_java_struct "Stat" stat_cols;
7785   close ();
7786
7787   let close = output_to "java/com/redhat/et/libguestfs/StatVFS.java" in
7788   generate_java_struct "StatVFS" statvfs_cols;
7789   close ();
7790
7791   let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
7792   generate_java_c ();
7793   close ();
7794
7795   let close = output_to "java/Bindtests.java" in
7796   generate_java_bindtests ();
7797   close ();
7798
7799   let close = output_to "haskell/Guestfs.hs" in
7800   generate_haskell_hs ();
7801   close ();
7802
7803   let close = output_to "haskell/bindtests.hs" in
7804   generate_haskell_bindtests ();
7805   close ();