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 (* "RStruct" is a function which returns a single named structure
70 * or an error indication (in C, a struct, and in other languages
71 * with varying representations, but usually very efficient). See
72 * after the function list below for the structures.
74 | RStruct of string * string (* name of retval, name of struct *)
75 (* "RStructList" is a function which returns either a list/array
76 * of structures (could be zero-length), or an error indication.
78 | RStructList of string * string (* name of retval, name of struct *)
79 (* Key-value pairs of untyped strings. Turns into a hashtable or
80 * dictionary in languages which support it. DON'T use this as a
81 * general "bucket" for results. Prefer a stronger typed return
82 * value if one is available, or write a custom struct. Don't use
83 * this if the list could potentially be very long, since it is
84 * inefficient. Keys should be unique. NULLs are not permitted.
86 | RHashtable of string
88 and args = argt list (* Function parameters, guestfs handle is implicit. *)
90 (* Note in future we should allow a "variable args" parameter as
91 * the final parameter, to allow commands like
92 * chmod mode file [file(s)...]
93 * This is not implemented yet, but many commands (such as chmod)
94 * are currently defined with the argument order keeping this future
95 * possibility in mind.
98 | String of string (* const char *name, cannot be NULL *)
99 | OptString of string (* const char *name, may be NULL *)
100 | StringList of string(* list of strings (each string cannot be NULL) *)
101 | Bool of string (* boolean *)
102 | Int of string (* int (smallish ints, signed, <= 31 bits) *)
103 (* These are treated as filenames (simple string parameters) in
104 * the C API and bindings. But in the RPC protocol, we transfer
105 * the actual file content up to or down from the daemon.
106 * FileIn: local machine -> daemon (in request)
107 * FileOut: daemon -> local machine (in reply)
108 * In guestfish (only), the special name "-" means read from
109 * stdin or write to stdout.
115 | ProtocolLimitWarning (* display warning about protocol size limits *)
116 | DangerWillRobinson (* flags particularly dangerous commands *)
117 | FishAlias of string (* provide an alias for this cmd in guestfish *)
118 | FishAction of string (* call this function in guestfish *)
119 | NotInFish (* do not export via guestfish *)
120 | NotInDocs (* do not add this function to documentation *)
122 let protocol_limit_warning =
123 "Because of the message protocol, there is a transfer limit
124 of somewhere between 2MB and 4MB. To transfer large files you should use
127 let danger_will_robinson =
128 "B<This command is dangerous. Without careful use you
129 can easily destroy all your data>."
131 (* You can supply zero or as many tests as you want per API call.
133 * Note that the test environment has 3 block devices, of size 500MB,
134 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
135 * a fourth squashfs block device with some known files on it (/dev/sdd).
137 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
138 * Number of cylinders was 63 for IDE emulated disks with precisely
139 * the same size. How exactly this is calculated is a mystery.
141 * The squashfs block device (/dev/sdd) comes from images/test.sqsh.
143 * To be able to run the tests in a reasonable amount of time,
144 * the virtual machine and block devices are reused between tests.
145 * So don't try testing kill_subprocess :-x
147 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
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 list of block devices (could be either
177 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
178 * character of each string).
180 | TestOutputListOfDevices of seq * string list
181 (* Run the command sequence and expect the output of the final
182 * command to be the integer.
184 | TestOutputInt of seq * int
185 (* Run the command sequence and expect the output of the final
186 * command to be a true value (!= 0 or != NULL).
188 | TestOutputTrue of seq
189 (* Run the command sequence and expect the output of the final
190 * command to be a false value (== 0 or == NULL, but not an error).
192 | TestOutputFalse of seq
193 (* Run the command sequence and expect the output of the final
194 * command to be a list of the given length (but don't care about
197 | TestOutputLength of seq * int
198 (* Run the command sequence and expect the output of the final
199 * command to be a structure.
201 | TestOutputStruct of seq * test_field_compare list
202 (* Run the command sequence and expect the final command (only)
205 | TestLastFail of seq
207 and test_field_compare =
208 | CompareWithInt of string * int
209 | CompareWithString of string * string
210 | CompareFieldsIntEq of string * string
211 | CompareFieldsStrEq of string * string
213 (* Test prerequisites. *)
215 (* Test always runs. *)
217 (* Test is currently disabled - eg. it fails, or it tests some
218 * unimplemented feature.
221 (* 'string' is some C code (a function body) that should return
222 * true or false. The test will run if the code returns true.
225 (* As for 'If' but the test runs _unless_ the code returns true. *)
228 (* Some initial scenarios for testing. *)
230 (* Do nothing, block devices could contain random stuff including
231 * LVM PVs, and some filesystems might be mounted. This is usually
235 (* Block devices are empty and no filesystems are mounted. *)
237 (* /dev/sda contains a single partition /dev/sda1, which is formatted
238 * as ext2, empty [except for lost+found] and mounted on /.
239 * /dev/sdb and /dev/sdc may have random content.
244 * /dev/sda1 (is a PV):
245 * /dev/VG/LV (size 8MB):
246 * formatted as ext2, empty [except for lost+found], mounted on /
247 * /dev/sdb and /dev/sdc may have random content.
251 (* Sequence of commands for testing. *)
253 and cmd = string list
255 (* Note about long descriptions: When referring to another
256 * action, use the format C<guestfs_other> (ie. the full name of
257 * the C function). This will be replaced as appropriate in other
260 * Apart from that, long descriptions are just perldoc paragraphs.
263 (* These test functions are used in the language binding tests. *)
265 let test_all_args = [
268 StringList "strlist";
275 let test_all_rets = [
276 (* except for RErr, which is tested thoroughly elsewhere *)
277 "test0rint", RInt "valout";
278 "test0rint64", RInt64 "valout";
279 "test0rbool", RBool "valout";
280 "test0rconststring", RConstString "valout";
281 "test0rstring", RString "valout";
282 "test0rstringlist", RStringList "valout";
283 "test0rstruct", RStruct ("valout", "lvm_pv");
284 "test0rstructlist", RStructList ("valout", "lvm_pv");
285 "test0rhashtable", RHashtable "valout";
288 let test_functions = [
289 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
291 "internal test function - do not use",
293 This is an internal test function which is used to test whether
294 the automatically generated bindings can handle every possible
295 parameter type correctly.
297 It echos the contents of each parameter to stdout.
299 You probably don't want to call this function.");
303 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
305 "internal test function - do not use",
307 This is an internal test function which is used to test whether
308 the automatically generated bindings can handle every possible
309 return type correctly.
311 It converts string C<val> to the return type.
313 You probably don't want to call this function.");
314 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
316 "internal test function - do not use",
318 This is an internal test function which is used to test whether
319 the automatically generated bindings can handle every possible
320 return type correctly.
322 This function always returns an error.
324 You probably don't want to call this function.")]
328 (* non_daemon_functions are any functions which don't get processed
329 * in the daemon, eg. functions for setting and getting local
330 * configuration values.
333 let non_daemon_functions = test_functions @ [
334 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
336 "launch the qemu subprocess",
338 Internally libguestfs is implemented by running a virtual machine
341 You should call this after configuring the handle
342 (eg. adding drives) but before performing any actions.");
344 ("wait_ready", (RErr, []), -1, [NotInFish],
346 "wait until the qemu subprocess launches",
348 Internally libguestfs is implemented by running a virtual machine
351 You should call this after C<guestfs_launch> to wait for the launch
354 ("kill_subprocess", (RErr, []), -1, [],
356 "kill the qemu subprocess",
358 This kills the qemu subprocess. You should never need to call this.");
360 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
362 "add an image to examine or modify",
364 This function adds a virtual machine disk image C<filename> to the
365 guest. The first time you call this function, the disk appears as IDE
366 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
369 You don't necessarily need to be root when using libguestfs. However
370 you obviously do need sufficient permissions to access the filename
371 for whatever operations you want to perform (ie. read access if you
372 just want to read the image or write access if you want to modify the
375 This is equivalent to the qemu parameter
376 C<-drive file=filename,cache=off,if=...>.
378 Note that this call checks for the existence of C<filename>. This
379 stops you from specifying other types of drive which are supported
380 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
381 the general C<guestfs_config> call instead.");
383 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
385 "add a CD-ROM disk image to examine",
387 This function adds a virtual CD-ROM disk image to the guest.
389 This is equivalent to the qemu parameter C<-cdrom filename>.
391 Note that this call checks for the existence of C<filename>. This
392 stops you from specifying other types of drive which are supported
393 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
394 the general C<guestfs_config> call instead.");
396 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
398 "add a drive in snapshot mode (read-only)",
400 This adds a drive in snapshot mode, making it effectively
403 Note that writes to the device are allowed, and will be seen for
404 the duration of the guestfs handle, but they are written
405 to a temporary file which is discarded as soon as the guestfs
406 handle is closed. We don't currently have any method to enable
407 changes to be committed, although qemu can support this.
409 This is equivalent to the qemu parameter
410 C<-drive file=filename,snapshot=on,if=...>.
412 Note that this call checks for the existence of C<filename>. This
413 stops you from specifying other types of drive which are supported
414 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
415 the general C<guestfs_config> call instead.");
417 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
419 "add qemu parameters",
421 This can be used to add arbitrary qemu command line parameters
422 of the form C<-param value>. Actually it's not quite arbitrary - we
423 prevent you from setting some parameters which would interfere with
424 parameters that we use.
426 The first character of C<param> string must be a C<-> (dash).
428 C<value> can be NULL.");
430 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
432 "set the qemu binary",
434 Set the qemu binary that we will use.
436 The default is chosen when the library was compiled by the
439 You can also override this by setting the C<LIBGUESTFS_QEMU>
440 environment variable.
442 Setting C<qemu> to C<NULL> restores the default qemu binary.");
444 ("get_qemu", (RConstString "qemu", []), -1, [],
446 "get the qemu binary",
448 Return the current qemu binary.
450 This is always non-NULL. If it wasn't set already, then this will
451 return the default qemu binary name.");
453 ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
455 "set the search path",
457 Set the path that libguestfs searches for kernel and initrd.img.
459 The default is C<$libdir/guestfs> unless overridden by setting
460 C<LIBGUESTFS_PATH> environment variable.
462 Setting C<path> to C<NULL> restores the default path.");
464 ("get_path", (RConstString "path", []), -1, [],
466 "get the search path",
468 Return the current search path.
470 This is always non-NULL. If it wasn't set already, then this will
471 return the default path.");
473 ("set_append", (RErr, [String "append"]), -1, [FishAlias "append"],
475 "add options to kernel command line",
477 This function is used to add additional options to the
478 guest kernel command line.
480 The default is C<NULL> unless overridden by setting
481 C<LIBGUESTFS_APPEND> environment variable.
483 Setting C<append> to C<NULL> means I<no> additional options
484 are passed (libguestfs always adds a few of its own).");
486 ("get_append", (RConstString "append", []), -1, [],
488 "get the additional kernel options",
490 Return the additional kernel options which are added to the
491 guest kernel command line.
493 If C<NULL> then no options are added.");
495 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
499 If C<autosync> is true, this enables autosync. Libguestfs will make a
500 best effort attempt to run C<guestfs_umount_all> followed by
501 C<guestfs_sync> when the handle is closed
502 (also if the program exits without closing handles).
504 This is disabled by default (except in guestfish where it is
505 enabled by default).");
507 ("get_autosync", (RBool "autosync", []), -1, [],
511 Get the autosync flag.");
513 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
517 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
519 Verbose messages are disabled unless the environment variable
520 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
522 ("get_verbose", (RBool "verbose", []), -1, [],
526 This returns the verbose messages flag.");
528 ("is_ready", (RBool "ready", []), -1, [],
530 "is ready to accept commands",
532 This returns true iff this handle is ready to accept commands
533 (in the C<READY> state).
535 For more information on states, see L<guestfs(3)>.");
537 ("is_config", (RBool "config", []), -1, [],
539 "is in configuration state",
541 This returns true iff this handle is being configured
542 (in the C<CONFIG> state).
544 For more information on states, see L<guestfs(3)>.");
546 ("is_launching", (RBool "launching", []), -1, [],
548 "is launching subprocess",
550 This returns true iff this handle is launching the subprocess
551 (in the C<LAUNCHING> state).
553 For more information on states, see L<guestfs(3)>.");
555 ("is_busy", (RBool "busy", []), -1, [],
557 "is busy processing a command",
559 This returns true iff this handle is busy processing a command
560 (in the C<BUSY> state).
562 For more information on states, see L<guestfs(3)>.");
564 ("get_state", (RInt "state", []), -1, [],
566 "get the current state",
568 This returns the current state as an opaque integer. This is
569 only useful for printing debug and internal error messages.
571 For more information on states, see L<guestfs(3)>.");
573 ("set_busy", (RErr, []), -1, [NotInFish],
577 This sets the state to C<BUSY>. This is only used when implementing
578 actions using the low-level API.
580 For more information on states, see L<guestfs(3)>.");
582 ("set_ready", (RErr, []), -1, [NotInFish],
584 "set state to ready",
586 This sets the state to C<READY>. This is only used when implementing
587 actions using the low-level API.
589 For more information on states, see L<guestfs(3)>.");
591 ("end_busy", (RErr, []), -1, [NotInFish],
593 "leave the busy state",
595 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
596 state as is. This is only used when implementing
597 actions using the low-level API.
599 For more information on states, see L<guestfs(3)>.");
601 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
603 "set memory allocated to the qemu subprocess",
605 This sets the memory size in megabytes allocated to the
606 qemu subprocess. This only has any effect if called before
609 You can also change this by setting the environment
610 variable C<LIBGUESTFS_MEMSIZE> before the handle is
613 For more information on the architecture of libguestfs,
614 see L<guestfs(3)>.");
616 ("get_memsize", (RInt "memsize", []), -1, [],
618 "get memory allocated to the qemu subprocess",
620 This gets the memory size in megabytes allocated to the
623 If C<guestfs_set_memsize> was not called
624 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
625 then this returns the compiled-in default value for memsize.
627 For more information on the architecture of libguestfs,
628 see L<guestfs(3)>.");
630 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
632 "get PID of qemu subprocess",
634 Return the process ID of the qemu subprocess. If there is no
635 qemu subprocess, then this will return an error.
637 This is an internal call used for debugging and testing.");
641 (* daemon_functions are any functions which cause some action
642 * to take place in the daemon.
645 let daemon_functions = [
646 ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
647 [InitEmpty, Always, TestOutput (
648 [["sfdiskM"; "/dev/sda"; ","];
649 ["mkfs"; "ext2"; "/dev/sda1"];
650 ["mount"; "/dev/sda1"; "/"];
651 ["write_file"; "/new"; "new file contents"; "0"];
652 ["cat"; "/new"]], "new file contents")],
653 "mount a guest disk at a position in the filesystem",
655 Mount a guest disk at a position in the filesystem. Block devices
656 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
657 the guest. If those block devices contain partitions, they will have
658 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
661 The rules are the same as for L<mount(2)>: A filesystem must
662 first be mounted on C</> before others can be mounted. Other
663 filesystems can only be mounted on directories which already
666 The mounted filesystem is writable, if we have sufficient permissions
667 on the underlying device.
669 The filesystem options C<sync> and C<noatime> are set with this
670 call, in order to improve reliability.");
672 ("sync", (RErr, []), 2, [],
673 [ InitEmpty, Always, TestRun [["sync"]]],
674 "sync disks, writes are flushed through to the disk image",
676 This syncs the disk, so that any writes are flushed through to the
677 underlying disk image.
679 You should always call this if you have modified a disk image, before
680 closing the handle.");
682 ("touch", (RErr, [String "path"]), 3, [],
683 [InitBasicFS, Always, TestOutputTrue (
685 ["exists"; "/new"]])],
686 "update file timestamps or create a new file",
688 Touch acts like the L<touch(1)> command. It can be used to
689 update the timestamps on a file, or, if the file does not exist,
690 to create a new zero-length file.");
692 ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
693 [InitBasicFS, Always, TestOutput (
694 [["write_file"; "/new"; "new file contents"; "0"];
695 ["cat"; "/new"]], "new file contents")],
696 "list the contents of a file",
698 Return the contents of the file named C<path>.
700 Note that this function cannot correctly handle binary files
701 (specifically, files containing C<\\0> character which is treated
702 as end of string). For those you need to use the C<guestfs_download>
703 function which has a more complex interface.");
705 ("ll", (RString "listing", [String "directory"]), 5, [],
706 [], (* XXX Tricky to test because it depends on the exact format
707 * of the 'ls -l' command, which changes between F10 and F11.
709 "list the files in a directory (long format)",
711 List the files in C<directory> (relative to the root directory,
712 there is no cwd) in the format of 'ls -la'.
714 This command is mostly useful for interactive sessions. It
715 is I<not> intended that you try to parse the output string.");
717 ("ls", (RStringList "listing", [String "directory"]), 6, [],
718 [InitBasicFS, Always, TestOutputList (
721 ["touch"; "/newest"];
722 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
723 "list the files in a directory",
725 List the files in C<directory> (relative to the root directory,
726 there is no cwd). The '.' and '..' entries are not returned, but
727 hidden files are shown.
729 This command is mostly useful for interactive sessions. Programs
730 should probably use C<guestfs_readdir> instead.");
732 ("list_devices", (RStringList "devices", []), 7, [],
733 [InitEmpty, Always, TestOutputListOfDevices (
734 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
735 "list the block devices",
737 List all the block devices.
739 The full block device names are returned, eg. C</dev/sda>");
741 ("list_partitions", (RStringList "partitions", []), 8, [],
742 [InitBasicFS, Always, TestOutputListOfDevices (
743 [["list_partitions"]], ["/dev/sda1"]);
744 InitEmpty, Always, TestOutputListOfDevices (
745 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
746 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
747 "list the partitions",
749 List all the partitions detected on all block devices.
751 The full partition device names are returned, eg. C</dev/sda1>
753 This does not return logical volumes. For that you will need to
754 call C<guestfs_lvs>.");
756 ("pvs", (RStringList "physvols", []), 9, [],
757 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
758 [["pvs"]], ["/dev/sda1"]);
759 InitEmpty, Always, TestOutputListOfDevices (
760 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
761 ["pvcreate"; "/dev/sda1"];
762 ["pvcreate"; "/dev/sda2"];
763 ["pvcreate"; "/dev/sda3"];
764 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
765 "list the LVM physical volumes (PVs)",
767 List all the physical volumes detected. This is the equivalent
768 of the L<pvs(8)> command.
770 This returns a list of just the device names that contain
771 PVs (eg. C</dev/sda2>).
773 See also C<guestfs_pvs_full>.");
775 ("vgs", (RStringList "volgroups", []), 10, [],
776 [InitBasicFSonLVM, Always, TestOutputList (
778 InitEmpty, Always, TestOutputList (
779 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
780 ["pvcreate"; "/dev/sda1"];
781 ["pvcreate"; "/dev/sda2"];
782 ["pvcreate"; "/dev/sda3"];
783 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
784 ["vgcreate"; "VG2"; "/dev/sda3"];
785 ["vgs"]], ["VG1"; "VG2"])],
786 "list the LVM volume groups (VGs)",
788 List all the volumes groups detected. This is the equivalent
789 of the L<vgs(8)> command.
791 This returns a list of just the volume group names that were
792 detected (eg. C<VolGroup00>).
794 See also C<guestfs_vgs_full>.");
796 ("lvs", (RStringList "logvols", []), 11, [],
797 [InitBasicFSonLVM, Always, TestOutputList (
798 [["lvs"]], ["/dev/VG/LV"]);
799 InitEmpty, Always, TestOutputList (
800 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
801 ["pvcreate"; "/dev/sda1"];
802 ["pvcreate"; "/dev/sda2"];
803 ["pvcreate"; "/dev/sda3"];
804 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
805 ["vgcreate"; "VG2"; "/dev/sda3"];
806 ["lvcreate"; "LV1"; "VG1"; "50"];
807 ["lvcreate"; "LV2"; "VG1"; "50"];
808 ["lvcreate"; "LV3"; "VG2"; "50"];
809 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
810 "list the LVM logical volumes (LVs)",
812 List all the logical volumes detected. This is the equivalent
813 of the L<lvs(8)> command.
815 This returns a list of the logical volume device names
816 (eg. C</dev/VolGroup00/LogVol00>).
818 See also C<guestfs_lvs_full>.");
820 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
821 [], (* XXX how to test? *)
822 "list the LVM physical volumes (PVs)",
824 List all the physical volumes detected. This is the equivalent
825 of the L<pvs(8)> command. The \"full\" version includes all fields.");
827 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
828 [], (* XXX how to test? *)
829 "list the LVM volume groups (VGs)",
831 List all the volumes groups detected. This is the equivalent
832 of the L<vgs(8)> command. The \"full\" version includes all fields.");
834 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
835 [], (* XXX how to test? *)
836 "list the LVM logical volumes (LVs)",
838 List all the logical volumes detected. This is the equivalent
839 of the L<lvs(8)> command. The \"full\" version includes all fields.");
841 ("read_lines", (RStringList "lines", [String "path"]), 15, [],
842 [InitBasicFS, Always, TestOutputList (
843 [["write_file"; "/new"; "line1\r\nline2\nline3"; "0"];
844 ["read_lines"; "/new"]], ["line1"; "line2"; "line3"]);
845 InitBasicFS, Always, TestOutputList (
846 [["write_file"; "/new"; ""; "0"];
847 ["read_lines"; "/new"]], [])],
848 "read file as lines",
850 Return the contents of the file named C<path>.
852 The file contents are returned as a list of lines. Trailing
853 C<LF> and C<CRLF> character sequences are I<not> returned.
855 Note that this function cannot correctly handle binary files
856 (specifically, files containing C<\\0> character which is treated
857 as end of line). For those you need to use the C<guestfs_read_file>
858 function which has a more complex interface.");
860 ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
861 [], (* XXX Augeas code needs tests. *)
862 "create a new Augeas handle",
864 Create a new Augeas handle for editing configuration files.
865 If there was any previous Augeas handle associated with this
866 guestfs session, then it is closed.
868 You must call this before using any other C<guestfs_aug_*>
871 C<root> is the filesystem root. C<root> must not be NULL,
874 The flags are the same as the flags defined in
875 E<lt>augeas.hE<gt>, the logical I<or> of the following
880 =item C<AUG_SAVE_BACKUP> = 1
882 Keep the original file with a C<.augsave> extension.
884 =item C<AUG_SAVE_NEWFILE> = 2
886 Save changes into a file with extension C<.augnew>, and
887 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
889 =item C<AUG_TYPE_CHECK> = 4
891 Typecheck lenses (can be expensive).
893 =item C<AUG_NO_STDINC> = 8
895 Do not use standard load path for modules.
897 =item C<AUG_SAVE_NOOP> = 16
899 Make save a no-op, just record what would have been changed.
901 =item C<AUG_NO_LOAD> = 32
903 Do not load the tree in C<guestfs_aug_init>.
907 To close the handle, you can call C<guestfs_aug_close>.
909 To find out more about Augeas, see L<http://augeas.net/>.");
911 ("aug_close", (RErr, []), 26, [],
912 [], (* XXX Augeas code needs tests. *)
913 "close the current Augeas handle",
915 Close the current Augeas handle and free up any resources
916 used by it. After calling this, you have to call
917 C<guestfs_aug_init> again before you can use any other
920 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
921 [], (* XXX Augeas code needs tests. *)
922 "define an Augeas variable",
924 Defines an Augeas variable C<name> whose value is the result
925 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
928 On success this returns the number of nodes in C<expr>, or
929 C<0> if C<expr> evaluates to something which is not a nodeset.");
931 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
932 [], (* XXX Augeas code needs tests. *)
933 "define an Augeas node",
935 Defines a variable C<name> whose value is the result of
938 If C<expr> evaluates to an empty nodeset, a node is created,
939 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
940 C<name> will be the nodeset containing that single node.
942 On success this returns a pair containing the
943 number of nodes in the nodeset, and a boolean flag
944 if a node was created.");
946 ("aug_get", (RString "val", [String "path"]), 19, [],
947 [], (* XXX Augeas code needs tests. *)
948 "look up the value of an Augeas path",
950 Look up the value associated with C<path>. If C<path>
951 matches exactly one node, the C<value> is returned.");
953 ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
954 [], (* XXX Augeas code needs tests. *)
955 "set Augeas path to value",
957 Set the value associated with C<path> to C<value>.");
959 ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
960 [], (* XXX Augeas code needs tests. *)
961 "insert a sibling Augeas node",
963 Create a new sibling C<label> for C<path>, inserting it into
964 the tree before or after C<path> (depending on the boolean
967 C<path> must match exactly one existing node in the tree, and
968 C<label> must be a label, ie. not contain C</>, C<*> or end
969 with a bracketed index C<[N]>.");
971 ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
972 [], (* XXX Augeas code needs tests. *)
973 "remove an Augeas path",
975 Remove C<path> and all of its children.
977 On success this returns the number of entries which were removed.");
979 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
980 [], (* XXX Augeas code needs tests. *)
983 Move the node C<src> to C<dest>. C<src> must match exactly
984 one node. C<dest> is overwritten if it exists.");
986 ("aug_match", (RStringList "matches", [String "path"]), 24, [],
987 [], (* XXX Augeas code needs tests. *)
988 "return Augeas nodes which match path",
990 Returns a list of paths which match the path expression C<path>.
991 The returned paths are sufficiently qualified so that they match
992 exactly one node in the current tree.");
994 ("aug_save", (RErr, []), 25, [],
995 [], (* XXX Augeas code needs tests. *)
996 "write all pending Augeas changes to disk",
998 This writes all pending changes to disk.
1000 The flags which were passed to C<guestfs_aug_init> affect exactly
1001 how files are saved.");
1003 ("aug_load", (RErr, []), 27, [],
1004 [], (* XXX Augeas code needs tests. *)
1005 "load files into the tree",
1007 Load files into the tree.
1009 See C<aug_load> in the Augeas documentation for the full gory
1012 ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
1013 [], (* XXX Augeas code needs tests. *)
1014 "list Augeas nodes under a path",
1016 This is just a shortcut for listing C<guestfs_aug_match>
1017 C<path/*> and sorting the resulting nodes into alphabetical order.");
1019 ("rm", (RErr, [String "path"]), 29, [],
1020 [InitBasicFS, Always, TestRun
1023 InitBasicFS, Always, TestLastFail
1025 InitBasicFS, Always, TestLastFail
1030 Remove the single file C<path>.");
1032 ("rmdir", (RErr, [String "path"]), 30, [],
1033 [InitBasicFS, Always, TestRun
1036 InitBasicFS, Always, TestLastFail
1037 [["rmdir"; "/new"]];
1038 InitBasicFS, Always, TestLastFail
1040 ["rmdir"; "/new"]]],
1041 "remove a directory",
1043 Remove the single directory C<path>.");
1045 ("rm_rf", (RErr, [String "path"]), 31, [],
1046 [InitBasicFS, Always, TestOutputFalse
1048 ["mkdir"; "/new/foo"];
1049 ["touch"; "/new/foo/bar"];
1051 ["exists"; "/new"]]],
1052 "remove a file or directory recursively",
1054 Remove the file or directory C<path>, recursively removing the
1055 contents if its a directory. This is like the C<rm -rf> shell
1058 ("mkdir", (RErr, [String "path"]), 32, [],
1059 [InitBasicFS, Always, TestOutputTrue
1061 ["is_dir"; "/new"]];
1062 InitBasicFS, Always, TestLastFail
1063 [["mkdir"; "/new/foo/bar"]]],
1064 "create a directory",
1066 Create a directory named C<path>.");
1068 ("mkdir_p", (RErr, [String "path"]), 33, [],
1069 [InitBasicFS, Always, TestOutputTrue
1070 [["mkdir_p"; "/new/foo/bar"];
1071 ["is_dir"; "/new/foo/bar"]];
1072 InitBasicFS, Always, TestOutputTrue
1073 [["mkdir_p"; "/new/foo/bar"];
1074 ["is_dir"; "/new/foo"]];
1075 InitBasicFS, Always, TestOutputTrue
1076 [["mkdir_p"; "/new/foo/bar"];
1077 ["is_dir"; "/new"]];
1078 (* Regression tests for RHBZ#503133: *)
1079 InitBasicFS, Always, TestRun
1081 ["mkdir_p"; "/new"]];
1082 InitBasicFS, Always, TestLastFail
1084 ["mkdir_p"; "/new"]]],
1085 "create a directory and parents",
1087 Create a directory named C<path>, creating any parent directories
1088 as necessary. This is like the C<mkdir -p> shell command.");
1090 ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1091 [], (* XXX Need stat command to test *)
1094 Change the mode (permissions) of C<path> to C<mode>. Only
1095 numeric modes are supported.");
1097 ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1098 [], (* XXX Need stat command to test *)
1099 "change file owner and group",
1101 Change the file owner to C<owner> and group to C<group>.
1103 Only numeric uid and gid are supported. If you want to use
1104 names, you will need to locate and parse the password file
1105 yourself (Augeas support makes this relatively easy).");
1107 ("exists", (RBool "existsflag", [String "path"]), 36, [],
1108 [InitBasicFS, Always, TestOutputTrue (
1110 ["exists"; "/new"]]);
1111 InitBasicFS, Always, TestOutputTrue (
1113 ["exists"; "/new"]])],
1114 "test if file or directory exists",
1116 This returns C<true> if and only if there is a file, directory
1117 (or anything) with the given C<path> name.
1119 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1121 ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1122 [InitBasicFS, Always, TestOutputTrue (
1124 ["is_file"; "/new"]]);
1125 InitBasicFS, Always, TestOutputFalse (
1127 ["is_file"; "/new"]])],
1128 "test if file exists",
1130 This returns C<true> if and only if there is a file
1131 with the given C<path> name. Note that it returns false for
1132 other objects like directories.
1134 See also C<guestfs_stat>.");
1136 ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1137 [InitBasicFS, Always, TestOutputFalse (
1139 ["is_dir"; "/new"]]);
1140 InitBasicFS, Always, TestOutputTrue (
1142 ["is_dir"; "/new"]])],
1143 "test if file exists",
1145 This returns C<true> if and only if there is a directory
1146 with the given C<path> name. Note that it returns false for
1147 other objects like files.
1149 See also C<guestfs_stat>.");
1151 ("pvcreate", (RErr, [String "device"]), 39, [],
1152 [InitEmpty, Always, TestOutputListOfDevices (
1153 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1154 ["pvcreate"; "/dev/sda1"];
1155 ["pvcreate"; "/dev/sda2"];
1156 ["pvcreate"; "/dev/sda3"];
1157 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1158 "create an LVM physical volume",
1160 This creates an LVM physical volume on the named C<device>,
1161 where C<device> should usually be a partition name such
1164 ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1165 [InitEmpty, Always, TestOutputList (
1166 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1167 ["pvcreate"; "/dev/sda1"];
1168 ["pvcreate"; "/dev/sda2"];
1169 ["pvcreate"; "/dev/sda3"];
1170 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1171 ["vgcreate"; "VG2"; "/dev/sda3"];
1172 ["vgs"]], ["VG1"; "VG2"])],
1173 "create an LVM volume group",
1175 This creates an LVM volume group called C<volgroup>
1176 from the non-empty list of physical volumes C<physvols>.");
1178 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1179 [InitEmpty, Always, TestOutputList (
1180 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1181 ["pvcreate"; "/dev/sda1"];
1182 ["pvcreate"; "/dev/sda2"];
1183 ["pvcreate"; "/dev/sda3"];
1184 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1185 ["vgcreate"; "VG2"; "/dev/sda3"];
1186 ["lvcreate"; "LV1"; "VG1"; "50"];
1187 ["lvcreate"; "LV2"; "VG1"; "50"];
1188 ["lvcreate"; "LV3"; "VG2"; "50"];
1189 ["lvcreate"; "LV4"; "VG2"; "50"];
1190 ["lvcreate"; "LV5"; "VG2"; "50"];
1192 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1193 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1194 "create an LVM volume group",
1196 This creates an LVM volume group called C<logvol>
1197 on the volume group C<volgroup>, with C<size> megabytes.");
1199 ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1200 [InitEmpty, Always, TestOutput (
1201 [["sfdiskM"; "/dev/sda"; ","];
1202 ["mkfs"; "ext2"; "/dev/sda1"];
1203 ["mount"; "/dev/sda1"; "/"];
1204 ["write_file"; "/new"; "new file contents"; "0"];
1205 ["cat"; "/new"]], "new file contents")],
1206 "make a filesystem",
1208 This creates a filesystem on C<device> (usually a partition
1209 or LVM logical volume). The filesystem type is C<fstype>, for
1212 ("sfdisk", (RErr, [String "device";
1213 Int "cyls"; Int "heads"; Int "sectors";
1214 StringList "lines"]), 43, [DangerWillRobinson],
1216 "create partitions on a block device",
1218 This is a direct interface to the L<sfdisk(8)> program for creating
1219 partitions on block devices.
1221 C<device> should be a block device, for example C</dev/sda>.
1223 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1224 and sectors on the device, which are passed directly to sfdisk as
1225 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1226 of these, then the corresponding parameter is omitted. Usually for
1227 'large' disks, you can just pass C<0> for these, but for small
1228 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1229 out the right geometry and you will need to tell it.
1231 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1232 information refer to the L<sfdisk(8)> manpage.
1234 To create a single partition occupying the whole disk, you would
1235 pass C<lines> as a single element list, when the single element being
1236 the string C<,> (comma).
1238 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1240 ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1241 [InitBasicFS, Always, TestOutput (
1242 [["write_file"; "/new"; "new file contents"; "0"];
1243 ["cat"; "/new"]], "new file contents");
1244 InitBasicFS, Always, TestOutput (
1245 [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1246 ["cat"; "/new"]], "\nnew file contents\n");
1247 InitBasicFS, Always, TestOutput (
1248 [["write_file"; "/new"; "\n\n"; "0"];
1249 ["cat"; "/new"]], "\n\n");
1250 InitBasicFS, Always, TestOutput (
1251 [["write_file"; "/new"; ""; "0"];
1252 ["cat"; "/new"]], "");
1253 InitBasicFS, Always, TestOutput (
1254 [["write_file"; "/new"; "\n\n\n"; "0"];
1255 ["cat"; "/new"]], "\n\n\n");
1256 InitBasicFS, Always, TestOutput (
1257 [["write_file"; "/new"; "\n"; "0"];
1258 ["cat"; "/new"]], "\n")],
1261 This call creates a file called C<path>. The contents of the
1262 file is the string C<content> (which can contain any 8 bit data),
1263 with length C<size>.
1265 As a special case, if C<size> is C<0>
1266 then the length is calculated using C<strlen> (so in this case
1267 the content cannot contain embedded ASCII NULs).
1269 I<NB.> Owing to a bug, writing content containing ASCII NUL
1270 characters does I<not> work, even if the length is specified.
1271 We hope to resolve this bug in a future version. In the meantime
1272 use C<guestfs_upload>.");
1274 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1275 [InitEmpty, Always, TestOutputListOfDevices (
1276 [["sfdiskM"; "/dev/sda"; ","];
1277 ["mkfs"; "ext2"; "/dev/sda1"];
1278 ["mount"; "/dev/sda1"; "/"];
1279 ["mounts"]], ["/dev/sda1"]);
1280 InitEmpty, Always, TestOutputList (
1281 [["sfdiskM"; "/dev/sda"; ","];
1282 ["mkfs"; "ext2"; "/dev/sda1"];
1283 ["mount"; "/dev/sda1"; "/"];
1286 "unmount a filesystem",
1288 This unmounts the given filesystem. The filesystem may be
1289 specified either by its mountpoint (path) or the device which
1290 contains the filesystem.");
1292 ("mounts", (RStringList "devices", []), 46, [],
1293 [InitBasicFS, Always, TestOutputListOfDevices (
1294 [["mounts"]], ["/dev/sda1"])],
1295 "show mounted filesystems",
1297 This returns the list of currently mounted filesystems. It returns
1298 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1300 Some internal mounts are not shown.");
1302 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1303 [InitBasicFS, Always, TestOutputList (
1306 (* check that umount_all can unmount nested mounts correctly: *)
1307 InitEmpty, Always, TestOutputList (
1308 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1309 ["mkfs"; "ext2"; "/dev/sda1"];
1310 ["mkfs"; "ext2"; "/dev/sda2"];
1311 ["mkfs"; "ext2"; "/dev/sda3"];
1312 ["mount"; "/dev/sda1"; "/"];
1314 ["mount"; "/dev/sda2"; "/mp1"];
1315 ["mkdir"; "/mp1/mp2"];
1316 ["mount"; "/dev/sda3"; "/mp1/mp2"];
1317 ["mkdir"; "/mp1/mp2/mp3"];
1320 "unmount all filesystems",
1322 This unmounts all mounted filesystems.
1324 Some internal mounts are not unmounted by this call.");
1326 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1328 "remove all LVM LVs, VGs and PVs",
1330 This command removes all LVM logical volumes, volume groups
1331 and physical volumes.");
1333 ("file", (RString "description", [String "path"]), 49, [],
1334 [InitBasicFS, Always, TestOutput (
1336 ["file"; "/new"]], "empty");
1337 InitBasicFS, Always, TestOutput (
1338 [["write_file"; "/new"; "some content\n"; "0"];
1339 ["file"; "/new"]], "ASCII text");
1340 InitBasicFS, Always, TestLastFail (
1341 [["file"; "/nofile"]])],
1342 "determine file type",
1344 This call uses the standard L<file(1)> command to determine
1345 the type or contents of the file. This also works on devices,
1346 for example to find out whether a partition contains a filesystem.
1348 The exact command which runs is C<file -bsL path>. Note in
1349 particular that the filename is not prepended to the output
1350 (the C<-b> option).");
1352 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1353 [InitBasicFS, Always, TestOutput (
1354 [["upload"; "test-command"; "/test-command"];
1355 ["chmod"; "0o755"; "/test-command"];
1356 ["command"; "/test-command 1"]], "Result1");
1357 InitBasicFS, Always, TestOutput (
1358 [["upload"; "test-command"; "/test-command"];
1359 ["chmod"; "0o755"; "/test-command"];
1360 ["command"; "/test-command 2"]], "Result2\n");
1361 InitBasicFS, Always, TestOutput (
1362 [["upload"; "test-command"; "/test-command"];
1363 ["chmod"; "0o755"; "/test-command"];
1364 ["command"; "/test-command 3"]], "\nResult3");
1365 InitBasicFS, Always, TestOutput (
1366 [["upload"; "test-command"; "/test-command"];
1367 ["chmod"; "0o755"; "/test-command"];
1368 ["command"; "/test-command 4"]], "\nResult4\n");
1369 InitBasicFS, Always, TestOutput (
1370 [["upload"; "test-command"; "/test-command"];
1371 ["chmod"; "0o755"; "/test-command"];
1372 ["command"; "/test-command 5"]], "\nResult5\n\n");
1373 InitBasicFS, Always, TestOutput (
1374 [["upload"; "test-command"; "/test-command"];
1375 ["chmod"; "0o755"; "/test-command"];
1376 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1377 InitBasicFS, Always, TestOutput (
1378 [["upload"; "test-command"; "/test-command"];
1379 ["chmod"; "0o755"; "/test-command"];
1380 ["command"; "/test-command 7"]], "");
1381 InitBasicFS, Always, TestOutput (
1382 [["upload"; "test-command"; "/test-command"];
1383 ["chmod"; "0o755"; "/test-command"];
1384 ["command"; "/test-command 8"]], "\n");
1385 InitBasicFS, Always, TestOutput (
1386 [["upload"; "test-command"; "/test-command"];
1387 ["chmod"; "0o755"; "/test-command"];
1388 ["command"; "/test-command 9"]], "\n\n");
1389 InitBasicFS, Always, TestOutput (
1390 [["upload"; "test-command"; "/test-command"];
1391 ["chmod"; "0o755"; "/test-command"];
1392 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1393 InitBasicFS, Always, TestOutput (
1394 [["upload"; "test-command"; "/test-command"];
1395 ["chmod"; "0o755"; "/test-command"];
1396 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1397 InitBasicFS, Always, TestLastFail (
1398 [["upload"; "test-command"; "/test-command"];
1399 ["chmod"; "0o755"; "/test-command"];
1400 ["command"; "/test-command"]])],
1401 "run a command from the guest filesystem",
1403 This call runs a command from the guest filesystem. The
1404 filesystem must be mounted, and must contain a compatible
1405 operating system (ie. something Linux, with the same
1406 or compatible processor architecture).
1408 The single parameter is an argv-style list of arguments.
1409 The first element is the name of the program to run.
1410 Subsequent elements are parameters. The list must be
1411 non-empty (ie. must contain a program name). Note that
1412 the command runs directly, and is I<not> invoked via
1413 the shell (see C<guestfs_sh>).
1415 The return value is anything printed to I<stdout> by
1418 If the command returns a non-zero exit status, then
1419 this function returns an error message. The error message
1420 string is the content of I<stderr> from the command.
1422 The C<$PATH> environment variable will contain at least
1423 C</usr/bin> and C</bin>. If you require a program from
1424 another location, you should provide the full path in the
1427 Shared libraries and data files required by the program
1428 must be available on filesystems which are mounted in the
1429 correct places. It is the caller's responsibility to ensure
1430 all filesystems that are needed are mounted at the right
1433 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1434 [InitBasicFS, Always, TestOutputList (
1435 [["upload"; "test-command"; "/test-command"];
1436 ["chmod"; "0o755"; "/test-command"];
1437 ["command_lines"; "/test-command 1"]], ["Result1"]);
1438 InitBasicFS, Always, TestOutputList (
1439 [["upload"; "test-command"; "/test-command"];
1440 ["chmod"; "0o755"; "/test-command"];
1441 ["command_lines"; "/test-command 2"]], ["Result2"]);
1442 InitBasicFS, Always, TestOutputList (
1443 [["upload"; "test-command"; "/test-command"];
1444 ["chmod"; "0o755"; "/test-command"];
1445 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1446 InitBasicFS, Always, TestOutputList (
1447 [["upload"; "test-command"; "/test-command"];
1448 ["chmod"; "0o755"; "/test-command"];
1449 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1450 InitBasicFS, Always, TestOutputList (
1451 [["upload"; "test-command"; "/test-command"];
1452 ["chmod"; "0o755"; "/test-command"];
1453 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1454 InitBasicFS, Always, TestOutputList (
1455 [["upload"; "test-command"; "/test-command"];
1456 ["chmod"; "0o755"; "/test-command"];
1457 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1458 InitBasicFS, Always, TestOutputList (
1459 [["upload"; "test-command"; "/test-command"];
1460 ["chmod"; "0o755"; "/test-command"];
1461 ["command_lines"; "/test-command 7"]], []);
1462 InitBasicFS, Always, TestOutputList (
1463 [["upload"; "test-command"; "/test-command"];
1464 ["chmod"; "0o755"; "/test-command"];
1465 ["command_lines"; "/test-command 8"]], [""]);
1466 InitBasicFS, Always, TestOutputList (
1467 [["upload"; "test-command"; "/test-command"];
1468 ["chmod"; "0o755"; "/test-command"];
1469 ["command_lines"; "/test-command 9"]], ["";""]);
1470 InitBasicFS, Always, TestOutputList (
1471 [["upload"; "test-command"; "/test-command"];
1472 ["chmod"; "0o755"; "/test-command"];
1473 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1474 InitBasicFS, Always, TestOutputList (
1475 [["upload"; "test-command"; "/test-command"];
1476 ["chmod"; "0o755"; "/test-command"];
1477 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1478 "run a command, returning lines",
1480 This is the same as C<guestfs_command>, but splits the
1481 result into a list of lines.
1483 See also: C<guestfs_sh_lines>");
1485 ("stat", (RStruct ("statbuf", "stat"), [String "path"]), 52, [],
1486 [InitBasicFS, Always, TestOutputStruct (
1488 ["stat"; "/new"]], [CompareWithInt ("size", 0)])],
1489 "get file information",
1491 Returns file information for the given C<path>.
1493 This is the same as the C<stat(2)> system call.");
1495 ("lstat", (RStruct ("statbuf", "stat"), [String "path"]), 53, [],
1496 [InitBasicFS, Always, TestOutputStruct (
1498 ["lstat"; "/new"]], [CompareWithInt ("size", 0)])],
1499 "get file information for a symbolic link",
1501 Returns file information for the given C<path>.
1503 This is the same as C<guestfs_stat> except that if C<path>
1504 is a symbolic link, then the link is stat-ed, not the file it
1507 This is the same as the C<lstat(2)> system call.");
1509 ("statvfs", (RStruct ("statbuf", "statvfs"), [String "path"]), 54, [],
1510 [InitBasicFS, Always, TestOutputStruct (
1511 [["statvfs"; "/"]], [CompareWithInt ("namemax", 255);
1512 CompareWithInt ("bsize", 1024)])],
1513 "get file system statistics",
1515 Returns file system statistics for any mounted file system.
1516 C<path> should be a file or directory in the mounted file system
1517 (typically it is the mount point itself, but it doesn't need to be).
1519 This is the same as the C<statvfs(2)> system call.");
1521 ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1523 "get ext2/ext3/ext4 superblock details",
1525 This returns the contents of the ext2, ext3 or ext4 filesystem
1526 superblock on C<device>.
1528 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
1529 manpage for more details. The list of fields returned isn't
1530 clearly defined, and depends on both the version of C<tune2fs>
1531 that libguestfs was built against, and the filesystem itself.");
1533 ("blockdev_setro", (RErr, [String "device"]), 56, [],
1534 [InitEmpty, Always, TestOutputTrue (
1535 [["blockdev_setro"; "/dev/sda"];
1536 ["blockdev_getro"; "/dev/sda"]])],
1537 "set block device to read-only",
1539 Sets the block device named C<device> to read-only.
1541 This uses the L<blockdev(8)> command.");
1543 ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1544 [InitEmpty, Always, TestOutputFalse (
1545 [["blockdev_setrw"; "/dev/sda"];
1546 ["blockdev_getro"; "/dev/sda"]])],
1547 "set block device to read-write",
1549 Sets the block device named C<device> to read-write.
1551 This uses the L<blockdev(8)> command.");
1553 ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1554 [InitEmpty, Always, TestOutputTrue (
1555 [["blockdev_setro"; "/dev/sda"];
1556 ["blockdev_getro"; "/dev/sda"]])],
1557 "is block device set to read-only",
1559 Returns a boolean indicating if the block device is read-only
1560 (true if read-only, false if not).
1562 This uses the L<blockdev(8)> command.");
1564 ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1565 [InitEmpty, Always, TestOutputInt (
1566 [["blockdev_getss"; "/dev/sda"]], 512)],
1567 "get sectorsize of block device",
1569 This returns the size of sectors on a block device.
1570 Usually 512, but can be larger for modern devices.
1572 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1575 This uses the L<blockdev(8)> command.");
1577 ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1578 [InitEmpty, Always, TestOutputInt (
1579 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1580 "get blocksize of block device",
1582 This returns the block size of a device.
1584 (Note this is different from both I<size in blocks> and
1585 I<filesystem block size>).
1587 This uses the L<blockdev(8)> command.");
1589 ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1591 "set blocksize of block device",
1593 This sets the block size of a device.
1595 (Note this is different from both I<size in blocks> and
1596 I<filesystem block size>).
1598 This uses the L<blockdev(8)> command.");
1600 ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1601 [InitEmpty, Always, TestOutputInt (
1602 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1603 "get total size of device in 512-byte sectors",
1605 This returns the size of the device in units of 512-byte sectors
1606 (even if the sectorsize isn't 512 bytes ... weird).
1608 See also C<guestfs_blockdev_getss> for the real sector size of
1609 the device, and C<guestfs_blockdev_getsize64> for the more
1610 useful I<size in bytes>.
1612 This uses the L<blockdev(8)> command.");
1614 ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1615 [InitEmpty, Always, TestOutputInt (
1616 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1617 "get total size of device in bytes",
1619 This returns the size of the device in bytes.
1621 See also C<guestfs_blockdev_getsz>.
1623 This uses the L<blockdev(8)> command.");
1625 ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1626 [InitEmpty, Always, TestRun
1627 [["blockdev_flushbufs"; "/dev/sda"]]],
1628 "flush device buffers",
1630 This tells the kernel to flush internal buffers associated
1633 This uses the L<blockdev(8)> command.");
1635 ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1636 [InitEmpty, Always, TestRun
1637 [["blockdev_rereadpt"; "/dev/sda"]]],
1638 "reread partition table",
1640 Reread the partition table on C<device>.
1642 This uses the L<blockdev(8)> command.");
1644 ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1645 [InitBasicFS, Always, TestOutput (
1646 (* Pick a file from cwd which isn't likely to change. *)
1647 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1648 ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1649 "upload a file from the local machine",
1651 Upload local file C<filename> to C<remotefilename> on the
1654 C<filename> can also be a named pipe.
1656 See also C<guestfs_download>.");
1658 ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1659 [InitBasicFS, Always, TestOutput (
1660 (* Pick a file from cwd which isn't likely to change. *)
1661 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1662 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1663 ["upload"; "testdownload.tmp"; "/upload"];
1664 ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1665 "download a file to the local machine",
1667 Download file C<remotefilename> and save it as C<filename>
1668 on the local machine.
1670 C<filename> can also be a named pipe.
1672 See also C<guestfs_upload>, C<guestfs_cat>.");
1674 ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1675 [InitBasicFS, Always, TestOutput (
1676 [["write_file"; "/new"; "test\n"; "0"];
1677 ["checksum"; "crc"; "/new"]], "935282863");
1678 InitBasicFS, Always, TestLastFail (
1679 [["checksum"; "crc"; "/new"]]);
1680 InitBasicFS, Always, TestOutput (
1681 [["write_file"; "/new"; "test\n"; "0"];
1682 ["checksum"; "md5"; "/new"]], "d8e8fca2dc0f896fd7cb4cb0031ba249");
1683 InitBasicFS, Always, TestOutput (
1684 [["write_file"; "/new"; "test\n"; "0"];
1685 ["checksum"; "sha1"; "/new"]], "4e1243bd22c66e76c2ba9eddc1f91394e57f9f83");
1686 InitBasicFS, Always, TestOutput (
1687 [["write_file"; "/new"; "test\n"; "0"];
1688 ["checksum"; "sha224"; "/new"]], "52f1bf093f4b7588726035c176c0cdb4376cfea53819f1395ac9e6ec");
1689 InitBasicFS, Always, TestOutput (
1690 [["write_file"; "/new"; "test\n"; "0"];
1691 ["checksum"; "sha256"; "/new"]], "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2");
1692 InitBasicFS, Always, TestOutput (
1693 [["write_file"; "/new"; "test\n"; "0"];
1694 ["checksum"; "sha384"; "/new"]], "109bb6b5b6d5547c1ce03c7a8bd7d8f80c1cb0957f50c4f7fda04692079917e4f9cad52b878f3d8234e1a170b154b72d");
1695 InitBasicFS, Always, TestOutput (
1696 [["write_file"; "/new"; "test\n"; "0"];
1697 ["checksum"; "sha512"; "/new"]], "0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123");
1698 InitBasicFS, Always, TestOutput (
1699 (* RHEL 5 thinks this is an HFS+ filesystem unless we give
1700 * the type explicitly.
1702 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
1703 ["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c")],
1704 "compute MD5, SHAx or CRC checksum of file",
1706 This call computes the MD5, SHAx or CRC checksum of the
1709 The type of checksum to compute is given by the C<csumtype>
1710 parameter which must have one of the following values:
1716 Compute the cyclic redundancy check (CRC) specified by POSIX
1717 for the C<cksum> command.
1721 Compute the MD5 hash (using the C<md5sum> program).
1725 Compute the SHA1 hash (using the C<sha1sum> program).
1729 Compute the SHA224 hash (using the C<sha224sum> program).
1733 Compute the SHA256 hash (using the C<sha256sum> program).
1737 Compute the SHA384 hash (using the C<sha384sum> program).
1741 Compute the SHA512 hash (using the C<sha512sum> program).
1745 The checksum is returned as a printable string.");
1747 ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1748 [InitBasicFS, Always, TestOutput (
1749 [["tar_in"; "../images/helloworld.tar"; "/"];
1750 ["cat"; "/hello"]], "hello\n")],
1751 "unpack tarfile to directory",
1753 This command uploads and unpacks local file C<tarfile> (an
1754 I<uncompressed> tar file) into C<directory>.
1756 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1758 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1760 "pack directory into tarfile",
1762 This command packs the contents of C<directory> and downloads
1763 it to local file C<tarfile>.
1765 To download a compressed tarball, use C<guestfs_tgz_out>.");
1767 ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1768 [InitBasicFS, Always, TestOutput (
1769 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1770 ["cat"; "/hello"]], "hello\n")],
1771 "unpack compressed tarball to directory",
1773 This command uploads and unpacks local file C<tarball> (a
1774 I<gzip compressed> tar file) into C<directory>.
1776 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1778 ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1780 "pack directory into compressed tarball",
1782 This command packs the contents of C<directory> and downloads
1783 it to local file C<tarball>.
1785 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1787 ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1788 [InitBasicFS, Always, TestLastFail (
1790 ["mount_ro"; "/dev/sda1"; "/"];
1791 ["touch"; "/new"]]);
1792 InitBasicFS, Always, TestOutput (
1793 [["write_file"; "/new"; "data"; "0"];
1795 ["mount_ro"; "/dev/sda1"; "/"];
1796 ["cat"; "/new"]], "data")],
1797 "mount a guest disk, read-only",
1799 This is the same as the C<guestfs_mount> command, but it
1800 mounts the filesystem with the read-only (I<-o ro>) flag.");
1802 ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1804 "mount a guest disk with mount options",
1806 This is the same as the C<guestfs_mount> command, but it
1807 allows you to set the mount options as for the
1808 L<mount(8)> I<-o> flag.");
1810 ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1812 "mount a guest disk with mount options and vfstype",
1814 This is the same as the C<guestfs_mount> command, but it
1815 allows you to set both the mount options and the vfstype
1816 as for the L<mount(8)> I<-o> and I<-t> flags.");
1818 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1820 "debugging and internals",
1822 The C<guestfs_debug> command exposes some internals of
1823 C<guestfsd> (the guestfs daemon) that runs inside the
1826 There is no comprehensive help for this command. You have
1827 to look at the file C<daemon/debug.c> in the libguestfs source
1828 to find out what you can do.");
1830 ("lvremove", (RErr, [String "device"]), 77, [],
1831 [InitEmpty, Always, TestOutputList (
1832 [["sfdiskM"; "/dev/sda"; ","];
1833 ["pvcreate"; "/dev/sda1"];
1834 ["vgcreate"; "VG"; "/dev/sda1"];
1835 ["lvcreate"; "LV1"; "VG"; "50"];
1836 ["lvcreate"; "LV2"; "VG"; "50"];
1837 ["lvremove"; "/dev/VG/LV1"];
1838 ["lvs"]], ["/dev/VG/LV2"]);
1839 InitEmpty, Always, TestOutputList (
1840 [["sfdiskM"; "/dev/sda"; ","];
1841 ["pvcreate"; "/dev/sda1"];
1842 ["vgcreate"; "VG"; "/dev/sda1"];
1843 ["lvcreate"; "LV1"; "VG"; "50"];
1844 ["lvcreate"; "LV2"; "VG"; "50"];
1845 ["lvremove"; "/dev/VG"];
1847 InitEmpty, Always, TestOutputList (
1848 [["sfdiskM"; "/dev/sda"; ","];
1849 ["pvcreate"; "/dev/sda1"];
1850 ["vgcreate"; "VG"; "/dev/sda1"];
1851 ["lvcreate"; "LV1"; "VG"; "50"];
1852 ["lvcreate"; "LV2"; "VG"; "50"];
1853 ["lvremove"; "/dev/VG"];
1855 "remove an LVM logical volume",
1857 Remove an LVM logical volume C<device>, where C<device> is
1858 the path to the LV, such as C</dev/VG/LV>.
1860 You can also remove all LVs in a volume group by specifying
1861 the VG name, C</dev/VG>.");
1863 ("vgremove", (RErr, [String "vgname"]), 78, [],
1864 [InitEmpty, Always, TestOutputList (
1865 [["sfdiskM"; "/dev/sda"; ","];
1866 ["pvcreate"; "/dev/sda1"];
1867 ["vgcreate"; "VG"; "/dev/sda1"];
1868 ["lvcreate"; "LV1"; "VG"; "50"];
1869 ["lvcreate"; "LV2"; "VG"; "50"];
1872 InitEmpty, Always, TestOutputList (
1873 [["sfdiskM"; "/dev/sda"; ","];
1874 ["pvcreate"; "/dev/sda1"];
1875 ["vgcreate"; "VG"; "/dev/sda1"];
1876 ["lvcreate"; "LV1"; "VG"; "50"];
1877 ["lvcreate"; "LV2"; "VG"; "50"];
1880 "remove an LVM volume group",
1882 Remove an LVM volume group C<vgname>, (for example C<VG>).
1884 This also forcibly removes all logical volumes in the volume
1887 ("pvremove", (RErr, [String "device"]), 79, [],
1888 [InitEmpty, Always, TestOutputListOfDevices (
1889 [["sfdiskM"; "/dev/sda"; ","];
1890 ["pvcreate"; "/dev/sda1"];
1891 ["vgcreate"; "VG"; "/dev/sda1"];
1892 ["lvcreate"; "LV1"; "VG"; "50"];
1893 ["lvcreate"; "LV2"; "VG"; "50"];
1895 ["pvremove"; "/dev/sda1"];
1897 InitEmpty, Always, TestOutputListOfDevices (
1898 [["sfdiskM"; "/dev/sda"; ","];
1899 ["pvcreate"; "/dev/sda1"];
1900 ["vgcreate"; "VG"; "/dev/sda1"];
1901 ["lvcreate"; "LV1"; "VG"; "50"];
1902 ["lvcreate"; "LV2"; "VG"; "50"];
1904 ["pvremove"; "/dev/sda1"];
1906 InitEmpty, Always, TestOutputListOfDevices (
1907 [["sfdiskM"; "/dev/sda"; ","];
1908 ["pvcreate"; "/dev/sda1"];
1909 ["vgcreate"; "VG"; "/dev/sda1"];
1910 ["lvcreate"; "LV1"; "VG"; "50"];
1911 ["lvcreate"; "LV2"; "VG"; "50"];
1913 ["pvremove"; "/dev/sda1"];
1915 "remove an LVM physical volume",
1917 This wipes a physical volume C<device> so that LVM will no longer
1920 The implementation uses the C<pvremove> command which refuses to
1921 wipe physical volumes that contain any volume groups, so you have
1922 to remove those first.");
1924 ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
1925 [InitBasicFS, Always, TestOutput (
1926 [["set_e2label"; "/dev/sda1"; "testlabel"];
1927 ["get_e2label"; "/dev/sda1"]], "testlabel")],
1928 "set the ext2/3/4 filesystem label",
1930 This sets the ext2/3/4 filesystem label of the filesystem on
1931 C<device> to C<label>. Filesystem labels are limited to
1934 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
1935 to return the existing label on a filesystem.");
1937 ("get_e2label", (RString "label", [String "device"]), 81, [],
1939 "get the ext2/3/4 filesystem label",
1941 This returns the ext2/3/4 filesystem label of the filesystem on
1944 ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
1945 [InitBasicFS, Always, TestOutput (
1946 [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
1947 ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
1948 InitBasicFS, Always, TestOutput (
1949 [["set_e2uuid"; "/dev/sda1"; "clear"];
1950 ["get_e2uuid"; "/dev/sda1"]], "");
1951 (* We can't predict what UUIDs will be, so just check the commands run. *)
1952 InitBasicFS, Always, TestRun (
1953 [["set_e2uuid"; "/dev/sda1"; "random"]]);
1954 InitBasicFS, Always, TestRun (
1955 [["set_e2uuid"; "/dev/sda1"; "time"]])],
1956 "set the ext2/3/4 filesystem UUID",
1958 This sets the ext2/3/4 filesystem UUID of the filesystem on
1959 C<device> to C<uuid>. The format of the UUID and alternatives
1960 such as C<clear>, C<random> and C<time> are described in the
1961 L<tune2fs(8)> manpage.
1963 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
1964 to return the existing UUID of a filesystem.");
1966 ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
1968 "get the ext2/3/4 filesystem UUID",
1970 This returns the ext2/3/4 filesystem UUID of the filesystem on
1973 ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
1974 [InitBasicFS, Always, TestOutputInt (
1975 [["umount"; "/dev/sda1"];
1976 ["fsck"; "ext2"; "/dev/sda1"]], 0);
1977 InitBasicFS, Always, TestOutputInt (
1978 [["umount"; "/dev/sda1"];
1979 ["zero"; "/dev/sda1"];
1980 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
1981 "run the filesystem checker",
1983 This runs the filesystem checker (fsck) on C<device> which
1984 should have filesystem type C<fstype>.
1986 The returned integer is the status. See L<fsck(8)> for the
1987 list of status codes from C<fsck>.
1995 Multiple status codes can be summed together.
1999 A non-zero return code can mean \"success\", for example if
2000 errors have been corrected on the filesystem.
2004 Checking or repairing NTFS volumes is not supported
2009 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2011 ("zero", (RErr, [String "device"]), 85, [],
2012 [InitBasicFS, Always, TestOutput (
2013 [["umount"; "/dev/sda1"];
2014 ["zero"; "/dev/sda1"];
2015 ["file"; "/dev/sda1"]], "data")],
2016 "write zeroes to the device",
2018 This command writes zeroes over the first few blocks of C<device>.
2020 How many blocks are zeroed isn't specified (but it's I<not> enough
2021 to securely wipe the device). It should be sufficient to remove
2022 any partition tables, filesystem superblocks and so on.
2024 See also: C<guestfs_scrub_device>.");
2026 ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
2027 (* Test disabled because grub-install incompatible with virtio-blk driver.
2028 * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2030 [InitBasicFS, Disabled, TestOutputTrue (
2031 [["grub_install"; "/"; "/dev/sda1"];
2032 ["is_dir"; "/boot"]])],
2035 This command installs GRUB (the Grand Unified Bootloader) on
2036 C<device>, with the root directory being C<root>.");
2038 ("cp", (RErr, [String "src"; String "dest"]), 87, [],
2039 [InitBasicFS, Always, TestOutput (
2040 [["write_file"; "/old"; "file content"; "0"];
2041 ["cp"; "/old"; "/new"];
2042 ["cat"; "/new"]], "file content");
2043 InitBasicFS, Always, TestOutputTrue (
2044 [["write_file"; "/old"; "file content"; "0"];
2045 ["cp"; "/old"; "/new"];
2046 ["is_file"; "/old"]]);
2047 InitBasicFS, Always, TestOutput (
2048 [["write_file"; "/old"; "file content"; "0"];
2050 ["cp"; "/old"; "/dir/new"];
2051 ["cat"; "/dir/new"]], "file content")],
2054 This copies a file from C<src> to C<dest> where C<dest> is
2055 either a destination filename or destination directory.");
2057 ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
2058 [InitBasicFS, Always, TestOutput (
2059 [["mkdir"; "/olddir"];
2060 ["mkdir"; "/newdir"];
2061 ["write_file"; "/olddir/file"; "file content"; "0"];
2062 ["cp_a"; "/olddir"; "/newdir"];
2063 ["cat"; "/newdir/olddir/file"]], "file content")],
2064 "copy a file or directory recursively",
2066 This copies a file or directory from C<src> to C<dest>
2067 recursively using the C<cp -a> command.");
2069 ("mv", (RErr, [String "src"; String "dest"]), 89, [],
2070 [InitBasicFS, Always, TestOutput (
2071 [["write_file"; "/old"; "file content"; "0"];
2072 ["mv"; "/old"; "/new"];
2073 ["cat"; "/new"]], "file content");
2074 InitBasicFS, Always, TestOutputFalse (
2075 [["write_file"; "/old"; "file content"; "0"];
2076 ["mv"; "/old"; "/new"];
2077 ["is_file"; "/old"]])],
2080 This moves a file from C<src> to C<dest> where C<dest> is
2081 either a destination filename or destination directory.");
2083 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2084 [InitEmpty, Always, TestRun (
2085 [["drop_caches"; "3"]])],
2086 "drop kernel page cache, dentries and inodes",
2088 This instructs the guest kernel to drop its page cache,
2089 and/or dentries and inode caches. The parameter C<whattodrop>
2090 tells the kernel what precisely to drop, see
2091 L<http://linux-mm.org/Drop_Caches>
2093 Setting C<whattodrop> to 3 should drop everything.
2095 This automatically calls L<sync(2)> before the operation,
2096 so that the maximum guest memory is freed.");
2098 ("dmesg", (RString "kmsgs", []), 91, [],
2099 [InitEmpty, Always, TestRun (
2101 "return kernel messages",
2103 This returns the kernel messages (C<dmesg> output) from
2104 the guest kernel. This is sometimes useful for extended
2105 debugging of problems.
2107 Another way to get the same information is to enable
2108 verbose messages with C<guestfs_set_verbose> or by setting
2109 the environment variable C<LIBGUESTFS_DEBUG=1> before
2110 running the program.");
2112 ("ping_daemon", (RErr, []), 92, [],
2113 [InitEmpty, Always, TestRun (
2114 [["ping_daemon"]])],
2115 "ping the guest daemon",
2117 This is a test probe into the guestfs daemon running inside
2118 the qemu subprocess. Calling this function checks that the
2119 daemon responds to the ping message, without affecting the daemon
2120 or attached block device(s) in any other way.");
2122 ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2123 [InitBasicFS, Always, TestOutputTrue (
2124 [["write_file"; "/file1"; "contents of a file"; "0"];
2125 ["cp"; "/file1"; "/file2"];
2126 ["equal"; "/file1"; "/file2"]]);
2127 InitBasicFS, Always, TestOutputFalse (
2128 [["write_file"; "/file1"; "contents of a file"; "0"];
2129 ["write_file"; "/file2"; "contents of another file"; "0"];
2130 ["equal"; "/file1"; "/file2"]]);
2131 InitBasicFS, Always, TestLastFail (
2132 [["equal"; "/file1"; "/file2"]])],
2133 "test if two files have equal contents",
2135 This compares the two files C<file1> and C<file2> and returns
2136 true if their content is exactly equal, or false otherwise.
2138 The external L<cmp(1)> program is used for the comparison.");
2140 ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2141 [InitBasicFS, Always, TestOutputList (
2142 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2143 ["strings"; "/new"]], ["hello"; "world"]);
2144 InitBasicFS, Always, TestOutputList (
2146 ["strings"; "/new"]], [])],
2147 "print the printable strings in a file",
2149 This runs the L<strings(1)> command on a file and returns
2150 the list of printable strings found.");
2152 ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2153 [InitBasicFS, Always, TestOutputList (
2154 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2155 ["strings_e"; "b"; "/new"]], []);
2156 InitBasicFS, Disabled, TestOutputList (
2157 [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2158 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2159 "print the printable strings in a file",
2161 This is like the C<guestfs_strings> command, but allows you to
2162 specify the encoding.
2164 See the L<strings(1)> manpage for the full list of encodings.
2166 Commonly useful encodings are C<l> (lower case L) which will
2167 show strings inside Windows/x86 files.
2169 The returned strings are transcoded to UTF-8.");
2171 ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2172 [InitBasicFS, Always, TestOutput (
2173 [["write_file"; "/new"; "hello\nworld\n"; "12"];
2174 ["hexdump"; "/new"]], "00000000 68 65 6c 6c 6f 0a 77 6f 72 6c 64 0a |hello.world.|\n0000000c\n");
2175 (* Test for RHBZ#501888c2 regression which caused large hexdump
2176 * commands to segfault.
2178 InitBasicFS, Always, TestRun (
2179 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2180 ["hexdump"; "/100krandom"]])],
2181 "dump a file in hexadecimal",
2183 This runs C<hexdump -C> on the given C<path>. The result is
2184 the human-readable, canonical hex dump of the file.");
2186 ("zerofree", (RErr, [String "device"]), 97, [],
2187 [InitNone, Always, TestOutput (
2188 [["sfdiskM"; "/dev/sda"; ","];
2189 ["mkfs"; "ext3"; "/dev/sda1"];
2190 ["mount"; "/dev/sda1"; "/"];
2191 ["write_file"; "/new"; "test file"; "0"];
2192 ["umount"; "/dev/sda1"];
2193 ["zerofree"; "/dev/sda1"];
2194 ["mount"; "/dev/sda1"; "/"];
2195 ["cat"; "/new"]], "test file")],
2196 "zero unused inodes and disk blocks on ext2/3 filesystem",
2198 This runs the I<zerofree> program on C<device>. This program
2199 claims to zero unused inodes and disk blocks on an ext2/3
2200 filesystem, thus making it possible to compress the filesystem
2203 You should B<not> run this program if the filesystem is
2206 It is possible that using this program can damage the filesystem
2207 or data on the filesystem.");
2209 ("pvresize", (RErr, [String "device"]), 98, [],
2211 "resize an LVM physical volume",
2213 This resizes (expands or shrinks) an existing LVM physical
2214 volume to match the new size of the underlying device.");
2216 ("sfdisk_N", (RErr, [String "device"; Int "partnum";
2217 Int "cyls"; Int "heads"; Int "sectors";
2218 String "line"]), 99, [DangerWillRobinson],
2220 "modify a single partition on a block device",
2222 This runs L<sfdisk(8)> option to modify just the single
2223 partition C<n> (note: C<n> counts from 1).
2225 For other parameters, see C<guestfs_sfdisk>. You should usually
2226 pass C<0> for the cyls/heads/sectors parameters.");
2228 ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2230 "display the partition table",
2232 This displays the partition table on C<device>, in the
2233 human-readable output of the L<sfdisk(8)> command. It is
2234 not intended to be parsed.");
2236 ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2238 "display the kernel geometry",
2240 This displays the kernel's idea of the geometry of C<device>.
2242 The result is in human-readable format, and not designed to
2245 ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2247 "display the disk geometry from the partition table",
2249 This displays the disk geometry of C<device> read from the
2250 partition table. Especially in the case where the underlying
2251 block device has been resized, this can be different from the
2252 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2254 The result is in human-readable format, and not designed to
2257 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2259 "activate or deactivate all volume groups",
2261 This command activates or (if C<activate> is false) deactivates
2262 all logical volumes in all volume groups.
2263 If activated, then they are made known to the
2264 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2265 then those devices disappear.
2267 This command is the same as running C<vgchange -a y|n>");
2269 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2271 "activate or deactivate some volume groups",
2273 This command activates or (if C<activate> is false) deactivates
2274 all logical volumes in the listed volume groups C<volgroups>.
2275 If activated, then they are made known to the
2276 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2277 then those devices disappear.
2279 This command is the same as running C<vgchange -a y|n volgroups...>
2281 Note that if C<volgroups> is an empty list then B<all> volume groups
2282 are activated or deactivated.");
2284 ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2285 [InitNone, Always, TestOutput (
2286 [["sfdiskM"; "/dev/sda"; ","];
2287 ["pvcreate"; "/dev/sda1"];
2288 ["vgcreate"; "VG"; "/dev/sda1"];
2289 ["lvcreate"; "LV"; "VG"; "10"];
2290 ["mkfs"; "ext2"; "/dev/VG/LV"];
2291 ["mount"; "/dev/VG/LV"; "/"];
2292 ["write_file"; "/new"; "test content"; "0"];
2294 ["lvresize"; "/dev/VG/LV"; "20"];
2295 ["e2fsck_f"; "/dev/VG/LV"];
2296 ["resize2fs"; "/dev/VG/LV"];
2297 ["mount"; "/dev/VG/LV"; "/"];
2298 ["cat"; "/new"]], "test content")],
2299 "resize an LVM logical volume",
2301 This resizes (expands or shrinks) an existing LVM logical
2302 volume to C<mbytes>. When reducing, data in the reduced part
2305 ("resize2fs", (RErr, [String "device"]), 106, [],
2306 [], (* lvresize tests this *)
2307 "resize an ext2/ext3 filesystem",
2309 This resizes an ext2 or ext3 filesystem to match the size of
2310 the underlying device.
2312 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2313 on the C<device> before calling this command. For unknown reasons
2314 C<resize2fs> sometimes gives an error about this and sometimes not.
2315 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2316 calling this function.");
2318 ("find", (RStringList "names", [String "directory"]), 107, [],
2319 [InitBasicFS, Always, TestOutputList (
2320 [["find"; "/"]], ["lost+found"]);
2321 InitBasicFS, Always, TestOutputList (
2325 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2326 InitBasicFS, Always, TestOutputList (
2327 [["mkdir_p"; "/a/b/c"];
2328 ["touch"; "/a/b/c/d"];
2329 ["find"; "/a/b/"]], ["c"; "c/d"])],
2330 "find all files and directories",
2332 This command lists out all files and directories, recursively,
2333 starting at C<directory>. It is essentially equivalent to
2334 running the shell command C<find directory -print> but some
2335 post-processing happens on the output, described below.
2337 This returns a list of strings I<without any prefix>. Thus
2338 if the directory structure was:
2344 then the returned list from C<guestfs_find> C</tmp> would be
2352 If C<directory> is not a directory, then this command returns
2355 The returned list is sorted.");
2357 ("e2fsck_f", (RErr, [String "device"]), 108, [],
2358 [], (* lvresize tests this *)
2359 "check an ext2/ext3 filesystem",
2361 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2362 filesystem checker on C<device>, noninteractively (C<-p>),
2363 even if the filesystem appears to be clean (C<-f>).
2365 This command is only needed because of C<guestfs_resize2fs>
2366 (q.v.). Normally you should use C<guestfs_fsck>.");
2368 ("sleep", (RErr, [Int "secs"]), 109, [],
2369 [InitNone, Always, TestRun (
2371 "sleep for some seconds",
2373 Sleep for C<secs> seconds.");
2375 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; String "device"]), 110, [],
2376 [InitNone, Always, TestOutputInt (
2377 [["sfdiskM"; "/dev/sda"; ","];
2378 ["mkfs"; "ntfs"; "/dev/sda1"];
2379 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2380 InitNone, Always, TestOutputInt (
2381 [["sfdiskM"; "/dev/sda"; ","];
2382 ["mkfs"; "ext2"; "/dev/sda1"];
2383 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2384 "probe NTFS volume",
2386 This command runs the L<ntfs-3g.probe(8)> command which probes
2387 an NTFS C<device> for mountability. (Not all NTFS volumes can
2388 be mounted read-write, and some cannot be mounted at all).
2390 C<rw> is a boolean flag. Set it to true if you want to test
2391 if the volume can be mounted read-write. Set it to false if
2392 you want to test if the volume can be mounted read-only.
2394 The return value is an integer which C<0> if the operation
2395 would succeed, or some non-zero value documented in the
2396 L<ntfs-3g.probe(8)> manual page.");
2398 ("sh", (RString "output", [String "command"]), 111, [],
2399 [], (* XXX needs tests *)
2400 "run a command via the shell",
2402 This call runs a command from the guest filesystem via the
2405 This is like C<guestfs_command>, but passes the command to:
2407 /bin/sh -c \"command\"
2409 Depending on the guest's shell, this usually results in
2410 wildcards being expanded, shell expressions being interpolated
2413 All the provisos about C<guestfs_command> apply to this call.");
2415 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2416 [], (* XXX needs tests *)
2417 "run a command via the shell returning lines",
2419 This is the same as C<guestfs_sh>, but splits the result
2420 into a list of lines.
2422 See also: C<guestfs_command_lines>");
2424 ("glob_expand", (RStringList "paths", [String "pattern"]), 113, [],
2425 [InitBasicFS, Always, TestOutputList (
2426 [["mkdir_p"; "/a/b/c"];
2427 ["touch"; "/a/b/c/d"];
2428 ["touch"; "/a/b/c/e"];
2429 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2430 InitBasicFS, Always, TestOutputList (
2431 [["mkdir_p"; "/a/b/c"];
2432 ["touch"; "/a/b/c/d"];
2433 ["touch"; "/a/b/c/e"];
2434 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2435 InitBasicFS, Always, TestOutputList (
2436 [["mkdir_p"; "/a/b/c"];
2437 ["touch"; "/a/b/c/d"];
2438 ["touch"; "/a/b/c/e"];
2439 ["glob_expand"; "/a/*/x/*"]], [])],
2440 "expand a wildcard path",
2442 This command searches for all the pathnames matching
2443 C<pattern> according to the wildcard expansion rules
2446 If no paths match, then this returns an empty list
2447 (note: not an error).
2449 It is just a wrapper around the C L<glob(3)> function
2450 with flags C<GLOB_MARK|GLOB_BRACE>.
2451 See that manual page for more details.");
2453 ("scrub_device", (RErr, [String "device"]), 114, [DangerWillRobinson],
2454 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2455 [["scrub_device"; "/dev/sdc"]])],
2456 "scrub (securely wipe) a device",
2458 This command writes patterns over C<device> to make data retrieval
2461 It is an interface to the L<scrub(1)> program. See that
2462 manual page for more details.");
2464 ("scrub_file", (RErr, [String "file"]), 115, [],
2465 [InitBasicFS, Always, TestRun (
2466 [["write_file"; "/file"; "content"; "0"];
2467 ["scrub_file"; "/file"]])],
2468 "scrub (securely wipe) a file",
2470 This command writes patterns over a file to make data retrieval
2473 The file is I<removed> after scrubbing.
2475 It is an interface to the L<scrub(1)> program. See that
2476 manual page for more details.");
2478 ("scrub_freespace", (RErr, [String "dir"]), 116, [],
2479 [], (* XXX needs testing *)
2480 "scrub (securely wipe) free space",
2482 This command creates the directory C<dir> and then fills it
2483 with files until the filesystem is full, and scrubs the files
2484 as for C<guestfs_scrub_file>, and deletes them.
2485 The intention is to scrub any free space on the partition
2488 It is an interface to the L<scrub(1)> program. See that
2489 manual page for more details.");
2491 ("mkdtemp", (RString "dir", [String "template"]), 117, [],
2492 [InitBasicFS, Always, TestRun (
2494 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2495 "create a temporary directory",
2497 This command creates a temporary directory. The
2498 C<template> parameter should be a full pathname for the
2499 temporary directory name with the final six characters being
2502 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2503 the second one being suitable for Windows filesystems.
2505 The name of the temporary directory that was created
2508 The temporary directory is created with mode 0700
2509 and is owned by root.
2511 The caller is responsible for deleting the temporary
2512 directory and its contents after use.
2514 See also: L<mkdtemp(3)>");
2516 ("wc_l", (RInt "lines", [String "path"]), 118, [],
2517 [InitBasicFS, Always, TestOutputInt (
2518 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2519 ["wc_l"; "/10klines"]], 10000)],
2520 "count lines in a file",
2522 This command counts the lines in a file, using the
2523 C<wc -l> external command.");
2525 ("wc_w", (RInt "words", [String "path"]), 119, [],
2526 [InitBasicFS, Always, TestOutputInt (
2527 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2528 ["wc_w"; "/10klines"]], 10000)],
2529 "count words in a file",
2531 This command counts the words in a file, using the
2532 C<wc -w> external command.");
2534 ("wc_c", (RInt "chars", [String "path"]), 120, [],
2535 [InitBasicFS, Always, TestOutputInt (
2536 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2537 ["wc_c"; "/100kallspaces"]], 102400)],
2538 "count characters in a file",
2540 This command counts the characters in a file, using the
2541 C<wc -c> external command.");
2543 ("head", (RStringList "lines", [String "path"]), 121, [ProtocolLimitWarning],
2544 [InitBasicFS, Always, TestOutputList (
2545 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2546 ["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2547 "return first 10 lines of a file",
2549 This command returns up to the first 10 lines of a file as
2550 a list of strings.");
2552 ("head_n", (RStringList "lines", [Int "nrlines"; String "path"]), 122, [ProtocolLimitWarning],
2553 [InitBasicFS, Always, TestOutputList (
2554 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2555 ["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2556 InitBasicFS, Always, TestOutputList (
2557 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2558 ["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2559 InitBasicFS, Always, TestOutputList (
2560 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2561 ["head_n"; "0"; "/10klines"]], [])],
2562 "return first N lines of a file",
2564 If the parameter C<nrlines> is a positive number, this returns the first
2565 C<nrlines> lines of the file C<path>.
2567 If the parameter C<nrlines> is a negative number, this returns lines
2568 from the file C<path>, excluding the last C<nrlines> lines.
2570 If the parameter C<nrlines> is zero, this returns an empty list.");
2572 ("tail", (RStringList "lines", [String "path"]), 123, [ProtocolLimitWarning],
2573 [InitBasicFS, Always, TestOutputList (
2574 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2575 ["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2576 "return last 10 lines of a file",
2578 This command returns up to the last 10 lines of a file as
2579 a list of strings.");
2581 ("tail_n", (RStringList "lines", [Int "nrlines"; String "path"]), 124, [ProtocolLimitWarning],
2582 [InitBasicFS, Always, TestOutputList (
2583 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2584 ["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2585 InitBasicFS, Always, TestOutputList (
2586 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2587 ["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2588 InitBasicFS, Always, TestOutputList (
2589 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2590 ["tail_n"; "0"; "/10klines"]], [])],
2591 "return last N lines of a file",
2593 If the parameter C<nrlines> is a positive number, this returns the last
2594 C<nrlines> lines of the file C<path>.
2596 If the parameter C<nrlines> is a negative number, this returns lines
2597 from the file C<path>, starting with the C<-nrlines>th line.
2599 If the parameter C<nrlines> is zero, this returns an empty list.");
2601 ("df", (RString "output", []), 125, [],
2602 [], (* XXX Tricky to test because it depends on the exact format
2603 * of the 'df' command and other imponderables.
2605 "report file system disk space usage",
2607 This command runs the C<df> command to report disk space used.
2609 This command is mostly useful for interactive sessions. It
2610 is I<not> intended that you try to parse the output string.
2611 Use C<statvfs> from programs.");
2613 ("df_h", (RString "output", []), 126, [],
2614 [], (* XXX Tricky to test because it depends on the exact format
2615 * of the 'df' command and other imponderables.
2617 "report file system disk space usage (human readable)",
2619 This command runs the C<df -h> command to report disk space used
2620 in human-readable format.
2622 This command is mostly useful for interactive sessions. It
2623 is I<not> intended that you try to parse the output string.
2624 Use C<statvfs> from programs.");
2626 ("du", (RInt64 "sizekb", [String "path"]), 127, [],
2627 [InitBasicFS, Always, TestOutputInt (
2629 ["du"; "/p"]], 1 (* ie. 1 block, so depends on ext3 blocksize *))],
2630 "estimate file space usage",
2632 This command runs the C<du -s> command to estimate file space
2635 C<path> can be a file or a directory. If C<path> is a directory
2636 then the estimate includes the contents of the directory and all
2637 subdirectories (recursively).
2639 The result is the estimated size in I<kilobytes>
2640 (ie. units of 1024 bytes).");
2642 ("initrd_list", (RStringList "filenames", [String "path"]), 128, [],
2643 [InitBasicFS, Always, TestOutputList (
2644 [["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"];
2645 ["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3"])],
2646 "list files in an initrd",
2648 This command lists out files contained in an initrd.
2650 The files are listed without any initial C</> character. The
2651 files are listed in the order they appear (not necessarily
2652 alphabetical). Directory names are listed as separate items.
2654 Old Linux kernels (2.4 and earlier) used a compressed ext2
2655 filesystem as initrd. We I<only> support the newer initramfs
2656 format (compressed cpio files).");
2658 ("mount_loop", (RErr, [String "file"; String "mountpoint"]), 129, [],
2660 "mount a file using the loop device",
2662 This command lets you mount C<file> (a filesystem image
2663 in a file) on a mount point. It is entirely equivalent to
2664 the command C<mount -o loop file mountpoint>.");
2666 ("mkswap", (RErr, [String "device"]), 130, [],
2667 [InitEmpty, Always, TestRun (
2668 [["sfdiskM"; "/dev/sda"; ","];
2669 ["mkswap"; "/dev/sda1"]])],
2670 "create a swap partition",
2672 Create a swap partition on C<device>.");
2674 ("mkswap_L", (RErr, [String "label"; String "device"]), 131, [],
2675 [InitEmpty, Always, TestRun (
2676 [["sfdiskM"; "/dev/sda"; ","];
2677 ["mkswap_L"; "hello"; "/dev/sda1"]])],
2678 "create a swap partition with a label",
2680 Create a swap partition on C<device> with label C<label>.");
2682 ("mkswap_U", (RErr, [String "uuid"; String "device"]), 132, [],
2683 [InitEmpty, Always, TestRun (
2684 [["sfdiskM"; "/dev/sda"; ","];
2685 ["mkswap_U"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"; "/dev/sda1"]])],
2686 "create a swap partition with an explicit UUID",
2688 Create a swap partition on C<device> with UUID C<uuid>.");
2690 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 133, [],
2691 [InitBasicFS, Always, TestOutputStruct (
2692 [["mknod"; "0o10777"; "0"; "0"; "/node"];
2693 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2694 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2695 InitBasicFS, Always, TestOutputStruct (
2696 [["mknod"; "0o60777"; "66"; "99"; "/node"];
2697 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2698 "make block, character or FIFO devices",
2700 This call creates block or character special devices, or
2701 named pipes (FIFOs).
2703 The C<mode> parameter should be the mode, using the standard
2704 constants. C<devmajor> and C<devminor> are the
2705 device major and minor numbers, only used when creating block
2706 and character special devices.");
2708 ("mkfifo", (RErr, [Int "mode"; String "path"]), 134, [],
2709 [InitBasicFS, Always, TestOutputStruct (
2710 [["mkfifo"; "0o777"; "/node"];
2711 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2712 "make FIFO (named pipe)",
2714 This call creates a FIFO (named pipe) called C<path> with
2715 mode C<mode>. It is just a convenient wrapper around
2716 C<guestfs_mknod>.");
2718 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 135, [],
2719 [InitBasicFS, Always, TestOutputStruct (
2720 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2721 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2722 "make block device node",
2724 This call creates a block device node called C<path> with
2725 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2726 It is just a convenient wrapper around C<guestfs_mknod>.");
2728 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 136, [],
2729 [InitBasicFS, Always, TestOutputStruct (
2730 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2731 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2732 "make char device node",
2734 This call creates a char device node called C<path> with
2735 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2736 It is just a convenient wrapper around C<guestfs_mknod>.");
2738 ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2739 [], (* XXX umask is one of those stateful things that we should
2740 * reset between each test.
2742 "set file mode creation mask (umask)",
2744 This function sets the mask used for creating new files and
2745 device nodes to C<mask & 0777>.
2747 Typical umask values would be C<022> which creates new files
2748 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2749 C<002> which creates new files with permissions like
2750 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2752 The default umask is C<022>. This is important because it
2753 means that directories and device nodes will be created with
2754 C<0644> or C<0755> mode even if you specify C<0777>.
2756 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2758 This call returns the previous umask.");
2760 ("readdir", (RStructList ("entries", "dirent"), [String "dir"]), 138, [],
2762 "read directories entries",
2764 This returns the list of directory entries in directory C<dir>.
2766 All entries in the directory are returned, including C<.> and
2767 C<..>. The entries are I<not> sorted, but returned in the same
2768 order as the underlying filesystem.
2770 This function is primarily intended for use by programs. To
2771 get a simple list of names, use C<guestfs_ls>. To get a printable
2772 directory for human consumption, use C<guestfs_ll>.");
2774 ("sfdiskM", (RErr, [String "device"; StringList "lines"]), 139, [DangerWillRobinson],
2776 "create partitions on a block device",
2778 This is a simplified interface to the C<guestfs_sfdisk>
2779 command, where partition sizes are specified in megabytes
2780 only (rounded to the nearest cylinder) and you don't need
2781 to specify the cyls, heads and sectors parameters which
2782 were rarely if ever used anyway.
2784 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
2788 let all_functions = non_daemon_functions @ daemon_functions
2790 (* In some places we want the functions to be displayed sorted
2791 * alphabetically, so this is useful:
2793 let all_functions_sorted =
2794 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
2795 compare n1 n2) all_functions
2797 (* Field types for structures. *)
2799 | FChar (* C 'char' (really, a 7 bit byte). *)
2800 | FString (* nul-terminated ASCII string. *)
2805 | FBytes (* Any int measure that counts bytes. *)
2806 | FUUID (* 32 bytes long, NOT nul-terminated. *)
2807 | FOptPercent (* [0..100], or -1 meaning "not present". *)
2809 (* Because we generate extra parsing code for LVM command line tools,
2810 * we have to pull out the LVM columns separately here.
2820 "pv_attr", FString (* XXX *);
2821 "pv_pe_count", FInt64;
2822 "pv_pe_alloc_count", FInt64;
2825 "pv_mda_count", FInt64;
2826 "pv_mda_free", FBytes;
2827 (* Not in Fedora 10:
2828 "pv_mda_size", FBytes;
2835 "vg_attr", FString (* XXX *);
2838 "vg_sysid", FString;
2839 "vg_extent_size", FBytes;
2840 "vg_extent_count", FInt64;
2841 "vg_free_count", FInt64;
2846 "snap_count", FInt64;
2849 "vg_mda_count", FInt64;
2850 "vg_mda_free", FBytes;
2851 (* Not in Fedora 10:
2852 "vg_mda_size", FBytes;
2858 "lv_attr", FString (* XXX *);
2861 "lv_kernel_major", FInt64;
2862 "lv_kernel_minor", FInt64;
2864 "seg_count", FInt64;
2866 "snap_percent", FOptPercent;
2867 "copy_percent", FOptPercent;
2870 "mirror_log", FString;
2874 (* Names and fields in all structures (in RStruct and RStructList)
2878 (* The old RIntBool return type, only ever used for aug_defnode. Do
2879 * not use this struct in any new code.
2882 "i", FInt32; (* for historical compatibility *)
2883 "b", FInt32; (* for historical compatibility *)
2886 (* LVM PVs, VGs, LVs. *)
2887 "lvm_pv", lvm_pv_cols;
2888 "lvm_vg", lvm_vg_cols;
2889 "lvm_lv", lvm_lv_cols;
2891 (* Column names and types from stat structures.
2892 * NB. Can't use things like 'st_atime' because glibc header files
2893 * define some of these as macros. Ugh.
2924 (* Column names in dirent structure. *)
2927 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
2931 ] (* end of structs *)
2933 (* Ugh, Java has to be different ..
2934 * These names are also used by the Haskell bindings.
2936 let java_structs = [
2937 "int_bool", "IntBool";
2942 "statvfs", "StatVFS";
2946 (* Used for testing language bindings. *)
2948 | CallString of string
2949 | CallOptString of string option
2950 | CallStringList of string list
2954 (* Used to memoize the result of pod2text. *)
2955 let pod2text_memo_filename = "src/.pod2text.data"
2956 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
2958 let chan = open_in pod2text_memo_filename in
2959 let v = input_value chan in
2963 _ -> Hashtbl.create 13
2965 (* Useful functions.
2966 * Note we don't want to use any external OCaml libraries which
2967 * makes this a bit harder than it should be.
2969 let failwithf fs = ksprintf failwith fs
2971 let replace_char s c1 c2 =
2972 let s2 = String.copy s in
2973 let r = ref false in
2974 for i = 0 to String.length s2 - 1 do
2975 if String.unsafe_get s2 i = c1 then (
2976 String.unsafe_set s2 i c2;
2980 if not !r then s else s2
2984 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
2986 let triml ?(test = isspace) str =
2988 let n = ref (String.length str) in
2989 while !n > 0 && test str.[!i]; do
2994 else String.sub str !i !n
2996 let trimr ?(test = isspace) str =
2997 let n = ref (String.length str) in
2998 while !n > 0 && test str.[!n-1]; do
3001 if !n = String.length str then str
3002 else String.sub str 0 !n
3004 let trim ?(test = isspace) str =
3005 trimr ~test (triml ~test str)
3007 let rec find s sub =
3008 let len = String.length s in
3009 let sublen = String.length sub in
3011 if i <= len-sublen then (
3013 if j < sublen then (
3014 if s.[i+j] = sub.[j] then loop2 (j+1)
3020 if r = -1 then loop (i+1) else r
3026 let rec replace_str s s1 s2 =
3027 let len = String.length s in
3028 let sublen = String.length s1 in
3029 let i = find s s1 in
3032 let s' = String.sub s 0 i in
3033 let s'' = String.sub s (i+sublen) (len-i-sublen) in
3034 s' ^ s2 ^ replace_str s'' s1 s2
3037 let rec string_split sep str =
3038 let len = String.length str in
3039 let seplen = String.length sep in
3040 let i = find str sep in
3041 if i = -1 then [str]
3043 let s' = String.sub str 0 i in
3044 let s'' = String.sub str (i+seplen) (len-i-seplen) in
3045 s' :: string_split sep s''
3048 let files_equal n1 n2 =
3049 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
3050 match Sys.command cmd with
3053 | i -> failwithf "%s: failed with error code %d" cmd i
3055 let rec find_map f = function
3056 | [] -> raise Not_found
3060 | None -> find_map f xs
3063 let rec loop i = function
3065 | x :: xs -> f i x; loop (i+1) xs
3070 let rec loop i = function
3072 | x :: xs -> let r = f i x in r :: loop (i+1) xs
3076 let name_of_argt = function
3077 | String n | OptString n | StringList n | Bool n | Int n
3078 | FileIn n | FileOut n -> n
3080 let java_name_of_struct typ =
3081 try List.assoc typ java_structs
3084 "java_name_of_struct: no java_structs entry corresponding to %s" typ
3086 let cols_of_struct typ =
3087 try List.assoc typ structs
3089 failwithf "cols_of_struct: unknown struct %s" typ
3091 let seq_of_test = function
3092 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
3093 | TestOutputListOfDevices (s, _)
3094 | TestOutputInt (s, _) | TestOutputTrue s | TestOutputFalse s
3095 | TestOutputLength (s, _) | TestOutputStruct (s, _)
3096 | TestLastFail s -> s
3098 (* Check function names etc. for consistency. *)
3099 let check_functions () =
3100 let contains_uppercase str =
3101 let len = String.length str in
3103 if i >= len then false
3106 if c >= 'A' && c <= 'Z' then true
3113 (* Check function names. *)
3115 fun (name, _, _, _, _, _, _) ->
3116 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
3117 failwithf "function name %s does not need 'guestfs' prefix" name;
3119 failwithf "function name is empty";
3120 if name.[0] < 'a' || name.[0] > 'z' then
3121 failwithf "function name %s must start with lowercase a-z" name;
3122 if String.contains name '-' then
3123 failwithf "function name %s should not contain '-', use '_' instead."
3127 (* Check function parameter/return names. *)
3129 fun (name, style, _, _, _, _, _) ->
3130 let check_arg_ret_name n =
3131 if contains_uppercase n then
3132 failwithf "%s param/ret %s should not contain uppercase chars"
3134 if String.contains n '-' || String.contains n '_' then
3135 failwithf "%s param/ret %s should not contain '-' or '_'"
3138 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;
3139 if n = "int" || n = "char" || n = "short" || n = "long" then
3140 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
3141 if n = "i" || n = "n" then
3142 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
3143 if n = "argv" || n = "args" then
3144 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
3147 (match fst style with
3149 | RInt n | RInt64 n | RBool n | RConstString n | RString n
3150 | RStringList n | RStruct (n, _) | RStructList (n, _)
3152 check_arg_ret_name n
3154 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
3157 (* Check short descriptions. *)
3159 fun (name, _, _, _, _, shortdesc, _) ->
3160 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
3161 failwithf "short description of %s should begin with lowercase." name;
3162 let c = shortdesc.[String.length shortdesc-1] in
3163 if c = '\n' || c = '.' then
3164 failwithf "short description of %s should not end with . or \\n." name
3167 (* Check long dscriptions. *)
3169 fun (name, _, _, _, _, _, longdesc) ->
3170 if longdesc.[String.length longdesc-1] = '\n' then
3171 failwithf "long description of %s should not end with \\n." name
3174 (* Check proc_nrs. *)
3176 fun (name, _, proc_nr, _, _, _, _) ->
3177 if proc_nr <= 0 then
3178 failwithf "daemon function %s should have proc_nr > 0" name
3182 fun (name, _, proc_nr, _, _, _, _) ->
3183 if proc_nr <> -1 then
3184 failwithf "non-daemon function %s should have proc_nr -1" name
3185 ) non_daemon_functions;
3188 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
3191 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
3192 let rec loop = function
3195 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
3197 | (name1,nr1) :: (name2,nr2) :: _ ->
3198 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
3206 (* Ignore functions that have no tests. We generate a
3207 * warning when the user does 'make check' instead.
3209 | name, _, _, _, [], _, _ -> ()
3210 | name, _, _, _, tests, _, _ ->
3214 match seq_of_test test with
3216 failwithf "%s has a test containing an empty sequence" name
3217 | cmds -> List.map List.hd cmds
3219 let funcs = List.flatten funcs in
3221 let tested = List.mem name funcs in
3224 failwithf "function %s has tests but does not test itself" name
3227 (* 'pr' prints to the current output file. *)
3228 let chan = ref stdout
3229 let pr fs = ksprintf (output_string !chan) fs
3231 (* Generate a header block in a number of standard styles. *)
3232 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
3233 type license = GPLv2 | LGPLv2
3235 let generate_header comment license =
3236 let c = match comment with
3237 | CStyle -> pr "/* "; " *"
3238 | HashStyle -> pr "# "; "#"
3239 | OCamlStyle -> pr "(* "; " *"
3240 | HaskellStyle -> pr "{- "; " " in
3241 pr "libguestfs generated file\n";
3242 pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
3243 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
3245 pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
3249 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
3250 pr "%s it under the terms of the GNU General Public License as published by\n" c;
3251 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
3252 pr "%s (at your option) any later version.\n" c;
3254 pr "%s This program is distributed in the hope that it will be useful,\n" c;
3255 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3256 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
3257 pr "%s GNU General Public License for more details.\n" c;
3259 pr "%s You should have received a copy of the GNU General Public License along\n" c;
3260 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
3261 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
3264 pr "%s This library is free software; you can redistribute it and/or\n" c;
3265 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
3266 pr "%s License as published by the Free Software Foundation; either\n" c;
3267 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
3269 pr "%s This library is distributed in the hope that it will be useful,\n" c;
3270 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3271 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
3272 pr "%s Lesser General Public License for more details.\n" c;
3274 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
3275 pr "%s License along with this library; if not, write to the Free Software\n" c;
3276 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
3279 | CStyle -> pr " */\n"
3281 | OCamlStyle -> pr " *)\n"
3282 | HaskellStyle -> pr "-}\n"
3286 (* Start of main code generation functions below this line. *)
3288 (* Generate the pod documentation for the C API. *)
3289 let rec generate_actions_pod () =
3291 fun (shortname, style, _, flags, _, _, longdesc) ->
3292 if not (List.mem NotInDocs flags) then (
3293 let name = "guestfs_" ^ shortname in
3294 pr "=head2 %s\n\n" name;
3296 generate_prototype ~extern:false ~handle:"handle" name style;
3298 pr "%s\n\n" longdesc;
3299 (match fst style with
3301 pr "This function returns 0 on success or -1 on error.\n\n"
3303 pr "On error this function returns -1.\n\n"
3305 pr "On error this function returns -1.\n\n"
3307 pr "This function returns a C truth value on success or -1 on error.\n\n"
3309 pr "This function returns a string, or NULL on error.
3310 The string is owned by the guest handle and must I<not> be freed.\n\n"
3312 pr "This function returns a string, or NULL on error.
3313 I<The caller must free the returned string after use>.\n\n"
3315 pr "This function returns a NULL-terminated array of strings
3316 (like L<environ(3)>), or NULL if there was an error.
3317 I<The caller must free the strings and the array after use>.\n\n"
3318 | RStruct (_, typ) ->
3319 pr "This function returns a C<struct guestfs_%s *>,
3320 or NULL if there was an error.
3321 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
3322 | RStructList (_, typ) ->
3323 pr "This function returns a C<struct guestfs_%s_list *>
3324 (see E<lt>guestfs-structs.hE<gt>),
3325 or NULL if there was an error.
3326 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
3328 pr "This function returns a NULL-terminated array of
3329 strings, or NULL if there was an error.
3330 The array of strings will always have length C<2n+1>, where
3331 C<n> keys and values alternate, followed by the trailing NULL entry.
3332 I<The caller must free the strings and the array after use>.\n\n"
3334 if List.mem ProtocolLimitWarning flags then
3335 pr "%s\n\n" protocol_limit_warning;
3336 if List.mem DangerWillRobinson flags then
3337 pr "%s\n\n" danger_will_robinson
3339 ) all_functions_sorted
3341 and generate_structs_pod () =
3342 (* Structs documentation. *)
3345 pr "=head2 guestfs_%s\n" typ;
3347 pr " struct guestfs_%s {\n" typ;
3350 | name, FChar -> pr " char %s;\n" name
3351 | name, FUInt32 -> pr " uint32_t %s;\n" name
3352 | name, FInt32 -> pr " int32_t %s;\n" name
3353 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3354 | name, FInt64 -> pr " int64_t %s;\n" name
3355 | name, FString -> pr " char *%s;\n" name
3357 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
3358 pr " char %s[32];\n" name
3359 | name, FOptPercent ->
3360 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
3361 pr " float %s;\n" name
3365 pr " struct guestfs_%s_list {\n" typ;
3366 pr " uint32_t len; /* Number of elements in list. */\n";
3367 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
3370 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
3371 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
3376 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
3377 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
3379 * We have to use an underscore instead of a dash because otherwise
3380 * rpcgen generates incorrect code.
3382 * This header is NOT exported to clients, but see also generate_structs_h.
3384 and generate_xdr () =
3385 generate_header CStyle LGPLv2;
3387 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
3388 pr "typedef string str<>;\n";
3391 (* Internal structures. *)
3395 pr "struct guestfs_int_%s {\n" typ;
3397 | name, FChar -> pr " char %s;\n" name
3398 | name, FString -> pr " string %s<>;\n" name
3399 | name, FUUID -> pr " opaque %s[32];\n" name
3400 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
3401 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
3402 | name, FOptPercent -> pr " float %s;\n" name
3406 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
3411 fun (shortname, style, _, _, _, _, _) ->
3412 let name = "guestfs_" ^ shortname in
3414 (match snd style with
3417 pr "struct %s_args {\n" name;
3420 | String n -> pr " string %s<>;\n" n
3421 | OptString n -> pr " str *%s;\n" n
3422 | StringList n -> pr " str %s<>;\n" n
3423 | Bool n -> pr " bool %s;\n" n
3424 | Int n -> pr " int %s;\n" n
3425 | FileIn _ | FileOut _ -> ()
3429 (match fst style with
3432 pr "struct %s_ret {\n" name;
3436 pr "struct %s_ret {\n" name;
3437 pr " hyper %s;\n" n;
3440 pr "struct %s_ret {\n" name;
3444 failwithf "RConstString cannot be returned from a daemon function"
3446 pr "struct %s_ret {\n" name;
3447 pr " string %s<>;\n" n;
3450 pr "struct %s_ret {\n" name;
3451 pr " str %s<>;\n" n;
3453 | RStruct (n, typ) ->
3454 pr "struct %s_ret {\n" name;
3455 pr " guestfs_int_%s %s;\n" typ n;
3457 | RStructList (n, typ) ->
3458 pr "struct %s_ret {\n" name;
3459 pr " guestfs_int_%s_list %s;\n" typ n;
3462 pr "struct %s_ret {\n" name;
3463 pr " str %s<>;\n" n;
3468 (* Table of procedure numbers. *)
3469 pr "enum guestfs_procedure {\n";
3471 fun (shortname, _, proc_nr, _, _, _, _) ->
3472 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
3474 pr " GUESTFS_PROC_NR_PROCS\n";
3478 (* Having to choose a maximum message size is annoying for several
3479 * reasons (it limits what we can do in the API), but it (a) makes
3480 * the protocol a lot simpler, and (b) provides a bound on the size
3481 * of the daemon which operates in limited memory space. For large
3482 * file transfers you should use FTP.
3484 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
3487 (* Message header, etc. *)
3489 /* The communication protocol is now documented in the guestfs(3)
3493 const GUESTFS_PROGRAM = 0x2000F5F5;
3494 const GUESTFS_PROTOCOL_VERSION = 1;
3496 /* These constants must be larger than any possible message length. */
3497 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
3498 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
3500 enum guestfs_message_direction {
3501 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
3502 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
3505 enum guestfs_message_status {
3506 GUESTFS_STATUS_OK = 0,
3507 GUESTFS_STATUS_ERROR = 1
3510 const GUESTFS_ERROR_LEN = 256;
3512 struct guestfs_message_error {
3513 string error_message<GUESTFS_ERROR_LEN>;
3516 struct guestfs_message_header {
3517 unsigned prog; /* GUESTFS_PROGRAM */
3518 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
3519 guestfs_procedure proc; /* GUESTFS_PROC_x */
3520 guestfs_message_direction direction;
3521 unsigned serial; /* message serial number */
3522 guestfs_message_status status;
3525 const GUESTFS_MAX_CHUNK_SIZE = 8192;
3527 struct guestfs_chunk {
3528 int cancel; /* if non-zero, transfer is cancelled */
3529 /* data size is 0 bytes if the transfer has finished successfully */
3530 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
3534 (* Generate the guestfs-structs.h file. *)
3535 and generate_structs_h () =
3536 generate_header CStyle LGPLv2;
3538 (* This is a public exported header file containing various
3539 * structures. The structures are carefully written to have
3540 * exactly the same in-memory format as the XDR structures that
3541 * we use on the wire to the daemon. The reason for creating
3542 * copies of these structures here is just so we don't have to
3543 * export the whole of guestfs_protocol.h (which includes much
3544 * unrelated and XDR-dependent stuff that we don't want to be
3545 * public, or required by clients).
3547 * To reiterate, we will pass these structures to and from the
3548 * client with a simple assignment or memcpy, so the format
3549 * must be identical to what rpcgen / the RFC defines.
3552 (* Public structures. *)
3555 pr "struct guestfs_%s {\n" typ;
3558 | name, FChar -> pr " char %s;\n" name
3559 | name, FString -> pr " char *%s;\n" name
3560 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3561 | name, FUInt32 -> pr " uint32_t %s;\n" name
3562 | name, FInt32 -> pr " int32_t %s;\n" name
3563 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3564 | name, FInt64 -> pr " int64_t %s;\n" name
3565 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
3569 pr "struct guestfs_%s_list {\n" typ;
3570 pr " uint32_t len;\n";
3571 pr " struct guestfs_%s *val;\n" typ;
3574 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
3575 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
3579 (* Generate the guestfs-actions.h file. *)
3580 and generate_actions_h () =
3581 generate_header CStyle LGPLv2;
3583 fun (shortname, style, _, _, _, _, _) ->
3584 let name = "guestfs_" ^ shortname in
3585 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3589 (* Generate the client-side dispatch stubs. *)
3590 and generate_client_actions () =
3591 generate_header CStyle LGPLv2;
3597 #include \"guestfs.h\"
3598 #include \"guestfs_protocol.h\"
3600 #define error guestfs_error
3601 #define perrorf guestfs_perrorf
3602 #define safe_malloc guestfs_safe_malloc
3603 #define safe_realloc guestfs_safe_realloc
3604 #define safe_strdup guestfs_safe_strdup
3605 #define safe_memdup guestfs_safe_memdup
3607 /* Check the return message from a call for validity. */
3609 check_reply_header (guestfs_h *g,
3610 const struct guestfs_message_header *hdr,
3611 int proc_nr, int serial)
3613 if (hdr->prog != GUESTFS_PROGRAM) {
3614 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3617 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3618 error (g, \"wrong protocol version (%%d/%%d)\",
3619 hdr->vers, GUESTFS_PROTOCOL_VERSION);
3622 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3623 error (g, \"unexpected message direction (%%d/%%d)\",
3624 hdr->direction, GUESTFS_DIRECTION_REPLY);
3627 if (hdr->proc != proc_nr) {
3628 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3631 if (hdr->serial != serial) {
3632 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3639 /* Check we are in the right state to run a high-level action. */
3641 check_state (guestfs_h *g, const char *caller)
3643 if (!guestfs_is_ready (g)) {
3644 if (guestfs_is_config (g))
3645 error (g, \"%%s: call launch() before using this function\",
3647 else if (guestfs_is_launching (g))
3648 error (g, \"%%s: call wait_ready() before using this function\",
3651 error (g, \"%%s called from the wrong state, %%d != READY\",
3652 caller, guestfs_get_state (g));
3660 (* Client-side stubs for each function. *)
3662 fun (shortname, style, _, _, _, _, _) ->
3663 let name = "guestfs_" ^ shortname in
3665 (* Generate the context struct which stores the high-level
3666 * state between callback functions.
3668 pr "struct %s_ctx {\n" shortname;
3669 pr " /* This flag is set by the callbacks, so we know we've done\n";
3670 pr " * the callbacks as expected, and in the right sequence.\n";
3671 pr " * 0 = not called, 1 = reply_cb called.\n";
3673 pr " int cb_sequence;\n";
3674 pr " struct guestfs_message_header hdr;\n";
3675 pr " struct guestfs_message_error err;\n";
3676 (match fst style with
3679 failwithf "RConstString cannot be returned from a daemon function"
3681 | RBool _ | RString _ | RStringList _
3682 | RStruct _ | RStructList _
3684 pr " struct %s_ret ret;\n" name
3689 (* Generate the reply callback function. *)
3690 pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
3692 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3693 pr " struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
3695 pr " /* This should definitely not happen. */\n";
3696 pr " if (ctx->cb_sequence != 0) {\n";
3697 pr " ctx->cb_sequence = 9999;\n";
3698 pr " error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
3702 pr " ml->main_loop_quit (ml, g);\n";
3704 pr " if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
3705 pr " error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
3708 pr " if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
3709 pr " if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
3710 pr " error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
3717 (match fst style with
3720 failwithf "RConstString cannot be returned from a daemon function"
3722 | RBool _ | RString _ | RStringList _
3723 | RStruct _ | RStructList _
3725 pr " if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
3726 pr " error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
3732 pr " ctx->cb_sequence = 1;\n";
3735 (* Generate the action stub. *)
3736 generate_prototype ~extern:false ~semicolon:false ~newline:true
3737 ~handle:"g" name style;
3740 match fst style with
3741 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
3743 failwithf "RConstString cannot be returned from a daemon function"
3744 | RString _ | RStringList _
3745 | RStruct _ | RStructList _
3751 (match snd style with
3753 | _ -> pr " struct %s_args args;\n" name
3756 pr " struct %s_ctx ctx;\n" shortname;
3757 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3758 pr " int serial;\n";
3760 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
3761 pr " guestfs_set_busy (g);\n";
3763 pr " memset (&ctx, 0, sizeof ctx);\n";
3766 (* Send the main header and arguments. *)
3767 (match snd style with
3769 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
3770 (String.uppercase shortname)
3775 pr " args.%s = (char *) %s;\n" n n
3777 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
3779 pr " args.%s.%s_val = (char **) %s;\n" n n n;
3780 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
3782 pr " args.%s = %s;\n" n n
3784 pr " args.%s = %s;\n" n n
3785 | FileIn _ | FileOut _ -> ()
3787 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
3788 (String.uppercase shortname);
3789 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
3792 pr " if (serial == -1) {\n";
3793 pr " guestfs_end_busy (g);\n";
3794 pr " return %s;\n" error_code;
3798 (* Send any additional files (FileIn) requested. *)
3799 let need_read_reply_label = ref false in
3806 pr " r = guestfs__send_file_sync (g, %s);\n" n;
3807 pr " if (r == -1) {\n";
3808 pr " guestfs_end_busy (g);\n";
3809 pr " return %s;\n" error_code;
3811 pr " if (r == -2) /* daemon cancelled */\n";
3812 pr " goto read_reply;\n";
3813 need_read_reply_label := true;
3819 (* Wait for the reply from the remote end. *)
3820 if !need_read_reply_label then pr " read_reply:\n";
3821 pr " guestfs__switch_to_receiving (g);\n";
3822 pr " ctx.cb_sequence = 0;\n";
3823 pr " guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
3824 pr " (void) ml->main_loop_run (ml, g);\n";
3825 pr " guestfs_set_reply_callback (g, NULL, NULL);\n";
3826 pr " if (ctx.cb_sequence != 1) {\n";
3827 pr " error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
3828 pr " guestfs_end_busy (g);\n";
3829 pr " return %s;\n" error_code;
3833 pr " if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
3834 (String.uppercase shortname);
3835 pr " guestfs_end_busy (g);\n";
3836 pr " return %s;\n" error_code;
3840 pr " if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
3841 pr " error (g, \"%%s\", ctx.err.error_message);\n";
3842 pr " free (ctx.err.error_message);\n";
3843 pr " guestfs_end_busy (g);\n";
3844 pr " return %s;\n" error_code;
3848 (* Expecting to receive further files (FileOut)? *)
3852 pr " if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
3853 pr " guestfs_end_busy (g);\n";
3854 pr " return %s;\n" error_code;
3860 pr " guestfs_end_busy (g);\n";
3862 (match fst style with
3863 | RErr -> pr " return 0;\n"
3864 | RInt n | RInt64 n | RBool n ->
3865 pr " return ctx.ret.%s;\n" n
3867 failwithf "RConstString cannot be returned from a daemon function"
3869 pr " return ctx.ret.%s; /* caller will free */\n" n
3870 | RStringList n | RHashtable n ->
3871 pr " /* caller will free this, but we need to add a NULL entry */\n";
3872 pr " ctx.ret.%s.%s_val =\n" n n;
3873 pr " safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
3874 pr " sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
3876 pr " ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
3877 pr " return ctx.ret.%s.%s_val;\n" n n
3879 pr " /* caller will free this */\n";
3880 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
3881 | RStructList (n, _) ->
3882 pr " /* caller will free this */\n";
3883 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
3889 (* Functions to free structures. *)
3890 pr "/* Structure-freeing functions. These rely on the fact that the\n";
3891 pr " * structure format is identical to the XDR format. See note in\n";
3892 pr " * generator.ml.\n";
3899 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
3901 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
3907 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
3909 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
3916 (* Generate daemon/actions.h. *)
3917 and generate_daemon_actions_h () =
3918 generate_header CStyle GPLv2;
3920 pr "#include \"../src/guestfs_protocol.h\"\n";
3924 fun (name, style, _, _, _, _, _) ->
3926 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
3930 (* Generate the server-side stubs. *)
3931 and generate_daemon_actions () =
3932 generate_header CStyle GPLv2;
3934 pr "#include <config.h>\n";
3936 pr "#include <stdio.h>\n";
3937 pr "#include <stdlib.h>\n";
3938 pr "#include <string.h>\n";
3939 pr "#include <inttypes.h>\n";
3940 pr "#include <ctype.h>\n";
3941 pr "#include <rpc/types.h>\n";
3942 pr "#include <rpc/xdr.h>\n";
3944 pr "#include \"daemon.h\"\n";
3945 pr "#include \"../src/guestfs_protocol.h\"\n";
3946 pr "#include \"actions.h\"\n";
3950 fun (name, style, _, _, _, _, _) ->
3951 (* Generate server-side stubs. *)
3952 pr "static void %s_stub (XDR *xdr_in)\n" name;
3955 match fst style with
3956 | RErr | RInt _ -> pr " int r;\n"; "-1"
3957 | RInt64 _ -> pr " int64_t r;\n"; "-1"
3958 | RBool _ -> pr " int r;\n"; "-1"
3960 failwithf "RConstString cannot be returned from a daemon function"
3961 | RString _ -> pr " char *r;\n"; "NULL"
3962 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
3963 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
3964 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL" in
3966 (match snd style with
3969 pr " struct guestfs_%s_args args;\n" name;
3972 (* Note we allow the string to be writable, in order to
3973 * allow device name translation. This is safe because
3974 * we can modify the string (passed from RPC).
3977 | OptString n -> pr " char *%s;\n" n
3978 | StringList n -> pr " char **%s;\n" n
3979 | Bool n -> pr " int %s;\n" n
3980 | Int n -> pr " int %s;\n" n
3981 | FileIn _ | FileOut _ -> ()
3986 (match snd style with
3989 pr " memset (&args, 0, sizeof args);\n";
3991 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
3992 pr " reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
3997 | String n -> pr " %s = args.%s;\n" n n
3998 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
4000 pr " %s = realloc (args.%s.%s_val,\n" n n n;
4001 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
4002 pr " if (%s == NULL) {\n" n;
4003 pr " reply_with_perror (\"realloc\");\n";
4006 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
4007 pr " args.%s.%s_val = %s;\n" n n n;
4008 | Bool n -> pr " %s = args.%s;\n" n n
4009 | Int n -> pr " %s = args.%s;\n" n n
4010 | FileIn _ | FileOut _ -> ()
4015 (* Don't want to call the impl with any FileIn or FileOut
4016 * parameters, since these go "outside" the RPC protocol.
4019 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
4021 pr " r = do_%s " name;
4022 generate_call_args argsnofile;
4025 pr " if (r == %s)\n" error_code;
4026 pr " /* do_%s has already called reply_with_error */\n" name;
4030 (* If there are any FileOut parameters, then the impl must
4031 * send its own reply.
4034 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
4036 pr " /* do_%s has already sent a reply */\n" name
4038 match fst style with
4039 | RErr -> pr " reply (NULL, NULL);\n"
4040 | RInt n | RInt64 n | RBool n ->
4041 pr " struct guestfs_%s_ret ret;\n" name;
4042 pr " ret.%s = r;\n" n;
4043 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4046 failwithf "RConstString cannot be returned from a daemon function"
4048 pr " struct guestfs_%s_ret ret;\n" name;
4049 pr " ret.%s = r;\n" n;
4050 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4053 | RStringList n | RHashtable n ->
4054 pr " struct guestfs_%s_ret ret;\n" name;
4055 pr " ret.%s.%s_len = count_strings (r);\n" n n;
4056 pr " ret.%s.%s_val = r;\n" n n;
4057 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4059 pr " free_strings (r);\n"
4061 pr " struct guestfs_%s_ret ret;\n" name;
4062 pr " ret.%s = *r;\n" n;
4063 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4065 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4067 | RStructList (n, _) ->
4068 pr " struct guestfs_%s_ret ret;\n" name;
4069 pr " ret.%s = *r;\n" n;
4070 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4072 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4076 (* Free the args. *)
4077 (match snd style with
4082 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
4089 (* Dispatch function. *)
4090 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
4092 pr " switch (proc_nr) {\n";
4095 fun (name, style, _, _, _, _, _) ->
4096 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
4097 pr " %s_stub (xdr_in);\n" name;
4102 pr " reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d, set LIBGUESTFS_PATH to point to the matching libguestfs appliance directory\", proc_nr);\n";
4107 (* LVM columns and tokenization functions. *)
4108 (* XXX This generates crap code. We should rethink how we
4114 pr "static const char *lvm_%s_cols = \"%s\";\n"
4115 typ (String.concat "," (List.map fst cols));
4118 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
4120 pr " char *tok, *p, *next;\n";
4124 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
4127 pr " if (!str) {\n";
4128 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
4131 pr " if (!*str || isspace (*str)) {\n";
4132 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
4137 fun (name, coltype) ->
4138 pr " if (!tok) {\n";
4139 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
4142 pr " p = strchrnul (tok, ',');\n";
4143 pr " if (*p) next = p+1; else next = NULL;\n";
4144 pr " *p = '\\0';\n";
4147 pr " r->%s = strdup (tok);\n" name;
4148 pr " if (r->%s == NULL) {\n" name;
4149 pr " perror (\"strdup\");\n";
4153 pr " for (i = j = 0; i < 32; ++j) {\n";
4154 pr " if (tok[j] == '\\0') {\n";
4155 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
4157 pr " } else if (tok[j] != '-')\n";
4158 pr " r->%s[i++] = tok[j];\n" name;
4161 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
4162 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4166 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
4167 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4171 pr " if (tok[0] == '\\0')\n";
4172 pr " r->%s = -1;\n" name;
4173 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
4174 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4177 | FInt32 | FUInt32 | FUInt64 | FChar ->
4178 assert false (* can never be an LVM column *)
4180 pr " tok = next;\n";
4183 pr " if (tok != NULL) {\n";
4184 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
4191 pr "guestfs_int_lvm_%s_list *\n" typ;
4192 pr "parse_command_line_%ss (void)\n" typ;
4194 pr " char *out, *err;\n";
4195 pr " char *p, *pend;\n";
4197 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
4198 pr " void *newp;\n";
4200 pr " ret = malloc (sizeof *ret);\n";
4201 pr " if (!ret) {\n";
4202 pr " reply_with_perror (\"malloc\");\n";
4203 pr " return NULL;\n";
4206 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
4207 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
4209 pr " r = command (&out, &err,\n";
4210 pr " \"/sbin/lvm\", \"%ss\",\n" typ;
4211 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
4212 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
4213 pr " if (r == -1) {\n";
4214 pr " reply_with_error (\"%%s\", err);\n";
4215 pr " free (out);\n";
4216 pr " free (err);\n";
4217 pr " free (ret);\n";
4218 pr " return NULL;\n";
4221 pr " free (err);\n";
4223 pr " /* Tokenize each line of the output. */\n";
4226 pr " while (p) {\n";
4227 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
4228 pr " if (pend) {\n";
4229 pr " *pend = '\\0';\n";
4233 pr " while (*p && isspace (*p)) /* Skip any leading whitespace. */\n";
4236 pr " if (!*p) { /* Empty line? Skip it. */\n";
4241 pr " /* Allocate some space to store this next entry. */\n";
4242 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
4243 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
4244 pr " if (newp == NULL) {\n";
4245 pr " reply_with_perror (\"realloc\");\n";
4246 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4247 pr " free (ret);\n";
4248 pr " free (out);\n";
4249 pr " return NULL;\n";
4251 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
4253 pr " /* Tokenize the next entry. */\n";
4254 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
4255 pr " if (r == -1) {\n";
4256 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
4257 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4258 pr " free (ret);\n";
4259 pr " free (out);\n";
4260 pr " return NULL;\n";
4267 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
4269 pr " free (out);\n";
4270 pr " return ret;\n";
4273 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
4275 (* Generate a list of function names, for debugging in the daemon.. *)
4276 and generate_daemon_names () =
4277 generate_header CStyle GPLv2;
4279 pr "#include <config.h>\n";
4281 pr "#include \"daemon.h\"\n";
4284 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
4285 pr "const char *function_names[] = {\n";
4287 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
4291 (* Generate the tests. *)
4292 and generate_tests () =
4293 generate_header CStyle GPLv2;
4300 #include <sys/types.h>
4303 #include \"guestfs.h\"
4305 static guestfs_h *g;
4306 static int suppress_error = 0;
4308 static void print_error (guestfs_h *g, void *data, const char *msg)
4310 if (!suppress_error)
4311 fprintf (stderr, \"%%s\\n\", msg);
4314 static void print_strings (char * const * const argv)
4318 for (argc = 0; argv[argc] != NULL; ++argc)
4319 printf (\"\\t%%s\\n\", argv[argc]);
4323 static void print_table (char * const * const argv)
4327 for (i = 0; argv[i] != NULL; i += 2)
4328 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
4332 static void no_test_warnings (void)
4338 | name, _, _, _, [], _, _ ->
4339 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
4340 | name, _, _, _, tests, _, _ -> ()
4346 (* Generate the actual tests. Note that we generate the tests
4347 * in reverse order, deliberately, so that (in general) the
4348 * newest tests run first. This makes it quicker and easier to
4353 fun (name, _, _, _, tests, _, _) ->
4354 mapi (generate_one_test name) tests
4355 ) (List.rev all_functions) in
4356 let test_names = List.concat test_names in
4357 let nr_tests = List.length test_names in
4360 int main (int argc, char *argv[])
4364 const char *filename;
4366 int nr_tests, test_num = 0;
4368 setbuf (stdout, NULL);
4370 no_test_warnings ();
4372 g = guestfs_create ();
4374 printf (\"guestfs_create FAILED\\n\");
4378 guestfs_set_error_handler (g, print_error, NULL);
4380 guestfs_set_path (g, \"../appliance\");
4382 filename = \"test1.img\";
4383 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4388 if (lseek (fd, %d, SEEK_SET) == -1) {
4394 if (write (fd, &c, 1) == -1) {
4400 if (close (fd) == -1) {
4405 if (guestfs_add_drive (g, filename) == -1) {
4406 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4410 filename = \"test2.img\";
4411 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4416 if (lseek (fd, %d, SEEK_SET) == -1) {
4422 if (write (fd, &c, 1) == -1) {
4428 if (close (fd) == -1) {
4433 if (guestfs_add_drive (g, filename) == -1) {
4434 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4438 filename = \"test3.img\";
4439 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4444 if (lseek (fd, %d, SEEK_SET) == -1) {
4450 if (write (fd, &c, 1) == -1) {
4456 if (close (fd) == -1) {
4461 if (guestfs_add_drive (g, filename) == -1) {
4462 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4466 if (guestfs_add_drive_ro (g, \"../images/test.sqsh\") == -1) {
4467 printf (\"guestfs_add_drive_ro ../images/test.sqsh FAILED\\n\");
4471 if (guestfs_launch (g) == -1) {
4472 printf (\"guestfs_launch FAILED\\n\");
4476 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
4479 if (guestfs_wait_ready (g) == -1) {
4480 printf (\"guestfs_wait_ready FAILED\\n\");
4484 /* Cancel previous alarm. */
4489 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
4493 pr " test_num++;\n";
4494 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
4495 pr " if (%s () == -1) {\n" test_name;
4496 pr " printf (\"%s FAILED\\n\");\n" test_name;
4502 pr " guestfs_close (g);\n";
4503 pr " unlink (\"test1.img\");\n";
4504 pr " unlink (\"test2.img\");\n";
4505 pr " unlink (\"test3.img\");\n";
4508 pr " if (failed > 0) {\n";
4509 pr " printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
4517 and generate_one_test name i (init, prereq, test) =
4518 let test_name = sprintf "test_%s_%d" name i in
4521 static int %s_skip (void)
4525 str = getenv (\"TEST_ONLY\");
4527 return strstr (str, \"%s\") == NULL;
4528 str = getenv (\"SKIP_%s\");
4529 if (str && strcmp (str, \"1\") == 0) return 1;
4530 str = getenv (\"SKIP_TEST_%s\");
4531 if (str && strcmp (str, \"1\") == 0) return 1;
4535 " test_name name (String.uppercase test_name) (String.uppercase name);
4538 | Disabled | Always -> ()
4539 | If code | Unless code ->
4540 pr "static int %s_prereq (void)\n" test_name;
4548 static int %s (void)
4551 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
4555 " test_name test_name test_name;
4559 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4561 pr " if (! %s_prereq ()) {\n" test_name;
4562 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4566 generate_one_test_body name i test_name init test;
4568 pr " if (%s_prereq ()) {\n" test_name;
4569 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4573 generate_one_test_body name i test_name init test;
4575 generate_one_test_body name i test_name init test
4583 and generate_one_test_body name i test_name init test =
4587 pr " /* InitNone|InitEmpty for %s */\n" test_name;
4588 List.iter (generate_test_command_call test_name)
4589 [["blockdev_setrw"; "/dev/sda"];
4593 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
4594 List.iter (generate_test_command_call test_name)
4595 [["blockdev_setrw"; "/dev/sda"];
4598 ["sfdiskM"; "/dev/sda"; ","];
4599 ["mkfs"; "ext2"; "/dev/sda1"];
4600 ["mount"; "/dev/sda1"; "/"]]
4601 | InitBasicFSonLVM ->
4602 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
4604 List.iter (generate_test_command_call test_name)
4605 [["blockdev_setrw"; "/dev/sda"];
4608 ["sfdiskM"; "/dev/sda"; ","];
4609 ["pvcreate"; "/dev/sda1"];
4610 ["vgcreate"; "VG"; "/dev/sda1"];
4611 ["lvcreate"; "LV"; "VG"; "8"];
4612 ["mkfs"; "ext2"; "/dev/VG/LV"];
4613 ["mount"; "/dev/VG/LV"; "/"]]
4616 let get_seq_last = function
4618 failwithf "%s: you cannot use [] (empty list) when expecting a command"
4621 let seq = List.rev seq in
4622 List.rev (List.tl seq), List.hd seq
4627 pr " /* TestRun for %s (%d) */\n" name i;
4628 List.iter (generate_test_command_call test_name) seq
4629 | TestOutput (seq, expected) ->
4630 pr " /* TestOutput for %s (%d) */\n" name i;
4631 pr " const char *expected = \"%s\";\n" (c_quote expected);
4632 let seq, last = get_seq_last seq in
4634 pr " if (strcmp (r, expected) != 0) {\n";
4635 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
4639 List.iter (generate_test_command_call test_name) seq;
4640 generate_test_command_call ~test test_name last
4641 | TestOutputList (seq, expected) ->
4642 pr " /* TestOutputList for %s (%d) */\n" name i;
4643 let seq, last = get_seq_last seq in
4647 pr " if (!r[%d]) {\n" i;
4648 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4649 pr " print_strings (r);\n";
4653 pr " const char *expected = \"%s\";\n" (c_quote str);
4654 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
4655 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4660 pr " if (r[%d] != NULL) {\n" (List.length expected);
4661 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4663 pr " print_strings (r);\n";
4667 List.iter (generate_test_command_call test_name) seq;
4668 generate_test_command_call ~test test_name last
4669 | TestOutputListOfDevices (seq, expected) ->
4670 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
4671 let seq, last = get_seq_last seq in
4675 pr " if (!r[%d]) {\n" i;
4676 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4677 pr " print_strings (r);\n";
4681 pr " const char *expected = \"%s\";\n" (c_quote str);
4682 pr " r[%d][5] = 's';\n" i;
4683 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
4684 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4689 pr " if (r[%d] != NULL) {\n" (List.length expected);
4690 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4692 pr " print_strings (r);\n";
4696 List.iter (generate_test_command_call test_name) seq;
4697 generate_test_command_call ~test test_name last
4698 | TestOutputInt (seq, expected) ->
4699 pr " /* TestOutputInt for %s (%d) */\n" name i;
4700 let seq, last = get_seq_last seq in
4702 pr " if (r != %d) {\n" expected;
4703 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
4709 List.iter (generate_test_command_call test_name) seq;
4710 generate_test_command_call ~test test_name last
4711 | TestOutputTrue seq ->
4712 pr " /* TestOutputTrue for %s (%d) */\n" name i;
4713 let seq, last = get_seq_last seq in
4716 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
4721 List.iter (generate_test_command_call test_name) seq;
4722 generate_test_command_call ~test test_name last
4723 | TestOutputFalse seq ->
4724 pr " /* TestOutputFalse for %s (%d) */\n" name i;
4725 let seq, last = get_seq_last seq in
4728 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
4733 List.iter (generate_test_command_call test_name) seq;
4734 generate_test_command_call ~test test_name last
4735 | TestOutputLength (seq, expected) ->
4736 pr " /* TestOutputLength for %s (%d) */\n" name i;
4737 let seq, last = get_seq_last seq in
4740 pr " for (j = 0; j < %d; ++j)\n" expected;
4741 pr " if (r[j] == NULL) {\n";
4742 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
4744 pr " print_strings (r);\n";
4747 pr " if (r[j] != NULL) {\n";
4748 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
4750 pr " print_strings (r);\n";
4754 List.iter (generate_test_command_call test_name) seq;
4755 generate_test_command_call ~test test_name last
4756 | TestOutputStruct (seq, checks) ->
4757 pr " /* TestOutputStruct for %s (%d) */\n" name i;
4758 let seq, last = get_seq_last seq in
4762 | CompareWithInt (field, expected) ->
4763 pr " if (r->%s != %d) {\n" field expected;
4764 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
4765 test_name field expected;
4766 pr " (int) r->%s);\n" field;
4769 | CompareWithString (field, expected) ->
4770 pr " if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
4771 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
4772 test_name field expected;
4773 pr " r->%s);\n" field;
4776 | CompareFieldsIntEq (field1, field2) ->
4777 pr " if (r->%s != r->%s) {\n" field1 field2;
4778 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
4779 test_name field1 field2;
4780 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
4783 | CompareFieldsStrEq (field1, field2) ->
4784 pr " if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
4785 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
4786 test_name field1 field2;
4787 pr " r->%s, r->%s);\n" field1 field2;
4792 List.iter (generate_test_command_call test_name) seq;
4793 generate_test_command_call ~test test_name last
4794 | TestLastFail seq ->
4795 pr " /* TestLastFail for %s (%d) */\n" name i;
4796 let seq, last = get_seq_last seq in
4797 List.iter (generate_test_command_call test_name) seq;
4798 generate_test_command_call test_name ~expect_error:true last
4800 (* Generate the code to run a command, leaving the result in 'r'.
4801 * If you expect to get an error then you should set expect_error:true.
4803 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
4805 | [] -> assert false
4807 (* Look up the command to find out what args/ret it has. *)
4810 let _, style, _, _, _, _, _ =
4811 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
4814 failwithf "%s: in test, command %s was not found" test_name name in
4816 if List.length (snd style) <> List.length args then
4817 failwithf "%s: in test, wrong number of args given to %s"
4824 | OptString n, "NULL" -> ()
4826 | OptString n, arg ->
4827 pr " const char *%s = \"%s\";\n" n (c_quote arg);
4830 | FileIn _, _ | FileOut _, _ -> ()
4831 | StringList n, arg ->
4832 let strs = string_split " " arg in
4835 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
4837 pr " const char *%s[] = {\n" n;
4839 fun i _ -> pr " %s_%d,\n" n i
4843 ) (List.combine (snd style) args);
4846 match fst style with
4847 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
4848 | RInt64 _ -> pr " int64_t r;\n"; "-1"
4849 | RConstString _ -> pr " const char *r;\n"; "NULL"
4850 | RString _ -> pr " char *r;\n"; "NULL"
4851 | RStringList _ | RHashtable _ ->
4855 | RStruct (_, typ) ->
4856 pr " struct guestfs_%s *r;\n" typ; "NULL"
4857 | RStructList (_, typ) ->
4858 pr " struct guestfs_%s_list *r;\n" typ; "NULL" in
4860 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
4861 pr " r = guestfs_%s (g" name;
4863 (* Generate the parameters. *)
4866 | OptString _, "NULL" -> pr ", NULL"
4870 | FileIn _, arg | FileOut _, arg ->
4871 pr ", \"%s\"" (c_quote arg)
4872 | StringList n, _ ->
4876 try int_of_string arg
4877 with Failure "int_of_string" ->
4878 failwithf "%s: expecting an int, but got '%s'" test_name arg in
4881 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
4882 ) (List.combine (snd style) args);
4885 if not expect_error then
4886 pr " if (r == %s)\n" error_code
4888 pr " if (r != %s)\n" error_code;
4891 (* Insert the test code. *)
4897 (match fst style with
4898 | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _ -> ()
4899 | RString _ -> pr " free (r);\n"
4900 | RStringList _ | RHashtable _ ->
4901 pr " for (i = 0; r[i] != NULL; ++i)\n";
4902 pr " free (r[i]);\n";
4904 | RStruct (_, typ) ->
4905 pr " guestfs_free_%s (r);\n" typ
4906 | RStructList (_, typ) ->
4907 pr " guestfs_free_%s_list (r);\n" typ
4913 let str = replace_str str "\r" "\\r" in
4914 let str = replace_str str "\n" "\\n" in
4915 let str = replace_str str "\t" "\\t" in
4916 let str = replace_str str "\000" "\\0" in
4919 (* Generate a lot of different functions for guestfish. *)
4920 and generate_fish_cmds () =
4921 generate_header CStyle GPLv2;
4925 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4927 let all_functions_sorted =
4929 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
4930 ) all_functions_sorted in
4932 pr "#include <stdio.h>\n";
4933 pr "#include <stdlib.h>\n";
4934 pr "#include <string.h>\n";
4935 pr "#include <inttypes.h>\n";
4937 pr "#include <guestfs.h>\n";
4938 pr "#include \"fish.h\"\n";
4941 (* list_commands function, which implements guestfish -h *)
4942 pr "void list_commands (void)\n";
4944 pr " printf (\" %%-16s %%s\\n\", \"Command\", \"Description\");\n";
4945 pr " list_builtin_commands ();\n";
4947 fun (name, _, _, flags, _, shortdesc, _) ->
4948 let name = replace_char name '_' '-' in
4949 pr " printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
4951 ) all_functions_sorted;
4952 pr " printf (\" Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
4956 (* display_command function, which implements guestfish -h cmd *)
4957 pr "void display_command (const char *cmd)\n";
4960 fun (name, style, _, flags, _, shortdesc, longdesc) ->
4961 let name2 = replace_char name '_' '-' in
4963 try find_map (function FishAlias n -> Some n | _ -> None) flags
4964 with Not_found -> name in
4965 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
4967 match snd style with
4971 name2 (String.concat "> <" (List.map name_of_argt args)) in
4974 if List.mem ProtocolLimitWarning flags then
4975 ("\n\n" ^ protocol_limit_warning)
4978 (* For DangerWillRobinson commands, we should probably have
4979 * guestfish prompt before allowing you to use them (especially
4980 * in interactive mode). XXX
4984 if List.mem DangerWillRobinson flags then
4985 ("\n\n" ^ danger_will_robinson)
4988 let describe_alias =
4989 if name <> alias then
4990 sprintf "\n\nYou can use '%s' as an alias for this command." alias
4994 pr "strcasecmp (cmd, \"%s\") == 0" name;
4995 if name <> name2 then
4996 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
4997 if name <> alias then
4998 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5000 pr " pod2text (\"%s - %s\", %S);\n"
5002 (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
5005 pr " display_builtin_command (cmd);\n";
5009 (* print_* functions *)
5012 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
5017 pr " printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
5019 pr " printf (\"%s: \");\n" name;
5020 pr " for (int i = 0; i < 32; ++i)\n";
5021 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
5022 pr " printf (\"\\n\");\n"
5023 | name, (FUInt64|FBytes) ->
5024 pr " printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
5026 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
5028 pr " printf (\"%s: %%\" PRIu32 \"\\n\", %s->%s);\n" name typ name
5030 pr " printf (\"%s: %%\" PRIi32 \"\\n\", %s->%s);\n" name typ name
5032 pr " printf (\"%s: %%c\\n\", %s->%s);\n" name typ name
5033 | name, FOptPercent ->
5034 pr " if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
5035 typ name name typ name;
5036 pr " else printf (\"%s: \\n\");\n" name
5040 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
5045 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
5046 pr " print_%s (&%ss->val[i]);\n" typ typ;
5051 (* run_<action> actions *)
5053 fun (name, style, _, flags, _, _, _) ->
5054 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
5056 (match fst style with
5059 | RBool _ -> pr " int r;\n"
5060 | RInt64 _ -> pr " int64_t r;\n"
5061 | RConstString _ -> pr " const char *r;\n"
5062 | RString _ -> pr " char *r;\n"
5063 | RStringList _ | RHashtable _ -> pr " char **r;\n"
5064 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
5065 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
5072 | FileOut n -> pr " const char *%s;\n" n
5073 | StringList n -> pr " char **%s;\n" n
5074 | Bool n -> pr " int %s;\n" n
5075 | Int n -> pr " int %s;\n" n
5078 (* Check and convert parameters. *)
5079 let argc_expected = List.length (snd style) in
5080 pr " if (argc != %d) {\n" argc_expected;
5081 pr " fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
5083 pr " fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
5089 | String name -> pr " %s = argv[%d];\n" name i
5091 pr " %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
5094 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
5097 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
5099 | StringList name ->
5100 pr " %s = parse_string_list (argv[%d]);\n" name i
5102 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
5104 pr " %s = atoi (argv[%d]);\n" name i
5107 (* Call C API function. *)
5109 try find_map (function FishAction n -> Some n | _ -> None) flags
5110 with Not_found -> sprintf "guestfs_%s" name in
5112 generate_call_args ~handle:"g" (snd style);
5115 (* Check return value for errors and display command results. *)
5116 (match fst style with
5117 | RErr -> pr " return r;\n"
5119 pr " if (r == -1) return -1;\n";
5120 pr " printf (\"%%d\\n\", r);\n";
5123 pr " if (r == -1) return -1;\n";
5124 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
5127 pr " if (r == -1) return -1;\n";
5128 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
5131 pr " if (r == NULL) return -1;\n";
5132 pr " printf (\"%%s\\n\", r);\n";
5135 pr " if (r == NULL) return -1;\n";
5136 pr " printf (\"%%s\\n\", r);\n";
5140 pr " if (r == NULL) return -1;\n";
5141 pr " print_strings (r);\n";
5142 pr " free_strings (r);\n";
5144 | RStruct (_, typ) ->
5145 pr " if (r == NULL) return -1;\n";
5146 pr " print_%s (r);\n" typ;
5147 pr " guestfs_free_%s (r);\n" typ;
5149 | RStructList (_, typ) ->
5150 pr " if (r == NULL) return -1;\n";
5151 pr " print_%s_list (r);\n" typ;
5152 pr " guestfs_free_%s_list (r);\n" typ;
5155 pr " if (r == NULL) return -1;\n";
5156 pr " print_table (r);\n";
5157 pr " free_strings (r);\n";
5164 (* run_action function *)
5165 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
5168 fun (name, _, _, flags, _, _, _) ->
5169 let name2 = replace_char name '_' '-' in
5171 try find_map (function FishAlias n -> Some n | _ -> None) flags
5172 with Not_found -> name in
5174 pr "strcasecmp (cmd, \"%s\") == 0" name;
5175 if name <> name2 then
5176 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5177 if name <> alias then
5178 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5180 pr " return run_%s (cmd, argc, argv);\n" name;
5184 pr " fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
5191 (* Readline completion for guestfish. *)
5192 and generate_fish_completion () =
5193 generate_header CStyle GPLv2;
5197 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5207 #ifdef HAVE_LIBREADLINE
5208 #include <readline/readline.h>
5213 #ifdef HAVE_LIBREADLINE
5215 static const char *const commands[] = {
5216 BUILTIN_COMMANDS_FOR_COMPLETION,
5219 (* Get the commands, including the aliases. They don't need to be
5220 * sorted - the generator() function just does a dumb linear search.
5224 fun (name, _, _, flags, _, _, _) ->
5225 let name2 = replace_char name '_' '-' in
5227 try find_map (function FishAlias n -> Some n | _ -> None) flags
5228 with Not_found -> name in
5230 if name <> alias then [name2; alias] else [name2]
5232 let commands = List.flatten commands in
5234 List.iter (pr " \"%s\",\n") commands;
5240 generator (const char *text, int state)
5242 static int index, len;
5247 len = strlen (text);
5250 rl_attempted_completion_over = 1;
5252 while ((name = commands[index]) != NULL) {
5254 if (strncasecmp (name, text, len) == 0)
5255 return strdup (name);
5261 #endif /* HAVE_LIBREADLINE */
5263 char **do_completion (const char *text, int start, int end)
5265 char **matches = NULL;
5267 #ifdef HAVE_LIBREADLINE
5268 rl_completion_append_character = ' ';
5271 matches = rl_completion_matches (text, generator);
5272 else if (complete_dest_paths)
5273 matches = rl_completion_matches (text, complete_dest_paths_generator);
5280 (* Generate the POD documentation for guestfish. *)
5281 and generate_fish_actions_pod () =
5282 let all_functions_sorted =
5284 fun (_, _, _, flags, _, _, _) ->
5285 not (List.mem NotInFish flags || List.mem NotInDocs flags)
5286 ) all_functions_sorted in
5288 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
5291 fun (name, style, _, flags, _, _, longdesc) ->
5293 Str.global_substitute rex (
5296 try Str.matched_group 1 s
5298 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
5299 "C<" ^ replace_char sub '_' '-' ^ ">"
5301 let name = replace_char name '_' '-' in
5303 try find_map (function FishAlias n -> Some n | _ -> None) flags
5304 with Not_found -> name in
5306 pr "=head2 %s" name;
5307 if name <> alias then
5314 | String n -> pr " %s" n
5315 | OptString n -> pr " %s" n
5316 | StringList n -> pr " '%s ...'" n
5317 | Bool _ -> pr " true|false"
5318 | Int n -> pr " %s" n
5319 | FileIn n | FileOut n -> pr " (%s|-)" n
5323 pr "%s\n\n" longdesc;
5325 if List.exists (function FileIn _ | FileOut _ -> true
5326 | _ -> false) (snd style) then
5327 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
5329 if List.mem ProtocolLimitWarning flags then
5330 pr "%s\n\n" protocol_limit_warning;
5332 if List.mem DangerWillRobinson flags then
5333 pr "%s\n\n" danger_will_robinson
5334 ) all_functions_sorted
5336 (* Generate a C function prototype. *)
5337 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
5338 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
5340 ?handle name style =
5341 if extern then pr "extern ";
5342 if static then pr "static ";
5343 (match fst style with
5345 | RInt _ -> pr "int "
5346 | RInt64 _ -> pr "int64_t "
5347 | RBool _ -> pr "int "
5348 | RConstString _ -> pr "const char *"
5349 | RString _ -> pr "char *"
5350 | RStringList _ | RHashtable _ -> pr "char **"
5351 | RStruct (_, typ) ->
5352 if not in_daemon then pr "struct guestfs_%s *" typ
5353 else pr "guestfs_int_%s *" typ
5354 | RStructList (_, typ) ->
5355 if not in_daemon then pr "struct guestfs_%s_list *" typ
5356 else pr "guestfs_int_%s_list *" typ
5358 pr "%s%s (" prefix name;
5359 if handle = None && List.length (snd style) = 0 then
5362 let comma = ref false in
5365 | Some handle -> pr "guestfs_h *%s" handle; comma := true
5369 if single_line then pr ", " else pr ",\n\t\t"
5378 if not in_daemon then pr "const char *%s" n
5379 else pr "char *%s" n
5382 if not in_daemon then pr "char * const* const %s" n
5383 else pr "char **%s" n
5384 | Bool n -> next (); pr "int %s" n
5385 | Int n -> next (); pr "int %s" n
5388 if not in_daemon then (next (); pr "const char *%s" n)
5392 if semicolon then pr ";";
5393 if newline then pr "\n"
5395 (* Generate C call arguments, eg "(handle, foo, bar)" *)
5396 and generate_call_args ?handle args =
5398 let comma = ref false in
5401 | Some handle -> pr "%s" handle; comma := true
5405 if !comma then pr ", ";
5407 pr "%s" (name_of_argt arg)
5411 (* Generate the OCaml bindings interface. *)
5412 and generate_ocaml_mli () =
5413 generate_header OCamlStyle LGPLv2;
5416 (** For API documentation you should refer to the C API
5417 in the guestfs(3) manual page. The OCaml API uses almost
5418 exactly the same calls. *)
5421 (** A [guestfs_h] handle. *)
5423 exception Error of string
5424 (** This exception is raised when there is an error. *)
5426 val create : unit -> t
5428 val close : t -> unit
5429 (** Handles are closed by the garbage collector when they become
5430 unreferenced, but callers can also call this in order to
5431 provide predictable cleanup. *)
5434 generate_ocaml_structure_decls ();
5438 fun (name, style, _, _, _, shortdesc, _) ->
5439 generate_ocaml_prototype name style;
5440 pr "(** %s *)\n" shortdesc;
5444 (* Generate the OCaml bindings implementation. *)
5445 and generate_ocaml_ml () =
5446 generate_header OCamlStyle LGPLv2;
5450 exception Error of string
5451 external create : unit -> t = \"ocaml_guestfs_create\"
5452 external close : t -> unit = \"ocaml_guestfs_close\"
5455 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
5459 generate_ocaml_structure_decls ();
5463 fun (name, style, _, _, _, shortdesc, _) ->
5464 generate_ocaml_prototype ~is_external:true name style;
5467 (* Generate the OCaml bindings C implementation. *)
5468 and generate_ocaml_c () =
5469 generate_header CStyle LGPLv2;
5476 #include <caml/config.h>
5477 #include <caml/alloc.h>
5478 #include <caml/callback.h>
5479 #include <caml/fail.h>
5480 #include <caml/memory.h>
5481 #include <caml/mlvalues.h>
5482 #include <caml/signals.h>
5484 #include <guestfs.h>
5486 #include \"guestfs_c.h\"
5488 /* Copy a hashtable of string pairs into an assoc-list. We return
5489 * the list in reverse order, but hashtables aren't supposed to be
5492 static CAMLprim value
5493 copy_table (char * const * argv)
5496 CAMLlocal5 (rv, pairv, kv, vv, cons);
5500 for (i = 0; argv[i] != NULL; i += 2) {
5501 kv = caml_copy_string (argv[i]);
5502 vv = caml_copy_string (argv[i+1]);
5503 pairv = caml_alloc (2, 0);
5504 Store_field (pairv, 0, kv);
5505 Store_field (pairv, 1, vv);
5506 cons = caml_alloc (2, 0);
5507 Store_field (cons, 1, rv);
5509 Store_field (cons, 0, pairv);
5517 (* Struct copy functions. *)
5520 let has_optpercent_col =
5521 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
5523 pr "static CAMLprim value\n";
5524 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5526 pr " CAMLparam0 ();\n";
5527 if has_optpercent_col then
5528 pr " CAMLlocal3 (rv, v, v2);\n"
5530 pr " CAMLlocal2 (rv, v);\n";
5532 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5537 pr " v = caml_copy_string (%s->%s);\n" typ name
5539 pr " v = caml_alloc_string (32);\n";
5540 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
5541 | name, (FBytes|FInt64|FUInt64) ->
5542 pr " v = caml_copy_int64 (%s->%s);\n" typ name
5543 | name, (FInt32|FUInt32) ->
5544 pr " v = caml_copy_int32 (%s->%s);\n" typ name
5545 | name, FOptPercent ->
5546 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
5547 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
5548 pr " v = caml_alloc (1, 0);\n";
5549 pr " Store_field (v, 0, v2);\n";
5550 pr " } else /* None */\n";
5551 pr " v = Val_int (0);\n";
5553 pr " v = Val_int (%s->%s);\n" typ name
5555 pr " Store_field (rv, %d, v);\n" i
5557 pr " CAMLreturn (rv);\n";
5561 pr "static CAMLprim value\n";
5562 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n"
5565 pr " CAMLparam0 ();\n";
5566 pr " CAMLlocal2 (rv, v);\n";
5569 pr " if (%ss->len == 0)\n" typ;
5570 pr " CAMLreturn (Atom (0));\n";
5572 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
5573 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
5574 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
5575 pr " caml_modify (&Field (rv, i), v);\n";
5577 pr " CAMLreturn (rv);\n";
5585 fun (name, style, _, _, _, _, _) ->
5587 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
5589 pr "CAMLprim value\n";
5590 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
5591 List.iter (pr ", value %s") (List.tl params);
5596 | [p1; p2; p3; p4; p5] ->
5597 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
5598 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
5599 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
5600 pr " CAMLxparam%d (%s);\n"
5601 (List.length rest) (String.concat ", " rest)
5603 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
5605 pr " CAMLlocal1 (rv);\n";
5608 pr " guestfs_h *g = Guestfs_val (gv);\n";
5609 pr " if (g == NULL)\n";
5610 pr " caml_failwith (\"%s: used handle after closing it\");\n" name;
5618 pr " const char *%s = String_val (%sv);\n" n n
5620 pr " const char *%s =\n" n;
5621 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
5624 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
5626 pr " int %s = Bool_val (%sv);\n" n n
5628 pr " int %s = Int_val (%sv);\n" n n
5631 match fst style with
5632 | RErr -> pr " int r;\n"; "-1"
5633 | RInt _ -> pr " int r;\n"; "-1"
5634 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5635 | RBool _ -> pr " int r;\n"; "-1"
5636 | RConstString _ -> pr " const char *r;\n"; "NULL"
5637 | RString _ -> pr " char *r;\n"; "NULL"
5642 | RStruct (_, typ) ->
5643 pr " struct guestfs_%s *r;\n" typ; "NULL"
5644 | RStructList (_, typ) ->
5645 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
5652 pr " caml_enter_blocking_section ();\n";
5653 pr " r = guestfs_%s " name;
5654 generate_call_args ~handle:"g" (snd style);
5656 pr " caml_leave_blocking_section ();\n";
5661 pr " ocaml_guestfs_free_strings (%s);\n" n;
5662 | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
5665 pr " if (r == %s)\n" error_code;
5666 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
5669 (match fst style with
5670 | RErr -> pr " rv = Val_unit;\n"
5671 | RInt _ -> pr " rv = Val_int (r);\n"
5673 pr " rv = caml_copy_int64 (r);\n"
5674 | RBool _ -> pr " rv = Val_bool (r);\n"
5675 | RConstString _ -> pr " rv = caml_copy_string (r);\n"
5677 pr " rv = caml_copy_string (r);\n";
5680 pr " rv = caml_copy_string_array ((const char **) r);\n";
5681 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5683 | RStruct (_, typ) ->
5684 pr " rv = copy_%s (r);\n" typ;
5685 pr " guestfs_free_%s (r);\n" typ;
5686 | RStructList (_, typ) ->
5687 pr " rv = copy_%s_list (r);\n" typ;
5688 pr " guestfs_free_%s_list (r);\n" typ;
5690 pr " rv = copy_table (r);\n";
5691 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
5695 pr " CAMLreturn (rv);\n";
5699 if List.length params > 5 then (
5700 pr "CAMLprim value\n";
5701 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
5703 pr " return ocaml_guestfs_%s (argv[0]" name;
5704 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
5711 and generate_ocaml_structure_decls () =
5714 pr "type %s = {\n" typ;
5717 | name, FString -> pr " %s : string;\n" name
5718 | name, FUUID -> pr " %s : string;\n" name
5719 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
5720 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
5721 | name, FChar -> pr " %s : char;\n" name
5722 | name, FOptPercent -> pr " %s : float option;\n" name
5728 and generate_ocaml_prototype ?(is_external = false) name style =
5729 if is_external then pr "external " else pr "val ";
5730 pr "%s : t -> " name;
5733 | String _ | FileIn _ | FileOut _ -> pr "string -> "
5734 | OptString _ -> pr "string option -> "
5735 | StringList _ -> pr "string array -> "
5736 | Bool _ -> pr "bool -> "
5737 | Int _ -> pr "int -> "
5739 (match fst style with
5740 | RErr -> pr "unit" (* all errors are turned into exceptions *)
5741 | RInt _ -> pr "int"
5742 | RInt64 _ -> pr "int64"
5743 | RBool _ -> pr "bool"
5744 | RConstString _ -> pr "string"
5745 | RString _ -> pr "string"
5746 | RStringList _ -> pr "string array"
5747 | RStruct (_, typ) -> pr "%s" typ
5748 | RStructList (_, typ) -> pr "%s array" typ
5749 | RHashtable _ -> pr "(string * string) list"
5751 if is_external then (
5753 if List.length (snd style) + 1 > 5 then
5754 pr "\"ocaml_guestfs_%s_byte\" " name;
5755 pr "\"ocaml_guestfs_%s\"" name
5759 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
5760 and generate_perl_xs () =
5761 generate_header CStyle LGPLv2;
5764 #include \"EXTERN.h\"
5768 #include <guestfs.h>
5771 #define PRId64 \"lld\"
5775 my_newSVll(long long val) {
5776 #ifdef USE_64_BIT_ALL
5777 return newSViv(val);
5781 len = snprintf(buf, 100, \"%%\" PRId64, val);
5782 return newSVpv(buf, len);
5787 #define PRIu64 \"llu\"
5791 my_newSVull(unsigned long long val) {
5792 #ifdef USE_64_BIT_ALL
5793 return newSVuv(val);
5797 len = snprintf(buf, 100, \"%%\" PRIu64, val);
5798 return newSVpv(buf, len);
5802 /* http://www.perlmonks.org/?node_id=680842 */
5804 XS_unpack_charPtrPtr (SV *arg) {
5809 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
5810 croak (\"array reference expected\");
5812 av = (AV *)SvRV (arg);
5813 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
5815 croak (\"malloc failed\");
5817 for (i = 0; i <= av_len (av); i++) {
5818 SV **elem = av_fetch (av, i, 0);
5820 if (!elem || !*elem)
5821 croak (\"missing element in list\");
5823 ret[i] = SvPV_nolen (*elem);
5831 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
5838 RETVAL = guestfs_create ();
5840 croak (\"could not create guestfs handle\");
5841 guestfs_set_error_handler (RETVAL, NULL, NULL);
5854 fun (name, style, _, _, _, _, _) ->
5855 (match fst style with
5856 | RErr -> pr "void\n"
5857 | RInt _ -> pr "SV *\n"
5858 | RInt64 _ -> pr "SV *\n"
5859 | RBool _ -> pr "SV *\n"
5860 | RConstString _ -> pr "SV *\n"
5861 | RString _ -> pr "SV *\n"
5863 | RStruct _ | RStructList _
5865 pr "void\n" (* all lists returned implictly on the stack *)
5867 (* Call and arguments. *)
5869 generate_call_args ~handle:"g" (snd style);
5871 pr " guestfs_h *g;\n";
5875 | String n | FileIn n | FileOut n -> pr " char *%s;\n" n
5877 (* http://www.perlmonks.org/?node_id=554277
5878 * Note that the implicit handle argument means we have
5879 * to add 1 to the ST(x) operator.
5881 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
5882 | StringList n -> pr " char **%s;\n" n
5883 | Bool n -> pr " int %s;\n" n
5884 | Int n -> pr " int %s;\n" n
5887 let do_cleanups () =
5890 | String _ | OptString _ | Bool _ | Int _
5891 | FileIn _ | FileOut _ -> ()
5892 | StringList n -> pr " free (%s);\n" n
5897 (match fst style with
5902 pr " r = guestfs_%s " name;
5903 generate_call_args ~handle:"g" (snd style);
5906 pr " if (r == -1)\n";
5907 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5913 pr " %s = guestfs_%s " n name;
5914 generate_call_args ~handle:"g" (snd style);
5917 pr " if (%s == -1)\n" n;
5918 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5919 pr " RETVAL = newSViv (%s);\n" n;
5924 pr " int64_t %s;\n" n;
5926 pr " %s = guestfs_%s " n name;
5927 generate_call_args ~handle:"g" (snd style);
5930 pr " if (%s == -1)\n" n;
5931 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5932 pr " RETVAL = my_newSVll (%s);\n" n;
5937 pr " const char *%s;\n" n;
5939 pr " %s = guestfs_%s " n name;
5940 generate_call_args ~handle:"g" (snd style);
5943 pr " if (%s == NULL)\n" n;
5944 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5945 pr " RETVAL = newSVpv (%s, 0);\n" n;
5950 pr " char *%s;\n" n;
5952 pr " %s = guestfs_%s " n name;
5953 generate_call_args ~handle:"g" (snd style);
5956 pr " if (%s == NULL)\n" n;
5957 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5958 pr " RETVAL = newSVpv (%s, 0);\n" n;
5959 pr " free (%s);\n" n;
5962 | RStringList n | RHashtable n ->
5964 pr " char **%s;\n" n;
5967 pr " %s = guestfs_%s " n name;
5968 generate_call_args ~handle:"g" (snd style);
5971 pr " if (%s == NULL)\n" n;
5972 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
5973 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
5974 pr " EXTEND (SP, n);\n";
5975 pr " for (i = 0; i < n; ++i) {\n";
5976 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
5977 pr " free (%s[i]);\n" n;
5979 pr " free (%s);\n" n;
5980 | RStruct (n, typ) ->
5981 let cols = cols_of_struct typ in
5982 generate_perl_struct_code typ cols name style n do_cleanups
5983 | RStructList (n, typ) ->
5984 let cols = cols_of_struct typ in
5985 generate_perl_struct_list_code typ cols name style n do_cleanups
5991 and generate_perl_struct_list_code typ cols name style n do_cleanups =
5993 pr " struct guestfs_%s_list *%s;\n" typ n;
5997 pr " %s = guestfs_%s " n name;
5998 generate_call_args ~handle:"g" (snd style);
6001 pr " if (%s == NULL)\n" n;
6002 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6003 pr " EXTEND (SP, %s->len);\n" n;
6004 pr " for (i = 0; i < %s->len; ++i) {\n" n;
6005 pr " hv = newHV ();\n";
6009 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
6010 name (String.length name) n name
6012 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
6013 name (String.length name) n name
6014 | name, (FBytes|FUInt64) ->
6015 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
6016 name (String.length name) n name
6018 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
6019 name (String.length name) n name
6020 | name, (FInt32|FUInt32) ->
6021 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6022 name (String.length name) n name
6024 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
6025 name (String.length name) n name
6026 | name, FOptPercent ->
6027 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6028 name (String.length name) n name
6030 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
6032 pr " guestfs_free_%s_list (%s);\n" typ n
6034 and generate_perl_struct_code typ cols name style n do_cleanups =
6036 pr " struct guestfs_%s *%s;\n" typ n;
6038 pr " %s = guestfs_%s " n name;
6039 generate_call_args ~handle:"g" (snd style);
6042 pr " if (%s == NULL)\n" n;
6043 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6044 pr " EXTEND (SP, %d);\n" (List.length cols);
6048 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
6051 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
6053 | name, (FBytes|FUInt64) ->
6054 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
6057 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
6059 | name, (FInt32|FUInt32) ->
6060 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6063 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
6065 | name, FOptPercent ->
6066 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6069 pr " free (%s);\n" n
6071 (* Generate Sys/Guestfs.pm. *)
6072 and generate_perl_pm () =
6073 generate_header HashStyle LGPLv2;
6080 Sys::Guestfs - Perl bindings for libguestfs
6086 my $h = Sys::Guestfs->new ();
6087 $h->add_drive ('guest.img');
6090 $h->mount ('/dev/sda1', '/');
6091 $h->touch ('/hello');
6096 The C<Sys::Guestfs> module provides a Perl XS binding to the
6097 libguestfs API for examining and modifying virtual machine
6100 Amongst the things this is good for: making batch configuration
6101 changes to guests, getting disk used/free statistics (see also:
6102 virt-df), migrating between virtualization systems (see also:
6103 virt-p2v), performing partial backups, performing partial guest
6104 clones, cloning guests and changing registry/UUID/hostname info, and
6107 Libguestfs uses Linux kernel and qemu code, and can access any type of
6108 guest filesystem that Linux and qemu can, including but not limited
6109 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6110 schemes, qcow, qcow2, vmdk.
6112 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6113 LVs, what filesystem is in each LV, etc.). It can also run commands
6114 in the context of the guest. Also you can access filesystems over FTP.
6118 All errors turn into calls to C<croak> (see L<Carp(3)>).
6126 package Sys::Guestfs;
6132 XSLoader::load ('Sys::Guestfs');
6134 =item $h = Sys::Guestfs->new ();
6136 Create a new guestfs handle.
6142 my $class = ref ($proto) || $proto;
6144 my $self = Sys::Guestfs::_create ();
6145 bless $self, $class;
6151 (* Actions. We only need to print documentation for these as
6152 * they are pulled in from the XS code automatically.
6155 fun (name, style, _, flags, _, _, longdesc) ->
6156 if not (List.mem NotInDocs flags) then (
6157 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
6159 generate_perl_prototype name style;
6161 pr "%s\n\n" longdesc;
6162 if List.mem ProtocolLimitWarning flags then
6163 pr "%s\n\n" protocol_limit_warning;
6164 if List.mem DangerWillRobinson flags then
6165 pr "%s\n\n" danger_will_robinson
6167 ) all_functions_sorted;
6179 Copyright (C) 2009 Red Hat Inc.
6183 Please see the file COPYING.LIB for the full license.
6187 L<guestfs(3)>, L<guestfish(1)>.
6192 and generate_perl_prototype name style =
6193 (match fst style with
6199 | RString n -> pr "$%s = " n
6201 | RHashtable n -> pr "%%%s = " n
6203 | RStructList (n,_) -> pr "@%s = " n
6206 let comma = ref false in
6209 if !comma then pr ", ";
6212 | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
6219 (* Generate Python C module. *)
6220 and generate_python_c () =
6221 generate_header CStyle LGPLv2;
6230 #include \"guestfs.h\"
6238 get_handle (PyObject *obj)
6241 assert (obj != Py_None);
6242 return ((Pyguestfs_Object *) obj)->g;
6246 put_handle (guestfs_h *g)
6250 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
6253 /* This list should be freed (but not the strings) after use. */
6254 static const char **
6255 get_string_list (PyObject *obj)
6262 if (!PyList_Check (obj)) {
6263 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
6267 len = PyList_Size (obj);
6268 r = malloc (sizeof (char *) * (len+1));
6270 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
6274 for (i = 0; i < len; ++i)
6275 r[i] = PyString_AsString (PyList_GetItem (obj, i));
6282 put_string_list (char * const * const argv)
6287 for (argc = 0; argv[argc] != NULL; ++argc)
6290 list = PyList_New (argc);
6291 for (i = 0; i < argc; ++i)
6292 PyList_SetItem (list, i, PyString_FromString (argv[i]));
6298 put_table (char * const * const argv)
6300 PyObject *list, *item;
6303 for (argc = 0; argv[argc] != NULL; ++argc)
6306 list = PyList_New (argc >> 1);
6307 for (i = 0; i < argc; i += 2) {
6308 item = PyTuple_New (2);
6309 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
6310 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
6311 PyList_SetItem (list, i >> 1, item);
6318 free_strings (char **argv)
6322 for (argc = 0; argv[argc] != NULL; ++argc)
6328 py_guestfs_create (PyObject *self, PyObject *args)
6332 g = guestfs_create ();
6334 PyErr_SetString (PyExc_RuntimeError,
6335 \"guestfs.create: failed to allocate handle\");
6338 guestfs_set_error_handler (g, NULL, NULL);
6339 return put_handle (g);
6343 py_guestfs_close (PyObject *self, PyObject *args)
6348 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
6350 g = get_handle (py_g);
6354 Py_INCREF (Py_None);
6360 (* Structures, turned into Python dictionaries. *)
6363 pr "static PyObject *\n";
6364 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
6366 pr " PyObject *dict;\n";
6368 pr " dict = PyDict_New ();\n";
6372 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6373 pr " PyString_FromString (%s->%s));\n"
6376 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6377 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
6379 | name, (FBytes|FUInt64) ->
6380 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6381 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
6384 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6385 pr " PyLong_FromLongLong (%s->%s));\n"
6388 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6389 pr " PyLong_FromUnsignedLong (%s->%s));\n"
6392 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6393 pr " PyLong_FromLong (%s->%s));\n"
6395 | name, FOptPercent ->
6396 pr " if (%s->%s >= 0)\n" typ name;
6397 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6398 pr " PyFloat_FromDouble ((double) %s->%s));\n"
6401 pr " Py_INCREF (Py_None);\n";
6402 pr " PyDict_SetItemString (dict, \"%s\", Py_None);" name;
6405 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6406 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
6408 pr " return dict;\n";
6412 pr "static PyObject *\n";
6413 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
6415 pr " PyObject *list;\n";
6418 pr " list = PyList_New (%ss->len);\n" typ;
6419 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
6420 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
6421 pr " return list;\n";
6426 (* Python wrapper functions. *)
6428 fun (name, style, _, _, _, _, _) ->
6429 pr "static PyObject *\n";
6430 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
6433 pr " PyObject *py_g;\n";
6434 pr " guestfs_h *g;\n";
6435 pr " PyObject *py_r;\n";
6438 match fst style with
6439 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
6440 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6441 | RConstString _ -> pr " const char *r;\n"; "NULL"
6442 | RString _ -> pr " char *r;\n"; "NULL"
6443 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6444 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
6445 | RStructList (_, typ) ->
6446 pr " struct guestfs_%s_list *r;\n" typ; "NULL" in
6450 | String n | FileIn n | FileOut n -> pr " const char *%s;\n" n
6451 | OptString n -> pr " const char *%s;\n" n
6453 pr " PyObject *py_%s;\n" n;
6454 pr " const char **%s;\n" n
6455 | Bool n -> pr " int %s;\n" n
6456 | Int n -> pr " int %s;\n" n
6461 (* Convert the parameters. *)
6462 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
6465 | String _ | FileIn _ | FileOut _ -> pr "s"
6466 | OptString _ -> pr "z"
6467 | StringList _ -> pr "O"
6468 | Bool _ -> pr "i" (* XXX Python has booleans? *)
6471 pr ":guestfs_%s\",\n" name;
6475 | String n | FileIn n | FileOut n -> pr ", &%s" n
6476 | OptString n -> pr ", &%s" n
6477 | StringList n -> pr ", &py_%s" n
6478 | Bool n -> pr ", &%s" n
6479 | Int n -> pr ", &%s" n
6483 pr " return NULL;\n";
6485 pr " g = get_handle (py_g);\n";
6488 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6490 pr " %s = get_string_list (py_%s);\n" n n;
6491 pr " if (!%s) return NULL;\n" n
6496 pr " r = guestfs_%s " name;
6497 generate_call_args ~handle:"g" (snd style);
6502 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6504 pr " free (%s);\n" n
6507 pr " if (r == %s) {\n" error_code;
6508 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6509 pr " return NULL;\n";
6513 (match fst style with
6515 pr " Py_INCREF (Py_None);\n";
6516 pr " py_r = Py_None;\n"
6518 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
6519 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
6520 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
6522 pr " py_r = PyString_FromString (r);\n";
6525 pr " py_r = put_string_list (r);\n";
6526 pr " free_strings (r);\n"
6527 | RStruct (_, typ) ->
6528 pr " py_r = put_%s (r);\n" typ;
6529 pr " guestfs_free_%s (r);\n" typ
6530 | RStructList (_, typ) ->
6531 pr " py_r = put_%s_list (r);\n" typ;
6532 pr " guestfs_free_%s_list (r);\n" typ
6534 pr " py_r = put_table (r);\n";
6535 pr " free_strings (r);\n"
6538 pr " return py_r;\n";
6543 (* Table of functions. *)
6544 pr "static PyMethodDef methods[] = {\n";
6545 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
6546 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
6548 fun (name, _, _, _, _, _, _) ->
6549 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
6552 pr " { NULL, NULL, 0, NULL }\n";
6556 (* Init function. *)
6559 initlibguestfsmod (void)
6561 static int initialized = 0;
6563 if (initialized) return;
6564 Py_InitModule ((char *) \"libguestfsmod\", methods);
6569 (* Generate Python module. *)
6570 and generate_python_py () =
6571 generate_header HashStyle LGPLv2;
6574 u\"\"\"Python bindings for libguestfs
6577 g = guestfs.GuestFS ()
6578 g.add_drive (\"guest.img\")
6581 parts = g.list_partitions ()
6583 The guestfs module provides a Python binding to the libguestfs API
6584 for examining and modifying virtual machine disk images.
6586 Amongst the things this is good for: making batch configuration
6587 changes to guests, getting disk used/free statistics (see also:
6588 virt-df), migrating between virtualization systems (see also:
6589 virt-p2v), performing partial backups, performing partial guest
6590 clones, cloning guests and changing registry/UUID/hostname info, and
6593 Libguestfs uses Linux kernel and qemu code, and can access any type of
6594 guest filesystem that Linux and qemu can, including but not limited
6595 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6596 schemes, qcow, qcow2, vmdk.
6598 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6599 LVs, what filesystem is in each LV, etc.). It can also run commands
6600 in the context of the guest. Also you can access filesystems over FTP.
6602 Errors which happen while using the API are turned into Python
6603 RuntimeError exceptions.
6605 To create a guestfs handle you usually have to perform the following
6608 # Create the handle, call add_drive at least once, and possibly
6609 # several times if the guest has multiple block devices:
6610 g = guestfs.GuestFS ()
6611 g.add_drive (\"guest.img\")
6613 # Launch the qemu subprocess and wait for it to become ready:
6617 # Now you can issue commands, for example:
6622 import libguestfsmod
6625 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
6627 def __init__ (self):
6628 \"\"\"Create a new libguestfs handle.\"\"\"
6629 self._o = libguestfsmod.create ()
6632 libguestfsmod.close (self._o)
6637 fun (name, style, _, flags, _, _, longdesc) ->
6639 generate_call_args ~handle:"self" (snd style);
6642 if not (List.mem NotInDocs flags) then (
6643 let doc = replace_str longdesc "C<guestfs_" "C<g." in
6645 match fst style with
6646 | RErr | RInt _ | RInt64 _ | RBool _ | RConstString _
6649 doc ^ "\n\nThis function returns a list of strings."
6650 | RStruct (_, typ) ->
6651 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
6652 | RStructList (_, typ) ->
6653 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
6655 doc ^ "\n\nThis function returns a dictionary." in
6657 if List.mem ProtocolLimitWarning flags then
6658 doc ^ "\n\n" ^ protocol_limit_warning
6661 if List.mem DangerWillRobinson flags then
6662 doc ^ "\n\n" ^ danger_will_robinson
6664 let doc = pod2text ~width:60 name doc in
6665 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
6666 let doc = String.concat "\n " doc in
6667 pr " u\"\"\"%s\"\"\"\n" doc;
6669 pr " return libguestfsmod.%s " name;
6670 generate_call_args ~handle:"self._o" (snd style);
6675 (* Useful if you need the longdesc POD text as plain text. Returns a
6678 * Because this is very slow (the slowest part of autogeneration),
6679 * we memoize the results.
6681 and pod2text ~width name longdesc =
6682 let key = width, name, longdesc in
6683 try Hashtbl.find pod2text_memo key
6685 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
6686 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
6688 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
6689 let chan = Unix.open_process_in cmd in
6690 let lines = ref [] in
6692 let line = input_line chan in
6693 if i = 1 then (* discard the first line of output *)
6696 let line = triml line in
6697 lines := line :: !lines;
6700 let lines = try loop 1 with End_of_file -> List.rev !lines in
6701 Unix.unlink filename;
6702 (match Unix.close_process_in chan with
6703 | Unix.WEXITED 0 -> ()
6705 failwithf "pod2text: process exited with non-zero status (%d)" i
6706 | Unix.WSIGNALED i | Unix.WSTOPPED i ->
6707 failwithf "pod2text: process signalled or stopped by signal %d" i
6709 Hashtbl.add pod2text_memo key lines;
6710 let chan = open_out pod2text_memo_filename in
6711 output_value chan pod2text_memo;
6715 (* Generate ruby bindings. *)
6716 and generate_ruby_c () =
6717 generate_header CStyle LGPLv2;
6725 #include \"guestfs.h\"
6727 #include \"extconf.h\"
6729 /* For Ruby < 1.9 */
6731 #define RARRAY_LEN(r) (RARRAY((r))->len)
6734 static VALUE m_guestfs; /* guestfs module */
6735 static VALUE c_guestfs; /* guestfs_h handle */
6736 static VALUE e_Error; /* used for all errors */
6738 static void ruby_guestfs_free (void *p)
6741 guestfs_close ((guestfs_h *) p);
6744 static VALUE ruby_guestfs_create (VALUE m)
6748 g = guestfs_create ();
6750 rb_raise (e_Error, \"failed to create guestfs handle\");
6752 /* Don't print error messages to stderr by default. */
6753 guestfs_set_error_handler (g, NULL, NULL);
6755 /* Wrap it, and make sure the close function is called when the
6758 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
6761 static VALUE ruby_guestfs_close (VALUE gv)
6764 Data_Get_Struct (gv, guestfs_h, g);
6766 ruby_guestfs_free (g);
6767 DATA_PTR (gv) = NULL;
6775 fun (name, style, _, _, _, _, _) ->
6776 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
6777 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
6780 pr " guestfs_h *g;\n";
6781 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
6783 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
6789 | String n | FileIn n | FileOut n ->
6790 pr " Check_Type (%sv, T_STRING);\n" n;
6791 pr " const char *%s = StringValueCStr (%sv);\n" n n;
6793 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
6794 pr " \"%s\", \"%s\");\n" n name
6796 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
6798 pr " char **%s;\n" n;
6799 pr " Check_Type (%sv, T_ARRAY);\n" n;
6801 pr " int i, len;\n";
6802 pr " len = RARRAY_LEN (%sv);\n" n;
6803 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
6805 pr " for (i = 0; i < len; ++i) {\n";
6806 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
6807 pr " %s[i] = StringValueCStr (v);\n" n;
6809 pr " %s[len] = NULL;\n" n;
6812 pr " int %s = RTEST (%sv);\n" n n
6814 pr " int %s = NUM2INT (%sv);\n" n n
6819 match fst style with
6820 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
6821 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6822 | RConstString _ -> pr " const char *r;\n"; "NULL"
6823 | RString _ -> pr " char *r;\n"; "NULL"
6824 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6825 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
6826 | RStructList (_, typ) ->
6827 pr " struct guestfs_%s_list *r;\n" typ; "NULL" in
6830 pr " r = guestfs_%s " name;
6831 generate_call_args ~handle:"g" (snd style);
6836 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6838 pr " free (%s);\n" n
6841 pr " if (r == %s)\n" error_code;
6842 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
6845 (match fst style with
6847 pr " return Qnil;\n"
6848 | RInt _ | RBool _ ->
6849 pr " return INT2NUM (r);\n"
6851 pr " return ULL2NUM (r);\n"
6853 pr " return rb_str_new2 (r);\n";
6855 pr " VALUE rv = rb_str_new2 (r);\n";
6859 pr " int i, len = 0;\n";
6860 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
6861 pr " VALUE rv = rb_ary_new2 (len);\n";
6862 pr " for (i = 0; r[i] != NULL; ++i) {\n";
6863 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
6864 pr " free (r[i]);\n";
6868 | RStruct (_, typ) ->
6869 let cols = cols_of_struct typ in
6870 generate_ruby_struct_code typ cols
6871 | RStructList (_, typ) ->
6872 let cols = cols_of_struct typ in
6873 generate_ruby_struct_list_code typ cols
6875 pr " VALUE rv = rb_hash_new ();\n";
6877 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
6878 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
6879 pr " free (r[i]);\n";
6880 pr " free (r[i+1]);\n";
6891 /* Initialize the module. */
6892 void Init__guestfs ()
6894 m_guestfs = rb_define_module (\"Guestfs\");
6895 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
6896 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
6898 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
6899 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
6902 (* Define the rest of the methods. *)
6904 fun (name, style, _, _, _, _, _) ->
6905 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
6906 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
6911 (* Ruby code to return a struct. *)
6912 and generate_ruby_struct_code typ cols =
6913 pr " VALUE rv = rb_hash_new ();\n";
6917 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
6919 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
6920 | name, (FBytes|FUInt64) ->
6921 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6923 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
6925 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
6927 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
6928 | name, FOptPercent ->
6929 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
6930 | name, FChar -> (* XXX wrong? *)
6931 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
6933 pr " guestfs_free_%s (r);\n" typ;
6936 (* Ruby code to return a struct list. *)
6937 and generate_ruby_struct_list_code typ cols =
6938 pr " VALUE rv = rb_ary_new2 (r->len);\n";
6940 pr " for (i = 0; i < r->len; ++i) {\n";
6941 pr " VALUE hv = rb_hash_new ();\n";
6945 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
6947 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
6948 | name, (FBytes|FUInt64) ->
6949 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
6951 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
6953 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
6955 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
6956 | name, FOptPercent ->
6957 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
6958 | name, FChar -> (* XXX wrong? *)
6959 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
6961 pr " rb_ary_push (rv, hv);\n";
6963 pr " guestfs_free_%s_list (r);\n" typ;
6966 (* Generate Java bindings GuestFS.java file. *)
6967 and generate_java_java () =
6968 generate_header CStyle LGPLv2;
6971 package com.redhat.et.libguestfs;
6973 import java.util.HashMap;
6974 import com.redhat.et.libguestfs.LibGuestFSException;
6975 import com.redhat.et.libguestfs.PV;
6976 import com.redhat.et.libguestfs.VG;
6977 import com.redhat.et.libguestfs.LV;
6978 import com.redhat.et.libguestfs.Stat;
6979 import com.redhat.et.libguestfs.StatVFS;
6980 import com.redhat.et.libguestfs.IntBool;
6981 import com.redhat.et.libguestfs.Dirent;
6984 * The GuestFS object is a libguestfs handle.
6988 public class GuestFS {
6989 // Load the native code.
6991 System.loadLibrary (\"guestfs_jni\");
6995 * The native guestfs_h pointer.
7000 * Create a libguestfs handle.
7002 * @throws LibGuestFSException
7004 public GuestFS () throws LibGuestFSException
7008 private native long _create () throws LibGuestFSException;
7011 * Close a libguestfs handle.
7013 * You can also leave handles to be collected by the garbage
7014 * collector, but this method ensures that the resources used
7015 * by the handle are freed up immediately. If you call any
7016 * other methods after closing the handle, you will get an
7019 * @throws LibGuestFSException
7021 public void close () throws LibGuestFSException
7027 private native void _close (long g) throws LibGuestFSException;
7029 public void finalize () throws LibGuestFSException
7037 fun (name, style, _, flags, _, shortdesc, longdesc) ->
7038 if not (List.mem NotInDocs flags); then (
7039 let doc = replace_str longdesc "C<guestfs_" "C<g." in
7041 if List.mem ProtocolLimitWarning flags then
7042 doc ^ "\n\n" ^ protocol_limit_warning
7045 if List.mem DangerWillRobinson flags then
7046 doc ^ "\n\n" ^ danger_will_robinson
7048 let doc = pod2text ~width:60 name doc in
7049 let doc = List.map ( (* RHBZ#501883 *)
7052 | nonempty -> nonempty
7054 let doc = String.concat "\n * " doc in
7057 pr " * %s\n" shortdesc;
7060 pr " * @throws LibGuestFSException\n";
7064 generate_java_prototype ~public:true ~semicolon:false name style;
7067 pr " if (g == 0)\n";
7068 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
7071 if fst style <> RErr then pr "return ";
7073 generate_call_args ~handle:"g" (snd style);
7077 generate_java_prototype ~privat:true ~native:true name style;
7084 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
7085 ?(semicolon=true) name style =
7086 if privat then pr "private ";
7087 if public then pr "public ";
7088 if native then pr "native ";
7091 (match fst style with
7092 | RErr -> pr "void ";
7093 | RInt _ -> pr "int ";
7094 | RInt64 _ -> pr "long ";
7095 | RBool _ -> pr "boolean ";
7096 | RConstString _ | RString _ -> pr "String ";
7097 | RStringList _ -> pr "String[] ";
7098 | RStruct (_, typ) ->
7099 let name = java_name_of_struct typ in
7101 | RStructList (_, typ) ->
7102 let name = java_name_of_struct typ in
7104 | RHashtable _ -> pr "HashMap<String,String> ";
7107 if native then pr "_%s " name else pr "%s " name;
7109 let needs_comma = ref false in
7118 if !needs_comma then pr ", ";
7119 needs_comma := true;
7136 pr " throws LibGuestFSException";
7137 if semicolon then pr ";"
7139 and generate_java_struct jtyp cols =
7140 generate_header CStyle LGPLv2;
7143 package com.redhat.et.libguestfs;
7146 * Libguestfs %s structure.
7157 | name, FUUID -> pr " public String %s;\n" name
7158 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
7159 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
7160 | name, FChar -> pr " public char %s;\n" name
7161 | name, FOptPercent ->
7162 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
7163 pr " public float %s;\n" name
7168 and generate_java_c () =
7169 generate_header CStyle LGPLv2;
7176 #include \"com_redhat_et_libguestfs_GuestFS.h\"
7177 #include \"guestfs.h\"
7179 /* Note that this function returns. The exception is not thrown
7180 * until after the wrapper function returns.
7183 throw_exception (JNIEnv *env, const char *msg)
7186 cl = (*env)->FindClass (env,
7187 \"com/redhat/et/libguestfs/LibGuestFSException\");
7188 (*env)->ThrowNew (env, cl, msg);
7191 JNIEXPORT jlong JNICALL
7192 Java_com_redhat_et_libguestfs_GuestFS__1create
7193 (JNIEnv *env, jobject obj)
7197 g = guestfs_create ();
7199 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
7202 guestfs_set_error_handler (g, NULL, NULL);
7203 return (jlong) (long) g;
7206 JNIEXPORT void JNICALL
7207 Java_com_redhat_et_libguestfs_GuestFS__1close
7208 (JNIEnv *env, jobject obj, jlong jg)
7210 guestfs_h *g = (guestfs_h *) (long) jg;
7217 fun (name, style, _, _, _, _, _) ->
7219 (match fst style with
7220 | RErr -> pr "void ";
7221 | RInt _ -> pr "jint ";
7222 | RInt64 _ -> pr "jlong ";
7223 | RBool _ -> pr "jboolean ";
7224 | RConstString _ | RString _ -> pr "jstring ";
7225 | RStruct _ | RHashtable _ ->
7227 | RStringList _ | RStructList _ ->
7231 pr "Java_com_redhat_et_libguestfs_GuestFS_";
7232 pr "%s" (replace_str ("_" ^ name) "_" "_1");
7234 pr " (JNIEnv *env, jobject obj, jlong jg";
7241 pr ", jstring j%s" n
7243 pr ", jobjectArray j%s" n
7245 pr ", jboolean j%s" n
7251 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
7252 let error_code, no_ret =
7253 match fst style with
7254 | RErr -> pr " int r;\n"; "-1", ""
7256 | RInt _ -> pr " int r;\n"; "-1", "0"
7257 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
7258 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
7260 pr " jstring jr;\n";
7261 pr " char *r;\n"; "NULL", "NULL"
7263 pr " jobjectArray jr;\n";
7266 pr " jstring jstr;\n";
7267 pr " char **r;\n"; "NULL", "NULL"
7268 | RStruct (_, typ) ->
7269 pr " jobject jr;\n";
7271 pr " jfieldID fl;\n";
7272 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
7273 | RStructList (_, typ) ->
7274 pr " jobjectArray jr;\n";
7276 pr " jfieldID fl;\n";
7277 pr " jobject jfl;\n";
7278 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
7279 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL" in
7286 pr " const char *%s;\n" n
7288 pr " int %s_len;\n" n;
7289 pr " const char **%s;\n" n
7296 (match fst style with
7297 | RStringList _ | RStructList _ -> true
7298 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
7299 | RString _ | RStruct _ | RHashtable _ -> false) ||
7300 List.exists (function StringList _ -> true | _ -> false) (snd style) in
7306 (* Get the parameters. *)
7312 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
7314 (* This is completely undocumented, but Java null becomes
7317 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
7319 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
7320 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
7321 pr " for (i = 0; i < %s_len; ++i) {\n" n;
7322 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
7324 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
7326 pr " %s[%s_len] = NULL;\n" n n;
7329 pr " %s = j%s;\n" n n
7332 (* Make the call. *)
7333 pr " r = guestfs_%s " name;
7334 generate_call_args ~handle:"g" (snd style);
7337 (* Release the parameters. *)
7343 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
7346 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
7348 pr " for (i = 0; i < %s_len; ++i) {\n" n;
7349 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
7351 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
7353 pr " free (%s);\n" n
7358 (* Check for errors. *)
7359 pr " if (r == %s) {\n" error_code;
7360 pr " throw_exception (env, guestfs_last_error (g));\n";
7361 pr " return %s;\n" no_ret;
7365 (match fst style with
7367 | RInt _ -> pr " return (jint) r;\n"
7368 | RBool _ -> pr " return (jboolean) r;\n"
7369 | RInt64 _ -> pr " return (jlong) r;\n"
7370 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
7372 pr " jr = (*env)->NewStringUTF (env, r);\n";
7376 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
7377 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
7378 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
7379 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
7380 pr " for (i = 0; i < r_len; ++i) {\n";
7381 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
7382 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
7383 pr " free (r[i]);\n";
7387 | RStruct (_, typ) ->
7388 let jtyp = java_name_of_struct typ in
7389 let cols = cols_of_struct typ in
7390 generate_java_struct_return typ jtyp cols
7391 | RStructList (_, typ) ->
7392 let jtyp = java_name_of_struct typ in
7393 let cols = cols_of_struct typ in
7394 generate_java_struct_list_return typ jtyp cols
7397 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
7398 pr " return NULL;\n"
7405 and generate_java_struct_return typ jtyp cols =
7406 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
7407 pr " jr = (*env)->AllocObject (env, cl);\n";
7411 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7412 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
7415 pr " char s[33];\n";
7416 pr " memcpy (s, r->%s, 32);\n" name;
7418 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7419 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
7421 | name, (FBytes|FUInt64|FInt64) ->
7422 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7423 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7424 | name, (FUInt32|FInt32) ->
7425 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
7426 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7427 | name, FOptPercent ->
7428 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7429 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
7431 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
7432 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7437 and generate_java_struct_list_return typ jtyp cols =
7438 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
7439 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
7440 pr " for (i = 0; i < r->len; ++i) {\n";
7441 pr " jfl = (*env)->AllocObject (env, cl);\n";
7445 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7446 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
7449 pr " char s[33];\n";
7450 pr " memcpy (s, r->val[i].%s, 32);\n" name;
7452 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7453 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
7455 | name, (FBytes|FUInt64|FInt64) ->
7456 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7457 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7458 | name, (FUInt32|FInt32) ->
7459 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
7460 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7461 | name, FOptPercent ->
7462 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7463 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
7465 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
7466 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
7468 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
7470 pr " guestfs_free_%s_list (r);\n" typ;
7473 and generate_haskell_hs () =
7474 generate_header HaskellStyle LGPLv2;
7476 (* XXX We only know how to generate partial FFI for Haskell
7477 * at the moment. Please help out!
7479 let can_generate style =
7483 | RInt64 _, _ -> true
7490 | RHashtable _, _ -> false in
7493 {-# INCLUDE <guestfs.h> #-}
7494 {-# LANGUAGE ForeignFunctionInterface #-}
7499 (* List out the names of the actions we want to export. *)
7501 fun (name, style, _, _, _, _, _) ->
7502 if can_generate style then pr ",\n %s" name
7509 import Foreign.C.Types
7511 import Control.Exception
7512 import Data.Typeable
7514 data GuestfsS = GuestfsS -- represents the opaque C struct
7515 type GuestfsP = Ptr GuestfsS -- guestfs_h *
7516 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
7518 -- XXX define properly later XXX
7522 data IntBool = IntBool
7524 data StatVFS = StatVFS
7525 data Hashtable = Hashtable
7527 foreign import ccall unsafe \"guestfs_create\" c_create
7529 foreign import ccall unsafe \"&guestfs_close\" c_close
7530 :: FunPtr (GuestfsP -> IO ())
7531 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
7532 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
7534 create :: IO GuestfsH
7537 c_set_error_handler p nullPtr nullPtr
7538 h <- newForeignPtr c_close p
7541 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
7542 :: GuestfsP -> IO CString
7544 -- last_error :: GuestfsH -> IO (Maybe String)
7545 -- last_error h = do
7546 -- str <- withForeignPtr h (\\p -> c_last_error p)
7547 -- maybePeek peekCString str
7549 last_error :: GuestfsH -> IO (String)
7551 str <- withForeignPtr h (\\p -> c_last_error p)
7553 then return \"no error\"
7554 else peekCString str
7558 (* Generate wrappers for each foreign function. *)
7560 fun (name, style, _, _, _, _, _) ->
7561 if can_generate style then (
7562 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
7564 generate_haskell_prototype ~handle:"GuestfsP" style;
7568 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
7570 pr "%s %s = do\n" name
7571 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
7573 (* Convert pointer arguments using with* functions. *)
7578 | String n -> pr "withCString %s $ \\%s -> " n n
7579 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
7580 | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
7581 | Bool _ | Int _ -> ()
7583 (* Convert integer arguments. *)
7587 | Bool n -> sprintf "(fromBool %s)" n
7588 | Int n -> sprintf "(fromIntegral %s)" n
7589 | FileIn n | FileOut n | String n | OptString n | StringList n -> n
7591 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
7592 (String.concat " " ("p" :: args));
7593 (match fst style with
7594 | RErr | RInt _ | RInt64 _ | RBool _ ->
7595 pr " if (r == -1)\n";
7597 pr " err <- last_error h\n";
7599 | RConstString _ | RString _ | RStringList _ | RStruct _
7600 | RStructList _ | RHashtable _ ->
7601 pr " if (r == nullPtr)\n";
7603 pr " err <- last_error h\n";
7606 (match fst style with
7608 pr " else return ()\n"
7610 pr " else return (fromIntegral r)\n"
7612 pr " else return (fromIntegral r)\n"
7614 pr " else return (toBool r)\n"
7621 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
7627 and generate_haskell_prototype ~handle ?(hs = false) style =
7629 let string = if hs then "String" else "CString" in
7630 let int = if hs then "Int" else "CInt" in
7631 let bool = if hs then "Bool" else "CInt" in
7632 let int64 = if hs then "Integer" else "Int64" in
7636 | String _ -> pr "%s" string
7637 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
7638 | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
7639 | Bool _ -> pr "%s" bool
7640 | Int _ -> pr "%s" int
7641 | FileIn _ -> pr "%s" string
7642 | FileOut _ -> pr "%s" string
7647 (match fst style with
7648 | RErr -> if not hs then pr "CInt"
7649 | RInt _ -> pr "%s" int
7650 | RInt64 _ -> pr "%s" int64
7651 | RBool _ -> pr "%s" bool
7652 | RConstString _ -> pr "%s" string
7653 | RString _ -> pr "%s" string
7654 | RStringList _ -> pr "[%s]" string
7655 | RStruct (_, typ) ->
7656 let name = java_name_of_struct typ in
7658 | RStructList (_, typ) ->
7659 let name = java_name_of_struct typ in
7661 | RHashtable _ -> pr "Hashtable"
7665 and generate_bindtests () =
7666 generate_header CStyle LGPLv2;
7671 #include <inttypes.h>
7674 #include \"guestfs.h\"
7675 #include \"guestfs_protocol.h\"
7677 #define error guestfs_error
7678 #define safe_calloc guestfs_safe_calloc
7679 #define safe_malloc guestfs_safe_malloc
7682 print_strings (char * const* const argv)
7687 for (argc = 0; argv[argc] != NULL; ++argc) {
7688 if (argc > 0) printf (\", \");
7689 printf (\"\\\"%%s\\\"\", argv[argc]);
7694 /* The test0 function prints its parameters to stdout. */
7698 match test_functions with
7699 | [] -> assert false
7700 | test0 :: tests -> test0, tests in
7703 let (name, style, _, _, _, _, _) = test0 in
7704 generate_prototype ~extern:false ~semicolon:false ~newline:true
7705 ~handle:"g" ~prefix:"guestfs_" name style;
7711 | FileOut n -> pr " printf (\"%%s\\n\", %s);\n" n
7712 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
7713 | StringList n -> pr " print_strings (%s);\n" n
7714 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
7715 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
7717 pr " /* Java changes stdout line buffering so we need this: */\n";
7718 pr " fflush (stdout);\n";
7724 fun (name, style, _, _, _, _, _) ->
7725 if String.sub name (String.length name - 3) 3 <> "err" then (
7726 pr "/* Test normal return. */\n";
7727 generate_prototype ~extern:false ~semicolon:false ~newline:true
7728 ~handle:"g" ~prefix:"guestfs_" name style;
7730 (match fst style with
7735 pr " sscanf (val, \"%%d\", &r);\n";
7739 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
7742 pr " return strcmp (val, \"true\") == 0;\n"
7744 (* Can't return the input string here. Return a static
7745 * string so we ensure we get a segfault if the caller
7748 pr " return \"static string\";\n"
7750 pr " return strdup (val);\n"
7752 pr " char **strs;\n";
7754 pr " sscanf (val, \"%%d\", &n);\n";
7755 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
7756 pr " for (i = 0; i < n; ++i) {\n";
7757 pr " strs[i] = safe_malloc (g, 16);\n";
7758 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
7760 pr " strs[n] = NULL;\n";
7761 pr " return strs;\n"
7762 | RStruct (_, typ) ->
7763 pr " struct guestfs_%s *r;\n" typ;
7764 pr " r = safe_calloc (g, sizeof *r, 1);\n";
7766 | RStructList (_, typ) ->
7767 pr " struct guestfs_%s_list *r;\n" typ;
7768 pr " r = safe_calloc (g, sizeof *r, 1);\n";
7769 pr " sscanf (val, \"%%d\", &r->len);\n";
7770 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
7773 pr " char **strs;\n";
7775 pr " sscanf (val, \"%%d\", &n);\n";
7776 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
7777 pr " for (i = 0; i < n; ++i) {\n";
7778 pr " strs[i*2] = safe_malloc (g, 16);\n";
7779 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
7780 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
7781 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
7783 pr " strs[n*2] = NULL;\n";
7784 pr " return strs;\n"
7789 pr "/* Test error return. */\n";
7790 generate_prototype ~extern:false ~semicolon:false ~newline:true
7791 ~handle:"g" ~prefix:"guestfs_" name style;
7793 pr " error (g, \"error\");\n";
7794 (match fst style with
7795 | RErr | RInt _ | RInt64 _ | RBool _ ->
7798 | RString _ | RStringList _ | RStruct _
7801 pr " return NULL;\n"
7808 and generate_ocaml_bindtests () =
7809 generate_header OCamlStyle GPLv2;
7813 let g = Guestfs.create () in
7820 | CallString s -> "\"" ^ s ^ "\""
7821 | CallOptString None -> "None"
7822 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
7823 | CallStringList xs ->
7824 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
7825 | CallInt i when i >= 0 -> string_of_int i
7826 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
7827 | CallBool b -> string_of_bool b
7832 generate_lang_bindtests (
7833 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
7836 pr "print_endline \"EOF\"\n"
7838 and generate_perl_bindtests () =
7839 pr "#!/usr/bin/perl -w\n";
7840 generate_header HashStyle GPLv2;
7847 my $g = Sys::Guestfs->new ();
7851 String.concat ", " (
7854 | CallString s -> "\"" ^ s ^ "\""
7855 | CallOptString None -> "undef"
7856 | CallOptString (Some s) -> sprintf "\"%s\"" s
7857 | CallStringList xs ->
7858 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7859 | CallInt i -> string_of_int i
7860 | CallBool b -> if b then "1" else "0"
7865 generate_lang_bindtests (
7866 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
7869 pr "print \"EOF\\n\"\n"
7871 and generate_python_bindtests () =
7872 generate_header HashStyle GPLv2;
7877 g = guestfs.GuestFS ()
7881 String.concat ", " (
7884 | CallString s -> "\"" ^ s ^ "\""
7885 | CallOptString None -> "None"
7886 | CallOptString (Some s) -> sprintf "\"%s\"" s
7887 | CallStringList xs ->
7888 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7889 | CallInt i -> string_of_int i
7890 | CallBool b -> if b then "1" else "0"
7895 generate_lang_bindtests (
7896 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
7899 pr "print \"EOF\"\n"
7901 and generate_ruby_bindtests () =
7902 generate_header HashStyle GPLv2;
7907 g = Guestfs::create()
7911 String.concat ", " (
7914 | CallString s -> "\"" ^ s ^ "\""
7915 | CallOptString None -> "nil"
7916 | CallOptString (Some s) -> sprintf "\"%s\"" s
7917 | CallStringList xs ->
7918 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7919 | CallInt i -> string_of_int i
7920 | CallBool b -> string_of_bool b
7925 generate_lang_bindtests (
7926 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
7929 pr "print \"EOF\\n\"\n"
7931 and generate_java_bindtests () =
7932 generate_header CStyle GPLv2;
7935 import com.redhat.et.libguestfs.*;
7937 public class Bindtests {
7938 public static void main (String[] argv)
7941 GuestFS g = new GuestFS ();
7945 String.concat ", " (
7948 | CallString s -> "\"" ^ s ^ "\""
7949 | CallOptString None -> "null"
7950 | CallOptString (Some s) -> sprintf "\"%s\"" s
7951 | CallStringList xs ->
7953 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
7954 | CallInt i -> string_of_int i
7955 | CallBool b -> string_of_bool b
7960 generate_lang_bindtests (
7961 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
7965 System.out.println (\"EOF\");
7967 catch (Exception exn) {
7968 System.err.println (exn);
7975 and generate_haskell_bindtests () =
7976 generate_header HaskellStyle GPLv2;
7979 module Bindtests where
7980 import qualified Guestfs
7990 | CallString s -> "\"" ^ s ^ "\""
7991 | CallOptString None -> "Nothing"
7992 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
7993 | CallStringList xs ->
7994 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
7995 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
7996 | CallInt i -> string_of_int i
7997 | CallBool true -> "True"
7998 | CallBool false -> "False"
8003 generate_lang_bindtests (
8004 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
8007 pr " putStrLn \"EOF\"\n"
8009 (* Language-independent bindings tests - we do it this way to
8010 * ensure there is parity in testing bindings across all languages.
8012 and generate_lang_bindtests call =
8013 call "test0" [CallString "abc"; CallOptString (Some "def");
8014 CallStringList []; CallBool false;
8015 CallInt 0; CallString "123"; CallString "456"];
8016 call "test0" [CallString "abc"; CallOptString None;
8017 CallStringList []; CallBool false;
8018 CallInt 0; CallString "123"; CallString "456"];
8019 call "test0" [CallString ""; CallOptString (Some "def");
8020 CallStringList []; CallBool false;
8021 CallInt 0; CallString "123"; CallString "456"];
8022 call "test0" [CallString ""; CallOptString (Some "");
8023 CallStringList []; CallBool false;
8024 CallInt 0; CallString "123"; CallString "456"];
8025 call "test0" [CallString "abc"; CallOptString (Some "def");
8026 CallStringList ["1"]; CallBool false;
8027 CallInt 0; CallString "123"; CallString "456"];
8028 call "test0" [CallString "abc"; CallOptString (Some "def");
8029 CallStringList ["1"; "2"]; CallBool false;
8030 CallInt 0; CallString "123"; CallString "456"];
8031 call "test0" [CallString "abc"; CallOptString (Some "def");
8032 CallStringList ["1"]; CallBool true;
8033 CallInt 0; CallString "123"; CallString "456"];
8034 call "test0" [CallString "abc"; CallOptString (Some "def");
8035 CallStringList ["1"]; CallBool false;
8036 CallInt (-1); CallString "123"; CallString "456"];
8037 call "test0" [CallString "abc"; CallOptString (Some "def");
8038 CallStringList ["1"]; CallBool false;
8039 CallInt (-2); CallString "123"; CallString "456"];
8040 call "test0" [CallString "abc"; CallOptString (Some "def");
8041 CallStringList ["1"]; CallBool false;
8042 CallInt 1; CallString "123"; CallString "456"];
8043 call "test0" [CallString "abc"; CallOptString (Some "def");
8044 CallStringList ["1"]; CallBool false;
8045 CallInt 2; CallString "123"; CallString "456"];
8046 call "test0" [CallString "abc"; CallOptString (Some "def");
8047 CallStringList ["1"]; CallBool false;
8048 CallInt 4095; CallString "123"; CallString "456"];
8049 call "test0" [CallString "abc"; CallOptString (Some "def");
8050 CallStringList ["1"]; CallBool false;
8051 CallInt 0; CallString ""; CallString ""]
8053 (* XXX Add here tests of the return and error functions. *)
8055 (* This is used to generate the src/MAX_PROC_NR file which
8056 * contains the maximum procedure number, a surrogate for the
8057 * ABI version number. See src/Makefile.am for the details.
8059 and generate_max_proc_nr () =
8060 let proc_nrs = List.map (
8061 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
8062 ) daemon_functions in
8064 let max_proc_nr = List.fold_left max 0 proc_nrs in
8066 pr "%d\n" max_proc_nr
8068 let output_to filename =
8069 let filename_new = filename ^ ".new" in
8070 chan := open_out filename_new;
8075 (* Is the new file different from the current file? *)
8076 if Sys.file_exists filename && files_equal filename filename_new then
8077 Unix.unlink filename_new (* same, so skip it *)
8079 (* different, overwrite old one *)
8080 (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
8081 Unix.rename filename_new filename;
8082 Unix.chmod filename 0o444;
8083 printf "written %s\n%!" filename;
8092 if not (Sys.file_exists "config.status") then (
8094 You are probably running this from the wrong directory.
8095 Run it from the top source directory using the command
8101 let close = output_to "src/guestfs_protocol.x" in
8105 let close = output_to "src/guestfs-structs.h" in
8106 generate_structs_h ();
8109 let close = output_to "src/guestfs-actions.h" in
8110 generate_actions_h ();
8113 let close = output_to "src/guestfs-actions.c" in
8114 generate_client_actions ();
8117 let close = output_to "daemon/actions.h" in
8118 generate_daemon_actions_h ();
8121 let close = output_to "daemon/stubs.c" in
8122 generate_daemon_actions ();
8125 let close = output_to "daemon/names.c" in
8126 generate_daemon_names ();
8129 let close = output_to "capitests/tests.c" in
8133 let close = output_to "src/guestfs-bindtests.c" in
8134 generate_bindtests ();
8137 let close = output_to "fish/cmds.c" in
8138 generate_fish_cmds ();
8141 let close = output_to "fish/completion.c" in
8142 generate_fish_completion ();
8145 let close = output_to "guestfs-structs.pod" in
8146 generate_structs_pod ();
8149 let close = output_to "guestfs-actions.pod" in
8150 generate_actions_pod ();
8153 let close = output_to "guestfish-actions.pod" in
8154 generate_fish_actions_pod ();
8157 let close = output_to "ocaml/guestfs.mli" in
8158 generate_ocaml_mli ();
8161 let close = output_to "ocaml/guestfs.ml" in
8162 generate_ocaml_ml ();
8165 let close = output_to "ocaml/guestfs_c_actions.c" in
8166 generate_ocaml_c ();
8169 let close = output_to "ocaml/bindtests.ml" in
8170 generate_ocaml_bindtests ();
8173 let close = output_to "perl/Guestfs.xs" in
8174 generate_perl_xs ();
8177 let close = output_to "perl/lib/Sys/Guestfs.pm" in
8178 generate_perl_pm ();
8181 let close = output_to "perl/bindtests.pl" in
8182 generate_perl_bindtests ();
8185 let close = output_to "python/guestfs-py.c" in
8186 generate_python_c ();
8189 let close = output_to "python/guestfs.py" in
8190 generate_python_py ();
8193 let close = output_to "python/bindtests.py" in
8194 generate_python_bindtests ();
8197 let close = output_to "ruby/ext/guestfs/_guestfs.c" in
8201 let close = output_to "ruby/bindtests.rb" in
8202 generate_ruby_bindtests ();
8205 let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
8206 generate_java_java ();
8211 let cols = cols_of_struct typ in
8212 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
8213 let close = output_to filename in
8214 generate_java_struct jtyp cols;
8218 let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
8222 let close = output_to "java/Bindtests.java" in
8223 generate_java_bindtests ();
8226 let close = output_to "haskell/Guestfs.hs" in
8227 generate_haskell_hs ();
8230 let close = output_to "haskell/Bindtests.hs" in
8231 generate_haskell_bindtests ();
8234 let close = output_to "src/MAX_PROC_NR" in
8235 generate_max_proc_nr ();
8238 (* Always generate this file last, and unconditionally. It's used
8239 * by the Makefile to know when we must re-run the generator.
8241 let chan = open_out "src/stamp-generator" in