3 * Copyright (C) 2009 Red Hat Inc.
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.
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.
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
20 (* This script generates a large amount of code and documentation for
21 * all the daemon actions.
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.
27 * After editing this file, run it (./src/generator.ml) to regenerate
28 * all the output files.
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]
40 type style = ret * args
42 (* "RErr" as a return value means an int used as a simple error
43 * indication, ie. 0 or -1.
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).
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).
56 (* "RBool" is a bool return value which can be true/false or
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.
65 | RConstString of string
66 (* "RString" and "RStringList" are caller-frees. *)
68 | RStringList of string
69 (* Some limited tuples are possible: *)
70 | RIntBool of string * string
71 (* LVM PVs, VGs and LVs. *)
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.
85 | RHashtable of string
87 and args = argt list (* Function parameters, guestfs handle is implicit. *)
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.
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.
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 *)
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
126 let danger_will_robinson =
127 "B<This command is dangerous. Without careful use you
128 can easily destroy all your data>."
130 (* You can supply zero or as many tests as you want per API call.
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.
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
140 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
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
149 * Don't assume anything about the previous contents of the block
150 * devices. Use 'Init*' to create some initial scenarios.
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.
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)
163 type tests = (test_init * test_prereq * test) list
165 (* Run the command sequence and just expect nothing to fail. *)
167 (* Run the command sequence and expect the output of the final
168 * command to be the string.
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.
174 | TestOutputList of seq * string list
175 (* Run the command sequence and expect the output of the final
176 * command to be the integer.
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).
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).
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
191 | TestOutputLength of seq * int
192 (* Run the command sequence and expect the output of the final
193 * command to be a structure.
195 | TestOutputStruct of seq * test_field_compare list
196 (* Run the command sequence and expect the final command (only)
199 | TestLastFail of seq
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
207 (* Test prerequisites. *)
209 (* Test always runs. *)
211 (* Test is currently disabled - eg. it fails, or it tests some
212 * unimplemented feature.
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.
219 (* As for 'If' but the test runs _unless_ the code returns true. *)
222 (* Some initial scenarios for testing. *)
224 (* Do nothing, block devices could contain random stuff including
225 * LVM PVs, and some filesystems might be mounted. This is usually
229 (* Block devices are empty and no filesystems are mounted. *)
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.
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.
245 (* Sequence of commands for testing. *)
247 and cmd = string list
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
254 * Apart from that, long descriptions are just perldoc paragraphs.
257 (* These test functions are used in the language binding tests. *)
259 let test_all_args = [
262 StringList "strlist";
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";
286 let test_functions = [
287 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
289 "internal test function - do not use",
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.
295 It echos the contents of each parameter to stdout.
297 You probably don't want to call this function.");
301 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
303 "internal test function - do not use",
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.
309 It converts string C<val> to the return type.
311 You probably don't want to call this function.");
312 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
314 "internal test function - do not use",
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.
320 This function always returns an error.
322 You probably don't want to call this function.")]
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.
331 let non_daemon_functions = test_functions @ [
332 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
334 "launch the qemu subprocess",
336 Internally libguestfs is implemented by running a virtual machine
339 You should call this after configuring the handle
340 (eg. adding drives) but before performing any actions.");
342 ("wait_ready", (RErr, []), -1, [NotInFish],
344 "wait until the qemu subprocess launches",
346 Internally libguestfs is implemented by running a virtual machine
349 You should call this after C<guestfs_launch> to wait for the launch
352 ("kill_subprocess", (RErr, []), -1, [],
354 "kill the qemu subprocess",
356 This kills the qemu subprocess. You should never need to call this.");
358 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
360 "add an image to examine or modify",
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
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
373 This is equivalent to the qemu parameter C<-drive file=filename>.");
375 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
377 "add a CD-ROM disk image to examine",
379 This function adds a virtual CD-ROM disk image to the guest.
381 This is equivalent to the qemu parameter C<-cdrom filename>.");
383 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
385 "add qemu parameters",
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.
392 The first character of C<param> string must be a C<-> (dash).
394 C<value> can be NULL.");
396 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
398 "set the qemu binary",
400 Set the qemu binary that we will use.
402 The default is chosen when the library was compiled by the
405 You can also override this by setting the C<LIBGUESTFS_QEMU>
406 environment variable.
408 Setting C<qemu> to C<NULL> restores the default qemu binary.");
410 ("get_qemu", (RConstString "qemu", []), -1, [],
412 "get the qemu binary",
414 Return the current qemu binary.
416 This is always non-NULL. If it wasn't set already, then this will
417 return the default qemu binary name.");
419 ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
421 "set the search path",
423 Set the path that libguestfs searches for kernel and initrd.img.
425 The default is C<$libdir/guestfs> unless overridden by setting
426 C<LIBGUESTFS_PATH> environment variable.
428 Setting C<path> to C<NULL> restores the default path.");
430 ("get_path", (RConstString "path", []), -1, [],
432 "get the search path",
434 Return the current search path.
436 This is always non-NULL. If it wasn't set already, then this will
437 return the default path.");
439 ("set_append", (RErr, [String "append"]), -1, [FishAlias "append"],
441 "add options to kernel command line",
443 This function is used to add additional options to the
444 guest kernel command line.
446 The default is C<NULL> unless overridden by setting
447 C<LIBGUESTFS_APPEND> environment variable.
449 Setting C<append> to C<NULL> means I<no> additional options
450 are passed (libguestfs always adds a few of its own).");
452 ("get_append", (RConstString "append", []), -1, [],
454 "get the additional kernel options",
456 Return the additional kernel options which are added to the
457 guest kernel command line.
459 If C<NULL> then no options are added.");
461 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
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).
470 This is disabled by default (except in guestfish where it is
471 enabled by default).");
473 ("get_autosync", (RBool "autosync", []), -1, [],
477 Get the autosync flag.");
479 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
483 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
485 Verbose messages are disabled unless the environment variable
486 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
488 ("get_verbose", (RBool "verbose", []), -1, [],
492 This returns the verbose messages flag.");
494 ("is_ready", (RBool "ready", []), -1, [],
496 "is ready to accept commands",
498 This returns true iff this handle is ready to accept commands
499 (in the C<READY> state).
501 For more information on states, see L<guestfs(3)>.");
503 ("is_config", (RBool "config", []), -1, [],
505 "is in configuration state",
507 This returns true iff this handle is being configured
508 (in the C<CONFIG> state).
510 For more information on states, see L<guestfs(3)>.");
512 ("is_launching", (RBool "launching", []), -1, [],
514 "is launching subprocess",
516 This returns true iff this handle is launching the subprocess
517 (in the C<LAUNCHING> state).
519 For more information on states, see L<guestfs(3)>.");
521 ("is_busy", (RBool "busy", []), -1, [],
523 "is busy processing a command",
525 This returns true iff this handle is busy processing a command
526 (in the C<BUSY> state).
528 For more information on states, see L<guestfs(3)>.");
530 ("get_state", (RInt "state", []), -1, [],
532 "get the current state",
534 This returns the current state as an opaque integer. This is
535 only useful for printing debug and internal error messages.
537 For more information on states, see L<guestfs(3)>.");
539 ("set_busy", (RErr, []), -1, [NotInFish],
543 This sets the state to C<BUSY>. This is only used when implementing
544 actions using the low-level API.
546 For more information on states, see L<guestfs(3)>.");
548 ("set_ready", (RErr, []), -1, [NotInFish],
550 "set state to ready",
552 This sets the state to C<READY>. This is only used when implementing
553 actions using the low-level API.
555 For more information on states, see L<guestfs(3)>.");
557 ("end_busy", (RErr, []), -1, [NotInFish],
559 "leave the busy state",
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.
565 For more information on states, see L<guestfs(3)>.");
569 (* daemon_functions are any functions which cause some action
570 * to take place in the daemon.
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",
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
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
594 The mounted filesystem is writable, if we have sufficient permissions
595 on the underlying device.
597 The filesystem options C<sync> and C<noatime> are set with this
598 call, in order to improve reliability.");
600 ("sync", (RErr, []), 2, [],
601 [ InitEmpty, Always, TestRun [["sync"]]],
602 "sync disks, writes are flushed through to the disk image",
604 This syncs the disk, so that any writes are flushed through to the
605 underlying disk image.
607 You should always call this if you have modified a disk image, before
608 closing the handle.");
610 ("touch", (RErr, [String "path"]), 3, [],
611 [InitBasicFS, Always, TestOutputTrue (
613 ["exists"; "/new"]])],
614 "update file timestamps or create a new file",
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.");
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",
626 Return the contents of the file named C<path>.
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.");
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.
637 "list the files in a directory (long format)",
639 List the files in C<directory> (relative to the root directory,
640 there is no cwd) in the format of 'ls -la'.
642 This command is mostly useful for interactive sessions. It
643 is I<not> intended that you try to parse the output string.");
645 ("ls", (RStringList "listing", [String "directory"]), 6, [],
646 [InitBasicFS, Always, TestOutputList (
649 ["touch"; "/newest"];
650 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
651 "list the files in a directory",
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.
657 This command is mostly useful for interactive sessions. Programs
658 should probably use C<guestfs_readdir> instead.");
660 ("list_devices", (RStringList "devices", []), 7, [],
661 [InitEmpty, Always, TestOutputList (
662 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"])],
663 "list the block devices",
665 List all the block devices.
667 The full block device names are returned, eg. C</dev/sda>");
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",
677 List all the partitions detected on all block devices.
679 The full partition device names are returned, eg. C</dev/sda1>
681 This does not return logical volumes. For that you will need to
682 call C<guestfs_lvs>.");
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)",
695 List all the physical volumes detected. This is the equivalent
696 of the L<pvs(8)> command.
698 This returns a list of just the device names that contain
699 PVs (eg. C</dev/sda2>).
701 See also C<guestfs_pvs_full>.");
703 ("vgs", (RStringList "volgroups", []), 10, [],
704 [InitBasicFSonLVM, Always, TestOutputList (
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)",
716 List all the volumes groups detected. This is the equivalent
717 of the L<vgs(8)> command.
719 This returns a list of just the volume group names that were
720 detected (eg. C<VolGroup00>).
722 See also C<guestfs_vgs_full>.");
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)",
740 List all the logical volumes detected. This is the equivalent
741 of the L<lvs(8)> command.
743 This returns a list of the logical volume device names
744 (eg. C</dev/VolGroup00/LogVol00>).
746 See also C<guestfs_lvs_full>.");
748 ("pvs_full", (RPVList "physvols", []), 12, [],
749 [], (* XXX how to test? *)
750 "list the LVM physical volumes (PVs)",
752 List all the physical volumes detected. This is the equivalent
753 of the L<pvs(8)> command. The \"full\" version includes all fields.");
755 ("vgs_full", (RVGList "volgroups", []), 13, [],
756 [], (* XXX how to test? *)
757 "list the LVM volume groups (VGs)",
759 List all the volumes groups detected. This is the equivalent
760 of the L<vgs(8)> command. The \"full\" version includes all fields.");
762 ("lvs_full", (RLVList "logvols", []), 14, [],
763 [], (* XXX how to test? *)
764 "list the LVM logical volumes (LVs)",
766 List all the logical volumes detected. This is the equivalent
767 of the L<lvs(8)> command. The \"full\" version includes all fields.");
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",
778 Return the contents of the file named C<path>.
780 The file contents are returned as a list of lines. Trailing
781 C<LF> and C<CRLF> character sequences are I<not> returned.
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.");
788 ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
789 [], (* XXX Augeas code needs tests. *)
790 "create a new Augeas handle",
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.
796 You must call this before using any other C<guestfs_aug_*>
799 C<root> is the filesystem root. C<root> must not be NULL,
802 The flags are the same as the flags defined in
803 E<lt>augeas.hE<gt>, the logical I<or> of the following
808 =item C<AUG_SAVE_BACKUP> = 1
810 Keep the original file with a C<.augsave> extension.
812 =item C<AUG_SAVE_NEWFILE> = 2
814 Save changes into a file with extension C<.augnew>, and
815 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
817 =item C<AUG_TYPE_CHECK> = 4
819 Typecheck lenses (can be expensive).
821 =item C<AUG_NO_STDINC> = 8
823 Do not use standard load path for modules.
825 =item C<AUG_SAVE_NOOP> = 16
827 Make save a no-op, just record what would have been changed.
829 =item C<AUG_NO_LOAD> = 32
831 Do not load the tree in C<guestfs_aug_init>.
835 To close the handle, you can call C<guestfs_aug_close>.
837 To find out more about Augeas, see L<http://augeas.net/>.");
839 ("aug_close", (RErr, []), 26, [],
840 [], (* XXX Augeas code needs tests. *)
841 "close the current Augeas handle",
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
848 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
849 [], (* XXX Augeas code needs tests. *)
850 "define an Augeas variable",
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
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.");
859 ("aug_defnode", (RIntBool ("nrnodes", "created"), [String "name"; String "expr"; String "val"]), 18, [],
860 [], (* XXX Augeas code needs tests. *)
861 "define an Augeas node",
863 Defines a variable C<name> whose value is the result of
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.
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.");
874 ("aug_get", (RString "val", [String "path"]), 19, [],
875 [], (* XXX Augeas code needs tests. *)
876 "look up the value of an Augeas path",
878 Look up the value associated with C<path>. If C<path>
879 matches exactly one node, the C<value> is returned.");
881 ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
882 [], (* XXX Augeas code needs tests. *)
883 "set Augeas path to value",
885 Set the value associated with C<path> to C<value>.");
887 ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
888 [], (* XXX Augeas code needs tests. *)
889 "insert a sibling Augeas node",
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
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]>.");
899 ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
900 [], (* XXX Augeas code needs tests. *)
901 "remove an Augeas path",
903 Remove C<path> and all of its children.
905 On success this returns the number of entries which were removed.");
907 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
908 [], (* XXX Augeas code needs tests. *)
911 Move the node C<src> to C<dest>. C<src> must match exactly
912 one node. C<dest> is overwritten if it exists.");
914 ("aug_match", (RStringList "matches", [String "path"]), 24, [],
915 [], (* XXX Augeas code needs tests. *)
916 "return Augeas nodes which match path",
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.");
922 ("aug_save", (RErr, []), 25, [],
923 [], (* XXX Augeas code needs tests. *)
924 "write all pending Augeas changes to disk",
926 This writes all pending changes to disk.
928 The flags which were passed to C<guestfs_aug_init> affect exactly
929 how files are saved.");
931 ("aug_load", (RErr, []), 27, [],
932 [], (* XXX Augeas code needs tests. *)
933 "load files into the tree",
935 Load files into the tree.
937 See C<aug_load> in the Augeas documentation for the full gory
940 ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
941 [], (* XXX Augeas code needs tests. *)
942 "list Augeas nodes under a path",
944 This is just a shortcut for listing C<guestfs_aug_match>
945 C<path/*> and sorting the resulting nodes into alphabetical order.");
947 ("rm", (RErr, [String "path"]), 29, [],
948 [InitBasicFS, Always, TestRun
951 InitBasicFS, Always, TestLastFail
953 InitBasicFS, Always, TestLastFail
958 Remove the single file C<path>.");
960 ("rmdir", (RErr, [String "path"]), 30, [],
961 [InitBasicFS, Always, TestRun
964 InitBasicFS, Always, TestLastFail
966 InitBasicFS, Always, TestLastFail
969 "remove a directory",
971 Remove the single directory C<path>.");
973 ("rm_rf", (RErr, [String "path"]), 31, [],
974 [InitBasicFS, Always, TestOutputFalse
976 ["mkdir"; "/new/foo"];
977 ["touch"; "/new/foo/bar"];
979 ["exists"; "/new"]]],
980 "remove a file or directory recursively",
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
986 ("mkdir", (RErr, [String "path"]), 32, [],
987 [InitBasicFS, Always, TestOutputTrue
990 InitBasicFS, Always, TestLastFail
991 [["mkdir"; "/new/foo/bar"]]],
992 "create a directory",
994 Create a directory named C<path>.");
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",
1008 Create a directory named C<path>, creating any parent directories
1009 as necessary. This is like the C<mkdir -p> shell command.");
1011 ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1012 [], (* XXX Need stat command to test *)
1015 Change the mode (permissions) of C<path> to C<mode>. Only
1016 numeric modes are supported.");
1018 ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1019 [], (* XXX Need stat command to test *)
1020 "change file owner and group",
1022 Change the file owner to C<owner> and group to C<group>.
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).");
1028 ("exists", (RBool "existsflag", [String "path"]), 36, [],
1029 [InitBasicFS, Always, TestOutputTrue (
1031 ["exists"; "/new"]]);
1032 InitBasicFS, Always, TestOutputTrue (
1034 ["exists"; "/new"]])],
1035 "test if file or directory exists",
1037 This returns C<true> if and only if there is a file, directory
1038 (or anything) with the given C<path> name.
1040 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1042 ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1043 [InitBasicFS, Always, TestOutputTrue (
1045 ["is_file"; "/new"]]);
1046 InitBasicFS, Always, TestOutputFalse (
1048 ["is_file"; "/new"]])],
1049 "test if file exists",
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.
1055 See also C<guestfs_stat>.");
1057 ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1058 [InitBasicFS, Always, TestOutputFalse (
1060 ["is_dir"; "/new"]]);
1061 InitBasicFS, Always, TestOutputTrue (
1063 ["is_dir"; "/new"]])],
1064 "test if file exists",
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.
1070 See also C<guestfs_stat>.");
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",
1081 This creates an LVM physical volume on the named C<device>,
1082 where C<device> should usually be a partition name such
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",
1096 This creates an LVM volume group called C<volgroup>
1097 from the non-empty list of physical volumes C<physvols>.");
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"];
1113 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1114 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1115 "create an LVM volume group",
1117 This creates an LVM volume group called C<logvol>
1118 on the volume group C<volgroup>, with C<size> megabytes.");
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",
1129 This creates a filesystem on C<device> (usually a partition
1130 or LVM logical volume). The filesystem type is C<fstype>, for
1133 ("sfdisk", (RErr, [String "device";
1134 Int "cyls"; Int "heads"; Int "sectors";
1135 StringList "lines"]), 43, [DangerWillRobinson],
1137 "create partitions on a block device",
1139 This is a direct interface to the L<sfdisk(8)> program for creating
1140 partitions on block devices.
1142 C<device> should be a block device, for example C</dev/sda>.
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.
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.
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).
1159 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
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")],
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>.
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).
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>.");
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"; "/"];
1207 "unmount a filesystem",
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.");
1213 ("mounts", (RStringList "devices", []), 46, [],
1214 [InitBasicFS, Always, TestOutputList (
1215 [["mounts"]], ["/dev/sda1"])],
1216 "show mounted filesystems",
1218 This returns the list of currently mounted filesystems. It returns
1219 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1221 Some internal mounts are not shown.");
1223 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1224 [InitBasicFS, Always, TestOutputList (
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"; "/"];
1235 ["mount"; "/dev/sda2"; "/mp1"];
1236 ["mkdir"; "/mp1/mp2"];
1237 ["mount"; "/dev/sda3"; "/mp1/mp2"];
1238 ["mkdir"; "/mp1/mp2/mp3"];
1241 "unmount all filesystems",
1243 This unmounts all mounted filesystems.
1245 Some internal mounts are not unmounted by this call.");
1247 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1249 "remove all LVM LVs, VGs and PVs",
1251 This command removes all LVM logical volumes, volume groups
1252 and physical volumes.");
1254 ("file", (RString "description", [String "path"]), 49, [],
1255 [InitBasicFS, Always, TestOutput (
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",
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.
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).");
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",
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).
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).
1334 The return value is anything printed to I<stdout> by
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.
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
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
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",
1399 This is the same as C<guestfs_command>, but splits the
1400 result into a list of lines.");
1402 ("stat", (RStat "statbuf", [String "path"]), 52, [],
1403 [InitBasicFS, Always, TestOutputStruct (
1405 ["stat"; "/new"]], [CompareWithInt ("size", 0)])],
1406 "get file information",
1408 Returns file information for the given C<path>.
1410 This is the same as the C<stat(2)> system call.");
1412 ("lstat", (RStat "statbuf", [String "path"]), 53, [],
1413 [InitBasicFS, Always, TestOutputStruct (
1415 ["lstat"; "/new"]], [CompareWithInt ("size", 0)])],
1416 "get file information for a symbolic link",
1418 Returns file information for the given C<path>.
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
1424 This is the same as the C<lstat(2)> system call.");
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",
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).
1437 This is the same as the C<statvfs(2)> system call.");
1439 ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1441 "get ext2/ext3/ext4 superblock details",
1443 This returns the contents of the ext2, ext3 or ext4 filesystem
1444 superblock on C<device>.
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.");
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",
1457 Sets the block device named C<device> to read-only.
1459 This uses the L<blockdev(8)> command.");
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",
1467 Sets the block device named C<device> to read-write.
1469 This uses the L<blockdev(8)> command.");
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",
1477 Returns a boolean indicating if the block device is read-only
1478 (true if read-only, false if not).
1480 This uses the L<blockdev(8)> command.");
1482 ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1483 [InitEmpty, Always, TestOutputInt (
1484 [["blockdev_getss"; "/dev/sda"]], 512)],
1485 "get sectorsize of block device",
1487 This returns the size of sectors on a block device.
1488 Usually 512, but can be larger for modern devices.
1490 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1493 This uses the L<blockdev(8)> command.");
1495 ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1496 [InitEmpty, Always, TestOutputInt (
1497 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1498 "get blocksize of block device",
1500 This returns the block size of a device.
1502 (Note this is different from both I<size in blocks> and
1503 I<filesystem block size>).
1505 This uses the L<blockdev(8)> command.");
1507 ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1509 "set blocksize of block device",
1511 This sets the block size of a device.
1513 (Note this is different from both I<size in blocks> and
1514 I<filesystem block size>).
1516 This uses the L<blockdev(8)> command.");
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",
1523 This returns the size of the device in units of 512-byte sectors
1524 (even if the sectorsize isn't 512 bytes ... weird).
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>.
1530 This uses the L<blockdev(8)> command.");
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",
1537 This returns the size of the device in bytes.
1539 See also C<guestfs_blockdev_getsz>.
1541 This uses the L<blockdev(8)> command.");
1543 ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1544 [InitEmpty, Always, TestRun
1545 [["blockdev_flushbufs"; "/dev/sda"]]],
1546 "flush device buffers",
1548 This tells the kernel to flush internal buffers associated
1551 This uses the L<blockdev(8)> command.");
1553 ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1554 [InitEmpty, Always, TestRun
1555 [["blockdev_rereadpt"; "/dev/sda"]]],
1556 "reread partition table",
1558 Reread the partition table on C<device>.
1560 This uses the L<blockdev(8)> command.");
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",
1569 Upload local file C<filename> to C<remotefilename> on the
1572 C<filename> can also be a named pipe.
1574 See also C<guestfs_download>.");
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",
1585 Download file C<remotefilename> and save it as C<filename>
1586 on the local machine.
1588 C<filename> can also be a named pipe.
1590 See also C<guestfs_upload>, C<guestfs_cat>.");
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",
1618 This call computes the MD5, SHAx or CRC checksum of the
1621 The type of checksum to compute is given by the C<csumtype>
1622 parameter which must have one of the following values:
1628 Compute the cyclic redundancy check (CRC) specified by POSIX
1629 for the C<cksum> command.
1633 Compute the MD5 hash (using the C<md5sum> program).
1637 Compute the SHA1 hash (using the C<sha1sum> program).
1641 Compute the SHA224 hash (using the C<sha224sum> program).
1645 Compute the SHA256 hash (using the C<sha256sum> program).
1649 Compute the SHA384 hash (using the C<sha384sum> program).
1653 Compute the SHA512 hash (using the C<sha512sum> program).
1657 The checksum is returned as a printable string.");
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",
1665 This command uploads and unpacks local file C<tarfile> (an
1666 I<uncompressed> tar file) into C<directory>.
1668 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1670 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1672 "pack directory into tarfile",
1674 This command packs the contents of C<directory> and downloads
1675 it to local file C<tarfile>.
1677 To download a compressed tarball, use C<guestfs_tgz_out>.");
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",
1685 This command uploads and unpacks local file C<tarball> (a
1686 I<gzip compressed> tar file) into C<directory>.
1688 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1690 ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1692 "pack directory into compressed tarball",
1694 This command packs the contents of C<directory> and downloads
1695 it to local file C<tarball>.
1697 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1699 ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1700 [InitBasicFS, Always, TestLastFail (
1702 ["mount_ro"; "/dev/sda1"; "/"];
1703 ["touch"; "/new"]]);
1704 InitBasicFS, Always, TestOutput (
1705 [["write_file"; "/new"; "data"; "0"];
1707 ["mount_ro"; "/dev/sda1"; "/"];
1708 ["cat"; "/new"]], "data")],
1709 "mount a guest disk, read-only",
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.");
1714 ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1716 "mount a guest disk with mount options",
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.");
1722 ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1724 "mount a guest disk with mount options and vfstype",
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.");
1730 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1732 "debugging and internals",
1734 The C<guestfs_debug> command exposes some internals of
1735 C<guestfsd> (the guestfs daemon) that runs inside the
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.");
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"];
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"];
1767 "remove an LVM logical volume",
1769 Remove an LVM logical volume C<device>, where C<device> is
1770 the path to the LV, such as C</dev/VG/LV>.
1772 You can also remove all LVs in a volume group by specifying
1773 the VG name, C</dev/VG>.");
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"];
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"];
1792 "remove an LVM volume group",
1794 Remove an LVM volume group C<vgname>, (for example C<VG>).
1796 This also forcibly removes all logical volumes in the volume
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"];
1807 ["pvremove"; "/dev/sda1"];
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"];
1816 ["pvremove"; "/dev/sda1"];
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"];
1825 ["pvremove"; "/dev/sda1"];
1827 "remove an LVM physical volume",
1829 This wipes a physical volume C<device> so that LVM will no longer
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.");
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",
1842 This sets the ext2/3/4 filesystem label of the filesystem on
1843 C<device> to C<label>. Filesystem labels are limited to
1846 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
1847 to return the existing label on a filesystem.");
1849 ("get_e2label", (RString "label", [String "device"]), 81, [],
1851 "get the ext2/3/4 filesystem label",
1853 This returns the ext2/3/4 filesystem label of the filesystem on
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",
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.
1875 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
1876 to return the existing UUID of a filesystem.");
1878 ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
1880 "get the ext2/3/4 filesystem UUID",
1882 This returns the ext2/3/4 filesystem UUID of the filesystem on
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",
1895 This runs the filesystem checker (fsck) on C<device> which
1896 should have filesystem type C<fstype>.
1898 The returned integer is the status. See L<fsck(8)> for the
1899 list of status codes from C<fsck>.
1907 Multiple status codes can be summed together.
1911 A non-zero return code can mean \"success\", for example if
1912 errors have been corrected on the filesystem.
1916 Checking or repairing NTFS volumes is not supported
1921 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
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",
1930 This command writes zeroes over the first few blocks of C<device>.
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.");
1936 ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
1937 [InitBasicFS, Always, TestOutputTrue (
1938 [["grub_install"; "/"; "/dev/sda1"];
1939 ["is_dir"; "/boot"]])],
1942 This command installs GRUB (the Grand Unified Bootloader) on
1943 C<device>, with the root directory being C<root>.");
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"];
1957 ["cp"; "/old"; "/dir/new"];
1958 ["cat"; "/dir/new"]], "file content")],
1961 This copies a file from C<src> to C<dest> where C<dest> is
1962 either a destination filename or destination directory.");
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",
1973 This copies a file or directory from C<src> to C<dest>
1974 recursively using the C<cp -a> command.");
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"]])],
1987 This moves a file from C<src> to C<dest> where C<dest> is
1988 either a destination filename or destination directory.");
1990 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
1991 [InitEmpty, Always, TestRun (
1992 [["drop_caches"; "3"]])],
1993 "drop kernel page cache, dentries and inodes",
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>
2000 Setting C<whattodrop> to 3 should drop everything.
2002 This automatically calls L<sync(2)> before the operation,
2003 so that the maximum guest memory is freed.");
2005 ("dmesg", (RString "kmsgs", []), 91, [],
2006 [InitEmpty, Always, TestRun (
2008 "return kernel messages",
2010 This returns the kernel messages (C<dmesg> output) from
2011 the guest kernel. This is sometimes useful for extended
2012 debugging of problems.
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.");
2019 ("ping_daemon", (RErr, []), 92, [],
2020 [InitEmpty, Always, TestRun (
2021 [["ping_daemon"]])],
2022 "ping the guest daemon",
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.");
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",
2042 This compares the two files C<file1> and C<file2> and returns
2043 true if their content is exactly equal, or false otherwise.
2045 The external L<cmp(1)> program is used for the comparison.");
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 (
2053 ["strings"; "/new"]], [])],
2054 "print the printable strings in a file",
2056 This runs the L<strings(1)> command on a file and returns
2057 the list of printable strings found.");
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",
2068 This is like the C<guestfs_strings> command, but allows you to
2069 specify the encoding.
2071 See the L<strings(1)> manpage for the full list of encodings.
2073 Commonly useful encodings are C<l> (lower case L) which will
2074 show strings inside Windows/x86 files.
2076 The returned strings are transcoded to UTF-8.");
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",
2084 This runs C<hexdump -C> on the given C<path>. The result is
2085 the human-readable, canonical hex dump of the file.");
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",
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
2104 You should B<not> run this program if the filesystem is
2107 It is possible that using this program can damage the filesystem
2108 or data on the filesystem.");
2110 ("pvresize", (RErr, [String "device"]), 98, [],
2112 "resize an LVM physical volume",
2114 This resizes (expands or shrinks) an existing LVM physical
2115 volume to match the new size of the underlying device.");
2117 ("sfdisk_N", (RErr, [String "device"; Int "n";
2118 Int "cyls"; Int "heads"; Int "sectors";
2119 String "line"]), 99, [DangerWillRobinson],
2121 "modify a single partition on a block device",
2123 This runs L<sfdisk(8)> option to modify just the single
2124 partition C<n> (note: C<n> counts from 1).
2126 For other parameters, see C<guestfs_sfdisk>. You should usually
2127 pass C<0> for the cyls/heads/sectors parameters.");
2129 ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2131 "display the partition table",
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.");
2137 ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2139 "display the kernel geometry",
2141 This displays the kernel's idea of the geometry of C<device>.
2143 The result is in human-readable format, and not designed to
2146 ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2148 "display the disk geometry from the partition table",
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>).
2155 The result is in human-readable format, and not designed to
2158 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2160 "activate or deactivate all volume groups",
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.
2168 This command is the same as running C<vgchange -a y|n>");
2170 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2172 "activate or deactivate some volume groups",
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.
2180 This command is the same as running C<vgchange -a y|n volgroups...>
2182 Note that if C<volgroups> is an empty list then B<all> volume groups
2183 are activated or deactivated.");
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"];
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",
2202 This resizes (expands or shrinks) an existing LVM logical
2203 volume to C<mbytes>. When reducing, data in the reduced part
2206 ("resize2fs", (RErr, [String "device"]), 106, [],
2207 [], (* lvresize tests this *)
2208 "resize an ext2/ext3 filesystem",
2210 This resizes an ext2 or ext3 filesystem to match the size of
2211 the underlying device.
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.");
2219 ("find", (RStringList "names", [String "directory"]), 107, [],
2220 [InitBasicFS, Always, TestOutputList (
2221 [["find"; "/"]], ["lost+found"]);
2222 InitBasicFS, Always, TestOutputList (
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",
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.
2238 This returns a list of strings I<without any prefix>. Thus
2239 if the directory structure was:
2245 then the returned list from C<guestfs_find> C</tmp> would be
2253 If C<directory> is not a directory, then this command returns
2256 The returned list is sorted.");
2258 ("e2fsck_f", (RErr, [String "device"]), 108, [],
2259 [], (* lvresize tests this *)
2260 "check an ext2/ext3 filesystem",
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>).
2266 This command is only needed because of C<guestfs_resize2fs>
2267 (q.v.). Normally you should use C<guestfs_fsck>.");
2271 let all_functions = non_daemon_functions @ daemon_functions
2273 (* In some places we want the functions to be displayed sorted
2274 * alphabetically, so this is useful:
2276 let all_functions_sorted =
2277 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
2278 compare n1 n2) all_functions
2280 (* Column names and types from LVM PVs/VGs/LVs. *)
2289 "pv_attr", `String (* XXX *);
2290 "pv_pe_count", `Int;
2291 "pv_pe_alloc_count", `Int;
2294 "pv_mda_count", `Int;
2295 "pv_mda_free", `Bytes;
2296 (* Not in Fedora 10:
2297 "pv_mda_size", `Bytes;
2304 "vg_attr", `String (* XXX *);
2307 "vg_sysid", `String;
2308 "vg_extent_size", `Bytes;
2309 "vg_extent_count", `Int;
2310 "vg_free_count", `Int;
2318 "vg_mda_count", `Int;
2319 "vg_mda_free", `Bytes;
2320 (* Not in Fedora 10:
2321 "vg_mda_size", `Bytes;
2327 "lv_attr", `String (* XXX *);
2330 "lv_kernel_major", `Int;
2331 "lv_kernel_minor", `Int;
2335 "snap_percent", `OptPercent;
2336 "copy_percent", `OptPercent;
2339 "mirror_log", `String;
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.
2362 let statvfs_cols = [
2376 (* Used for testing language bindings. *)
2378 | CallString of string
2379 | CallOptString of string option
2380 | CallStringList of string list
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.
2388 let failwithf fs = ksprintf failwith fs
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;
2399 if not !r then s else s2
2403 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
2405 let triml ?(test = isspace) str =
2407 let n = ref (String.length str) in
2408 while !n > 0 && test str.[!i]; do
2413 else String.sub str !i !n
2415 let trimr ?(test = isspace) str =
2416 let n = ref (String.length str) in
2417 while !n > 0 && test str.[!n-1]; do
2420 if !n = String.length str then str
2421 else String.sub str 0 !n
2423 let trim ?(test = isspace) str =
2424 trimr ~test (triml ~test str)
2426 let rec find s sub =
2427 let len = String.length s in
2428 let sublen = String.length sub in
2430 if i <= len-sublen then (
2432 if j < sublen then (
2433 if s.[i+j] = sub.[j] then loop2 (j+1)
2439 if r = -1 then loop (i+1) else r
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
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
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]
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''
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
2472 | i -> failwithf "%s: failed with error code %d" cmd i
2474 let rec find_map f = function
2475 | [] -> raise Not_found
2479 | None -> find_map f xs
2482 let rec loop i = function
2484 | x :: xs -> f i x; loop (i+1) xs
2489 let rec loop i = function
2491 | x :: xs -> let r = f i x in r :: loop (i+1) xs
2495 let name_of_argt = function
2496 | String n | OptString n | StringList n | Bool n | Int n
2497 | FileIn n | FileOut n -> n
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
2505 (* Check function names etc. for consistency. *)
2506 let check_functions () =
2507 let contains_uppercase str =
2508 let len = String.length str in
2510 if i >= len then false
2513 if c >= 'A' && c <= 'Z' then true
2520 (* Check function names. *)
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;
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."
2534 (* Check function parameter/return names. *)
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"
2541 if String.contains n '-' || String.contains n '_' then
2542 failwithf "%s param/ret %s should not contain '-' or '_'"
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;
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
2554 (match fst style with
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
2560 check_arg_ret_name n
2562 check_arg_ret_name n;
2563 check_arg_ret_name m
2565 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
2568 (* Check short descriptions. *)
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
2578 (* Check long dscriptions. *)
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
2585 (* Check proc_nrs. *)
2587 fun (name, _, proc_nr, _, _, _, _) ->
2588 if proc_nr <= 0 then
2589 failwithf "daemon function %s should have proc_nr > 0" name
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;
2599 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
2602 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
2603 let rec loop = function
2606 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
2608 | (name1,nr1) :: (name2,nr2) :: _ ->
2609 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
2617 (* Ignore functions that have no tests. We generate a
2618 * warning when the user does 'make check' instead.
2620 | name, _, _, _, [], _, _ -> ()
2621 | name, _, _, _, tests, _, _ ->
2625 match seq_of_test test with
2627 failwithf "%s has a test containing an empty sequence" name
2628 | cmds -> List.map List.hd cmds
2630 let funcs = List.flatten funcs in
2632 let tested = List.mem name funcs in
2635 failwithf "function %s has tests but does not test itself" name
2638 (* 'pr' prints to the current output file. *)
2639 let chan = ref stdout
2640 let pr fs = ksprintf (output_string !chan) fs
2642 (* Generate a header block in a number of standard styles. *)
2643 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
2644 type license = GPLv2 | LGPLv2
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;
2656 pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
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;
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;
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;
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;
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;
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;
2690 | CStyle -> pr " */\n"
2692 | OCamlStyle -> pr " *)\n"
2693 | HaskellStyle -> pr "-}\n"
2697 (* Start of main code generation functions below this line. *)
2699 (* Generate the pod documentation for the C API. *)
2700 let rec generate_actions_pod () =
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;
2707 generate_prototype ~extern:false ~handle:"handle" name style;
2709 pr "%s\n\n" longdesc;
2710 (match fst style with
2712 pr "This function returns 0 on success or -1 on error.\n\n"
2714 pr "On error this function returns -1.\n\n"
2716 pr "On error this function returns -1.\n\n"
2718 pr "This function returns a C truth value on success or -1 on error.\n\n"
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"
2723 pr "This function returns a string, or NULL on error.
2724 I<The caller must free the returned string after use>.\n\n"
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"
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"
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"
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"
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"
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"
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"
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"
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
2770 ) all_functions_sorted
2772 and generate_structs_pod () =
2773 (* LVM structs documentation. *)
2776 pr "=head2 guestfs_lvm_%s\n" typ;
2778 pr " struct guestfs_lvm_%s {\n" typ;
2781 | name, `String -> pr " char *%s;\n" name
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
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;
2797 pr " void guestfs_free_lvm_%s_list (struct guestfs_free_lvm_%s_list *);\n"
2800 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
2802 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
2803 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
2805 * We have to use an underscore instead of a dash because otherwise
2806 * rpcgen generates incorrect code.
2808 * This header is NOT exported to clients, but see also generate_structs_h.
2810 and generate_xdr () =
2811 generate_header CStyle LGPLv2;
2813 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
2814 pr "typedef string str<>;\n";
2817 (* LVM internal structures. *)
2821 pr "struct guestfs_lvm_int_%s {\n" typ;
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
2831 pr "typedef struct guestfs_lvm_int_%s guestfs_lvm_int_%s_list<>;\n" typ typ;
2833 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
2835 (* Stat internal structures. *)
2839 pr "struct guestfs_int_%s {\n" typ;
2841 | name, `Int -> pr " hyper %s;\n" name
2845 ) ["stat", stat_cols; "statvfs", statvfs_cols];
2848 fun (shortname, style, _, _, _, _, _) ->
2849 let name = "guestfs_" ^ shortname in
2851 (match snd style with
2854 pr "struct %s_args {\n" name;
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 _ -> ()
2866 (match fst style with
2869 pr "struct %s_ret {\n" name;
2873 pr "struct %s_ret {\n" name;
2874 pr " hyper %s;\n" n;
2877 pr "struct %s_ret {\n" name;
2881 failwithf "RConstString cannot be returned from a daemon function"
2883 pr "struct %s_ret {\n" name;
2884 pr " string %s<>;\n" n;
2887 pr "struct %s_ret {\n" name;
2888 pr " str %s<>;\n" n;
2891 pr "struct %s_ret {\n" name;
2896 pr "struct %s_ret {\n" name;
2897 pr " guestfs_lvm_int_pv_list %s;\n" n;
2900 pr "struct %s_ret {\n" name;
2901 pr " guestfs_lvm_int_vg_list %s;\n" n;
2904 pr "struct %s_ret {\n" name;
2905 pr " guestfs_lvm_int_lv_list %s;\n" n;
2908 pr "struct %s_ret {\n" name;
2909 pr " guestfs_int_stat %s;\n" n;
2912 pr "struct %s_ret {\n" name;
2913 pr " guestfs_int_statvfs %s;\n" n;
2916 pr "struct %s_ret {\n" name;
2917 pr " str %s<>;\n" n;
2922 (* Table of procedure numbers. *)
2923 pr "enum guestfs_procedure {\n";
2925 fun (shortname, _, proc_nr, _, _, _, _) ->
2926 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
2928 pr " GUESTFS_PROC_NR_PROCS\n";
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.
2938 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
2941 (* Message header, etc. *)
2943 /* The communication protocol is now documented in the guestfs(3)
2947 const GUESTFS_PROGRAM = 0x2000F5F5;
2948 const GUESTFS_PROTOCOL_VERSION = 1;
2950 /* These constants must be larger than any possible message length. */
2951 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
2952 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
2954 enum guestfs_message_direction {
2955 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
2956 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
2959 enum guestfs_message_status {
2960 GUESTFS_STATUS_OK = 0,
2961 GUESTFS_STATUS_ERROR = 1
2964 const GUESTFS_ERROR_LEN = 256;
2966 struct guestfs_message_error {
2967 string error_message<GUESTFS_ERROR_LEN>;
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;
2979 const GUESTFS_MAX_CHUNK_SIZE = 8192;
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>;
2988 (* Generate the guestfs-structs.h file. *)
2989 and generate_structs_h () =
2990 generate_header CStyle LGPLv2;
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).
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.
3006 (* guestfs_int_bool structure. *)
3007 pr "struct guestfs_int_bool {\n";
3013 (* LVM public structures. *)
3017 pr "struct guestfs_lvm_%s {\n" typ;
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
3028 pr "struct guestfs_lvm_%s_list {\n" typ;
3029 pr " uint32_t len;\n";
3030 pr " struct guestfs_lvm_%s *val;\n" typ;
3033 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
3035 (* Stat structures. *)
3039 pr "struct guestfs_%s {\n" typ;
3042 | name, `Int -> pr " int64_t %s;\n" name
3046 ) ["stat", stat_cols; "statvfs", statvfs_cols]
3048 (* Generate the guestfs-actions.h file. *)
3049 and generate_actions_h () =
3050 generate_header CStyle LGPLv2;
3052 fun (shortname, style, _, _, _, _, _) ->
3053 let name = "guestfs_" ^ shortname in
3054 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3058 (* Generate the client-side dispatch stubs. *)
3059 and generate_client_actions () =
3060 generate_header CStyle LGPLv2;
3066 #include \"guestfs.h\"
3067 #include \"guestfs_protocol.h\"
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
3076 /* Check the return message from a call for validity. */
3078 check_reply_header (guestfs_h *g,
3079 const struct guestfs_message_header *hdr,
3080 int proc_nr, int serial)
3082 if (hdr->prog != GUESTFS_PROGRAM) {
3083 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3086 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3087 error (g, \"wrong protocol version (%%d/%%d)\",
3088 hdr->vers, GUESTFS_PROTOCOL_VERSION);
3091 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3092 error (g, \"unexpected message direction (%%d/%%d)\",
3093 hdr->direction, GUESTFS_DIRECTION_REPLY);
3096 if (hdr->proc != proc_nr) {
3097 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3100 if (hdr->serial != serial) {
3101 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3108 /* Check we are in the right state to run a high-level action. */
3110 check_state (guestfs_h *g, const char *caller)
3112 if (!guestfs_is_ready (g)) {
3113 if (guestfs_is_config (g))
3114 error (g, \"%%s: call launch() before using this function\",
3116 else if (guestfs_is_launching (g))
3117 error (g, \"%%s: call wait_ready() before using this function\",
3120 error (g, \"%%s called from the wrong state, %%d != READY\",
3121 caller, guestfs_get_state (g));
3129 (* Client-side stubs for each function. *)
3131 fun (shortname, style, _, _, _, _, _) ->
3132 let name = "guestfs_" ^ shortname in
3134 (* Generate the context struct which stores the high-level
3135 * state between callback functions.
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";
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
3148 failwithf "RConstString cannot be returned from a daemon function"
3150 | RBool _ | RString _ | RStringList _
3152 | RPVList _ | RVGList _ | RLVList _
3153 | RStat _ | RStatVFS _
3155 pr " struct %s_ret ret;\n" name
3160 (* Generate the reply callback function. *)
3161 pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
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;
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;
3173 pr " ml->main_loop_quit (ml, g);\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;
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"
3188 (match fst style with
3191 failwithf "RConstString cannot be returned from a daemon function"
3193 | RBool _ | RString _ | RStringList _
3195 | RPVList _ | RVGList _ | RLVList _
3196 | RStat _ | RStatVFS _
3198 pr " if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
3199 pr " error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
3205 pr " ctx->cb_sequence = 1;\n";
3208 (* Generate the action stub. *)
3209 generate_prototype ~extern:false ~semicolon:false ~newline:true
3210 ~handle:"g" name style;
3213 match fst style with
3214 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
3216 failwithf "RConstString cannot be returned from a daemon function"
3217 | RString _ | RStringList _ | RIntBool _
3218 | RPVList _ | RVGList _ | RLVList _
3219 | RStat _ | RStatVFS _
3225 (match snd style with
3227 | _ -> pr " struct %s_args args;\n" name
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";
3234 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
3235 pr " guestfs_set_busy (g);\n";
3237 pr " memset (&ctx, 0, sizeof ctx);\n";
3240 (* Send the main header and arguments. *)
3241 (match snd style with
3243 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
3244 (String.uppercase shortname)
3249 pr " args.%s = (char *) %s;\n" n n
3251 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n 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;
3256 pr " args.%s = %s;\n" n n
3258 pr " args.%s = %s;\n" n n
3259 | FileIn _ | FileOut _ -> ()
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"
3266 pr " if (serial == -1) {\n";
3267 pr " guestfs_end_busy (g);\n";
3268 pr " return %s;\n" error_code;
3272 (* Send any additional files (FileIn) requested. *)
3273 let need_read_reply_label = ref false in
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;
3285 pr " if (r == -2) /* daemon cancelled */\n";
3286 pr " goto read_reply;\n";
3287 need_read_reply_label := true;
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;
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;
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;
3322 (* Expecting to receive further files (FileOut)? *)
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;
3334 pr " guestfs_end_busy (g);\n";
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
3341 failwithf "RConstString cannot be returned from a daemon function"
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"
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
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
3364 (* Generate daemon/actions.h. *)
3365 and generate_daemon_actions_h () =
3366 generate_header CStyle GPLv2;
3368 pr "#include \"../src/guestfs_protocol.h\"\n";
3372 fun (name, style, _, _, _, _, _) ->
3374 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
3378 (* Generate the server-side stubs. *)
3379 and generate_daemon_actions () =
3380 generate_header CStyle GPLv2;
3382 pr "#include <config.h>\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";
3392 pr "#include \"daemon.h\"\n";
3393 pr "#include \"../src/guestfs_protocol.h\"\n";
3394 pr "#include \"actions.h\"\n";
3398 fun (name, style, _, _, _, _, _) ->
3399 (* Generate server-side stubs. *)
3400 pr "static void %s_stub (XDR *xdr_in)\n" name;
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"
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
3418 (match snd style with
3421 pr " struct guestfs_%s_args args;\n" name;
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 _ -> ()
3434 (match snd style with
3437 pr " memset (&args, 0, sizeof args);\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;
3445 | String n -> pr " %s = args.%s;\n" n n
3446 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n 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";
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 _ -> ()
3463 (* Don't want to call the impl with any FileIn or FileOut
3464 * parameters, since these go "outside" the RPC protocol.
3467 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
3469 pr " r = do_%s " name;
3470 generate_call_args argsnofile;
3473 pr " if (r == %s)\n" error_code;
3474 pr " /* do_%s has already called reply_with_error */\n" name;
3478 (* If there are any FileOut parameters, then the impl must
3479 * send its own reply.
3482 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
3484 pr " /* do_%s has already sent a reply */\n" name
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"
3494 failwithf "RConstString cannot be returned from a daemon function"
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"
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"
3507 pr " free_strings (r);\n"
3509 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) r);\n"
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"
3518 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
3522 (* Free the args. *)
3523 (match snd style with
3528 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
3535 (* Dispatch function. *)
3536 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
3538 pr " switch (proc_nr) {\n";
3541 fun (name, style, _, _, _, _, _) ->
3542 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
3543 pr " %s_stub (xdr_in);\n" name;
3548 pr " reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d\", proc_nr);\n";
3553 (* LVM columns and tokenization functions. *)
3554 (* XXX This generates crap code. We should rethink how we
3560 pr "static const char *lvm_%s_cols = \"%s\";\n"
3561 typ (String.concat "," (List.map fst cols));
3564 pr "static int lvm_tokenize_%s (char *str, struct guestfs_lvm_int_%s *r)\n" typ typ;
3566 pr " char *tok, *p, *next;\n";
3570 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
3573 pr " if (!str) {\n";
3574 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\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";
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;
3588 pr " p = strchrnul (tok, ',');\n";
3589 pr " if (*p) next = p+1; else next = NULL;\n";
3590 pr " *p = '\\0';\n";
3593 pr " r->%s = strdup (tok);\n" name;
3594 pr " if (r->%s == NULL) {\n" name;
3595 pr " perror (\"strdup\");\n";
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";
3603 pr " } else if (tok[j] != '-')\n";
3604 pr " r->%s[i++] = tok[j];\n" name;
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;
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;
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;
3624 pr " tok = next;\n";
3627 pr " if (tok != NULL) {\n";
3628 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
3635 pr "guestfs_lvm_int_%s_list *\n" typ;
3636 pr "parse_command_line_%ss (void)\n" typ;
3638 pr " char *out, *err;\n";
3639 pr " char *p, *pend;\n";
3641 pr " guestfs_lvm_int_%s_list *ret;\n" typ;
3642 pr " void *newp;\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";
3650 pr " ret->guestfs_lvm_int_%s_list_len = 0;\n" typ;
3651 pr " ret->guestfs_lvm_int_%s_list_val = NULL;\n" typ;
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";
3665 pr " free (err);\n";
3667 pr " /* Tokenize each line of the output. */\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";
3677 pr " while (*p && isspace (*p)) /* Skip any leading whitespace. */\n";
3680 pr " if (!*p) { /* Empty line? Skip it. */\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";
3695 pr " ret->guestfs_lvm_int_%s_list_val = newp;\n" typ;
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";
3711 pr " ret->guestfs_lvm_int_%s_list_len = i;\n" typ;
3713 pr " free (out);\n";
3714 pr " return ret;\n";
3717 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
3719 (* Generate the tests. *)
3720 and generate_tests () =
3721 generate_header CStyle GPLv2;
3728 #include <sys/types.h>
3731 #include \"guestfs.h\"
3733 static guestfs_h *g;
3734 static int suppress_error = 0;
3736 /* This will be 's' or 'h' depending on whether the guest kernel
3737 * names IDE devices /dev/sd* or /dev/hd*.
3739 static char devchar = 's';
3741 static void print_error (guestfs_h *g, void *data, const char *msg)
3743 if (!suppress_error)
3744 fprintf (stderr, \"%%s\\n\", msg);
3747 static void print_strings (char * const * const argv)
3751 for (argc = 0; argv[argc] != NULL; ++argc)
3752 printf (\"\\t%%s\\n\", argv[argc]);
3756 static void print_table (char * const * const argv)
3760 for (i = 0; argv[i] != NULL; i += 2)
3761 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
3765 static void no_test_warnings (void)
3771 | name, _, _, _, [], _, _ ->
3772 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
3773 | name, _, _, _, tests, _, _ -> ()
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
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
3793 int main (int argc, char *argv[])
3798 const char *filename;
3800 int nr_tests, test_num = 0;
3803 no_test_warnings ();
3805 g = guestfs_create ();
3807 printf (\"guestfs_create FAILED\\n\");
3811 guestfs_set_error_handler (g, print_error, NULL);
3813 guestfs_set_path (g, \"../appliance\");
3815 filename = \"test1.img\";
3816 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3821 if (lseek (fd, %d, SEEK_SET) == -1) {
3827 if (write (fd, &c, 1) == -1) {
3833 if (close (fd) == -1) {
3838 if (guestfs_add_drive (g, filename) == -1) {
3839 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3843 filename = \"test2.img\";
3844 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3849 if (lseek (fd, %d, SEEK_SET) == -1) {
3855 if (write (fd, &c, 1) == -1) {
3861 if (close (fd) == -1) {
3866 if (guestfs_add_drive (g, filename) == -1) {
3867 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3871 filename = \"test3.img\";
3872 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
3877 if (lseek (fd, %d, SEEK_SET) == -1) {
3883 if (write (fd, &c, 1) == -1) {
3889 if (close (fd) == -1) {
3894 if (guestfs_add_drive (g, filename) == -1) {
3895 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
3899 if (guestfs_launch (g) == -1) {
3900 printf (\"guestfs_launch FAILED\\n\");
3903 if (guestfs_wait_ready (g) == -1) {
3904 printf (\"guestfs_wait_ready FAILED\\n\");
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
3912 devs = guestfs_list_devices (g);
3913 if (devs == NULL || devs[0] == NULL) {
3914 printf (\"guestfs_list_devices FAILED\\n\");
3917 if (strncmp (devs[0], \"/dev/sd\", 7) == 0)
3919 else if (strncmp (devs[0], \"/dev/hd\", 7) == 0)
3922 printf (\"guestfs_list_devices returned unexpected string '%%s'\\n\",
3926 for (i = 0; devs[i] != NULL; ++i)
3932 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
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;
3945 pr " guestfs_close (g);\n";
3946 pr " unlink (\"test1.img\");\n";
3947 pr " unlink (\"test2.img\");\n";
3948 pr " unlink (\"test3.img\");\n";
3951 pr " if (failed > 0) {\n";
3952 pr " printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
3960 and generate_one_test name i (init, prereq, test) =
3961 let test_name = sprintf "test_%s_%d" name i in
3964 static int %s_skip (void)
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;
3975 " test_name (String.uppercase test_name) (String.uppercase name);
3978 | Disabled | Always -> ()
3979 | If code | Unless code ->
3980 pr "static int %s_prereq (void)\n" test_name;
3988 static int %s (void)
3991 printf (\"%%s skipped (reason: SKIP_TEST_* variable set)\\n\", \"%s\");
3995 " test_name test_name test_name;
3999 pr " printf (\"%%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4001 pr " if (! %s_prereq ()) {\n" test_name;
4002 pr " printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4006 generate_one_test_body name i test_name init test;
4008 pr " if (%s_prereq ()) {\n" test_name;
4009 pr " printf (\"%%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4013 generate_one_test_body name i test_name init test;
4015 generate_one_test_body name i test_name init test
4023 and generate_one_test_body name i test_name init test =
4027 pr " /* InitNone|InitEmpty for %s */\n" test_name;
4028 List.iter (generate_test_command_call test_name)
4029 [["blockdev_setrw"; "/dev/sda"];
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"];
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"
4044 List.iter (generate_test_command_call test_name)
4045 [["blockdev_setrw"; "/dev/sda"];
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"; "/"]]
4056 let get_seq_last = function
4058 failwithf "%s: you cannot use [] (empty list) when expecting a command"
4061 let seq = List.rev seq in
4062 List.rev (List.tl seq), List.hd 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
4077 pr " if (strcmp (r, expected) != 0) {\n";
4078 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
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
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";
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;
4105 pr " if (r[%d] != NULL) {\n" (List.length expected);
4106 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4108 pr " print_strings (r);\n";
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
4118 pr " if (r != %d) {\n" expected;
4119 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
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
4132 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
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
4144 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
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
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"
4160 pr " print_strings (r);\n";
4163 pr " if (r[j] != NULL) {\n";
4164 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
4166 pr " print_strings (r);\n";
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
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;
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;
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;
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;
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
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.
4219 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
4221 | [] -> assert false
4223 (* Look up the command to find out what args/ret it has. *)
4226 let _, style, _, _, _, _, _ =
4227 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
4230 failwithf "%s: in test, command %s was not found" test_name name in
4232 if List.length (snd style) <> List.length args then
4233 failwithf "%s: in test, wrong number of args given to %s"
4240 | OptString n, "NULL" -> ()
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
4248 | FileIn _, _ | FileOut _, _ -> ()
4249 | StringList n, arg ->
4250 let strs = string_split " " arg in
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
4257 pr " char *%s[] = {\n" n;
4259 fun i _ -> pr " %s_%d,\n" n i
4263 ) (List.combine (snd style) args);
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 _ ->
4276 pr " struct guestfs_int_bool *r;\n"; "NULL"
4278 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
4280 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
4282 pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
4284 pr " struct guestfs_stat *r;\n"; "NULL"
4286 pr " struct guestfs_statvfs *r;\n"; "NULL" in
4288 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
4289 pr " r = guestfs_%s (g" name;
4291 (* Generate the parameters. *)
4294 | OptString _, "NULL" -> pr ", NULL"
4298 | FileIn _, arg | FileOut _, arg ->
4299 pr ", \"%s\"" (c_quote arg)
4300 | StringList n, _ ->
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
4309 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
4310 ) (List.combine (snd style) args);
4313 if not expect_error then
4314 pr " if (r == %s)\n" error_code
4316 pr " if (r != %s)\n" error_code;
4319 (* Insert the test code. *)
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";
4333 pr " guestfs_free_int_bool (r);\n"
4335 pr " guestfs_free_lvm_pv_list (r);\n"
4337 pr " guestfs_free_lvm_vg_list (r);\n"
4339 pr " guestfs_free_lvm_lv_list (r);\n"
4340 | RStat _ | RStatVFS _ ->
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
4353 (* Generate a lot of different functions for guestfish. *)
4354 and generate_fish_cmds () =
4355 generate_header CStyle GPLv2;
4359 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4361 let all_functions_sorted =
4363 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4364 ) all_functions_sorted in
4366 pr "#include <stdio.h>\n";
4367 pr "#include <stdlib.h>\n";
4368 pr "#include <string.h>\n";
4369 pr "#include <inttypes.h>\n";
4371 pr "#include <guestfs.h>\n";
4372 pr "#include \"fish.h\"\n";
4375 (* list_commands function, which implements guestfish -h *)
4376 pr "void list_commands (void)\n";
4378 pr " printf (\" %%-16s %%s\\n\", \"Command\", \"Description\");\n";
4379 pr " list_builtin_commands ();\n";
4381 fun (name, _, _, flags, _, shortdesc, _) ->
4382 let name = replace_char name '_' '-' in
4383 pr " printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
4385 ) all_functions_sorted;
4386 pr " printf (\" Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
4390 (* display_command function, which implements guestfish -h cmd *)
4391 pr "void display_command (const char *cmd)\n";
4394 fun (name, style, _, flags, _, shortdesc, longdesc) ->
4395 let name2 = replace_char name '_' '-' in
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
4401 match snd style with
4405 name2 (String.concat "> <" (List.map name_of_argt args)) in
4408 if List.mem ProtocolLimitWarning flags then
4409 ("\n\n" ^ protocol_limit_warning)
4412 (* For DangerWillRobinson commands, we should probably have
4413 * guestfish prompt before allowing you to use them (especially
4414 * in interactive mode). XXX
4418 if List.mem DangerWillRobinson flags then
4419 ("\n\n" ^ danger_will_robinson)
4422 let describe_alias =
4423 if name <> alias then
4424 sprintf "\n\nYou can use '%s' as an alias for this command." alias
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;
4434 pr " pod2text (\"%s - %s\", %S);\n"
4436 (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
4439 pr " display_builtin_command (cmd);\n";
4443 (* print_{pv,vg,lv}_list functions *)
4447 pr "static void print_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
4454 pr " printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
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"
4461 pr " printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
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
4471 pr "static void print_%s_list (struct guestfs_lvm_%s_list *%ss)\n"
4476 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
4477 pr " print_%s (&%ss->val[i]);\n" typ typ;
4480 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
4482 (* print_{stat,statvfs} functions *)
4486 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
4491 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
4495 ) ["stat", stat_cols; "statvfs", statvfs_cols];
4497 (* run_<action> actions *)
4499 fun (name, style, _, flags, _, _, _) ->
4500 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
4502 (match fst style with
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"
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
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"
4533 pr " fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
4539 | String name -> pr " %s = argv[%d];\n" name i
4541 pr " %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
4544 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
4547 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
4549 | StringList name ->
4550 pr " %s = parse_string_list (argv[%d]);\n" name i
4552 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
4554 pr " %s = atoi (argv[%d]);\n" name i
4557 (* Call C API function. *)
4559 try find_map (function FishAction n -> Some n | _ -> None) flags
4560 with Not_found -> sprintf "guestfs_%s" name in
4562 generate_call_args ~handle:"g" (snd style);
4565 (* Check return value for errors and display command results. *)
4566 (match fst style with
4567 | RErr -> pr " return r;\n"
4569 pr " if (r == -1) return -1;\n";
4570 pr " printf (\"%%d\\n\", r);\n";
4573 pr " if (r == -1) return -1;\n";
4574 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
4577 pr " if (r == -1) return -1;\n";
4578 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
4581 pr " if (r == NULL) return -1;\n";
4582 pr " printf (\"%%s\\n\", r);\n";
4585 pr " if (r == NULL) return -1;\n";
4586 pr " printf (\"%%s\\n\", r);\n";
4590 pr " if (r == NULL) return -1;\n";
4591 pr " print_strings (r);\n";
4592 pr " free_strings (r);\n";
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";
4601 pr " if (r == NULL) return -1;\n";
4602 pr " print_pv_list (r);\n";
4603 pr " guestfs_free_lvm_pv_list (r);\n";
4606 pr " if (r == NULL) return -1;\n";
4607 pr " print_vg_list (r);\n";
4608 pr " guestfs_free_lvm_vg_list (r);\n";
4611 pr " if (r == NULL) return -1;\n";
4612 pr " print_lv_list (r);\n";
4613 pr " guestfs_free_lvm_lv_list (r);\n";
4616 pr " if (r == NULL) return -1;\n";
4617 pr " print_stat (r);\n";
4621 pr " if (r == NULL) return -1;\n";
4622 pr " print_statvfs (r);\n";
4626 pr " if (r == NULL) return -1;\n";
4627 pr " print_table (r);\n";
4628 pr " free_strings (r);\n";
4635 (* run_action function *)
4636 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
4639 fun (name, _, _, flags, _, _, _) ->
4640 let name2 = replace_char name '_' '-' in
4642 try find_map (function FishAlias n -> Some n | _ -> None) flags
4643 with Not_found -> name in
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;
4651 pr " return run_%s (cmd, argc, argv);\n" name;
4655 pr " fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
4662 (* Readline completion for guestfish. *)
4663 and generate_fish_completion () =
4664 generate_header CStyle GPLv2;
4668 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4678 #ifdef HAVE_LIBREADLINE
4679 #include <readline/readline.h>
4684 #ifdef HAVE_LIBREADLINE
4686 static const char *const commands[] = {
4687 BUILTIN_COMMANDS_FOR_COMPLETION,
4690 (* Get the commands, including the aliases. They don't need to be
4691 * sorted - the generator() function just does a dumb linear search.
4695 fun (name, _, _, flags, _, _, _) ->
4696 let name2 = replace_char name '_' '-' in
4698 try find_map (function FishAlias n -> Some n | _ -> None) flags
4699 with Not_found -> name in
4701 if name <> alias then [name2; alias] else [name2]
4703 let commands = List.flatten commands in
4705 List.iter (pr " \"%s\",\n") commands;
4711 generator (const char *text, int state)
4713 static int index, len;
4718 len = strlen (text);
4721 while ((name = commands[index]) != NULL) {
4723 if (strncasecmp (name, text, len) == 0)
4724 return strdup (name);
4730 #endif /* HAVE_LIBREADLINE */
4732 char **do_completion (const char *text, int start, int end)
4734 char **matches = NULL;
4736 #ifdef HAVE_LIBREADLINE
4738 matches = rl_completion_matches (text, generator);
4745 (* Generate the POD documentation for guestfish. *)
4746 and generate_fish_actions_pod () =
4747 let all_functions_sorted =
4749 fun (_, _, _, flags, _, _, _) ->
4750 not (List.mem NotInFish flags || List.mem NotInDocs flags)
4751 ) all_functions_sorted in
4753 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
4756 fun (name, style, _, flags, _, _, longdesc) ->
4758 Str.global_substitute rex (
4761 try Str.matched_group 1 s
4763 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
4764 "C<" ^ replace_char sub '_' '-' ^ ">"
4766 let name = replace_char name '_' '-' in
4768 try find_map (function FishAlias n -> Some n | _ -> None) flags
4769 with Not_found -> name in
4771 pr "=head2 %s" name;
4772 if name <> alias then
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
4788 pr "%s\n\n" longdesc;
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";
4794 if List.mem ProtocolLimitWarning flags then
4795 pr "%s\n\n" protocol_limit_warning;
4797 if List.mem DangerWillRobinson flags then
4798 pr "%s\n\n" danger_will_robinson
4799 ) all_functions_sorted
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)
4805 ?handle name style =
4806 if extern then pr "extern ";
4807 if static then pr "static ";
4808 (match fst style with
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 **"
4817 if not in_daemon then pr "struct guestfs_int_bool *"
4818 else pr "guestfs_%s_ret *" name
4820 if not in_daemon then pr "struct guestfs_lvm_pv_list *"
4821 else pr "guestfs_lvm_int_pv_list *"
4823 if not in_daemon then pr "struct guestfs_lvm_vg_list *"
4824 else pr "guestfs_lvm_int_vg_list *"
4826 if not in_daemon then pr "struct guestfs_lvm_lv_list *"
4827 else pr "guestfs_lvm_int_lv_list *"
4829 if not in_daemon then pr "struct guestfs_stat *"
4830 else pr "guestfs_int_stat *"
4832 if not in_daemon then pr "struct guestfs_statvfs *"
4833 else pr "guestfs_int_statvfs *"
4835 pr "%s%s (" prefix name;
4836 if handle = None && List.length (snd style) = 0 then
4839 let comma = ref false in
4842 | Some handle -> pr "guestfs_h *%s" handle; comma := true
4846 if single_line then pr ", " else pr ",\n\t\t"
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
4859 if not in_daemon then (next (); pr "const char *%s" n)
4863 if semicolon then pr ";";
4864 if newline then pr "\n"
4866 (* Generate C call arguments, eg "(handle, foo, bar)" *)
4867 and generate_call_args ?handle args =
4869 let comma = ref false in
4872 | Some handle -> pr "%s" handle; comma := true
4876 if !comma then pr ", ";
4878 pr "%s" (name_of_argt arg)
4882 (* Generate the OCaml bindings interface. *)
4883 and generate_ocaml_mli () =
4884 generate_header OCamlStyle LGPLv2;
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. *)
4892 (** A [guestfs_h] handle. *)
4894 exception Error of string
4895 (** This exception is raised when there is an error. *)
4897 val create : unit -> t
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. *)
4905 generate_ocaml_lvm_structure_decls ();
4907 generate_ocaml_stat_structure_decls ();
4911 fun (name, style, _, _, _, shortdesc, _) ->
4912 generate_ocaml_prototype name style;
4913 pr "(** %s *)\n" shortdesc;
4917 (* Generate the OCaml bindings implementation. *)
4918 and generate_ocaml_ml () =
4919 generate_header OCamlStyle LGPLv2;
4923 exception Error of string
4924 external create : unit -> t = \"ocaml_guestfs_create\"
4925 external close : t -> unit = \"ocaml_guestfs_close\"
4928 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
4932 generate_ocaml_lvm_structure_decls ();
4934 generate_ocaml_stat_structure_decls ();
4938 fun (name, style, _, _, _, shortdesc, _) ->
4939 generate_ocaml_prototype ~is_external:true name style;
4942 (* Generate the OCaml bindings C implementation. *)
4943 and generate_ocaml_c () =
4944 generate_header CStyle LGPLv2;
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>
4959 #include <guestfs.h>
4961 #include \"guestfs_c.h\"
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
4967 static CAMLprim value
4968 copy_table (char * const * argv)
4971 CAMLlocal5 (rv, pairv, kv, vv, cons);
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);
4984 Store_field (cons, 0, pairv);
4992 (* LVM struct copy functions. *)
4995 let has_optpercent_col =
4996 List.exists (function (_, `OptPercent) -> true | _ -> false) cols in
4998 pr "static CAMLprim value\n";
4999 pr "copy_lvm_%s (const struct guestfs_lvm_%s *%s)\n" typ typ typ;
5001 pr " CAMLparam0 ();\n";
5002 if has_optpercent_col then
5003 pr " CAMLlocal3 (rv, v, v2);\n"
5005 pr " CAMLlocal2 (rv, v);\n";
5007 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5012 pr " v = caml_copy_string (%s->%s);\n" typ name
5014 pr " v = caml_alloc_string (32);\n";
5015 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
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";
5027 pr " Store_field (rv, %d, v);\n" i
5029 pr " CAMLreturn (rv);\n";
5033 pr "static CAMLprim value\n";
5034 pr "copy_lvm_%s_list (const struct guestfs_lvm_%s_list *%ss)\n"
5037 pr " CAMLparam0 ();\n";
5038 pr " CAMLlocal2 (rv, v);\n";
5041 pr " if (%ss->len == 0)\n" typ;
5042 pr " CAMLreturn (Atom (0));\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";
5049 pr " CAMLreturn (rv);\n";
5053 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5055 (* Stat copy functions. *)
5058 pr "static CAMLprim value\n";
5059 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5061 pr " CAMLparam0 ();\n";
5062 pr " CAMLlocal2 (rv, v);\n";
5064 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5069 pr " v = caml_copy_int64 (%s->%s);\n" typ name
5071 pr " Store_field (rv, %d, v);\n" i
5073 pr " CAMLreturn (rv);\n";
5076 ) ["stat", stat_cols; "statvfs", statvfs_cols];
5080 fun (name, style, _, _, _, _, _) ->
5082 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
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);
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)
5098 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
5100 pr " CAMLlocal1 (rv);\n";
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;
5113 pr " const char *%s = String_val (%sv);\n" n n
5115 pr " const char *%s =\n" n;
5116 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
5119 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
5121 pr " int %s = Bool_val (%sv);\n" n n
5123 pr " int %s = Int_val (%sv);\n" n n
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"
5138 pr " struct guestfs_int_bool *r;\n"; "NULL"
5140 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL"
5142 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL"
5144 pr " struct guestfs_lvm_lv_list *r;\n"; "NULL"
5146 pr " struct guestfs_stat *r;\n"; "NULL"
5148 pr " struct guestfs_statvfs *r;\n"; "NULL"
5155 pr " caml_enter_blocking_section ();\n";
5156 pr " r = guestfs_%s " name;
5157 generate_call_args ~handle:"g" (snd style);
5159 pr " caml_leave_blocking_section ();\n";
5164 pr " ocaml_guestfs_free_strings (%s);\n" n;
5165 | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
5168 pr " if (r == %s)\n" error_code;
5169 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
5172 (match fst style with
5173 | RErr -> pr " rv = Val_unit;\n"
5174 | RInt _ -> pr " rv = Val_int (r);\n"
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"
5180 pr " rv = caml_copy_string (r);\n";
5183 pr " rv = caml_copy_string_array ((const char **) r);\n";
5184 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
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";
5192 pr " rv = copy_lvm_pv_list (r);\n";
5193 pr " guestfs_free_lvm_pv_list (r);\n";
5195 pr " rv = copy_lvm_vg_list (r);\n";
5196 pr " guestfs_free_lvm_vg_list (r);\n";
5198 pr " rv = copy_lvm_lv_list (r);\n";
5199 pr " guestfs_free_lvm_lv_list (r);\n";
5201 pr " rv = copy_stat (r);\n";
5204 pr " rv = copy_statvfs (r);\n";
5207 pr " rv = copy_table (r);\n";
5208 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5212 pr " CAMLreturn (rv);\n";
5216 if List.length params > 5 then (
5217 pr "CAMLprim value\n";
5218 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
5220 pr " return ocaml_guestfs_%s (argv[0]" name;
5221 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
5228 and generate_ocaml_lvm_structure_decls () =
5231 pr "type lvm_%s = {\n" typ;
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
5242 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols]
5244 and generate_ocaml_stat_structure_decls () =
5247 pr "type %s = {\n" typ;
5250 | name, `Int -> pr " %s : int64;\n" name
5254 ) ["stat", stat_cols; "statvfs", statvfs_cols]
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;
5261 | String _ | FileIn _ | FileOut _ -> pr "string -> "
5262 | OptString _ -> pr "string option -> "
5263 | StringList _ -> pr "string array -> "
5264 | Bool _ -> pr "bool -> "
5265 | Int _ -> pr "int -> "
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"
5283 if is_external then (
5285 if List.length (snd style) + 1 > 5 then
5286 pr "\"ocaml_guestfs_%s_byte\" " name;
5287 pr "\"ocaml_guestfs_%s\"" name
5291 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
5292 and generate_perl_xs () =
5293 generate_header CStyle LGPLv2;
5296 #include \"EXTERN.h\"
5300 #include <guestfs.h>
5303 #define PRId64 \"lld\"
5307 my_newSVll(long long val) {
5308 #ifdef USE_64_BIT_ALL
5309 return newSViv(val);
5313 len = snprintf(buf, 100, \"%%\" PRId64, val);
5314 return newSVpv(buf, len);
5319 #define PRIu64 \"llu\"
5323 my_newSVull(unsigned long long val) {
5324 #ifdef USE_64_BIT_ALL
5325 return newSVuv(val);
5329 len = snprintf(buf, 100, \"%%\" PRIu64, val);
5330 return newSVpv(buf, len);
5334 /* http://www.perlmonks.org/?node_id=680842 */
5336 XS_unpack_charPtrPtr (SV *arg) {
5341 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
5342 croak (\"array reference expected\");
5344 av = (AV *)SvRV (arg);
5345 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
5347 croak (\"malloc failed\");
5349 for (i = 0; i <= av_len (av); i++) {
5350 SV **elem = av_fetch (av, i, 0);
5352 if (!elem || !*elem)
5353 croak (\"missing element in list\");
5355 ret[i] = SvPV_nolen (*elem);
5363 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
5370 RETVAL = guestfs_create ();
5372 croak (\"could not create guestfs handle\");
5373 guestfs_set_error_handler (RETVAL, NULL, NULL);
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"
5396 | RPVList _ | RVGList _ | RLVList _
5397 | RStat _ | RStatVFS _
5399 pr "void\n" (* all lists returned implictly on the stack *)
5401 (* Call and arguments. *)
5403 generate_call_args ~handle:"g" (snd style);
5405 pr " guestfs_h *g;\n";
5409 | String n | FileIn n | FileOut n -> pr " char *%s;\n" 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.
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
5421 let do_cleanups () =
5424 | String _ | OptString _ | Bool _ | Int _
5425 | FileIn _ | FileOut _ -> ()
5426 | StringList n -> pr " free (%s);\n" n
5431 (match fst style with
5436 pr " r = guestfs_%s " name;
5437 generate_call_args ~handle:"g" (snd style);
5440 pr " if (r == -1)\n";
5441 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5447 pr " %s = guestfs_%s " n name;
5448 generate_call_args ~handle:"g" (snd style);
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;
5458 pr " int64_t %s;\n" n;
5460 pr " %s = guestfs_%s " n name;
5461 generate_call_args ~handle:"g" (snd style);
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;
5471 pr " const char *%s;\n" n;
5473 pr " %s = guestfs_%s " n name;
5474 generate_call_args ~handle:"g" (snd style);
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;
5484 pr " char *%s;\n" n;
5486 pr " %s = guestfs_%s " n name;
5487 generate_call_args ~handle:"g" (snd style);
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;
5496 | RStringList n | RHashtable n ->
5498 pr " char **%s;\n" n;
5501 pr " %s = guestfs_%s " n name;
5502 generate_call_args ~handle:"g" (snd style);
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;
5513 pr " free (%s);\n" n;
5516 pr " struct guestfs_int_bool *r;\n";
5518 pr " r = guestfs_%s " name;
5519 generate_call_args ~handle:"g" (snd style);
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";
5529 generate_perl_lvm_code "pv" pv_cols name style n do_cleanups
5531 generate_perl_lvm_code "vg" vg_cols name style n do_cleanups
5533 generate_perl_lvm_code "lv" lv_cols name style n do_cleanups
5535 generate_perl_stat_code "stat" stat_cols name style n do_cleanups
5537 generate_perl_stat_code
5538 "statvfs" statvfs_cols name style n do_cleanups
5544 and generate_perl_lvm_code typ cols name style n do_cleanups =
5546 pr " struct guestfs_lvm_%s_list *%s;\n" typ n;
5550 pr " %s = guestfs_%s " n name;
5551 generate_call_args ~handle:"g" (snd style);
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";
5562 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
5563 name (String.length name) n name
5565 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
5566 name (String.length name) n name
5568 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
5569 name (String.length name) n name
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
5577 pr " PUSHs (sv_2mortal ((SV *) hv));\n";
5579 pr " guestfs_free_lvm_%s_list (%s);\n" typ n
5581 and generate_perl_stat_code typ cols name style n do_cleanups =
5583 pr " struct guestfs_%s *%s;\n" typ n;
5585 pr " %s = guestfs_%s " n name;
5586 generate_call_args ~handle:"g" (snd style);
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);
5595 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n" n name
5597 pr " free (%s);\n" n
5599 (* Generate Sys/Guestfs.pm. *)
5600 and generate_perl_pm () =
5601 generate_header HashStyle LGPLv2;
5608 Sys::Guestfs - Perl bindings for libguestfs
5614 my $h = Sys::Guestfs->new ();
5615 $h->add_drive ('guest.img');
5618 $h->mount ('/dev/sda1', '/');
5619 $h->touch ('/hello');
5624 The C<Sys::Guestfs> module provides a Perl XS binding to the
5625 libguestfs API for examining and modifying virtual machine
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
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.
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.
5646 All errors turn into calls to C<croak> (see L<Carp(3)>).
5654 package Sys::Guestfs;
5660 XSLoader::load ('Sys::Guestfs');
5662 =item $h = Sys::Guestfs->new ();
5664 Create a new guestfs handle.
5670 my $class = ref ($proto) || $proto;
5672 my $self = Sys::Guestfs::_create ();
5673 bless $self, $class;
5679 (* Actions. We only need to print documentation for these as
5680 * they are pulled in from the XS code automatically.
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
5687 generate_perl_prototype name style;
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
5695 ) all_functions_sorted;
5707 Copyright (C) 2009 Red Hat Inc.
5711 Please see the file COPYING.LIB for the full license.
5715 L<guestfs(3)>, L<guestfish(1)>.
5720 and generate_perl_prototype name style =
5721 (match fst style with
5727 | RString n -> pr "$%s = " n
5728 | RIntBool (n, m) -> pr "($%s, $%s) = " n m
5732 | RLVList n -> pr "@%s = " n
5735 | RHashtable n -> pr "%%%s = " n
5738 let comma = ref false in
5741 if !comma then pr ", ";
5744 | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
5751 (* Generate Python C module. *)
5752 and generate_python_c () =
5753 generate_header CStyle LGPLv2;
5762 #include \"guestfs.h\"
5770 get_handle (PyObject *obj)
5773 assert (obj != Py_None);
5774 return ((Pyguestfs_Object *) obj)->g;
5778 put_handle (guestfs_h *g)
5782 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
5785 /* This list should be freed (but not the strings) after use. */
5786 static const char **
5787 get_string_list (PyObject *obj)
5794 if (!PyList_Check (obj)) {
5795 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
5799 len = PyList_Size (obj);
5800 r = malloc (sizeof (char *) * (len+1));
5802 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
5806 for (i = 0; i < len; ++i)
5807 r[i] = PyString_AsString (PyList_GetItem (obj, i));
5814 put_string_list (char * const * const argv)
5819 for (argc = 0; argv[argc] != NULL; ++argc)
5822 list = PyList_New (argc);
5823 for (i = 0; i < argc; ++i)
5824 PyList_SetItem (list, i, PyString_FromString (argv[i]));
5830 put_table (char * const * const argv)
5832 PyObject *list, *item;
5835 for (argc = 0; argv[argc] != NULL; ++argc)
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);
5850 free_strings (char **argv)
5854 for (argc = 0; argv[argc] != NULL; ++argc)
5860 py_guestfs_create (PyObject *self, PyObject *args)
5864 g = guestfs_create ();
5866 PyErr_SetString (PyExc_RuntimeError,
5867 \"guestfs.create: failed to allocate handle\");
5870 guestfs_set_error_handler (g, NULL, NULL);
5871 return put_handle (g);
5875 py_guestfs_close (PyObject *self, PyObject *args)
5880 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
5882 g = get_handle (py_g);
5886 Py_INCREF (Py_None);
5892 (* LVM structures, turned into Python dictionaries. *)
5895 pr "static PyObject *\n";
5896 pr "put_lvm_%s (struct guestfs_lvm_%s *%s)\n" typ typ typ;
5898 pr " PyObject *dict;\n";
5900 pr " dict = PyDict_New ();\n";
5904 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5905 pr " PyString_FromString (%s->%s));\n"
5908 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5909 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
5912 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5913 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
5916 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5917 pr " PyLong_FromLongLong (%s->%s));\n"
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"
5925 pr " Py_INCREF (Py_None);\n";
5926 pr " PyDict_SetItemString (dict, \"%s\", Py_None);" name;
5929 pr " return dict;\n";
5933 pr "static PyObject *\n";
5934 pr "put_lvm_%s_list (struct guestfs_lvm_%s_list *%ss)\n" typ typ typ;
5936 pr " PyObject *list;\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";
5945 ) ["pv", pv_cols; "vg", vg_cols; "lv", lv_cols];
5947 (* Stat structures, turned into Python dictionaries. *)
5950 pr "static PyObject *\n";
5951 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
5953 pr " PyObject *dict;\n";
5955 pr " dict = PyDict_New ();\n";
5959 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
5960 pr " PyLong_FromLongLong (%s->%s));\n"
5963 pr " return dict;\n";
5966 ) ["stat", stat_cols; "statvfs", statvfs_cols];
5968 (* Python wrapper functions. *)
5970 fun (name, style, _, _, _, _, _) ->
5971 pr "static PyObject *\n";
5972 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
5975 pr " PyObject *py_g;\n";
5976 pr " guestfs_h *g;\n";
5977 pr " PyObject *py_r;\n";
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
5995 | String n | FileIn n | FileOut n -> pr " const char *%s;\n" n
5996 | OptString n -> pr " const char *%s;\n" 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
6006 (* Convert the parameters. *)
6007 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
6010 | String _ | FileIn _ | FileOut _ -> pr "s"
6011 | OptString _ -> pr "z"
6012 | StringList _ -> pr "O"
6013 | Bool _ -> pr "i" (* XXX Python has booleans? *)
6016 pr ":guestfs_%s\",\n" name;
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
6028 pr " return NULL;\n";
6030 pr " g = get_handle (py_g);\n";
6033 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6035 pr " %s = get_string_list (py_%s);\n" n n;
6036 pr " if (!%s) return NULL;\n" n
6041 pr " r = guestfs_%s " name;
6042 generate_call_args ~handle:"g" (snd style);
6047 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6049 pr " free (%s);\n" n
6052 pr " if (r == %s) {\n" error_code;
6053 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6054 pr " return NULL;\n";
6058 (match fst style with
6060 pr " Py_INCREF (Py_None);\n";
6061 pr " py_r = Py_None;\n"
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"
6067 pr " py_r = PyString_FromString (r);\n";
6070 pr " py_r = put_string_list (r);\n";
6071 pr " free_strings (r);\n"
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"
6078 pr " py_r = put_lvm_pv_list (r);\n";
6079 pr " guestfs_free_lvm_pv_list (r);\n"
6081 pr " py_r = put_lvm_vg_list (r);\n";
6082 pr " guestfs_free_lvm_vg_list (r);\n"
6084 pr " py_r = put_lvm_lv_list (r);\n";
6085 pr " guestfs_free_lvm_lv_list (r);\n"
6087 pr " py_r = put_stat (r);\n";
6090 pr " py_r = put_statvfs (r);\n";
6093 pr " py_r = put_table (r);\n";
6094 pr " free_strings (r);\n"
6097 pr " return py_r;\n";
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";
6107 fun (name, _, _, _, _, _, _) ->
6108 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
6111 pr " { NULL, NULL, 0, NULL }\n";
6115 (* Init function. *)
6118 initlibguestfsmod (void)
6120 static int initialized = 0;
6122 if (initialized) return;
6123 Py_InitModule ((char *) \"libguestfsmod\", methods);
6128 (* Generate Python module. *)
6129 and generate_python_py () =
6130 generate_header HashStyle LGPLv2;
6133 u\"\"\"Python bindings for libguestfs
6136 g = guestfs.GuestFS ()
6137 g.add_drive (\"guest.img\")
6140 parts = g.list_partitions ()
6142 The guestfs module provides a Python binding to the libguestfs API
6143 for examining and modifying virtual machine disk images.
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
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.
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.
6161 Errors which happen while using the API are turned into Python
6162 RuntimeError exceptions.
6164 To create a guestfs handle you usually have to perform the following
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\")
6172 # Launch the qemu subprocess and wait for it to become ready:
6176 # Now you can issue commands, for example:
6181 import libguestfsmod
6184 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
6186 def __init__ (self):
6187 \"\"\"Create a new libguestfs handle.\"\"\"
6188 self._o = libguestfsmod.create ()
6191 libguestfsmod.close (self._o)
6196 fun (name, style, _, flags, _, _, longdesc) ->
6198 generate_call_args ~handle:"self" (snd style);
6201 if not (List.mem NotInDocs flags) then (
6202 let doc = replace_str longdesc "C<guestfs_" "C<g." in
6204 match fst style with
6205 | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _
6208 doc ^ "\n\nThis function returns a list of strings."
6210 doc ^ "\n\nThis function returns a tuple (int, bool).\n"
6212 doc ^ "\n\nThis function returns a list of PVs. Each PV is represented as a dictionary."
6214 doc ^ "\n\nThis function returns a list of VGs. Each VG is represented as a dictionary."
6216 doc ^ "\n\nThis function returns a list of LVs. Each LV is represented as a dictionary."
6218 doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the stat structure."
6220 doc ^ "\n\nThis function returns a dictionary, with keys matching the various fields in the statvfs structure."
6222 doc ^ "\n\nThis function returns a dictionary." in
6224 if List.mem ProtocolLimitWarning flags then
6225 doc ^ "\n\n" ^ protocol_limit_warning
6228 if List.mem DangerWillRobinson flags then
6229 doc ^ "\n\n" ^ danger_will_robinson
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;
6236 pr " return libguestfsmod.%s " name;
6237 generate_call_args ~handle:"self._o" (snd style);
6242 (* Useful if you need the longdesc POD text as plain text. Returns a
6245 * This is the slowest thing about autogeneration.
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;
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
6255 let line = input_line chan in
6256 if i = 1 then (* discard the first line of output *)
6259 let line = triml line in
6260 lines := line :: !lines;
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
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
6272 (* Generate ruby bindings. *)
6273 and generate_ruby_c () =
6274 generate_header CStyle LGPLv2;
6282 #include \"guestfs.h\"
6284 #include \"extconf.h\"
6286 /* For Ruby < 1.9 */
6288 #define RARRAY_LEN(r) (RARRAY((r))->len)
6291 static VALUE m_guestfs; /* guestfs module */
6292 static VALUE c_guestfs; /* guestfs_h handle */
6293 static VALUE e_Error; /* used for all errors */
6295 static void ruby_guestfs_free (void *p)
6298 guestfs_close ((guestfs_h *) p);
6301 static VALUE ruby_guestfs_create (VALUE m)
6305 g = guestfs_create ();
6307 rb_raise (e_Error, \"failed to create guestfs handle\");
6309 /* Don't print error messages to stderr by default. */
6310 guestfs_set_error_handler (g, NULL, NULL);
6312 /* Wrap it, and make sure the close function is called when the
6315 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
6318 static VALUE ruby_guestfs_close (VALUE gv)
6321 Data_Get_Struct (gv, guestfs_h, g);
6323 ruby_guestfs_free (g);
6324 DATA_PTR (gv) = NULL;
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);
6337 pr " guestfs_h *g;\n";
6338 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
6340 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
6346 | String n | FileIn n | FileOut n ->
6347 pr " const char *%s = StringValueCStr (%sv);\n" n n;
6349 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
6350 pr " \"%s\", \"%s\");\n" n name
6352 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n 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"
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;
6364 pr " %s[len] = NULL;\n" n;
6367 pr " int %s = RTEST (%sv);\n" n n
6369 pr " int %s = NUM2INT (%sv);\n" n n
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
6388 pr " r = guestfs_%s " name;
6389 generate_call_args ~handle:"g" (snd style);
6394 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6396 pr " free (%s);\n" n
6399 pr " if (r == %s)\n" error_code;
6400 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
6403 (match fst style with
6405 pr " return Qnil;\n"
6406 | RInt _ | RBool _ ->
6407 pr " return INT2NUM (r);\n"
6409 pr " return ULL2NUM (r);\n"
6411 pr " return rb_str_new2 (r);\n";
6413 pr " VALUE rv = rb_str_new2 (r);\n";
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";
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";
6433 generate_ruby_lvm_code "pv" pv_cols
6435 generate_ruby_lvm_code "vg" vg_cols
6437 generate_ruby_lvm_code "lv" lv_cols
6439 pr " VALUE rv = rb_hash_new ();\n";
6443 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6448 pr " VALUE rv = rb_hash_new ();\n";
6452 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6457 pr " VALUE rv = rb_hash_new ();\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";
6473 /* Initialize the module. */
6474 void Init__guestfs ()
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);
6480 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
6481 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
6484 (* Define the rest of the methods. *)
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))
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";
6497 pr " for (i = 0; i < r->len; ++i) {\n";
6498 pr " VALUE hv = rb_hash_new ();\n";
6502 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
6504 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
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
6511 pr " rb_ary_push (rv, hv);\n";
6513 pr " guestfs_free_lvm_%s_list (r);\n" typ;
6516 (* Generate Java bindings GuestFS.java file. *)
6517 and generate_java_java () =
6518 generate_header CStyle LGPLv2;
6521 package com.redhat.et.libguestfs;
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;
6533 * The GuestFS object is a libguestfs handle.
6537 public class GuestFS {
6538 // Load the native code.
6540 System.loadLibrary (\"guestfs_jni\");
6544 * The native guestfs_h pointer.
6549 * Create a libguestfs handle.
6551 * @throws LibGuestFSException
6553 public GuestFS () throws LibGuestFSException
6557 private native long _create () throws LibGuestFSException;
6560 * Close a libguestfs handle.
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
6568 * @throws LibGuestFSException
6570 public void close () throws LibGuestFSException
6576 private native void _close (long g) throws LibGuestFSException;
6578 public void finalize () throws LibGuestFSException
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
6590 if List.mem ProtocolLimitWarning flags then
6591 doc ^ "\n\n" ^ protocol_limit_warning
6594 if List.mem DangerWillRobinson flags then
6595 doc ^ "\n\n" ^ danger_will_robinson
6597 let doc = pod2text ~width:60 name doc in
6598 let doc = List.map ( (* RHBZ#501883 *)
6601 | nonempty -> nonempty
6603 let doc = String.concat "\n * " doc in
6606 pr " * %s\n" shortdesc;
6609 pr " * @throws LibGuestFSException\n";
6613 generate_java_prototype ~public:true ~semicolon:false name style;
6616 pr " if (g == 0)\n";
6617 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
6620 if fst style <> RErr then pr "return ";
6622 generate_call_args ~handle:"g" (snd style);
6626 generate_java_prototype ~privat:true ~native:true name style;
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 ";
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> ";
6656 if native then pr "_%s " name else pr "%s " name;
6658 let needs_comma = ref false in
6667 if !needs_comma then pr ", ";
6668 needs_comma := true;
6685 pr " throws LibGuestFSException";
6686 if semicolon then pr ";"
6688 and generate_java_struct typ cols =
6689 generate_header CStyle LGPLv2;
6692 package com.redhat.et.libguestfs;
6695 * Libguestfs %s structure.
6706 | name, `UUID -> pr " public String %s;\n" name
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
6716 and generate_java_c () =
6717 generate_header CStyle LGPLv2;
6724 #include \"com_redhat_et_libguestfs_GuestFS.h\"
6725 #include \"guestfs.h\"
6727 /* Note that this function returns. The exception is not thrown
6728 * until after the wrapper function returns.
6731 throw_exception (JNIEnv *env, const char *msg)
6734 cl = (*env)->FindClass (env,
6735 \"com/redhat/et/libguestfs/LibGuestFSException\");
6736 (*env)->ThrowNew (env, cl, msg);
6739 JNIEXPORT jlong JNICALL
6740 Java_com_redhat_et_libguestfs_GuestFS__1create
6741 (JNIEnv *env, jobject obj)
6745 g = guestfs_create ();
6747 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
6750 guestfs_set_error_handler (g, NULL, NULL);
6751 return (jlong) (long) g;
6754 JNIEXPORT void JNICALL
6755 Java_com_redhat_et_libguestfs_GuestFS__1close
6756 (JNIEnv *env, jobject obj, jlong jg)
6758 guestfs_h *g = (guestfs_h *) (long) jg;
6765 fun (name, style, _, _, _, _, _) ->
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 _ ->
6775 | RStringList _ | RPVList _ | RVGList _ | RLVList _ ->
6779 pr "Java_com_redhat_et_libguestfs_GuestFS_";
6780 pr "%s" (replace_str ("_" ^ name) "_" "_1");
6782 pr " (JNIEnv *env, jobject obj, jlong jg";
6789 pr ", jstring j%s" n
6791 pr ", jobjectArray j%s" n
6793 pr ", jboolean j%s" 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", ""
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"
6808 pr " jstring jr;\n";
6809 pr " char *r;\n"; "NULL", "NULL"
6811 pr " jobjectArray jr;\n";
6814 pr " jstring jstr;\n";
6815 pr " char **r;\n"; "NULL", "NULL"
6817 pr " jobject jr;\n";
6819 pr " jfieldID fl;\n";
6820 pr " struct guestfs_int_bool *r;\n"; "NULL", "NULL"
6822 pr " jobject jr;\n";
6824 pr " jfieldID fl;\n";
6825 pr " struct guestfs_stat *r;\n"; "NULL", "NULL"
6827 pr " jobject jr;\n";
6829 pr " jfieldID fl;\n";
6830 pr " struct guestfs_statvfs *r;\n"; "NULL", "NULL"
6832 pr " jobjectArray jr;\n";
6834 pr " jfieldID fl;\n";
6835 pr " jobject jfl;\n";
6836 pr " struct guestfs_lvm_pv_list *r;\n"; "NULL", "NULL"
6838 pr " jobjectArray jr;\n";
6840 pr " jfieldID fl;\n";
6841 pr " jobject jfl;\n";
6842 pr " struct guestfs_lvm_vg_list *r;\n"; "NULL", "NULL"
6844 pr " jobjectArray jr;\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
6856 pr " const char *%s;\n" n
6858 pr " int %s_len;\n" n;
6859 pr " const char **%s;\n" n
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
6877 (* Get the parameters. *)
6883 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
6885 (* This is completely undocumented, but Java null becomes
6888 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n 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"
6895 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
6897 pr " %s[%s_len] = NULL;\n" n n;
6900 pr " %s = j%s;\n" n n
6903 (* Make the call. *)
6904 pr " r = guestfs_%s " name;
6905 generate_call_args ~handle:"g" (snd style);
6908 (* Release the parameters. *)
6914 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6917 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
6919 pr " for (i = 0; i < %s_len; ++i) {\n" n;
6920 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
6922 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
6924 pr " free (%s);\n" n
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;
6936 (match fst style with
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"
6943 pr " jr = (*env)->NewStringUTF (env, r);\n";
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";
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";
6968 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/Stat\");\n";
6969 pr " jr = (*env)->AllocObject (env, cl);\n";
6973 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6975 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6980 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/StatVFS\");\n";
6981 pr " jr = (*env)->AllocObject (env, cl);\n";
6985 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n"
6987 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
6992 generate_java_lvm_return "pv" "PV" pv_cols
6994 generate_java_lvm_return "vg" "VG" vg_cols
6996 generate_java_lvm_return "lv" "LV" lv_cols
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"
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";
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;
7019 pr " char s[33];\n";
7020 pr " memcpy (s, r->val[i].%s, 32);\n" name;
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";
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;
7032 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
7034 pr " guestfs_free_lvm_%s_list (r);\n" typ;
7037 and generate_haskell_hs () =
7038 generate_header HaskellStyle LGPLv2;
7040 (* XXX We only know how to generate partial FFI for Haskell
7041 * at the moment. Please help out!
7043 let can_generate style =
7044 let check_no_bad_args =
7045 List.for_all (function Bool _ | Int _ -> false | _ -> true)
7048 | RErr, args -> check_no_bad_args args
7061 | RHashtable _, _ -> false in
7064 {-# INCLUDE <guestfs.h> #-}
7065 {-# LANGUAGE ForeignFunctionInterface #-}
7070 (* List out the names of the actions we want to export. *)
7072 fun (name, style, _, _, _, _, _) ->
7073 if can_generate style then pr ",\n %s" name
7081 import Control.Exception
7082 import Data.Typeable
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
7088 -- XXX define properly later XXX
7092 data IntBool = IntBool
7094 data StatVFS = StatVFS
7095 data Hashtable = Hashtable
7097 foreign import ccall unsafe \"guestfs_create\" c_create
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 ()
7104 create :: IO GuestfsH
7107 c_set_error_handler p nullPtr nullPtr
7108 h <- newForeignPtr c_close p
7111 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
7112 :: GuestfsP -> IO CString
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
7119 last_error :: GuestfsH -> IO (String)
7121 str <- withForeignPtr h (\\p -> c_last_error p)
7123 then return \"no error\"
7124 else peekCString str
7128 (* Generate wrappers for each foreign function. *)
7130 fun (name, style, _, _, _, _, _) ->
7131 if can_generate style then (
7132 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
7134 generate_haskell_prototype ~handle:"GuestfsP" style;
7138 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
7140 pr "%s %s = do\n" name
7141 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
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
7151 (* XXX this doesn't work *)
7153 pr " %s = case %s of\n" n n;
7156 pr " in fromIntegral %s $ \\%s ->\n" n n
7157 | Int n -> pr "fromIntegral %s $ \\%s -> " n n
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";
7165 pr " err <- last_error h\n";
7167 | RConstString _ | RString _ | RStringList _ | RIntBool _
7168 | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7170 pr " if (r == nullPtr)\n";
7172 pr " err <- last_error h\n";
7175 (match fst style with
7177 pr " else return ()\n"
7179 pr " else return (fromIntegral r)\n"
7181 pr " else return (fromIntegral r)\n"
7183 pr " else return (toBool r)\n"
7194 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
7200 and generate_haskell_prototype ~handle ?(hs = false) style =
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
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
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"
7238 and generate_bindtests () =
7239 generate_header CStyle LGPLv2;
7244 #include <inttypes.h>
7247 #include \"guestfs.h\"
7248 #include \"guestfs_protocol.h\"
7250 #define error guestfs_error
7253 print_strings (char * const* const argv)
7258 for (argc = 0; argv[argc] != NULL; ++argc) {
7259 if (argc > 0) printf (\", \");
7260 printf (\"\\\"%%s\\\"\", argv[argc]);
7265 /* The test0 function prints its parameters to stdout. */
7269 match test_functions with
7270 | [] -> assert false
7271 | test0 :: tests -> test0, tests in
7274 let (name, style, _, _, _, _, _) = test0 in
7275 generate_prototype ~extern:false ~semicolon:false ~newline:true
7276 ~handle:"g" ~prefix:"guestfs_" name style;
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
7288 pr " /* Java changes stdout line buffering so we need this: */\n";
7289 pr " fflush (stdout);\n";
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;
7301 (match fst style with
7306 pr " sscanf (val, \"%%d\", &r);\n";
7310 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
7313 pr " return strcmp (val, \"true\") == 0;\n"
7315 (* Can't return the input string here. Return a static
7316 * string so we ensure we get a segfault if the caller
7319 pr " return \"static string\";\n"
7321 pr " return strdup (val);\n"
7323 pr " char **strs;\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";
7331 pr " strs[n] = NULL;\n";
7332 pr " return strs;\n"
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";
7340 pr " struct guestfs_lvm_pv_list *r;\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";
7351 pr " struct guestfs_lvm_vg_list *r;\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";
7362 pr " struct guestfs_lvm_lv_list *r;\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";
7373 pr " struct guestfs_stat *r;\n";
7374 pr " r = calloc (1, sizeof (*r));\n";
7375 pr " sscanf (val, \"%%\" SCNi64, &r->dev);\n";
7378 pr " struct guestfs_statvfs *r;\n";
7379 pr " r = calloc (1, sizeof (*r));\n";
7380 pr " sscanf (val, \"%%\" SCNi64, &r->bsize);\n";
7383 pr " char **strs;\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";
7393 pr " strs[n*2] = NULL;\n";
7394 pr " return strs;\n"
7399 pr "/* Test error return. */\n";
7400 generate_prototype ~extern:false ~semicolon:false ~newline:true
7401 ~handle:"g" ~prefix:"guestfs_" name style;
7403 pr " error (g, \"error\");\n";
7404 (match fst style with
7405 | RErr | RInt _ | RInt64 _ | RBool _ ->
7408 | RString _ | RStringList _ | RIntBool _
7409 | RPVList _ | RVGList _ | RLVList _ | RStat _ | RStatVFS _
7411 pr " return NULL;\n"
7418 and generate_ocaml_bindtests () =
7419 generate_header OCamlStyle GPLv2;
7423 let g = Guestfs.create () in
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
7442 generate_lang_bindtests (
7443 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
7446 pr "print_endline \"EOF\"\n"
7448 and generate_perl_bindtests () =
7449 pr "#!/usr/bin/perl -w\n";
7450 generate_header HashStyle GPLv2;
7457 my $g = Sys::Guestfs->new ();
7461 String.concat ", " (
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"
7475 generate_lang_bindtests (
7476 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
7479 pr "print \"EOF\\n\"\n"
7481 and generate_python_bindtests () =
7482 generate_header HashStyle GPLv2;
7487 g = guestfs.GuestFS ()
7491 String.concat ", " (
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"
7505 generate_lang_bindtests (
7506 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
7509 pr "print \"EOF\"\n"
7511 and generate_ruby_bindtests () =
7512 generate_header HashStyle GPLv2;
7517 g = Guestfs::create()
7521 String.concat ", " (
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
7535 generate_lang_bindtests (
7536 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
7539 pr "print \"EOF\\n\"\n"
7541 and generate_java_bindtests () =
7542 generate_header CStyle GPLv2;
7545 import com.redhat.et.libguestfs.*;
7547 public class Bindtests {
7548 public static void main (String[] argv)
7551 GuestFS g = new GuestFS ();
7555 String.concat ", " (
7558 | CallString s -> "\"" ^ s ^ "\""
7559 | CallOptString None -> "null"
7560 | CallOptString (Some s) -> sprintf "\"%s\"" s
7561 | CallStringList xs ->
7563 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
7564 | CallInt i -> string_of_int i
7565 | CallBool b -> string_of_bool b
7570 generate_lang_bindtests (
7571 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
7575 System.out.println (\"EOF\");
7577 catch (Exception exn) {
7578 System.err.println (exn);
7585 and generate_haskell_bindtests () =
7586 () (* XXX Haskell bindings need to be fleshed out. *)
7588 (* Language-independent bindings tests - we do it this way to
7589 * ensure there is parity in testing bindings across all languages.
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 ""]
7632 (* XXX Add here tests of the return and error functions. *)
7634 let output_to filename =
7635 let filename_new = filename ^ ".new" in
7636 chan := open_out filename_new;
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 *)
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;
7658 if not (Sys.file_exists "configure.ac") then (
7660 You are probably running this from the wrong directory.
7661 Run it from the top source directory using the command
7667 let close = output_to "src/guestfs_protocol.x" in
7671 let close = output_to "src/guestfs-structs.h" in
7672 generate_structs_h ();
7675 let close = output_to "src/guestfs-actions.h" in
7676 generate_actions_h ();
7679 let close = output_to "src/guestfs-actions.c" in
7680 generate_client_actions ();
7683 let close = output_to "daemon/actions.h" in
7684 generate_daemon_actions_h ();
7687 let close = output_to "daemon/stubs.c" in
7688 generate_daemon_actions ();
7691 let close = output_to "capitests/tests.c" in
7695 let close = output_to "src/guestfs-bindtests.c" in
7696 generate_bindtests ();
7699 let close = output_to "fish/cmds.c" in
7700 generate_fish_cmds ();
7703 let close = output_to "fish/completion.c" in
7704 generate_fish_completion ();
7707 let close = output_to "guestfs-structs.pod" in
7708 generate_structs_pod ();
7711 let close = output_to "guestfs-actions.pod" in
7712 generate_actions_pod ();
7715 let close = output_to "guestfish-actions.pod" in
7716 generate_fish_actions_pod ();
7719 let close = output_to "ocaml/guestfs.mli" in
7720 generate_ocaml_mli ();
7723 let close = output_to "ocaml/guestfs.ml" in
7724 generate_ocaml_ml ();
7727 let close = output_to "ocaml/guestfs_c_actions.c" in
7728 generate_ocaml_c ();
7731 let close = output_to "ocaml/bindtests.ml" in
7732 generate_ocaml_bindtests ();
7735 let close = output_to "perl/Guestfs.xs" in
7736 generate_perl_xs ();
7739 let close = output_to "perl/lib/Sys/Guestfs.pm" in
7740 generate_perl_pm ();
7743 let close = output_to "perl/bindtests.pl" in
7744 generate_perl_bindtests ();
7747 let close = output_to "python/guestfs-py.c" in
7748 generate_python_c ();
7751 let close = output_to "python/guestfs.py" in
7752 generate_python_py ();
7755 let close = output_to "python/bindtests.py" in
7756 generate_python_bindtests ();
7759 let close = output_to "ruby/ext/guestfs/_guestfs.c" in
7763 let close = output_to "ruby/bindtests.rb" in
7764 generate_ruby_bindtests ();
7767 let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
7768 generate_java_java ();
7771 let close = output_to "java/com/redhat/et/libguestfs/PV.java" in
7772 generate_java_struct "PV" pv_cols;
7775 let close = output_to "java/com/redhat/et/libguestfs/VG.java" in
7776 generate_java_struct "VG" vg_cols;
7779 let close = output_to "java/com/redhat/et/libguestfs/LV.java" in
7780 generate_java_struct "LV" lv_cols;
7783 let close = output_to "java/com/redhat/et/libguestfs/Stat.java" in
7784 generate_java_struct "Stat" stat_cols;
7787 let close = output_to "java/com/redhat/et/libguestfs/StatVFS.java" in
7788 generate_java_struct "StatVFS" statvfs_cols;
7791 let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
7795 let close = output_to "java/Bindtests.java" in
7796 generate_java_bindtests ();
7799 let close = output_to "haskell/Guestfs.hs" in
7800 generate_haskell_hs ();
7803 let close = output_to "haskell/bindtests.hs" in
7804 generate_haskell_bindtests ();