3 * Copyright (C) 2009-2010 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 of
25 * 'daemon_functions' below), and daemon/<somefile>.c to write the
28 * After editing this file, run it (./src/generator.ml) to regenerate
29 * all the output files. 'make' will rerun this automatically when
30 * necessary. Note that if you are using a separate build directory
31 * you must run generator.ml from the _source_ directory.
33 * IMPORTANT: This script should NOT print any warnings. If it prints
34 * warnings, you should treat them as errors.
37 * (1) In emacs, install tuareg-mode to display and format OCaml code
38 * correctly. 'vim' comes with a good OCaml editing mode by default.
39 * (2) Read the resources at http://ocaml-tutorial.org/
44 #directory "+xml-light";;
45 #load "xml-light.cma";;
50 type style = ret * args
52 (* "RErr" as a return value means an int used as a simple error
53 * indication, ie. 0 or -1.
57 (* "RInt" as a return value means an int which is -1 for error
58 * or any value >= 0 on success. Only use this for smallish
59 * positive ints (0 <= i < 2^30).
63 (* "RInt64" is the same as RInt, but is guaranteed to be able
64 * to return a full 64 bit value, _except_ that -1 means error
65 * (so -1 cannot be a valid, non-error return value).
69 (* "RBool" is a bool return value which can be true/false or
74 (* "RConstString" is a string that refers to a constant value.
75 * The return value must NOT be NULL (since NULL indicates
78 * Try to avoid using this. In particular you cannot use this
79 * for values returned from the daemon, because there is no
80 * thread-safe way to return them in the C API.
82 | RConstString of string
84 (* "RConstOptString" is an even more broken version of
85 * "RConstString". The returned string may be NULL and there
86 * is no way to return an error indication. Avoid using this!
88 | RConstOptString of string
90 (* "RString" is a returned string. It must NOT be NULL, since
91 * a NULL return indicates an error. The caller frees this.
95 (* "RStringList" is a list of strings. No string in the list
96 * can be NULL. The caller frees the strings and the array.
98 | RStringList of string
100 (* "RStruct" is a function which returns a single named structure
101 * or an error indication (in C, a struct, and in other languages
102 * with varying representations, but usually very efficient). See
103 * after the function list below for the structures.
105 | RStruct of string * string (* name of retval, name of struct *)
107 (* "RStructList" is a function which returns either a list/array
108 * of structures (could be zero-length), or an error indication.
110 | RStructList of string * string (* name of retval, name of struct *)
112 (* Key-value pairs of untyped strings. Turns into a hashtable or
113 * dictionary in languages which support it. DON'T use this as a
114 * general "bucket" for results. Prefer a stronger typed return
115 * value if one is available, or write a custom struct. Don't use
116 * this if the list could potentially be very long, since it is
117 * inefficient. Keys should be unique. NULLs are not permitted.
119 | RHashtable of string
121 (* "RBufferOut" is handled almost exactly like RString, but
122 * it allows the string to contain arbitrary 8 bit data including
123 * ASCII NUL. In the C API this causes an implicit extra parameter
124 * to be added of type <size_t *size_r>. The extra parameter
125 * returns the actual size of the return buffer in bytes.
127 * Other programming languages support strings with arbitrary 8 bit
130 * At the RPC layer we have to use the opaque<> type instead of
131 * string<>. Returned data is still limited to the max message
134 | RBufferOut of string
136 and args = argt list (* Function parameters, guestfs handle is implicit. *)
138 (* Note in future we should allow a "variable args" parameter as
139 * the final parameter, to allow commands like
140 * chmod mode file [file(s)...]
141 * This is not implemented yet, but many commands (such as chmod)
142 * are currently defined with the argument order keeping this future
143 * possibility in mind.
146 | String of string (* const char *name, cannot be NULL *)
147 | Device of string (* /dev device name, cannot be NULL *)
148 | Pathname of string (* file name, cannot be NULL *)
149 | Dev_or_Path of string (* /dev device name or Pathname, cannot be NULL *)
150 | OptString of string (* const char *name, may be NULL *)
151 | StringList of string(* list of strings (each string cannot be NULL) *)
152 | DeviceList of string(* list of Device names (each cannot be NULL) *)
153 | Bool of string (* boolean *)
154 | Int of string (* int (smallish ints, signed, <= 31 bits) *)
155 | Int64 of string (* any 64 bit int *)
156 (* These are treated as filenames (simple string parameters) in
157 * the C API and bindings. But in the RPC protocol, we transfer
158 * the actual file content up to or down from the daemon.
159 * FileIn: local machine -> daemon (in request)
160 * FileOut: daemon -> local machine (in reply)
161 * In guestfish (only), the special name "-" means read from
162 * stdin or write to stdout.
167 (* Opaque buffer which can contain arbitrary 8 bit data.
168 * In the C API, this is expressed as <char *, int> pair.
169 * Most other languages have a string type which can contain
170 * ASCII NUL. We use whatever type is appropriate for each
172 * Buffers are limited by the total message size. To transfer
173 * large blocks of data, use FileIn/FileOut parameters instead.
174 * To return an arbitrary buffer, use RBufferOut.
180 | ProtocolLimitWarning (* display warning about protocol size limits *)
181 | DangerWillRobinson (* flags particularly dangerous commands *)
182 | FishAlias of string (* provide an alias for this cmd in guestfish *)
183 | FishAction of string (* call this function in guestfish *)
184 | NotInFish (* do not export via guestfish *)
185 | NotInDocs (* do not add this function to documentation *)
186 | DeprecatedBy of string (* function is deprecated, use .. instead *)
187 | Optional of string (* function is part of an optional group *)
189 (* You can supply zero or as many tests as you want per API call.
191 * Note that the test environment has 3 block devices, of size 500MB,
192 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
193 * a fourth ISO block device with some known files on it (/dev/sdd).
195 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
196 * Number of cylinders was 63 for IDE emulated disks with precisely
197 * the same size. How exactly this is calculated is a mystery.
199 * The ISO block device (/dev/sdd) comes from images/test.iso.
201 * To be able to run the tests in a reasonable amount of time,
202 * the virtual machine and block devices are reused between tests.
203 * So don't try testing kill_subprocess :-x
205 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
207 * Don't assume anything about the previous contents of the block
208 * devices. Use 'Init*' to create some initial scenarios.
210 * You can add a prerequisite clause to any individual test. This
211 * is a run-time check, which, if it fails, causes the test to be
212 * skipped. Useful if testing a command which might not work on
213 * all variations of libguestfs builds. A test that has prerequisite
214 * of 'Always' is run unconditionally.
216 * In addition, packagers can skip individual tests by setting the
217 * environment variables: eg:
218 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
219 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
221 type tests = (test_init * test_prereq * test) list
223 (* Run the command sequence and just expect nothing to fail. *)
226 (* Run the command sequence and expect the output of the final
227 * command to be the string.
229 | TestOutput of seq * string
231 (* Run the command sequence and expect the output of the final
232 * command to be the list of strings.
234 | TestOutputList of seq * string list
236 (* Run the command sequence and expect the output of the final
237 * command to be the list of block devices (could be either
238 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
239 * character of each string).
241 | TestOutputListOfDevices of seq * string list
243 (* Run the command sequence and expect the output of the final
244 * command to be the integer.
246 | TestOutputInt of seq * int
248 (* Run the command sequence and expect the output of the final
249 * command to be <op> <int>, eg. ">=", "1".
251 | TestOutputIntOp of seq * string * int
253 (* Run the command sequence and expect the output of the final
254 * command to be a true value (!= 0 or != NULL).
256 | TestOutputTrue of seq
258 (* Run the command sequence and expect the output of the final
259 * command to be a false value (== 0 or == NULL, but not an error).
261 | TestOutputFalse of seq
263 (* Run the command sequence and expect the output of the final
264 * command to be a list of the given length (but don't care about
267 | TestOutputLength of seq * int
269 (* Run the command sequence and expect the output of the final
270 * command to be a buffer (RBufferOut), ie. string + size.
272 | TestOutputBuffer of seq * string
274 (* Run the command sequence and expect the output of the final
275 * command to be a structure.
277 | TestOutputStruct of seq * test_field_compare list
279 (* Run the command sequence and expect the final command (only)
282 | TestLastFail of seq
284 and test_field_compare =
285 | CompareWithInt of string * int
286 | CompareWithIntOp of string * string * int
287 | CompareWithString of string * string
288 | CompareFieldsIntEq of string * string
289 | CompareFieldsStrEq of string * string
291 (* Test prerequisites. *)
293 (* Test always runs. *)
296 (* Test is currently disabled - eg. it fails, or it tests some
297 * unimplemented feature.
301 (* 'string' is some C code (a function body) that should return
302 * true or false. The test will run if the code returns true.
306 (* As for 'If' but the test runs _unless_ the code returns true. *)
309 (* Some initial scenarios for testing. *)
311 (* Do nothing, block devices could contain random stuff including
312 * LVM PVs, and some filesystems might be mounted. This is usually
317 (* Block devices are empty and no filesystems are mounted. *)
320 (* /dev/sda contains a single partition /dev/sda1, with random
321 * content. /dev/sdb and /dev/sdc may have random content.
326 (* /dev/sda contains a single partition /dev/sda1, which is formatted
327 * as ext2, empty [except for lost+found] and mounted on /.
328 * /dev/sdb and /dev/sdc may have random content.
334 * /dev/sda1 (is a PV):
335 * /dev/VG/LV (size 8MB):
336 * formatted as ext2, empty [except for lost+found], mounted on /
337 * /dev/sdb and /dev/sdc may have random content.
341 (* /dev/sdd (the ISO, see images/ directory in source)
346 (* Sequence of commands for testing. *)
348 and cmd = string list
350 (* Note about long descriptions: When referring to another
351 * action, use the format C<guestfs_other> (ie. the full name of
352 * the C function). This will be replaced as appropriate in other
355 * Apart from that, long descriptions are just perldoc paragraphs.
358 (* Generate a random UUID (used in tests). *)
360 let chan = open_process_in "uuidgen" in
361 let uuid = input_line chan in
362 (match close_process_in chan with
365 failwith "uuidgen: process exited with non-zero status"
366 | WSIGNALED _ | WSTOPPED _ ->
367 failwith "uuidgen: process signalled or stopped by signal"
371 (* These test functions are used in the language binding tests. *)
373 let test_all_args = [
376 StringList "strlist";
384 let test_all_rets = [
385 (* except for RErr, which is tested thoroughly elsewhere *)
386 "test0rint", RInt "valout";
387 "test0rint64", RInt64 "valout";
388 "test0rbool", RBool "valout";
389 "test0rconststring", RConstString "valout";
390 "test0rconstoptstring", RConstOptString "valout";
391 "test0rstring", RString "valout";
392 "test0rstringlist", RStringList "valout";
393 "test0rstruct", RStruct ("valout", "lvm_pv");
394 "test0rstructlist", RStructList ("valout", "lvm_pv");
395 "test0rhashtable", RHashtable "valout";
398 let test_functions = [
399 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
401 "internal test function - do not use",
403 This is an internal test function which is used to test whether
404 the automatically generated bindings can handle every possible
405 parameter type correctly.
407 It echos the contents of each parameter to stdout.
409 You probably don't want to call this function.");
413 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
415 "internal test function - do not use",
417 This is an internal test function which is used to test whether
418 the automatically generated bindings can handle every possible
419 return type correctly.
421 It converts string C<val> to the return type.
423 You probably don't want to call this function.");
424 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
426 "internal test function - do not use",
428 This is an internal test function which is used to test whether
429 the automatically generated bindings can handle every possible
430 return type correctly.
432 This function always returns an error.
434 You probably don't want to call this function.")]
438 (* non_daemon_functions are any functions which don't get processed
439 * in the daemon, eg. functions for setting and getting local
440 * configuration values.
443 let non_daemon_functions = test_functions @ [
444 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
446 "launch the qemu subprocess",
448 Internally libguestfs is implemented by running a virtual machine
451 You should call this after configuring the handle
452 (eg. adding drives) but before performing any actions.");
454 ("wait_ready", (RErr, []), -1, [NotInFish],
456 "wait until the qemu subprocess launches (no op)",
458 This function is a no op.
460 In versions of the API E<lt> 1.0.71 you had to call this function
461 just after calling C<guestfs_launch> to wait for the launch
462 to complete. However this is no longer necessary because
463 C<guestfs_launch> now does the waiting.
465 If you see any calls to this function in code then you can just
466 remove them, unless you want to retain compatibility with older
467 versions of the API.");
469 ("kill_subprocess", (RErr, []), -1, [],
471 "kill the qemu subprocess",
473 This kills the qemu subprocess. You should never need to call this.");
475 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
477 "add an image to examine or modify",
479 This function adds a virtual machine disk image C<filename> to the
480 guest. The first time you call this function, the disk appears as IDE
481 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
484 You don't necessarily need to be root when using libguestfs. However
485 you obviously do need sufficient permissions to access the filename
486 for whatever operations you want to perform (ie. read access if you
487 just want to read the image or write access if you want to modify the
490 This is equivalent to the qemu parameter
491 C<-drive file=filename,cache=off,if=...>.
493 C<cache=off> is omitted in cases where it is not supported by
494 the underlying filesystem.
496 C<if=...> is set at compile time by the configuration option
497 C<./configure --with-drive-if=...>. In the rare case where you
498 might need to change this at run time, use C<guestfs_add_drive_with_if>
499 or C<guestfs_add_drive_ro_with_if>.
501 Note that this call checks for the existence of C<filename>. This
502 stops you from specifying other types of drive which are supported
503 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
504 the general C<guestfs_config> call instead.");
506 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
508 "add a CD-ROM disk image to examine",
510 This function adds a virtual CD-ROM disk image to the guest.
512 This is equivalent to the qemu parameter C<-cdrom filename>.
520 This call checks for the existence of C<filename>. This
521 stops you from specifying other types of drive which are supported
522 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
523 the general C<guestfs_config> call instead.
527 If you just want to add an ISO file (often you use this as an
528 efficient way to transfer large files into the guest), then you
529 should probably use C<guestfs_add_drive_ro> instead.
533 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
535 "add a drive in snapshot mode (read-only)",
537 This adds a drive in snapshot mode, making it effectively
540 Note that writes to the device are allowed, and will be seen for
541 the duration of the guestfs handle, but they are written
542 to a temporary file which is discarded as soon as the guestfs
543 handle is closed. We don't currently have any method to enable
544 changes to be committed, although qemu can support this.
546 This is equivalent to the qemu parameter
547 C<-drive file=filename,snapshot=on,if=...>.
549 C<if=...> is set at compile time by the configuration option
550 C<./configure --with-drive-if=...>. In the rare case where you
551 might need to change this at run time, use C<guestfs_add_drive_with_if>
552 or C<guestfs_add_drive_ro_with_if>.
554 Note that this call checks for the existence of C<filename>. This
555 stops you from specifying other types of drive which are supported
556 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
557 the general C<guestfs_config> call instead.");
559 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
561 "add qemu parameters",
563 This can be used to add arbitrary qemu command line parameters
564 of the form C<-param value>. Actually it's not quite arbitrary - we
565 prevent you from setting some parameters which would interfere with
566 parameters that we use.
568 The first character of C<param> string must be a C<-> (dash).
570 C<value> can be NULL.");
572 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
574 "set the qemu binary",
576 Set the qemu binary that we will use.
578 The default is chosen when the library was compiled by the
581 You can also override this by setting the C<LIBGUESTFS_QEMU>
582 environment variable.
584 Setting C<qemu> to C<NULL> restores the default qemu binary.");
586 ("get_qemu", (RConstString "qemu", []), -1, [],
587 [InitNone, Always, TestRun (
589 "get the qemu binary",
591 Return the current qemu binary.
593 This is always non-NULL. If it wasn't set already, then this will
594 return the default qemu binary name.");
596 ("set_path", (RErr, [String "searchpath"]), -1, [FishAlias "path"],
598 "set the search path",
600 Set the path that libguestfs searches for kernel and initrd.img.
602 The default is C<$libdir/guestfs> unless overridden by setting
603 C<LIBGUESTFS_PATH> environment variable.
605 Setting C<path> to C<NULL> restores the default path.");
607 ("get_path", (RConstString "path", []), -1, [],
608 [InitNone, Always, TestRun (
610 "get the search path",
612 Return the current search path.
614 This is always non-NULL. If it wasn't set already, then this will
615 return the default path.");
617 ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
619 "add options to kernel command line",
621 This function is used to add additional options to the
622 guest kernel command line.
624 The default is C<NULL> unless overridden by setting
625 C<LIBGUESTFS_APPEND> environment variable.
627 Setting C<append> to C<NULL> means I<no> additional options
628 are passed (libguestfs always adds a few of its own).");
630 ("get_append", (RConstOptString "append", []), -1, [],
631 (* This cannot be tested with the current framework. The
632 * function can return NULL in normal operations, which the
633 * test framework interprets as an error.
636 "get the additional kernel options",
638 Return the additional kernel options which are added to the
639 guest kernel command line.
641 If C<NULL> then no options are added.");
643 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
647 If C<autosync> is true, this enables autosync. Libguestfs will make a
648 best effort attempt to run C<guestfs_umount_all> followed by
649 C<guestfs_sync> when the handle is closed
650 (also if the program exits without closing handles).
652 This is disabled by default (except in guestfish where it is
653 enabled by default).");
655 ("get_autosync", (RBool "autosync", []), -1, [],
656 [InitNone, Always, TestRun (
657 [["get_autosync"]])],
660 Get the autosync flag.");
662 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
666 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
668 Verbose messages are disabled unless the environment variable
669 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
671 ("get_verbose", (RBool "verbose", []), -1, [],
675 This returns the verbose messages flag.");
677 ("is_ready", (RBool "ready", []), -1, [],
678 [InitNone, Always, TestOutputTrue (
680 "is ready to accept commands",
682 This returns true iff this handle is ready to accept commands
683 (in the C<READY> state).
685 For more information on states, see L<guestfs(3)>.");
687 ("is_config", (RBool "config", []), -1, [],
688 [InitNone, Always, TestOutputFalse (
690 "is in configuration state",
692 This returns true iff this handle is being configured
693 (in the C<CONFIG> state).
695 For more information on states, see L<guestfs(3)>.");
697 ("is_launching", (RBool "launching", []), -1, [],
698 [InitNone, Always, TestOutputFalse (
699 [["is_launching"]])],
700 "is launching subprocess",
702 This returns true iff this handle is launching the subprocess
703 (in the C<LAUNCHING> state).
705 For more information on states, see L<guestfs(3)>.");
707 ("is_busy", (RBool "busy", []), -1, [],
708 [InitNone, Always, TestOutputFalse (
710 "is busy processing a command",
712 This returns true iff this handle is busy processing a command
713 (in the C<BUSY> state).
715 For more information on states, see L<guestfs(3)>.");
717 ("get_state", (RInt "state", []), -1, [],
719 "get the current state",
721 This returns the current state as an opaque integer. This is
722 only useful for printing debug and internal error messages.
724 For more information on states, see L<guestfs(3)>.");
726 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
727 [InitNone, Always, TestOutputInt (
728 [["set_memsize"; "500"];
729 ["get_memsize"]], 500)],
730 "set memory allocated to the qemu subprocess",
732 This sets the memory size in megabytes allocated to the
733 qemu subprocess. This only has any effect if called before
736 You can also change this by setting the environment
737 variable C<LIBGUESTFS_MEMSIZE> before the handle is
740 For more information on the architecture of libguestfs,
741 see L<guestfs(3)>.");
743 ("get_memsize", (RInt "memsize", []), -1, [],
744 [InitNone, Always, TestOutputIntOp (
745 [["get_memsize"]], ">=", 256)],
746 "get memory allocated to the qemu subprocess",
748 This gets the memory size in megabytes allocated to the
751 If C<guestfs_set_memsize> was not called
752 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
753 then this returns the compiled-in default value for memsize.
755 For more information on the architecture of libguestfs,
756 see L<guestfs(3)>.");
758 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
759 [InitNone, Always, TestOutputIntOp (
760 [["get_pid"]], ">=", 1)],
761 "get PID of qemu subprocess",
763 Return the process ID of the qemu subprocess. If there is no
764 qemu subprocess, then this will return an error.
766 This is an internal call used for debugging and testing.");
768 ("version", (RStruct ("version", "version"), []), -1, [],
769 [InitNone, Always, TestOutputStruct (
770 [["version"]], [CompareWithInt ("major", 1)])],
771 "get the library version number",
773 Return the libguestfs version number that the program is linked
776 Note that because of dynamic linking this is not necessarily
777 the version of libguestfs that you compiled against. You can
778 compile the program, and then at runtime dynamically link
779 against a completely different C<libguestfs.so> library.
781 This call was added in version C<1.0.58>. In previous
782 versions of libguestfs there was no way to get the version
783 number. From C code you can use ELF weak linking tricks to find out if
784 this symbol exists (if it doesn't, then it's an earlier version).
786 The call returns a structure with four elements. The first
787 three (C<major>, C<minor> and C<release>) are numbers and
788 correspond to the usual version triplet. The fourth element
789 (C<extra>) is a string and is normally empty, but may be
790 used for distro-specific information.
792 To construct the original version string:
793 C<$major.$minor.$release$extra>
795 I<Note:> Don't use this call to test for availability
796 of features. Distro backports makes this unreliable. Use
797 C<guestfs_available> instead.");
799 ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
800 [InitNone, Always, TestOutputTrue (
801 [["set_selinux"; "true"];
803 "set SELinux enabled or disabled at appliance boot",
805 This sets the selinux flag that is passed to the appliance
806 at boot time. The default is C<selinux=0> (disabled).
808 Note that if SELinux is enabled, it is always in
809 Permissive mode (C<enforcing=0>).
811 For more information on the architecture of libguestfs,
812 see L<guestfs(3)>.");
814 ("get_selinux", (RBool "selinux", []), -1, [],
816 "get SELinux enabled flag",
818 This returns the current setting of the selinux flag which
819 is passed to the appliance at boot time. See C<guestfs_set_selinux>.
821 For more information on the architecture of libguestfs,
822 see L<guestfs(3)>.");
824 ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
825 [InitNone, Always, TestOutputFalse (
826 [["set_trace"; "false"];
828 "enable or disable command traces",
830 If the command trace flag is set to 1, then commands are
831 printed on stdout before they are executed in a format
832 which is very similar to the one used by guestfish. In
833 other words, you can run a program with this enabled, and
834 you will get out a script which you can feed to guestfish
835 to perform the same set of actions.
837 If you want to trace C API calls into libguestfs (and
838 other libraries) then possibly a better way is to use
839 the external ltrace(1) command.
841 Command traces are disabled unless the environment variable
842 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
844 ("get_trace", (RBool "trace", []), -1, [],
846 "get command trace enabled flag",
848 Return the command trace flag.");
850 ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
851 [InitNone, Always, TestOutputFalse (
852 [["set_direct"; "false"];
854 "enable or disable direct appliance mode",
856 If the direct appliance mode flag is enabled, then stdin and
857 stdout are passed directly through to the appliance once it
860 One consequence of this is that log messages aren't caught
861 by the library and handled by C<guestfs_set_log_message_callback>,
862 but go straight to stdout.
864 You probably don't want to use this unless you know what you
867 The default is disabled.");
869 ("get_direct", (RBool "direct", []), -1, [],
871 "get direct appliance mode flag",
873 Return the direct appliance mode flag.");
875 ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
876 [InitNone, Always, TestOutputTrue (
877 [["set_recovery_proc"; "true"];
878 ["get_recovery_proc"]])],
879 "enable or disable the recovery process",
881 If this is called with the parameter C<false> then
882 C<guestfs_launch> does not create a recovery process. The
883 purpose of the recovery process is to stop runaway qemu
884 processes in the case where the main program aborts abruptly.
886 This only has any effect if called before C<guestfs_launch>,
887 and the default is true.
889 About the only time when you would want to disable this is
890 if the main process will fork itself into the background
891 (\"daemonize\" itself). In this case the recovery process
892 thinks that the main program has disappeared and so kills
893 qemu, which is not very helpful.");
895 ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
897 "get recovery process enabled flag",
899 Return the recovery process enabled flag.");
901 ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
903 "add a drive specifying the QEMU block emulation to use",
905 This is the same as C<guestfs_add_drive> but it allows you
906 to specify the QEMU interface emulation to use at run time.");
908 ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
910 "add a drive read-only specifying the QEMU block emulation to use",
912 This is the same as C<guestfs_add_drive_ro> but it allows you
913 to specify the QEMU interface emulation to use at run time.");
917 (* daemon_functions are any functions which cause some action
918 * to take place in the daemon.
921 let daemon_functions = [
922 ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
923 [InitEmpty, Always, TestOutput (
924 [["part_disk"; "/dev/sda"; "mbr"];
925 ["mkfs"; "ext2"; "/dev/sda1"];
926 ["mount"; "/dev/sda1"; "/"];
927 ["write_file"; "/new"; "new file contents"; "0"];
928 ["cat"; "/new"]], "new file contents")],
929 "mount a guest disk at a position in the filesystem",
931 Mount a guest disk at a position in the filesystem. Block devices
932 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
933 the guest. If those block devices contain partitions, they will have
934 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
937 The rules are the same as for L<mount(2)>: A filesystem must
938 first be mounted on C</> before others can be mounted. Other
939 filesystems can only be mounted on directories which already
942 The mounted filesystem is writable, if we have sufficient permissions
943 on the underlying device.
945 The filesystem options C<sync> and C<noatime> are set with this
946 call, in order to improve reliability.");
948 ("sync", (RErr, []), 2, [],
949 [ InitEmpty, Always, TestRun [["sync"]]],
950 "sync disks, writes are flushed through to the disk image",
952 This syncs the disk, so that any writes are flushed through to the
953 underlying disk image.
955 You should always call this if you have modified a disk image, before
956 closing the handle.");
958 ("touch", (RErr, [Pathname "path"]), 3, [],
959 [InitBasicFS, Always, TestOutputTrue (
961 ["exists"; "/new"]])],
962 "update file timestamps or create a new file",
964 Touch acts like the L<touch(1)> command. It can be used to
965 update the timestamps on a file, or, if the file does not exist,
966 to create a new zero-length file.");
968 ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
969 [InitISOFS, Always, TestOutput (
970 [["cat"; "/known-2"]], "abcdef\n")],
971 "list the contents of a file",
973 Return the contents of the file named C<path>.
975 Note that this function cannot correctly handle binary files
976 (specifically, files containing C<\\0> character which is treated
977 as end of string). For those you need to use the C<guestfs_read_file>
978 or C<guestfs_download> functions which have a more complex interface.");
980 ("ll", (RString "listing", [Pathname "directory"]), 5, [],
981 [], (* XXX Tricky to test because it depends on the exact format
982 * of the 'ls -l' command, which changes between F10 and F11.
984 "list the files in a directory (long format)",
986 List the files in C<directory> (relative to the root directory,
987 there is no cwd) in the format of 'ls -la'.
989 This command is mostly useful for interactive sessions. It
990 is I<not> intended that you try to parse the output string.");
992 ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
993 [InitBasicFS, Always, TestOutputList (
996 ["touch"; "/newest"];
997 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
998 "list the files in a directory",
1000 List the files in C<directory> (relative to the root directory,
1001 there is no cwd). The '.' and '..' entries are not returned, but
1002 hidden files are shown.
1004 This command is mostly useful for interactive sessions. Programs
1005 should probably use C<guestfs_readdir> instead.");
1007 ("list_devices", (RStringList "devices", []), 7, [],
1008 [InitEmpty, Always, TestOutputListOfDevices (
1009 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1010 "list the block devices",
1012 List all the block devices.
1014 The full block device names are returned, eg. C</dev/sda>");
1016 ("list_partitions", (RStringList "partitions", []), 8, [],
1017 [InitBasicFS, Always, TestOutputListOfDevices (
1018 [["list_partitions"]], ["/dev/sda1"]);
1019 InitEmpty, Always, TestOutputListOfDevices (
1020 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1021 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1022 "list the partitions",
1024 List all the partitions detected on all block devices.
1026 The full partition device names are returned, eg. C</dev/sda1>
1028 This does not return logical volumes. For that you will need to
1029 call C<guestfs_lvs>.");
1031 ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1032 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1033 [["pvs"]], ["/dev/sda1"]);
1034 InitEmpty, Always, TestOutputListOfDevices (
1035 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1036 ["pvcreate"; "/dev/sda1"];
1037 ["pvcreate"; "/dev/sda2"];
1038 ["pvcreate"; "/dev/sda3"];
1039 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1040 "list the LVM physical volumes (PVs)",
1042 List all the physical volumes detected. This is the equivalent
1043 of the L<pvs(8)> command.
1045 This returns a list of just the device names that contain
1046 PVs (eg. C</dev/sda2>).
1048 See also C<guestfs_pvs_full>.");
1050 ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1051 [InitBasicFSonLVM, Always, TestOutputList (
1053 InitEmpty, Always, TestOutputList (
1054 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1055 ["pvcreate"; "/dev/sda1"];
1056 ["pvcreate"; "/dev/sda2"];
1057 ["pvcreate"; "/dev/sda3"];
1058 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1059 ["vgcreate"; "VG2"; "/dev/sda3"];
1060 ["vgs"]], ["VG1"; "VG2"])],
1061 "list the LVM volume groups (VGs)",
1063 List all the volumes groups detected. This is the equivalent
1064 of the L<vgs(8)> command.
1066 This returns a list of just the volume group names that were
1067 detected (eg. C<VolGroup00>).
1069 See also C<guestfs_vgs_full>.");
1071 ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1072 [InitBasicFSonLVM, Always, TestOutputList (
1073 [["lvs"]], ["/dev/VG/LV"]);
1074 InitEmpty, Always, TestOutputList (
1075 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1076 ["pvcreate"; "/dev/sda1"];
1077 ["pvcreate"; "/dev/sda2"];
1078 ["pvcreate"; "/dev/sda3"];
1079 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1080 ["vgcreate"; "VG2"; "/dev/sda3"];
1081 ["lvcreate"; "LV1"; "VG1"; "50"];
1082 ["lvcreate"; "LV2"; "VG1"; "50"];
1083 ["lvcreate"; "LV3"; "VG2"; "50"];
1084 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1085 "list the LVM logical volumes (LVs)",
1087 List all the logical volumes detected. This is the equivalent
1088 of the L<lvs(8)> command.
1090 This returns a list of the logical volume device names
1091 (eg. C</dev/VolGroup00/LogVol00>).
1093 See also C<guestfs_lvs_full>.");
1095 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1096 [], (* XXX how to test? *)
1097 "list the LVM physical volumes (PVs)",
1099 List all the physical volumes detected. This is the equivalent
1100 of the L<pvs(8)> command. The \"full\" version includes all fields.");
1102 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1103 [], (* XXX how to test? *)
1104 "list the LVM volume groups (VGs)",
1106 List all the volumes groups detected. This is the equivalent
1107 of the L<vgs(8)> command. The \"full\" version includes all fields.");
1109 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1110 [], (* XXX how to test? *)
1111 "list the LVM logical volumes (LVs)",
1113 List all the logical volumes detected. This is the equivalent
1114 of the L<lvs(8)> command. The \"full\" version includes all fields.");
1116 ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1117 [InitISOFS, Always, TestOutputList (
1118 [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1119 InitISOFS, Always, TestOutputList (
1120 [["read_lines"; "/empty"]], [])],
1121 "read file as lines",
1123 Return the contents of the file named C<path>.
1125 The file contents are returned as a list of lines. Trailing
1126 C<LF> and C<CRLF> character sequences are I<not> returned.
1128 Note that this function cannot correctly handle binary files
1129 (specifically, files containing C<\\0> character which is treated
1130 as end of line). For those you need to use the C<guestfs_read_file>
1131 function which has a more complex interface.");
1133 ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1134 [], (* XXX Augeas code needs tests. *)
1135 "create a new Augeas handle",
1137 Create a new Augeas handle for editing configuration files.
1138 If there was any previous Augeas handle associated with this
1139 guestfs session, then it is closed.
1141 You must call this before using any other C<guestfs_aug_*>
1144 C<root> is the filesystem root. C<root> must not be NULL,
1147 The flags are the same as the flags defined in
1148 E<lt>augeas.hE<gt>, the logical I<or> of the following
1153 =item C<AUG_SAVE_BACKUP> = 1
1155 Keep the original file with a C<.augsave> extension.
1157 =item C<AUG_SAVE_NEWFILE> = 2
1159 Save changes into a file with extension C<.augnew>, and
1160 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
1162 =item C<AUG_TYPE_CHECK> = 4
1164 Typecheck lenses (can be expensive).
1166 =item C<AUG_NO_STDINC> = 8
1168 Do not use standard load path for modules.
1170 =item C<AUG_SAVE_NOOP> = 16
1172 Make save a no-op, just record what would have been changed.
1174 =item C<AUG_NO_LOAD> = 32
1176 Do not load the tree in C<guestfs_aug_init>.
1180 To close the handle, you can call C<guestfs_aug_close>.
1182 To find out more about Augeas, see L<http://augeas.net/>.");
1184 ("aug_close", (RErr, []), 26, [Optional "augeas"],
1185 [], (* XXX Augeas code needs tests. *)
1186 "close the current Augeas handle",
1188 Close the current Augeas handle and free up any resources
1189 used by it. After calling this, you have to call
1190 C<guestfs_aug_init> again before you can use any other
1191 Augeas functions.");
1193 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1194 [], (* XXX Augeas code needs tests. *)
1195 "define an Augeas variable",
1197 Defines an Augeas variable C<name> whose value is the result
1198 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
1201 On success this returns the number of nodes in C<expr>, or
1202 C<0> if C<expr> evaluates to something which is not a nodeset.");
1204 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1205 [], (* XXX Augeas code needs tests. *)
1206 "define an Augeas node",
1208 Defines a variable C<name> whose value is the result of
1211 If C<expr> evaluates to an empty nodeset, a node is created,
1212 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1213 C<name> will be the nodeset containing that single node.
1215 On success this returns a pair containing the
1216 number of nodes in the nodeset, and a boolean flag
1217 if a node was created.");
1219 ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1220 [], (* XXX Augeas code needs tests. *)
1221 "look up the value of an Augeas path",
1223 Look up the value associated with C<path>. If C<path>
1224 matches exactly one node, the C<value> is returned.");
1226 ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1227 [], (* XXX Augeas code needs tests. *)
1228 "set Augeas path to value",
1230 Set the value associated with C<path> to C<value>.");
1232 ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1233 [], (* XXX Augeas code needs tests. *)
1234 "insert a sibling Augeas node",
1236 Create a new sibling C<label> for C<path>, inserting it into
1237 the tree before or after C<path> (depending on the boolean
1240 C<path> must match exactly one existing node in the tree, and
1241 C<label> must be a label, ie. not contain C</>, C<*> or end
1242 with a bracketed index C<[N]>.");
1244 ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1245 [], (* XXX Augeas code needs tests. *)
1246 "remove an Augeas path",
1248 Remove C<path> and all of its children.
1250 On success this returns the number of entries which were removed.");
1252 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1253 [], (* XXX Augeas code needs tests. *)
1256 Move the node C<src> to C<dest>. C<src> must match exactly
1257 one node. C<dest> is overwritten if it exists.");
1259 ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1260 [], (* XXX Augeas code needs tests. *)
1261 "return Augeas nodes which match augpath",
1263 Returns a list of paths which match the path expression C<path>.
1264 The returned paths are sufficiently qualified so that they match
1265 exactly one node in the current tree.");
1267 ("aug_save", (RErr, []), 25, [Optional "augeas"],
1268 [], (* XXX Augeas code needs tests. *)
1269 "write all pending Augeas changes to disk",
1271 This writes all pending changes to disk.
1273 The flags which were passed to C<guestfs_aug_init> affect exactly
1274 how files are saved.");
1276 ("aug_load", (RErr, []), 27, [Optional "augeas"],
1277 [], (* XXX Augeas code needs tests. *)
1278 "load files into the tree",
1280 Load files into the tree.
1282 See C<aug_load> in the Augeas documentation for the full gory
1285 ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1286 [], (* XXX Augeas code needs tests. *)
1287 "list Augeas nodes under augpath",
1289 This is just a shortcut for listing C<guestfs_aug_match>
1290 C<path/*> and sorting the resulting nodes into alphabetical order.");
1292 ("rm", (RErr, [Pathname "path"]), 29, [],
1293 [InitBasicFS, Always, TestRun
1296 InitBasicFS, Always, TestLastFail
1298 InitBasicFS, Always, TestLastFail
1303 Remove the single file C<path>.");
1305 ("rmdir", (RErr, [Pathname "path"]), 30, [],
1306 [InitBasicFS, Always, TestRun
1309 InitBasicFS, Always, TestLastFail
1310 [["rmdir"; "/new"]];
1311 InitBasicFS, Always, TestLastFail
1313 ["rmdir"; "/new"]]],
1314 "remove a directory",
1316 Remove the single directory C<path>.");
1318 ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1319 [InitBasicFS, Always, TestOutputFalse
1321 ["mkdir"; "/new/foo"];
1322 ["touch"; "/new/foo/bar"];
1324 ["exists"; "/new"]]],
1325 "remove a file or directory recursively",
1327 Remove the file or directory C<path>, recursively removing the
1328 contents if its a directory. This is like the C<rm -rf> shell
1331 ("mkdir", (RErr, [Pathname "path"]), 32, [],
1332 [InitBasicFS, Always, TestOutputTrue
1334 ["is_dir"; "/new"]];
1335 InitBasicFS, Always, TestLastFail
1336 [["mkdir"; "/new/foo/bar"]]],
1337 "create a directory",
1339 Create a directory named C<path>.");
1341 ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1342 [InitBasicFS, Always, TestOutputTrue
1343 [["mkdir_p"; "/new/foo/bar"];
1344 ["is_dir"; "/new/foo/bar"]];
1345 InitBasicFS, Always, TestOutputTrue
1346 [["mkdir_p"; "/new/foo/bar"];
1347 ["is_dir"; "/new/foo"]];
1348 InitBasicFS, Always, TestOutputTrue
1349 [["mkdir_p"; "/new/foo/bar"];
1350 ["is_dir"; "/new"]];
1351 (* Regression tests for RHBZ#503133: *)
1352 InitBasicFS, Always, TestRun
1354 ["mkdir_p"; "/new"]];
1355 InitBasicFS, Always, TestLastFail
1357 ["mkdir_p"; "/new"]]],
1358 "create a directory and parents",
1360 Create a directory named C<path>, creating any parent directories
1361 as necessary. This is like the C<mkdir -p> shell command.");
1363 ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1364 [], (* XXX Need stat command to test *)
1367 Change the mode (permissions) of C<path> to C<mode>. Only
1368 numeric modes are supported.
1370 I<Note>: When using this command from guestfish, C<mode>
1371 by default would be decimal, unless you prefix it with
1372 C<0> to get octal, ie. use C<0700> not C<700>.");
1374 ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1375 [], (* XXX Need stat command to test *)
1376 "change file owner and group",
1378 Change the file owner to C<owner> and group to C<group>.
1380 Only numeric uid and gid are supported. If you want to use
1381 names, you will need to locate and parse the password file
1382 yourself (Augeas support makes this relatively easy).");
1384 ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1385 [InitISOFS, Always, TestOutputTrue (
1386 [["exists"; "/empty"]]);
1387 InitISOFS, Always, TestOutputTrue (
1388 [["exists"; "/directory"]])],
1389 "test if file or directory exists",
1391 This returns C<true> if and only if there is a file, directory
1392 (or anything) with the given C<path> name.
1394 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1396 ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1397 [InitISOFS, Always, TestOutputTrue (
1398 [["is_file"; "/known-1"]]);
1399 InitISOFS, Always, TestOutputFalse (
1400 [["is_file"; "/directory"]])],
1401 "test if file exists",
1403 This returns C<true> if and only if there is a file
1404 with the given C<path> name. Note that it returns false for
1405 other objects like directories.
1407 See also C<guestfs_stat>.");
1409 ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1410 [InitISOFS, Always, TestOutputFalse (
1411 [["is_dir"; "/known-3"]]);
1412 InitISOFS, Always, TestOutputTrue (
1413 [["is_dir"; "/directory"]])],
1414 "test if file exists",
1416 This returns C<true> if and only if there is a directory
1417 with the given C<path> name. Note that it returns false for
1418 other objects like files.
1420 See also C<guestfs_stat>.");
1422 ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1423 [InitEmpty, Always, TestOutputListOfDevices (
1424 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1425 ["pvcreate"; "/dev/sda1"];
1426 ["pvcreate"; "/dev/sda2"];
1427 ["pvcreate"; "/dev/sda3"];
1428 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1429 "create an LVM physical volume",
1431 This creates an LVM physical volume on the named C<device>,
1432 where C<device> should usually be a partition name such
1435 ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1436 [InitEmpty, Always, TestOutputList (
1437 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1438 ["pvcreate"; "/dev/sda1"];
1439 ["pvcreate"; "/dev/sda2"];
1440 ["pvcreate"; "/dev/sda3"];
1441 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1442 ["vgcreate"; "VG2"; "/dev/sda3"];
1443 ["vgs"]], ["VG1"; "VG2"])],
1444 "create an LVM volume group",
1446 This creates an LVM volume group called C<volgroup>
1447 from the non-empty list of physical volumes C<physvols>.");
1449 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1450 [InitEmpty, Always, TestOutputList (
1451 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1452 ["pvcreate"; "/dev/sda1"];
1453 ["pvcreate"; "/dev/sda2"];
1454 ["pvcreate"; "/dev/sda3"];
1455 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1456 ["vgcreate"; "VG2"; "/dev/sda3"];
1457 ["lvcreate"; "LV1"; "VG1"; "50"];
1458 ["lvcreate"; "LV2"; "VG1"; "50"];
1459 ["lvcreate"; "LV3"; "VG2"; "50"];
1460 ["lvcreate"; "LV4"; "VG2"; "50"];
1461 ["lvcreate"; "LV5"; "VG2"; "50"];
1463 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1464 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1465 "create an LVM volume group",
1467 This creates an LVM volume group called C<logvol>
1468 on the volume group C<volgroup>, with C<size> megabytes.");
1470 ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1471 [InitEmpty, Always, TestOutput (
1472 [["part_disk"; "/dev/sda"; "mbr"];
1473 ["mkfs"; "ext2"; "/dev/sda1"];
1474 ["mount_options"; ""; "/dev/sda1"; "/"];
1475 ["write_file"; "/new"; "new file contents"; "0"];
1476 ["cat"; "/new"]], "new file contents")],
1477 "make a filesystem",
1479 This creates a filesystem on C<device> (usually a partition
1480 or LVM logical volume). The filesystem type is C<fstype>, for
1483 ("sfdisk", (RErr, [Device "device";
1484 Int "cyls"; Int "heads"; Int "sectors";
1485 StringList "lines"]), 43, [DangerWillRobinson],
1487 "create partitions on a block device",
1489 This is a direct interface to the L<sfdisk(8)> program for creating
1490 partitions on block devices.
1492 C<device> should be a block device, for example C</dev/sda>.
1494 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1495 and sectors on the device, which are passed directly to sfdisk as
1496 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1497 of these, then the corresponding parameter is omitted. Usually for
1498 'large' disks, you can just pass C<0> for these, but for small
1499 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1500 out the right geometry and you will need to tell it.
1502 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1503 information refer to the L<sfdisk(8)> manpage.
1505 To create a single partition occupying the whole disk, you would
1506 pass C<lines> as a single element list, when the single element being
1507 the string C<,> (comma).
1509 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1510 C<guestfs_part_init>");
1512 ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1513 [InitBasicFS, Always, TestOutput (
1514 [["write_file"; "/new"; "new file contents"; "0"];
1515 ["cat"; "/new"]], "new file contents");
1516 InitBasicFS, Always, TestOutput (
1517 [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1518 ["cat"; "/new"]], "\nnew file contents\n");
1519 InitBasicFS, Always, TestOutput (
1520 [["write_file"; "/new"; "\n\n"; "0"];
1521 ["cat"; "/new"]], "\n\n");
1522 InitBasicFS, Always, TestOutput (
1523 [["write_file"; "/new"; ""; "0"];
1524 ["cat"; "/new"]], "");
1525 InitBasicFS, Always, TestOutput (
1526 [["write_file"; "/new"; "\n\n\n"; "0"];
1527 ["cat"; "/new"]], "\n\n\n");
1528 InitBasicFS, Always, TestOutput (
1529 [["write_file"; "/new"; "\n"; "0"];
1530 ["cat"; "/new"]], "\n")],
1533 This call creates a file called C<path>. The contents of the
1534 file is the string C<content> (which can contain any 8 bit data),
1535 with length C<size>.
1537 As a special case, if C<size> is C<0>
1538 then the length is calculated using C<strlen> (so in this case
1539 the content cannot contain embedded ASCII NULs).
1541 I<NB.> Owing to a bug, writing content containing ASCII NUL
1542 characters does I<not> work, even if the length is specified.
1543 We hope to resolve this bug in a future version. In the meantime
1544 use C<guestfs_upload>.");
1546 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1547 [InitEmpty, Always, TestOutputListOfDevices (
1548 [["part_disk"; "/dev/sda"; "mbr"];
1549 ["mkfs"; "ext2"; "/dev/sda1"];
1550 ["mount_options"; ""; "/dev/sda1"; "/"];
1551 ["mounts"]], ["/dev/sda1"]);
1552 InitEmpty, Always, TestOutputList (
1553 [["part_disk"; "/dev/sda"; "mbr"];
1554 ["mkfs"; "ext2"; "/dev/sda1"];
1555 ["mount_options"; ""; "/dev/sda1"; "/"];
1558 "unmount a filesystem",
1560 This unmounts the given filesystem. The filesystem may be
1561 specified either by its mountpoint (path) or the device which
1562 contains the filesystem.");
1564 ("mounts", (RStringList "devices", []), 46, [],
1565 [InitBasicFS, Always, TestOutputListOfDevices (
1566 [["mounts"]], ["/dev/sda1"])],
1567 "show mounted filesystems",
1569 This returns the list of currently mounted filesystems. It returns
1570 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1572 Some internal mounts are not shown.
1574 See also: C<guestfs_mountpoints>");
1576 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1577 [InitBasicFS, Always, TestOutputList (
1580 (* check that umount_all can unmount nested mounts correctly: *)
1581 InitEmpty, Always, TestOutputList (
1582 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1583 ["mkfs"; "ext2"; "/dev/sda1"];
1584 ["mkfs"; "ext2"; "/dev/sda2"];
1585 ["mkfs"; "ext2"; "/dev/sda3"];
1586 ["mount_options"; ""; "/dev/sda1"; "/"];
1588 ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1589 ["mkdir"; "/mp1/mp2"];
1590 ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1591 ["mkdir"; "/mp1/mp2/mp3"];
1594 "unmount all filesystems",
1596 This unmounts all mounted filesystems.
1598 Some internal mounts are not unmounted by this call.");
1600 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1602 "remove all LVM LVs, VGs and PVs",
1604 This command removes all LVM logical volumes, volume groups
1605 and physical volumes.");
1607 ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
1608 [InitISOFS, Always, TestOutput (
1609 [["file"; "/empty"]], "empty");
1610 InitISOFS, Always, TestOutput (
1611 [["file"; "/known-1"]], "ASCII text");
1612 InitISOFS, Always, TestLastFail (
1613 [["file"; "/notexists"]])],
1614 "determine file type",
1616 This call uses the standard L<file(1)> command to determine
1617 the type or contents of the file. This also works on devices,
1618 for example to find out whether a partition contains a filesystem.
1620 This call will also transparently look inside various types
1623 The exact command which runs is C<file -zbsL path>. Note in
1624 particular that the filename is not prepended to the output
1625 (the C<-b> option).");
1627 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1628 [InitBasicFS, Always, TestOutput (
1629 [["upload"; "test-command"; "/test-command"];
1630 ["chmod"; "0o755"; "/test-command"];
1631 ["command"; "/test-command 1"]], "Result1");
1632 InitBasicFS, Always, TestOutput (
1633 [["upload"; "test-command"; "/test-command"];
1634 ["chmod"; "0o755"; "/test-command"];
1635 ["command"; "/test-command 2"]], "Result2\n");
1636 InitBasicFS, Always, TestOutput (
1637 [["upload"; "test-command"; "/test-command"];
1638 ["chmod"; "0o755"; "/test-command"];
1639 ["command"; "/test-command 3"]], "\nResult3");
1640 InitBasicFS, Always, TestOutput (
1641 [["upload"; "test-command"; "/test-command"];
1642 ["chmod"; "0o755"; "/test-command"];
1643 ["command"; "/test-command 4"]], "\nResult4\n");
1644 InitBasicFS, Always, TestOutput (
1645 [["upload"; "test-command"; "/test-command"];
1646 ["chmod"; "0o755"; "/test-command"];
1647 ["command"; "/test-command 5"]], "\nResult5\n\n");
1648 InitBasicFS, Always, TestOutput (
1649 [["upload"; "test-command"; "/test-command"];
1650 ["chmod"; "0o755"; "/test-command"];
1651 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1652 InitBasicFS, Always, TestOutput (
1653 [["upload"; "test-command"; "/test-command"];
1654 ["chmod"; "0o755"; "/test-command"];
1655 ["command"; "/test-command 7"]], "");
1656 InitBasicFS, Always, TestOutput (
1657 [["upload"; "test-command"; "/test-command"];
1658 ["chmod"; "0o755"; "/test-command"];
1659 ["command"; "/test-command 8"]], "\n");
1660 InitBasicFS, Always, TestOutput (
1661 [["upload"; "test-command"; "/test-command"];
1662 ["chmod"; "0o755"; "/test-command"];
1663 ["command"; "/test-command 9"]], "\n\n");
1664 InitBasicFS, Always, TestOutput (
1665 [["upload"; "test-command"; "/test-command"];
1666 ["chmod"; "0o755"; "/test-command"];
1667 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1668 InitBasicFS, Always, TestOutput (
1669 [["upload"; "test-command"; "/test-command"];
1670 ["chmod"; "0o755"; "/test-command"];
1671 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1672 InitBasicFS, Always, TestLastFail (
1673 [["upload"; "test-command"; "/test-command"];
1674 ["chmod"; "0o755"; "/test-command"];
1675 ["command"; "/test-command"]])],
1676 "run a command from the guest filesystem",
1678 This call runs a command from the guest filesystem. The
1679 filesystem must be mounted, and must contain a compatible
1680 operating system (ie. something Linux, with the same
1681 or compatible processor architecture).
1683 The single parameter is an argv-style list of arguments.
1684 The first element is the name of the program to run.
1685 Subsequent elements are parameters. The list must be
1686 non-empty (ie. must contain a program name). Note that
1687 the command runs directly, and is I<not> invoked via
1688 the shell (see C<guestfs_sh>).
1690 The return value is anything printed to I<stdout> by
1693 If the command returns a non-zero exit status, then
1694 this function returns an error message. The error message
1695 string is the content of I<stderr> from the command.
1697 The C<$PATH> environment variable will contain at least
1698 C</usr/bin> and C</bin>. If you require a program from
1699 another location, you should provide the full path in the
1702 Shared libraries and data files required by the program
1703 must be available on filesystems which are mounted in the
1704 correct places. It is the caller's responsibility to ensure
1705 all filesystems that are needed are mounted at the right
1708 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1709 [InitBasicFS, Always, TestOutputList (
1710 [["upload"; "test-command"; "/test-command"];
1711 ["chmod"; "0o755"; "/test-command"];
1712 ["command_lines"; "/test-command 1"]], ["Result1"]);
1713 InitBasicFS, Always, TestOutputList (
1714 [["upload"; "test-command"; "/test-command"];
1715 ["chmod"; "0o755"; "/test-command"];
1716 ["command_lines"; "/test-command 2"]], ["Result2"]);
1717 InitBasicFS, Always, TestOutputList (
1718 [["upload"; "test-command"; "/test-command"];
1719 ["chmod"; "0o755"; "/test-command"];
1720 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1721 InitBasicFS, Always, TestOutputList (
1722 [["upload"; "test-command"; "/test-command"];
1723 ["chmod"; "0o755"; "/test-command"];
1724 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1725 InitBasicFS, Always, TestOutputList (
1726 [["upload"; "test-command"; "/test-command"];
1727 ["chmod"; "0o755"; "/test-command"];
1728 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1729 InitBasicFS, Always, TestOutputList (
1730 [["upload"; "test-command"; "/test-command"];
1731 ["chmod"; "0o755"; "/test-command"];
1732 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1733 InitBasicFS, Always, TestOutputList (
1734 [["upload"; "test-command"; "/test-command"];
1735 ["chmod"; "0o755"; "/test-command"];
1736 ["command_lines"; "/test-command 7"]], []);
1737 InitBasicFS, Always, TestOutputList (
1738 [["upload"; "test-command"; "/test-command"];
1739 ["chmod"; "0o755"; "/test-command"];
1740 ["command_lines"; "/test-command 8"]], [""]);
1741 InitBasicFS, Always, TestOutputList (
1742 [["upload"; "test-command"; "/test-command"];
1743 ["chmod"; "0o755"; "/test-command"];
1744 ["command_lines"; "/test-command 9"]], ["";""]);
1745 InitBasicFS, Always, TestOutputList (
1746 [["upload"; "test-command"; "/test-command"];
1747 ["chmod"; "0o755"; "/test-command"];
1748 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1749 InitBasicFS, Always, TestOutputList (
1750 [["upload"; "test-command"; "/test-command"];
1751 ["chmod"; "0o755"; "/test-command"];
1752 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1753 "run a command, returning lines",
1755 This is the same as C<guestfs_command>, but splits the
1756 result into a list of lines.
1758 See also: C<guestfs_sh_lines>");
1760 ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
1761 [InitISOFS, Always, TestOutputStruct (
1762 [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
1763 "get file information",
1765 Returns file information for the given C<path>.
1767 This is the same as the C<stat(2)> system call.");
1769 ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
1770 [InitISOFS, Always, TestOutputStruct (
1771 [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
1772 "get file information for a symbolic link",
1774 Returns file information for the given C<path>.
1776 This is the same as C<guestfs_stat> except that if C<path>
1777 is a symbolic link, then the link is stat-ed, not the file it
1780 This is the same as the C<lstat(2)> system call.");
1782 ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
1783 [InitISOFS, Always, TestOutputStruct (
1784 [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
1785 "get file system statistics",
1787 Returns file system statistics for any mounted file system.
1788 C<path> should be a file or directory in the mounted file system
1789 (typically it is the mount point itself, but it doesn't need to be).
1791 This is the same as the C<statvfs(2)> system call.");
1793 ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
1795 "get ext2/ext3/ext4 superblock details",
1797 This returns the contents of the ext2, ext3 or ext4 filesystem
1798 superblock on C<device>.
1800 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
1801 manpage for more details. The list of fields returned isn't
1802 clearly defined, and depends on both the version of C<tune2fs>
1803 that libguestfs was built against, and the filesystem itself.");
1805 ("blockdev_setro", (RErr, [Device "device"]), 56, [],
1806 [InitEmpty, Always, TestOutputTrue (
1807 [["blockdev_setro"; "/dev/sda"];
1808 ["blockdev_getro"; "/dev/sda"]])],
1809 "set block device to read-only",
1811 Sets the block device named C<device> to read-only.
1813 This uses the L<blockdev(8)> command.");
1815 ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
1816 [InitEmpty, Always, TestOutputFalse (
1817 [["blockdev_setrw"; "/dev/sda"];
1818 ["blockdev_getro"; "/dev/sda"]])],
1819 "set block device to read-write",
1821 Sets the block device named C<device> to read-write.
1823 This uses the L<blockdev(8)> command.");
1825 ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
1826 [InitEmpty, Always, TestOutputTrue (
1827 [["blockdev_setro"; "/dev/sda"];
1828 ["blockdev_getro"; "/dev/sda"]])],
1829 "is block device set to read-only",
1831 Returns a boolean indicating if the block device is read-only
1832 (true if read-only, false if not).
1834 This uses the L<blockdev(8)> command.");
1836 ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
1837 [InitEmpty, Always, TestOutputInt (
1838 [["blockdev_getss"; "/dev/sda"]], 512)],
1839 "get sectorsize of block device",
1841 This returns the size of sectors on a block device.
1842 Usually 512, but can be larger for modern devices.
1844 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1847 This uses the L<blockdev(8)> command.");
1849 ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
1850 [InitEmpty, Always, TestOutputInt (
1851 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1852 "get blocksize of block device",
1854 This returns the block size of a device.
1856 (Note this is different from both I<size in blocks> and
1857 I<filesystem block size>).
1859 This uses the L<blockdev(8)> command.");
1861 ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
1863 "set blocksize of block device",
1865 This sets the block size of a device.
1867 (Note this is different from both I<size in blocks> and
1868 I<filesystem block size>).
1870 This uses the L<blockdev(8)> command.");
1872 ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
1873 [InitEmpty, Always, TestOutputInt (
1874 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1875 "get total size of device in 512-byte sectors",
1877 This returns the size of the device in units of 512-byte sectors
1878 (even if the sectorsize isn't 512 bytes ... weird).
1880 See also C<guestfs_blockdev_getss> for the real sector size of
1881 the device, and C<guestfs_blockdev_getsize64> for the more
1882 useful I<size in bytes>.
1884 This uses the L<blockdev(8)> command.");
1886 ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
1887 [InitEmpty, Always, TestOutputInt (
1888 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1889 "get total size of device in bytes",
1891 This returns the size of the device in bytes.
1893 See also C<guestfs_blockdev_getsz>.
1895 This uses the L<blockdev(8)> command.");
1897 ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
1898 [InitEmpty, Always, TestRun
1899 [["blockdev_flushbufs"; "/dev/sda"]]],
1900 "flush device buffers",
1902 This tells the kernel to flush internal buffers associated
1905 This uses the L<blockdev(8)> command.");
1907 ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
1908 [InitEmpty, Always, TestRun
1909 [["blockdev_rereadpt"; "/dev/sda"]]],
1910 "reread partition table",
1912 Reread the partition table on C<device>.
1914 This uses the L<blockdev(8)> command.");
1916 ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
1917 [InitBasicFS, Always, TestOutput (
1918 (* Pick a file from cwd which isn't likely to change. *)
1919 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1920 ["checksum"; "md5"; "/COPYING.LIB"]],
1921 Digest.to_hex (Digest.file "COPYING.LIB"))],
1922 "upload a file from the local machine",
1924 Upload local file C<filename> to C<remotefilename> on the
1927 C<filename> can also be a named pipe.
1929 See also C<guestfs_download>.");
1931 ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [],
1932 [InitBasicFS, Always, TestOutput (
1933 (* Pick a file from cwd which isn't likely to change. *)
1934 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1935 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1936 ["upload"; "testdownload.tmp"; "/upload"];
1937 ["checksum"; "md5"; "/upload"]],
1938 Digest.to_hex (Digest.file "COPYING.LIB"))],
1939 "download a file to the local machine",
1941 Download file C<remotefilename> and save it as C<filename>
1942 on the local machine.
1944 C<filename> can also be a named pipe.
1946 See also C<guestfs_upload>, C<guestfs_cat>.");
1948 ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
1949 [InitISOFS, Always, TestOutput (
1950 [["checksum"; "crc"; "/known-3"]], "2891671662");
1951 InitISOFS, Always, TestLastFail (
1952 [["checksum"; "crc"; "/notexists"]]);
1953 InitISOFS, Always, TestOutput (
1954 [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
1955 InitISOFS, Always, TestOutput (
1956 [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
1957 InitISOFS, Always, TestOutput (
1958 [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
1959 InitISOFS, Always, TestOutput (
1960 [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
1961 InitISOFS, Always, TestOutput (
1962 [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
1963 InitISOFS, Always, TestOutput (
1964 [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6")],
1965 "compute MD5, SHAx or CRC checksum of file",
1967 This call computes the MD5, SHAx or CRC checksum of the
1970 The type of checksum to compute is given by the C<csumtype>
1971 parameter which must have one of the following values:
1977 Compute the cyclic redundancy check (CRC) specified by POSIX
1978 for the C<cksum> command.
1982 Compute the MD5 hash (using the C<md5sum> program).
1986 Compute the SHA1 hash (using the C<sha1sum> program).
1990 Compute the SHA224 hash (using the C<sha224sum> program).
1994 Compute the SHA256 hash (using the C<sha256sum> program).
1998 Compute the SHA384 hash (using the C<sha384sum> program).
2002 Compute the SHA512 hash (using the C<sha512sum> program).
2006 The checksum is returned as a printable string.");
2008 ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
2009 [InitBasicFS, Always, TestOutput (
2010 [["tar_in"; "../images/helloworld.tar"; "/"];
2011 ["cat"; "/hello"]], "hello\n")],
2012 "unpack tarfile to directory",
2014 This command uploads and unpacks local file C<tarfile> (an
2015 I<uncompressed> tar file) into C<directory>.
2017 To upload a compressed tarball, use C<guestfs_tgz_in>.");
2019 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2021 "pack directory into tarfile",
2023 This command packs the contents of C<directory> and downloads
2024 it to local file C<tarfile>.
2026 To download a compressed tarball, use C<guestfs_tgz_out>.");
2028 ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
2029 [InitBasicFS, Always, TestOutput (
2030 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2031 ["cat"; "/hello"]], "hello\n")],
2032 "unpack compressed tarball to directory",
2034 This command uploads and unpacks local file C<tarball> (a
2035 I<gzip compressed> tar file) into C<directory>.
2037 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2039 ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2041 "pack directory into compressed tarball",
2043 This command packs the contents of C<directory> and downloads
2044 it to local file C<tarball>.
2046 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2048 ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2049 [InitBasicFS, Always, TestLastFail (
2051 ["mount_ro"; "/dev/sda1"; "/"];
2052 ["touch"; "/new"]]);
2053 InitBasicFS, Always, TestOutput (
2054 [["write_file"; "/new"; "data"; "0"];
2056 ["mount_ro"; "/dev/sda1"; "/"];
2057 ["cat"; "/new"]], "data")],
2058 "mount a guest disk, read-only",
2060 This is the same as the C<guestfs_mount> command, but it
2061 mounts the filesystem with the read-only (I<-o ro>) flag.");
2063 ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2065 "mount a guest disk with mount options",
2067 This is the same as the C<guestfs_mount> command, but it
2068 allows you to set the mount options as for the
2069 L<mount(8)> I<-o> flag.");
2071 ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2073 "mount a guest disk with mount options and vfstype",
2075 This is the same as the C<guestfs_mount> command, but it
2076 allows you to set both the mount options and the vfstype
2077 as for the L<mount(8)> I<-o> and I<-t> flags.");
2079 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2081 "debugging and internals",
2083 The C<guestfs_debug> command exposes some internals of
2084 C<guestfsd> (the guestfs daemon) that runs inside the
2087 There is no comprehensive help for this command. You have
2088 to look at the file C<daemon/debug.c> in the libguestfs source
2089 to find out what you can do.");
2091 ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2092 [InitEmpty, Always, TestOutputList (
2093 [["part_disk"; "/dev/sda"; "mbr"];
2094 ["pvcreate"; "/dev/sda1"];
2095 ["vgcreate"; "VG"; "/dev/sda1"];
2096 ["lvcreate"; "LV1"; "VG"; "50"];
2097 ["lvcreate"; "LV2"; "VG"; "50"];
2098 ["lvremove"; "/dev/VG/LV1"];
2099 ["lvs"]], ["/dev/VG/LV2"]);
2100 InitEmpty, Always, TestOutputList (
2101 [["part_disk"; "/dev/sda"; "mbr"];
2102 ["pvcreate"; "/dev/sda1"];
2103 ["vgcreate"; "VG"; "/dev/sda1"];
2104 ["lvcreate"; "LV1"; "VG"; "50"];
2105 ["lvcreate"; "LV2"; "VG"; "50"];
2106 ["lvremove"; "/dev/VG"];
2108 InitEmpty, Always, TestOutputList (
2109 [["part_disk"; "/dev/sda"; "mbr"];
2110 ["pvcreate"; "/dev/sda1"];
2111 ["vgcreate"; "VG"; "/dev/sda1"];
2112 ["lvcreate"; "LV1"; "VG"; "50"];
2113 ["lvcreate"; "LV2"; "VG"; "50"];
2114 ["lvremove"; "/dev/VG"];
2116 "remove an LVM logical volume",
2118 Remove an LVM logical volume C<device>, where C<device> is
2119 the path to the LV, such as C</dev/VG/LV>.
2121 You can also remove all LVs in a volume group by specifying
2122 the VG name, C</dev/VG>.");
2124 ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2125 [InitEmpty, Always, TestOutputList (
2126 [["part_disk"; "/dev/sda"; "mbr"];
2127 ["pvcreate"; "/dev/sda1"];
2128 ["vgcreate"; "VG"; "/dev/sda1"];
2129 ["lvcreate"; "LV1"; "VG"; "50"];
2130 ["lvcreate"; "LV2"; "VG"; "50"];
2133 InitEmpty, Always, TestOutputList (
2134 [["part_disk"; "/dev/sda"; "mbr"];
2135 ["pvcreate"; "/dev/sda1"];
2136 ["vgcreate"; "VG"; "/dev/sda1"];
2137 ["lvcreate"; "LV1"; "VG"; "50"];
2138 ["lvcreate"; "LV2"; "VG"; "50"];
2141 "remove an LVM volume group",
2143 Remove an LVM volume group C<vgname>, (for example C<VG>).
2145 This also forcibly removes all logical volumes in the volume
2148 ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2149 [InitEmpty, Always, TestOutputListOfDevices (
2150 [["part_disk"; "/dev/sda"; "mbr"];
2151 ["pvcreate"; "/dev/sda1"];
2152 ["vgcreate"; "VG"; "/dev/sda1"];
2153 ["lvcreate"; "LV1"; "VG"; "50"];
2154 ["lvcreate"; "LV2"; "VG"; "50"];
2156 ["pvremove"; "/dev/sda1"];
2158 InitEmpty, Always, TestOutputListOfDevices (
2159 [["part_disk"; "/dev/sda"; "mbr"];
2160 ["pvcreate"; "/dev/sda1"];
2161 ["vgcreate"; "VG"; "/dev/sda1"];
2162 ["lvcreate"; "LV1"; "VG"; "50"];
2163 ["lvcreate"; "LV2"; "VG"; "50"];
2165 ["pvremove"; "/dev/sda1"];
2167 InitEmpty, Always, TestOutputListOfDevices (
2168 [["part_disk"; "/dev/sda"; "mbr"];
2169 ["pvcreate"; "/dev/sda1"];
2170 ["vgcreate"; "VG"; "/dev/sda1"];
2171 ["lvcreate"; "LV1"; "VG"; "50"];
2172 ["lvcreate"; "LV2"; "VG"; "50"];
2174 ["pvremove"; "/dev/sda1"];
2176 "remove an LVM physical volume",
2178 This wipes a physical volume C<device> so that LVM will no longer
2181 The implementation uses the C<pvremove> command which refuses to
2182 wipe physical volumes that contain any volume groups, so you have
2183 to remove those first.");
2185 ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2186 [InitBasicFS, Always, TestOutput (
2187 [["set_e2label"; "/dev/sda1"; "testlabel"];
2188 ["get_e2label"; "/dev/sda1"]], "testlabel")],
2189 "set the ext2/3/4 filesystem label",
2191 This sets the ext2/3/4 filesystem label of the filesystem on
2192 C<device> to C<label>. Filesystem labels are limited to
2195 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2196 to return the existing label on a filesystem.");
2198 ("get_e2label", (RString "label", [Device "device"]), 81, [],
2200 "get the ext2/3/4 filesystem label",
2202 This returns the ext2/3/4 filesystem label of the filesystem on
2205 ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2206 (let uuid = uuidgen () in
2207 [InitBasicFS, Always, TestOutput (
2208 [["set_e2uuid"; "/dev/sda1"; uuid];
2209 ["get_e2uuid"; "/dev/sda1"]], uuid);
2210 InitBasicFS, Always, TestOutput (
2211 [["set_e2uuid"; "/dev/sda1"; "clear"];
2212 ["get_e2uuid"; "/dev/sda1"]], "");
2213 (* We can't predict what UUIDs will be, so just check the commands run. *)
2214 InitBasicFS, Always, TestRun (
2215 [["set_e2uuid"; "/dev/sda1"; "random"]]);
2216 InitBasicFS, Always, TestRun (
2217 [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2218 "set the ext2/3/4 filesystem UUID",
2220 This sets the ext2/3/4 filesystem UUID of the filesystem on
2221 C<device> to C<uuid>. The format of the UUID and alternatives
2222 such as C<clear>, C<random> and C<time> are described in the
2223 L<tune2fs(8)> manpage.
2225 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2226 to return the existing UUID of a filesystem.");
2228 ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [],
2230 "get the ext2/3/4 filesystem UUID",
2232 This returns the ext2/3/4 filesystem UUID of the filesystem on
2235 ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [],
2236 [InitBasicFS, Always, TestOutputInt (
2237 [["umount"; "/dev/sda1"];
2238 ["fsck"; "ext2"; "/dev/sda1"]], 0);
2239 InitBasicFS, Always, TestOutputInt (
2240 [["umount"; "/dev/sda1"];
2241 ["zero"; "/dev/sda1"];
2242 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2243 "run the filesystem checker",
2245 This runs the filesystem checker (fsck) on C<device> which
2246 should have filesystem type C<fstype>.
2248 The returned integer is the status. See L<fsck(8)> for the
2249 list of status codes from C<fsck>.
2257 Multiple status codes can be summed together.
2261 A non-zero return code can mean \"success\", for example if
2262 errors have been corrected on the filesystem.
2266 Checking or repairing NTFS volumes is not supported
2271 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2273 ("zero", (RErr, [Device "device"]), 85, [],
2274 [InitBasicFS, Always, TestOutput (
2275 [["umount"; "/dev/sda1"];
2276 ["zero"; "/dev/sda1"];
2277 ["file"; "/dev/sda1"]], "data")],
2278 "write zeroes to the device",
2280 This command writes zeroes over the first few blocks of C<device>.
2282 How many blocks are zeroed isn't specified (but it's I<not> enough
2283 to securely wipe the device). It should be sufficient to remove
2284 any partition tables, filesystem superblocks and so on.
2286 See also: C<guestfs_scrub_device>.");
2288 ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2289 (* Test disabled because grub-install incompatible with virtio-blk driver.
2290 * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2292 [InitBasicFS, Disabled, TestOutputTrue (
2293 [["grub_install"; "/"; "/dev/sda1"];
2294 ["is_dir"; "/boot"]])],
2297 This command installs GRUB (the Grand Unified Bootloader) on
2298 C<device>, with the root directory being C<root>.");
2300 ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2301 [InitBasicFS, Always, TestOutput (
2302 [["write_file"; "/old"; "file content"; "0"];
2303 ["cp"; "/old"; "/new"];
2304 ["cat"; "/new"]], "file content");
2305 InitBasicFS, Always, TestOutputTrue (
2306 [["write_file"; "/old"; "file content"; "0"];
2307 ["cp"; "/old"; "/new"];
2308 ["is_file"; "/old"]]);
2309 InitBasicFS, Always, TestOutput (
2310 [["write_file"; "/old"; "file content"; "0"];
2312 ["cp"; "/old"; "/dir/new"];
2313 ["cat"; "/dir/new"]], "file content")],
2316 This copies a file from C<src> to C<dest> where C<dest> is
2317 either a destination filename or destination directory.");
2319 ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2320 [InitBasicFS, Always, TestOutput (
2321 [["mkdir"; "/olddir"];
2322 ["mkdir"; "/newdir"];
2323 ["write_file"; "/olddir/file"; "file content"; "0"];
2324 ["cp_a"; "/olddir"; "/newdir"];
2325 ["cat"; "/newdir/olddir/file"]], "file content")],
2326 "copy a file or directory recursively",
2328 This copies a file or directory from C<src> to C<dest>
2329 recursively using the C<cp -a> command.");
2331 ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2332 [InitBasicFS, Always, TestOutput (
2333 [["write_file"; "/old"; "file content"; "0"];
2334 ["mv"; "/old"; "/new"];
2335 ["cat"; "/new"]], "file content");
2336 InitBasicFS, Always, TestOutputFalse (
2337 [["write_file"; "/old"; "file content"; "0"];
2338 ["mv"; "/old"; "/new"];
2339 ["is_file"; "/old"]])],
2342 This moves a file from C<src> to C<dest> where C<dest> is
2343 either a destination filename or destination directory.");
2345 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2346 [InitEmpty, Always, TestRun (
2347 [["drop_caches"; "3"]])],
2348 "drop kernel page cache, dentries and inodes",
2350 This instructs the guest kernel to drop its page cache,
2351 and/or dentries and inode caches. The parameter C<whattodrop>
2352 tells the kernel what precisely to drop, see
2353 L<http://linux-mm.org/Drop_Caches>
2355 Setting C<whattodrop> to 3 should drop everything.
2357 This automatically calls L<sync(2)> before the operation,
2358 so that the maximum guest memory is freed.");
2360 ("dmesg", (RString "kmsgs", []), 91, [],
2361 [InitEmpty, Always, TestRun (
2363 "return kernel messages",
2365 This returns the kernel messages (C<dmesg> output) from
2366 the guest kernel. This is sometimes useful for extended
2367 debugging of problems.
2369 Another way to get the same information is to enable
2370 verbose messages with C<guestfs_set_verbose> or by setting
2371 the environment variable C<LIBGUESTFS_DEBUG=1> before
2372 running the program.");
2374 ("ping_daemon", (RErr, []), 92, [],
2375 [InitEmpty, Always, TestRun (
2376 [["ping_daemon"]])],
2377 "ping the guest daemon",
2379 This is a test probe into the guestfs daemon running inside
2380 the qemu subprocess. Calling this function checks that the
2381 daemon responds to the ping message, without affecting the daemon
2382 or attached block device(s) in any other way.");
2384 ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2385 [InitBasicFS, Always, TestOutputTrue (
2386 [["write_file"; "/file1"; "contents of a file"; "0"];
2387 ["cp"; "/file1"; "/file2"];
2388 ["equal"; "/file1"; "/file2"]]);
2389 InitBasicFS, Always, TestOutputFalse (
2390 [["write_file"; "/file1"; "contents of a file"; "0"];
2391 ["write_file"; "/file2"; "contents of another file"; "0"];
2392 ["equal"; "/file1"; "/file2"]]);
2393 InitBasicFS, Always, TestLastFail (
2394 [["equal"; "/file1"; "/file2"]])],
2395 "test if two files have equal contents",
2397 This compares the two files C<file1> and C<file2> and returns
2398 true if their content is exactly equal, or false otherwise.
2400 The external L<cmp(1)> program is used for the comparison.");
2402 ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2403 [InitISOFS, Always, TestOutputList (
2404 [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2405 InitISOFS, Always, TestOutputList (
2406 [["strings"; "/empty"]], [])],
2407 "print the printable strings in a file",
2409 This runs the L<strings(1)> command on a file and returns
2410 the list of printable strings found.");
2412 ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2413 [InitISOFS, Always, TestOutputList (
2414 [["strings_e"; "b"; "/known-5"]], []);
2415 InitBasicFS, Disabled, TestOutputList (
2416 [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2417 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2418 "print the printable strings in a file",
2420 This is like the C<guestfs_strings> command, but allows you to
2421 specify the encoding.
2423 See the L<strings(1)> manpage for the full list of encodings.
2425 Commonly useful encodings are C<l> (lower case L) which will
2426 show strings inside Windows/x86 files.
2428 The returned strings are transcoded to UTF-8.");
2430 ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2431 [InitISOFS, Always, TestOutput (
2432 [["hexdump"; "/known-4"]], "00000000 61 62 63 0a 64 65 66 0a 67 68 69 |abc.def.ghi|\n0000000b\n");
2433 (* Test for RHBZ#501888c2 regression which caused large hexdump
2434 * commands to segfault.
2436 InitISOFS, Always, TestRun (
2437 [["hexdump"; "/100krandom"]])],
2438 "dump a file in hexadecimal",
2440 This runs C<hexdump -C> on the given C<path>. The result is
2441 the human-readable, canonical hex dump of the file.");
2443 ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2444 [InitNone, Always, TestOutput (
2445 [["part_disk"; "/dev/sda"; "mbr"];
2446 ["mkfs"; "ext3"; "/dev/sda1"];
2447 ["mount_options"; ""; "/dev/sda1"; "/"];
2448 ["write_file"; "/new"; "test file"; "0"];
2449 ["umount"; "/dev/sda1"];
2450 ["zerofree"; "/dev/sda1"];
2451 ["mount_options"; ""; "/dev/sda1"; "/"];
2452 ["cat"; "/new"]], "test file")],
2453 "zero unused inodes and disk blocks on ext2/3 filesystem",
2455 This runs the I<zerofree> program on C<device>. This program
2456 claims to zero unused inodes and disk blocks on an ext2/3
2457 filesystem, thus making it possible to compress the filesystem
2460 You should B<not> run this program if the filesystem is
2463 It is possible that using this program can damage the filesystem
2464 or data on the filesystem.");
2466 ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2468 "resize an LVM physical volume",
2470 This resizes (expands or shrinks) an existing LVM physical
2471 volume to match the new size of the underlying device.");
2473 ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2474 Int "cyls"; Int "heads"; Int "sectors";
2475 String "line"]), 99, [DangerWillRobinson],
2477 "modify a single partition on a block device",
2479 This runs L<sfdisk(8)> option to modify just the single
2480 partition C<n> (note: C<n> counts from 1).
2482 For other parameters, see C<guestfs_sfdisk>. You should usually
2483 pass C<0> for the cyls/heads/sectors parameters.
2485 See also: C<guestfs_part_add>");
2487 ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2489 "display the partition table",
2491 This displays the partition table on C<device>, in the
2492 human-readable output of the L<sfdisk(8)> command. It is
2493 not intended to be parsed.
2495 See also: C<guestfs_part_list>");
2497 ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2499 "display the kernel geometry",
2501 This displays the kernel's idea of the geometry of C<device>.
2503 The result is in human-readable format, and not designed to
2506 ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2508 "display the disk geometry from the partition table",
2510 This displays the disk geometry of C<device> read from the
2511 partition table. Especially in the case where the underlying
2512 block device has been resized, this can be different from the
2513 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2515 The result is in human-readable format, and not designed to
2518 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2520 "activate or deactivate all volume groups",
2522 This command activates or (if C<activate> is false) deactivates
2523 all logical volumes in all volume groups.
2524 If activated, then they are made known to the
2525 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2526 then those devices disappear.
2528 This command is the same as running C<vgchange -a y|n>");
2530 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
2532 "activate or deactivate some volume groups",
2534 This command activates or (if C<activate> is false) deactivates
2535 all logical volumes in the listed volume groups C<volgroups>.
2536 If activated, then they are made known to the
2537 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2538 then those devices disappear.
2540 This command is the same as running C<vgchange -a y|n volgroups...>
2542 Note that if C<volgroups> is an empty list then B<all> volume groups
2543 are activated or deactivated.");
2545 ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
2546 [InitNone, Always, TestOutput (
2547 [["part_disk"; "/dev/sda"; "mbr"];
2548 ["pvcreate"; "/dev/sda1"];
2549 ["vgcreate"; "VG"; "/dev/sda1"];
2550 ["lvcreate"; "LV"; "VG"; "10"];
2551 ["mkfs"; "ext2"; "/dev/VG/LV"];
2552 ["mount_options"; ""; "/dev/VG/LV"; "/"];
2553 ["write_file"; "/new"; "test content"; "0"];
2555 ["lvresize"; "/dev/VG/LV"; "20"];
2556 ["e2fsck_f"; "/dev/VG/LV"];
2557 ["resize2fs"; "/dev/VG/LV"];
2558 ["mount_options"; ""; "/dev/VG/LV"; "/"];
2559 ["cat"; "/new"]], "test content")],
2560 "resize an LVM logical volume",
2562 This resizes (expands or shrinks) an existing LVM logical
2563 volume to C<mbytes>. When reducing, data in the reduced part
2566 ("resize2fs", (RErr, [Device "device"]), 106, [],
2567 [], (* lvresize tests this *)
2568 "resize an ext2/ext3 filesystem",
2570 This resizes an ext2 or ext3 filesystem to match the size of
2571 the underlying device.
2573 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2574 on the C<device> before calling this command. For unknown reasons
2575 C<resize2fs> sometimes gives an error about this and sometimes not.
2576 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2577 calling this function.");
2579 ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
2580 [InitBasicFS, Always, TestOutputList (
2581 [["find"; "/"]], ["lost+found"]);
2582 InitBasicFS, Always, TestOutputList (
2586 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2587 InitBasicFS, Always, TestOutputList (
2588 [["mkdir_p"; "/a/b/c"];
2589 ["touch"; "/a/b/c/d"];
2590 ["find"; "/a/b/"]], ["c"; "c/d"])],
2591 "find all files and directories",
2593 This command lists out all files and directories, recursively,
2594 starting at C<directory>. It is essentially equivalent to
2595 running the shell command C<find directory -print> but some
2596 post-processing happens on the output, described below.
2598 This returns a list of strings I<without any prefix>. Thus
2599 if the directory structure was:
2605 then the returned list from C<guestfs_find> C</tmp> would be
2613 If C<directory> is not a directory, then this command returns
2616 The returned list is sorted.
2618 See also C<guestfs_find0>.");
2620 ("e2fsck_f", (RErr, [Device "device"]), 108, [],
2621 [], (* lvresize tests this *)
2622 "check an ext2/ext3 filesystem",
2624 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2625 filesystem checker on C<device>, noninteractively (C<-p>),
2626 even if the filesystem appears to be clean (C<-f>).
2628 This command is only needed because of C<guestfs_resize2fs>
2629 (q.v.). Normally you should use C<guestfs_fsck>.");
2631 ("sleep", (RErr, [Int "secs"]), 109, [],
2632 [InitNone, Always, TestRun (
2634 "sleep for some seconds",
2636 Sleep for C<secs> seconds.");
2638 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
2639 [InitNone, Always, TestOutputInt (
2640 [["part_disk"; "/dev/sda"; "mbr"];
2641 ["mkfs"; "ntfs"; "/dev/sda1"];
2642 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2643 InitNone, Always, TestOutputInt (
2644 [["part_disk"; "/dev/sda"; "mbr"];
2645 ["mkfs"; "ext2"; "/dev/sda1"];
2646 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2647 "probe NTFS volume",
2649 This command runs the L<ntfs-3g.probe(8)> command which probes
2650 an NTFS C<device> for mountability. (Not all NTFS volumes can
2651 be mounted read-write, and some cannot be mounted at all).
2653 C<rw> is a boolean flag. Set it to true if you want to test
2654 if the volume can be mounted read-write. Set it to false if
2655 you want to test if the volume can be mounted read-only.
2657 The return value is an integer which C<0> if the operation
2658 would succeed, or some non-zero value documented in the
2659 L<ntfs-3g.probe(8)> manual page.");
2661 ("sh", (RString "output", [String "command"]), 111, [],
2662 [], (* XXX needs tests *)
2663 "run a command via the shell",
2665 This call runs a command from the guest filesystem via the
2668 This is like C<guestfs_command>, but passes the command to:
2670 /bin/sh -c \"command\"
2672 Depending on the guest's shell, this usually results in
2673 wildcards being expanded, shell expressions being interpolated
2676 All the provisos about C<guestfs_command> apply to this call.");
2678 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2679 [], (* XXX needs tests *)
2680 "run a command via the shell returning lines",
2682 This is the same as C<guestfs_sh>, but splits the result
2683 into a list of lines.
2685 See also: C<guestfs_command_lines>");
2687 ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
2688 (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
2689 * code in stubs.c, since all valid glob patterns must start with "/".
2690 * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
2692 [InitBasicFS, Always, TestOutputList (
2693 [["mkdir_p"; "/a/b/c"];
2694 ["touch"; "/a/b/c/d"];
2695 ["touch"; "/a/b/c/e"];
2696 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2697 InitBasicFS, Always, TestOutputList (
2698 [["mkdir_p"; "/a/b/c"];
2699 ["touch"; "/a/b/c/d"];
2700 ["touch"; "/a/b/c/e"];
2701 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2702 InitBasicFS, Always, TestOutputList (
2703 [["mkdir_p"; "/a/b/c"];
2704 ["touch"; "/a/b/c/d"];
2705 ["touch"; "/a/b/c/e"];
2706 ["glob_expand"; "/a/*/x/*"]], [])],
2707 "expand a wildcard path",
2709 This command searches for all the pathnames matching
2710 C<pattern> according to the wildcard expansion rules
2713 If no paths match, then this returns an empty list
2714 (note: not an error).
2716 It is just a wrapper around the C L<glob(3)> function
2717 with flags C<GLOB_MARK|GLOB_BRACE>.
2718 See that manual page for more details.");
2720 ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
2721 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2722 [["scrub_device"; "/dev/sdc"]])],
2723 "scrub (securely wipe) a device",
2725 This command writes patterns over C<device> to make data retrieval
2728 It is an interface to the L<scrub(1)> program. See that
2729 manual page for more details.");
2731 ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
2732 [InitBasicFS, Always, TestRun (
2733 [["write_file"; "/file"; "content"; "0"];
2734 ["scrub_file"; "/file"]])],
2735 "scrub (securely wipe) a file",
2737 This command writes patterns over a file to make data retrieval
2740 The file is I<removed> after scrubbing.
2742 It is an interface to the L<scrub(1)> program. See that
2743 manual page for more details.");
2745 ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
2746 [], (* XXX needs testing *)
2747 "scrub (securely wipe) free space",
2749 This command creates the directory C<dir> and then fills it
2750 with files until the filesystem is full, and scrubs the files
2751 as for C<guestfs_scrub_file>, and deletes them.
2752 The intention is to scrub any free space on the partition
2755 It is an interface to the L<scrub(1)> program. See that
2756 manual page for more details.");
2758 ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
2759 [InitBasicFS, Always, TestRun (
2761 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2762 "create a temporary directory",
2764 This command creates a temporary directory. The
2765 C<template> parameter should be a full pathname for the
2766 temporary directory name with the final six characters being
2769 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2770 the second one being suitable for Windows filesystems.
2772 The name of the temporary directory that was created
2775 The temporary directory is created with mode 0700
2776 and is owned by root.
2778 The caller is responsible for deleting the temporary
2779 directory and its contents after use.
2781 See also: L<mkdtemp(3)>");
2783 ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
2784 [InitISOFS, Always, TestOutputInt (
2785 [["wc_l"; "/10klines"]], 10000)],
2786 "count lines in a file",
2788 This command counts the lines in a file, using the
2789 C<wc -l> external command.");
2791 ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
2792 [InitISOFS, Always, TestOutputInt (
2793 [["wc_w"; "/10klines"]], 10000)],
2794 "count words in a file",
2796 This command counts the words in a file, using the
2797 C<wc -w> external command.");
2799 ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
2800 [InitISOFS, Always, TestOutputInt (
2801 [["wc_c"; "/100kallspaces"]], 102400)],
2802 "count characters in a file",
2804 This command counts the characters in a file, using the
2805 C<wc -c> external command.");
2807 ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
2808 [InitISOFS, Always, TestOutputList (
2809 [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2810 "return first 10 lines of a file",
2812 This command returns up to the first 10 lines of a file as
2813 a list of strings.");
2815 ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
2816 [InitISOFS, Always, TestOutputList (
2817 [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2818 InitISOFS, Always, TestOutputList (
2819 [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2820 InitISOFS, Always, TestOutputList (
2821 [["head_n"; "0"; "/10klines"]], [])],
2822 "return first N lines of a file",
2824 If the parameter C<nrlines> is a positive number, this returns the first
2825 C<nrlines> lines of the file C<path>.
2827 If the parameter C<nrlines> is a negative number, this returns lines
2828 from the file C<path>, excluding the last C<nrlines> lines.
2830 If the parameter C<nrlines> is zero, this returns an empty list.");
2832 ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
2833 [InitISOFS, Always, TestOutputList (
2834 [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2835 "return last 10 lines of a file",
2837 This command returns up to the last 10 lines of a file as
2838 a list of strings.");
2840 ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
2841 [InitISOFS, Always, TestOutputList (
2842 [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2843 InitISOFS, Always, TestOutputList (
2844 [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2845 InitISOFS, Always, TestOutputList (
2846 [["tail_n"; "0"; "/10klines"]], [])],
2847 "return last N lines of a file",
2849 If the parameter C<nrlines> is a positive number, this returns the last
2850 C<nrlines> lines of the file C<path>.
2852 If the parameter C<nrlines> is a negative number, this returns lines
2853 from the file C<path>, starting with the C<-nrlines>th line.
2855 If the parameter C<nrlines> is zero, this returns an empty list.");
2857 ("df", (RString "output", []), 125, [],
2858 [], (* XXX Tricky to test because it depends on the exact format
2859 * of the 'df' command and other imponderables.
2861 "report file system disk space usage",
2863 This command runs the C<df> command to report disk space used.
2865 This command is mostly useful for interactive sessions. It
2866 is I<not> intended that you try to parse the output string.
2867 Use C<statvfs> from programs.");
2869 ("df_h", (RString "output", []), 126, [],
2870 [], (* XXX Tricky to test because it depends on the exact format
2871 * of the 'df' command and other imponderables.
2873 "report file system disk space usage (human readable)",
2875 This command runs the C<df -h> command to report disk space used
2876 in human-readable format.
2878 This command is mostly useful for interactive sessions. It
2879 is I<not> intended that you try to parse the output string.
2880 Use C<statvfs> from programs.");
2882 ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
2883 [InitISOFS, Always, TestOutputInt (
2884 [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
2885 "estimate file space usage",
2887 This command runs the C<du -s> command to estimate file space
2890 C<path> can be a file or a directory. If C<path> is a directory
2891 then the estimate includes the contents of the directory and all
2892 subdirectories (recursively).
2894 The result is the estimated size in I<kilobytes>
2895 (ie. units of 1024 bytes).");
2897 ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
2898 [InitISOFS, Always, TestOutputList (
2899 [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
2900 "list files in an initrd",
2902 This command lists out files contained in an initrd.
2904 The files are listed without any initial C</> character. The
2905 files are listed in the order they appear (not necessarily
2906 alphabetical). Directory names are listed as separate items.
2908 Old Linux kernels (2.4 and earlier) used a compressed ext2
2909 filesystem as initrd. We I<only> support the newer initramfs
2910 format (compressed cpio files).");
2912 ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
2914 "mount a file using the loop device",
2916 This command lets you mount C<file> (a filesystem image
2917 in a file) on a mount point. It is entirely equivalent to
2918 the command C<mount -o loop file mountpoint>.");
2920 ("mkswap", (RErr, [Device "device"]), 130, [],
2921 [InitEmpty, Always, TestRun (
2922 [["part_disk"; "/dev/sda"; "mbr"];
2923 ["mkswap"; "/dev/sda1"]])],
2924 "create a swap partition",
2926 Create a swap partition on C<device>.");
2928 ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
2929 [InitEmpty, Always, TestRun (
2930 [["part_disk"; "/dev/sda"; "mbr"];
2931 ["mkswap_L"; "hello"; "/dev/sda1"]])],
2932 "create a swap partition with a label",
2934 Create a swap partition on C<device> with label C<label>.
2936 Note that you cannot attach a swap label to a block device
2937 (eg. C</dev/sda>), just to a partition. This appears to be
2938 a limitation of the kernel or swap tools.");
2940 ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
2941 (let uuid = uuidgen () in
2942 [InitEmpty, Always, TestRun (
2943 [["part_disk"; "/dev/sda"; "mbr"];
2944 ["mkswap_U"; uuid; "/dev/sda1"]])]),
2945 "create a swap partition with an explicit UUID",
2947 Create a swap partition on C<device> with UUID C<uuid>.");
2949 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
2950 [InitBasicFS, Always, TestOutputStruct (
2951 [["mknod"; "0o10777"; "0"; "0"; "/node"];
2952 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2953 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2954 InitBasicFS, Always, TestOutputStruct (
2955 [["mknod"; "0o60777"; "66"; "99"; "/node"];
2956 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2957 "make block, character or FIFO devices",
2959 This call creates block or character special devices, or
2960 named pipes (FIFOs).
2962 The C<mode> parameter should be the mode, using the standard
2963 constants. C<devmajor> and C<devminor> are the
2964 device major and minor numbers, only used when creating block
2965 and character special devices.");
2967 ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
2968 [InitBasicFS, Always, TestOutputStruct (
2969 [["mkfifo"; "0o777"; "/node"];
2970 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2971 "make FIFO (named pipe)",
2973 This call creates a FIFO (named pipe) called C<path> with
2974 mode C<mode>. It is just a convenient wrapper around
2975 C<guestfs_mknod>.");
2977 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
2978 [InitBasicFS, Always, TestOutputStruct (
2979 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2980 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2981 "make block device node",
2983 This call creates a block device node called C<path> with
2984 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2985 It is just a convenient wrapper around C<guestfs_mknod>.");
2987 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
2988 [InitBasicFS, Always, TestOutputStruct (
2989 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2990 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2991 "make char device node",
2993 This call creates a char device node called C<path> with
2994 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2995 It is just a convenient wrapper around C<guestfs_mknod>.");
2997 ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2998 [], (* XXX umask is one of those stateful things that we should
2999 * reset between each test.
3001 "set file mode creation mask (umask)",
3003 This function sets the mask used for creating new files and
3004 device nodes to C<mask & 0777>.
3006 Typical umask values would be C<022> which creates new files
3007 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3008 C<002> which creates new files with permissions like
3009 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3011 The default umask is C<022>. This is important because it
3012 means that directories and device nodes will be created with
3013 C<0644> or C<0755> mode even if you specify C<0777>.
3015 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3017 This call returns the previous umask.");
3019 ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3021 "read directories entries",
3023 This returns the list of directory entries in directory C<dir>.
3025 All entries in the directory are returned, including C<.> and
3026 C<..>. The entries are I<not> sorted, but returned in the same
3027 order as the underlying filesystem.
3029 Also this call returns basic file type information about each
3030 file. The C<ftyp> field will contain one of the following characters:
3068 The L<readdir(3)> returned a C<d_type> field with an
3073 This function is primarily intended for use by programs. To
3074 get a simple list of names, use C<guestfs_ls>. To get a printable
3075 directory for human consumption, use C<guestfs_ll>.");
3077 ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3079 "create partitions on a block device",
3081 This is a simplified interface to the C<guestfs_sfdisk>
3082 command, where partition sizes are specified in megabytes
3083 only (rounded to the nearest cylinder) and you don't need
3084 to specify the cyls, heads and sectors parameters which
3085 were rarely if ever used anyway.
3087 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3088 and C<guestfs_part_disk>");
3090 ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3092 "determine file type inside a compressed file",
3094 This command runs C<file> after first decompressing C<path>
3097 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3099 Since 1.0.63, use C<guestfs_file> instead which can now
3100 process compressed files.");
3102 ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3104 "list extended attributes of a file or directory",
3106 This call lists the extended attributes of the file or directory
3109 At the system call level, this is a combination of the
3110 L<listxattr(2)> and L<getxattr(2)> calls.
3112 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3114 ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3116 "list extended attributes of a file or directory",
3118 This is the same as C<guestfs_getxattrs>, but if C<path>
3119 is a symbolic link, then it returns the extended attributes
3120 of the link itself.");
3122 ("setxattr", (RErr, [String "xattr";
3123 String "val"; Int "vallen"; (* will be BufferIn *)
3124 Pathname "path"]), 143, [Optional "linuxxattrs"],
3126 "set extended attribute of a file or directory",
3128 This call sets the extended attribute named C<xattr>
3129 of the file C<path> to the value C<val> (of length C<vallen>).
3130 The value is arbitrary 8 bit data.
3132 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3134 ("lsetxattr", (RErr, [String "xattr";
3135 String "val"; Int "vallen"; (* will be BufferIn *)
3136 Pathname "path"]), 144, [Optional "linuxxattrs"],
3138 "set extended attribute of a file or directory",
3140 This is the same as C<guestfs_setxattr>, but if C<path>
3141 is a symbolic link, then it sets an extended attribute
3142 of the link itself.");
3144 ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3146 "remove extended attribute of a file or directory",
3148 This call removes the extended attribute named C<xattr>
3149 of the file C<path>.
3151 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3153 ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3155 "remove extended attribute of a file or directory",
3157 This is the same as C<guestfs_removexattr>, but if C<path>
3158 is a symbolic link, then it removes an extended attribute
3159 of the link itself.");
3161 ("mountpoints", (RHashtable "mps", []), 147, [],
3165 This call is similar to C<guestfs_mounts>. That call returns
3166 a list of devices. This one returns a hash table (map) of
3167 device name to directory where the device is mounted.");
3169 ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3170 (* This is a special case: while you would expect a parameter
3171 * of type "Pathname", that doesn't work, because it implies
3172 * NEED_ROOT in the generated calling code in stubs.c, and
3173 * this function cannot use NEED_ROOT.
3176 "create a mountpoint",
3178 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3179 specialized calls that can be used to create extra mountpoints
3180 before mounting the first filesystem.
3182 These calls are I<only> necessary in some very limited circumstances,
3183 mainly the case where you want to mount a mix of unrelated and/or
3184 read-only filesystems together.
3186 For example, live CDs often contain a \"Russian doll\" nest of
3187 filesystems, an ISO outer layer, with a squashfs image inside, with
3188 an ext2/3 image inside that. You can unpack this as follows
3191 add-ro Fedora-11-i686-Live.iso
3194 mkmountpoint /squash
3197 mount-loop /cd/LiveOS/squashfs.img /squash
3198 mount-loop /squash/LiveOS/ext3fs.img /ext3
3200 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3202 ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3204 "remove a mountpoint",
3206 This calls removes a mountpoint that was previously created
3207 with C<guestfs_mkmountpoint>. See C<guestfs_mkmountpoint>
3208 for full details.");
3210 ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3211 [InitISOFS, Always, TestOutputBuffer (
3212 [["read_file"; "/known-4"]], "abc\ndef\nghi")],
3215 This calls returns the contents of the file C<path> as a
3218 Unlike C<guestfs_cat>, this function can correctly
3219 handle files that contain embedded ASCII NUL characters.
3220 However unlike C<guestfs_download>, this function is limited
3221 in the total size of file that can be handled.");
3223 ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3224 [InitISOFS, Always, TestOutputList (
3225 [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3226 InitISOFS, Always, TestOutputList (
3227 [["grep"; "nomatch"; "/test-grep.txt"]], [])],
3228 "return lines matching a pattern",
3230 This calls the external C<grep> program and returns the
3233 ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3234 [InitISOFS, Always, TestOutputList (
3235 [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3236 "return lines matching a pattern",
3238 This calls the external C<egrep> program and returns the
3241 ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3242 [InitISOFS, Always, TestOutputList (
3243 [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3244 "return lines matching a pattern",
3246 This calls the external C<fgrep> program and returns the
3249 ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3250 [InitISOFS, Always, TestOutputList (
3251 [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3252 "return lines matching a pattern",
3254 This calls the external C<grep -i> program and returns the
3257 ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3258 [InitISOFS, Always, TestOutputList (
3259 [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3260 "return lines matching a pattern",
3262 This calls the external C<egrep -i> program and returns the
3265 ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3266 [InitISOFS, Always, TestOutputList (
3267 [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3268 "return lines matching a pattern",
3270 This calls the external C<fgrep -i> program and returns the
3273 ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3274 [InitISOFS, Always, TestOutputList (
3275 [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3276 "return lines matching a pattern",
3278 This calls the external C<zgrep> program and returns the
3281 ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3282 [InitISOFS, Always, TestOutputList (
3283 [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3284 "return lines matching a pattern",
3286 This calls the external C<zegrep> program and returns the
3289 ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3290 [InitISOFS, Always, TestOutputList (
3291 [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3292 "return lines matching a pattern",
3294 This calls the external C<zfgrep> program and returns the
3297 ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3298 [InitISOFS, Always, TestOutputList (
3299 [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3300 "return lines matching a pattern",
3302 This calls the external C<zgrep -i> program and returns the
3305 ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3306 [InitISOFS, Always, TestOutputList (
3307 [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3308 "return lines matching a pattern",
3310 This calls the external C<zegrep -i> program and returns the
3313 ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3314 [InitISOFS, Always, TestOutputList (
3315 [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3316 "return lines matching a pattern",
3318 This calls the external C<zfgrep -i> program and returns the
3321 ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3322 [InitISOFS, Always, TestOutput (
3323 [["realpath"; "/../directory"]], "/directory")],
3324 "canonicalized absolute pathname",
3326 Return the canonicalized absolute pathname of C<path>. The
3327 returned path has no C<.>, C<..> or symbolic link path elements.");
3329 ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3330 [InitBasicFS, Always, TestOutputStruct (
3333 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3334 "create a hard link",
3336 This command creates a hard link using the C<ln> command.");
3338 ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3339 [InitBasicFS, Always, TestOutputStruct (
3342 ["ln_f"; "/a"; "/b"];
3343 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3344 "create a hard link",
3346 This command creates a hard link using the C<ln -f> command.
3347 The C<-f> option removes the link (C<linkname>) if it exists already.");
3349 ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3350 [InitBasicFS, Always, TestOutputStruct (
3352 ["ln_s"; "a"; "/b"];
3353 ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3354 "create a symbolic link",
3356 This command creates a symbolic link using the C<ln -s> command.");
3358 ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3359 [InitBasicFS, Always, TestOutput (
3360 [["mkdir_p"; "/a/b"];
3361 ["touch"; "/a/b/c"];
3362 ["ln_sf"; "../d"; "/a/b/c"];
3363 ["readlink"; "/a/b/c"]], "../d")],
3364 "create a symbolic link",
3366 This command creates a symbolic link using the C<ln -sf> command,
3367 The C<-f> option removes the link (C<linkname>) if it exists already.");
3369 ("readlink", (RString "link", [Pathname "path"]), 168, [],
3370 [] (* XXX tested above *),
3371 "read the target of a symbolic link",
3373 This command reads the target of a symbolic link.");
3375 ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [],
3376 [InitBasicFS, Always, TestOutputStruct (
3377 [["fallocate"; "/a"; "1000000"];
3378 ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3379 "preallocate a file in the guest filesystem",
3381 This command preallocates a file (containing zero bytes) named
3382 C<path> of size C<len> bytes. If the file exists already, it
3385 Do not confuse this with the guestfish-specific
3386 C<alloc> command which allocates a file in the host and
3387 attaches it as a device.");
3389 ("swapon_device", (RErr, [Device "device"]), 170, [],
3390 [InitPartition, Always, TestRun (
3391 [["mkswap"; "/dev/sda1"];
3392 ["swapon_device"; "/dev/sda1"];
3393 ["swapoff_device"; "/dev/sda1"]])],
3394 "enable swap on device",
3396 This command enables the libguestfs appliance to use the
3397 swap device or partition named C<device>. The increased
3398 memory is made available for all commands, for example
3399 those run using C<guestfs_command> or C<guestfs_sh>.
3401 Note that you should not swap to existing guest swap
3402 partitions unless you know what you are doing. They may
3403 contain hibernation information, or other information that
3404 the guest doesn't want you to trash. You also risk leaking
3405 information about the host to the guest this way. Instead,
3406 attach a new host device to the guest and swap on that.");
3408 ("swapoff_device", (RErr, [Device "device"]), 171, [],
3409 [], (* XXX tested by swapon_device *)
3410 "disable swap on device",
3412 This command disables the libguestfs appliance swap
3413 device or partition named C<device>.
3414 See C<guestfs_swapon_device>.");
3416 ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3417 [InitBasicFS, Always, TestRun (
3418 [["fallocate"; "/swap"; "8388608"];
3419 ["mkswap_file"; "/swap"];
3420 ["swapon_file"; "/swap"];
3421 ["swapoff_file"; "/swap"]])],
3422 "enable swap on file",
3424 This command enables swap to a file.
3425 See C<guestfs_swapon_device> for other notes.");
3427 ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3428 [], (* XXX tested by swapon_file *)
3429 "disable swap on file",
3431 This command disables the libguestfs appliance swap on file.");
3433 ("swapon_label", (RErr, [String "label"]), 174, [],
3434 [InitEmpty, Always, TestRun (
3435 [["part_disk"; "/dev/sdb"; "mbr"];
3436 ["mkswap_L"; "swapit"; "/dev/sdb1"];
3437 ["swapon_label"; "swapit"];
3438 ["swapoff_label"; "swapit"];
3439 ["zero"; "/dev/sdb"];
3440 ["blockdev_rereadpt"; "/dev/sdb"]])],
3441 "enable swap on labeled swap partition",
3443 This command enables swap to a labeled swap partition.
3444 See C<guestfs_swapon_device> for other notes.");
3446 ("swapoff_label", (RErr, [String "label"]), 175, [],
3447 [], (* XXX tested by swapon_label *)
3448 "disable swap on labeled swap partition",
3450 This command disables the libguestfs appliance swap on
3451 labeled swap partition.");
3453 ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3454 (let uuid = uuidgen () in
3455 [InitEmpty, Always, TestRun (
3456 [["mkswap_U"; uuid; "/dev/sdb"];
3457 ["swapon_uuid"; uuid];
3458 ["swapoff_uuid"; uuid]])]),
3459 "enable swap on swap partition by UUID",
3461 This command enables swap to a swap partition with the given UUID.
3462 See C<guestfs_swapon_device> for other notes.");
3464 ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3465 [], (* XXX tested by swapon_uuid *)
3466 "disable swap on swap partition by UUID",
3468 This command disables the libguestfs appliance swap partition
3469 with the given UUID.");
3471 ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3472 [InitBasicFS, Always, TestRun (
3473 [["fallocate"; "/swap"; "8388608"];
3474 ["mkswap_file"; "/swap"]])],
3475 "create a swap file",
3479 This command just writes a swap file signature to an existing
3480 file. To create the file itself, use something like C<guestfs_fallocate>.");
3482 ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
3483 [InitISOFS, Always, TestRun (
3484 [["inotify_init"; "0"]])],
3485 "create an inotify handle",
3487 This command creates a new inotify handle.
3488 The inotify subsystem can be used to notify events which happen to
3489 objects in the guest filesystem.
3491 C<maxevents> is the maximum number of events which will be
3492 queued up between calls to C<guestfs_inotify_read> or
3493 C<guestfs_inotify_files>.
3494 If this is passed as C<0>, then the kernel (or previously set)
3495 default is used. For Linux 2.6.29 the default was 16384 events.
3496 Beyond this limit, the kernel throws away events, but records
3497 the fact that it threw them away by setting a flag
3498 C<IN_Q_OVERFLOW> in the returned structure list (see
3499 C<guestfs_inotify_read>).
3501 Before any events are generated, you have to add some
3502 watches to the internal watch list. See:
3503 C<guestfs_inotify_add_watch>,
3504 C<guestfs_inotify_rm_watch> and
3505 C<guestfs_inotify_watch_all>.
3507 Queued up events should be read periodically by calling
3508 C<guestfs_inotify_read>
3509 (or C<guestfs_inotify_files> which is just a helpful
3510 wrapper around C<guestfs_inotify_read>). If you don't
3511 read the events out often enough then you risk the internal
3514 The handle should be closed after use by calling
3515 C<guestfs_inotify_close>. This also removes any
3516 watches automatically.
3518 See also L<inotify(7)> for an overview of the inotify interface
3519 as exposed by the Linux kernel, which is roughly what we expose
3520 via libguestfs. Note that there is one global inotify handle
3521 per libguestfs instance.");
3523 ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
3524 [InitBasicFS, Always, TestOutputList (
3525 [["inotify_init"; "0"];
3526 ["inotify_add_watch"; "/"; "1073741823"];
3529 ["inotify_files"]], ["a"; "b"])],
3530 "add an inotify watch",
3532 Watch C<path> for the events listed in C<mask>.
3534 Note that if C<path> is a directory then events within that
3535 directory are watched, but this does I<not> happen recursively
3536 (in subdirectories).
3538 Note for non-C or non-Linux callers: the inotify events are
3539 defined by the Linux kernel ABI and are listed in
3540 C</usr/include/sys/inotify.h>.");
3542 ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
3544 "remove an inotify watch",
3546 Remove a previously defined inotify watch.
3547 See C<guestfs_inotify_add_watch>.");
3549 ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
3551 "return list of inotify events",
3553 Return the complete queue of events that have happened
3554 since the previous read call.
3556 If no events have happened, this returns an empty list.
3558 I<Note>: In order to make sure that all events have been
3559 read, you must call this function repeatedly until it
3560 returns an empty list. The reason is that the call will
3561 read events up to the maximum appliance-to-host message
3562 size and leave remaining events in the queue.");
3564 ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
3566 "return list of watched files that had events",
3568 This function is a helpful wrapper around C<guestfs_inotify_read>
3569 which just returns a list of pathnames of objects that were
3570 touched. The returned pathnames are sorted and deduplicated.");
3572 ("inotify_close", (RErr, []), 184, [Optional "inotify"],
3574 "close the inotify handle",
3576 This closes the inotify handle which was previously
3577 opened by inotify_init. It removes all watches, throws
3578 away any pending events, and deallocates all resources.");
3580 ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
3582 "set SELinux security context",
3584 This sets the SELinux security context of the daemon
3585 to the string C<context>.
3587 See the documentation about SELINUX in L<guestfs(3)>.");
3589 ("getcon", (RString "context", []), 186, [Optional "selinux"],
3591 "get SELinux security context",
3593 This gets the SELinux security context of the daemon.
3595 See the documentation about SELINUX in L<guestfs(3)>,
3596 and C<guestfs_setcon>");
3598 ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
3599 [InitEmpty, Always, TestOutput (
3600 [["part_disk"; "/dev/sda"; "mbr"];
3601 ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
3602 ["mount_options"; ""; "/dev/sda1"; "/"];
3603 ["write_file"; "/new"; "new file contents"; "0"];
3604 ["cat"; "/new"]], "new file contents")],
3605 "make a filesystem with block size",
3607 This call is similar to C<guestfs_mkfs>, but it allows you to
3608 control the block size of the resulting filesystem. Supported
3609 block sizes depend on the filesystem type, but typically they
3610 are C<1024>, C<2048> or C<4096> only.");
3612 ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
3613 [InitEmpty, Always, TestOutput (
3614 [["sfdiskM"; "/dev/sda"; ",100 ,"];
3615 ["mke2journal"; "4096"; "/dev/sda1"];
3616 ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
3617 ["mount_options"; ""; "/dev/sda2"; "/"];
3618 ["write_file"; "/new"; "new file contents"; "0"];
3619 ["cat"; "/new"]], "new file contents")],
3620 "make ext2/3/4 external journal",
3622 This creates an ext2 external journal on C<device>. It is equivalent
3625 mke2fs -O journal_dev -b blocksize device");
3627 ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
3628 [InitEmpty, Always, TestOutput (
3629 [["sfdiskM"; "/dev/sda"; ",100 ,"];
3630 ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
3631 ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
3632 ["mount_options"; ""; "/dev/sda2"; "/"];
3633 ["write_file"; "/new"; "new file contents"; "0"];
3634 ["cat"; "/new"]], "new file contents")],
3635 "make ext2/3/4 external journal with label",
3637 This creates an ext2 external journal on C<device> with label C<label>.");
3639 ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
3640 (let uuid = uuidgen () in
3641 [InitEmpty, Always, TestOutput (
3642 [["sfdiskM"; "/dev/sda"; ",100 ,"];
3643 ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
3644 ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
3645 ["mount_options"; ""; "/dev/sda2"; "/"];
3646 ["write_file"; "/new"; "new file contents"; "0"];
3647 ["cat"; "/new"]], "new file contents")]),
3648 "make ext2/3/4 external journal with UUID",
3650 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
3652 ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
3654 "make ext2/3/4 filesystem with external journal",
3656 This creates an ext2/3/4 filesystem on C<device> with
3657 an external journal on C<journal>. It is equivalent
3660 mke2fs -t fstype -b blocksize -J device=<journal> <device>
3662 See also C<guestfs_mke2journal>.");
3664 ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
3666 "make ext2/3/4 filesystem with external journal",
3668 This creates an ext2/3/4 filesystem on C<device> with
3669 an external journal on the journal labeled C<label>.
3671 See also C<guestfs_mke2journal_L>.");
3673 ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
3675 "make ext2/3/4 filesystem with external journal",
3677 This creates an ext2/3/4 filesystem on C<device> with
3678 an external journal on the journal with UUID C<uuid>.
3680 See also C<guestfs_mke2journal_U>.");
3682 ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
3683 [InitNone, Always, TestRun [["modprobe"; "fat"]]],
3684 "load a kernel module",
3686 This loads a kernel module in the appliance.
3688 The kernel module must have been whitelisted when libguestfs
3689 was built (see C<appliance/kmod.whitelist.in> in the source).");
3691 ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
3692 [InitNone, Always, TestOutput (
3693 [["echo_daemon"; "This is a test"]], "This is a test"
3695 "echo arguments back to the client",
3697 This command concatenate the list of C<words> passed with single spaces between
3698 them and returns the resulting string.
3700 You can use this command to test the connection through to the daemon.
3702 See also C<guestfs_ping_daemon>.");
3704 ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
3705 [], (* There is a regression test for this. *)
3706 "find all files and directories, returning NUL-separated list",
3708 This command lists out all files and directories, recursively,
3709 starting at C<directory>, placing the resulting list in the
3710 external file called C<files>.
3712 This command works the same way as C<guestfs_find> with the
3713 following exceptions:
3719 The resulting list is written to an external file.
3723 Items (filenames) in the result are separated
3724 by C<\\0> characters. See L<find(1)> option I<-print0>.
3728 This command is not limited in the number of names that it
3733 The result list is not sorted.
3737 ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
3738 [InitISOFS, Always, TestOutput (
3739 [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
3740 InitISOFS, Always, TestOutput (
3741 [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
3742 InitISOFS, Always, TestOutput (
3743 [["case_sensitive_path"; "/Known-1"]], "/known-1");
3744 InitISOFS, Always, TestLastFail (
3745 [["case_sensitive_path"; "/Known-1/"]]);
3746 InitBasicFS, Always, TestOutput (
3748 ["mkdir"; "/a/bbb"];
3749 ["touch"; "/a/bbb/c"];
3750 ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
3751 InitBasicFS, Always, TestOutput (
3753 ["mkdir"; "/a/bbb"];
3754 ["touch"; "/a/bbb/c"];
3755 ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
3756 InitBasicFS, Always, TestLastFail (
3758 ["mkdir"; "/a/bbb"];
3759 ["touch"; "/a/bbb/c"];
3760 ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
3761 "return true path on case-insensitive filesystem",
3763 This can be used to resolve case insensitive paths on
3764 a filesystem which is case sensitive. The use case is
3765 to resolve paths which you have read from Windows configuration
3766 files or the Windows Registry, to the true path.
3768 The command handles a peculiarity of the Linux ntfs-3g
3769 filesystem driver (and probably others), which is that although
3770 the underlying filesystem is case-insensitive, the driver
3771 exports the filesystem to Linux as case-sensitive.
3773 One consequence of this is that special directories such
3774 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
3775 (or other things) depending on the precise details of how
3776 they were created. In Windows itself this would not be
3779 Bug or feature? You decide:
3780 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
3782 This function resolves the true case of each element in the
3783 path and returns the case-sensitive path.
3785 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
3786 might return C<\"/WINDOWS/system32\"> (the exact return value
3787 would depend on details of how the directories were originally
3788 created under Windows).
3791 This function does not handle drive names, backslashes etc.
3793 See also C<guestfs_realpath>.");
3795 ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
3796 [InitBasicFS, Always, TestOutput (
3797 [["vfs_type"; "/dev/sda1"]], "ext2")],
3798 "get the Linux VFS type corresponding to a mounted device",
3800 This command gets the block device type corresponding to
3801 a mounted device called C<device>.
3803 Usually the result is the name of the Linux VFS module that
3804 is used to mount this device (probably determined automatically
3805 if you used the C<guestfs_mount> call).");
3807 ("truncate", (RErr, [Pathname "path"]), 199, [],
3808 [InitBasicFS, Always, TestOutputStruct (
3809 [["write_file"; "/test"; "some stuff so size is not zero"; "0"];
3810 ["truncate"; "/test"];
3811 ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
3812 "truncate a file to zero size",
3814 This command truncates C<path> to a zero-length file. The
3815 file must exist already.");
3817 ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
3818 [InitBasicFS, Always, TestOutputStruct (
3819 [["touch"; "/test"];
3820 ["truncate_size"; "/test"; "1000"];
3821 ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
3822 "truncate a file to a particular size",
3824 This command truncates C<path> to size C<size> bytes. The file
3825 must exist already. If the file is smaller than C<size> then
3826 the file is extended to the required size with null bytes.");
3828 ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
3829 [InitBasicFS, Always, TestOutputStruct (
3830 [["touch"; "/test"];
3831 ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
3832 ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
3833 "set timestamp of a file with nanosecond precision",
3835 This command sets the timestamps of a file with nanosecond
3838 C<atsecs, atnsecs> are the last access time (atime) in secs and
3839 nanoseconds from the epoch.
3841 C<mtsecs, mtnsecs> are the last modification time (mtime) in
3842 secs and nanoseconds from the epoch.
3844 If the C<*nsecs> field contains the special value C<-1> then
3845 the corresponding timestamp is set to the current time. (The
3846 C<*secs> field is ignored in this case).
3848 If the C<*nsecs> field contains the special value C<-2> then
3849 the corresponding timestamp is left unchanged. (The
3850 C<*secs> field is ignored in this case).");
3852 ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
3853 [InitBasicFS, Always, TestOutputStruct (
3854 [["mkdir_mode"; "/test"; "0o111"];
3855 ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
3856 "create a directory with a particular mode",
3858 This command creates a directory, setting the initial permissions
3859 of the directory to C<mode>. See also C<guestfs_mkdir>.");
3861 ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
3863 "change file owner and group",
3865 Change the file owner to C<owner> and group to C<group>.
3866 This is like C<guestfs_chown> but if C<path> is a symlink then
3867 the link itself is changed, not the target.
3869 Only numeric uid and gid are supported. If you want to use
3870 names, you will need to locate and parse the password file
3871 yourself (Augeas support makes this relatively easy).");
3873 ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
3875 "lstat on multiple files",
3877 This call allows you to perform the C<guestfs_lstat> operation
3878 on multiple files, where all files are in the directory C<path>.
3879 C<names> is the list of files from this directory.
3881 On return you get a list of stat structs, with a one-to-one
3882 correspondence to the C<names> list. If any name did not exist
3883 or could not be lstat'd, then the C<ino> field of that structure
3886 This call is intended for programs that want to efficiently
3887 list a directory contents without making many round-trips.
3888 See also C<guestfs_lxattrlist> for a similarly efficient call
3889 for getting extended attributes. Very long directory listings
3890 might cause the protocol message size to be exceeded, causing
3891 this call to fail. The caller must split up such requests
3892 into smaller groups of names.");
3894 ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
3896 "lgetxattr on multiple files",
3898 This call allows you to get the extended attributes
3899 of multiple files, where all files are in the directory C<path>.
3900 C<names> is the list of files from this directory.
3902 On return you get a flat list of xattr structs which must be
3903 interpreted sequentially. The first xattr struct always has a zero-length
3904 C<attrname>. C<attrval> in this struct is zero-length
3905 to indicate there was an error doing C<lgetxattr> for this
3906 file, I<or> is a C string which is a decimal number
3907 (the number of following attributes for this file, which could
3908 be C<\"0\">). Then after the first xattr struct are the
3909 zero or more attributes for the first named file.
3910 This repeats for the second and subsequent files.
3912 This call is intended for programs that want to efficiently
3913 list a directory contents without making many round-trips.
3914 See also C<guestfs_lstatlist> for a similarly efficient call
3915 for getting standard stats. Very long directory listings
3916 might cause the protocol message size to be exceeded, causing
3917 this call to fail. The caller must split up such requests
3918 into smaller groups of names.");
3920 ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
3922 "readlink on multiple files",
3924 This call allows you to do a C<readlink> operation
3925 on multiple files, where all files are in the directory C<path>.
3926 C<names> is the list of files from this directory.
3928 On return you get a list of strings, with a one-to-one
3929 correspondence to the C<names> list. Each string is the
3930 value of the symbol link.
3932 If the C<readlink(2)> operation fails on any name, then
3933 the corresponding result string is the empty string C<\"\">.
3934 However the whole operation is completed even if there
3935 were C<readlink(2)> errors, and so you can call this
3936 function with names where you don't know if they are
3937 symbolic links already (albeit slightly less efficient).
3939 This call is intended for programs that want to efficiently
3940 list a directory contents without making many round-trips.
3941 Very long directory listings might cause the protocol
3942 message size to be exceeded, causing
3943 this call to fail. The caller must split up such requests
3944 into smaller groups of names.");
3946 ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
3947 [InitISOFS, Always, TestOutputBuffer (
3948 [["pread"; "/known-4"; "1"; "3"]], "\n");
3949 InitISOFS, Always, TestOutputBuffer (
3950 [["pread"; "/empty"; "0"; "100"]], "")],
3951 "read part of a file",
3953 This command lets you read part of a file. It reads C<count>
3954 bytes of the file, starting at C<offset>, from file C<path>.
3956 This may read fewer bytes than requested. For further details
3957 see the L<pread(2)> system call.");
3959 ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
3960 [InitEmpty, Always, TestRun (
3961 [["part_init"; "/dev/sda"; "gpt"]])],
3962 "create an empty partition table",
3964 This creates an empty partition table on C<device> of one of the
3965 partition types listed below. Usually C<parttype> should be
3966 either C<msdos> or C<gpt> (for large disks).
3968 Initially there are no partitions. Following this, you should
3969 call C<guestfs_part_add> for each partition required.
3971 Possible values for C<parttype> are:
3975 =item B<efi> | B<gpt>
3977 Intel EFI / GPT partition table.
3979 This is recommended for >= 2 TB partitions that will be accessed
3980 from Linux and Intel-based Mac OS X. It also has limited backwards
3981 compatibility with the C<mbr> format.
3983 =item B<mbr> | B<msdos>
3985 The standard PC \"Master Boot Record\" (MBR) format used
3986 by MS-DOS and Windows. This partition type will B<only> work
3987 for device sizes up to 2 TB. For large disks we recommend
3992 Other partition table types that may work but are not
4001 =item B<amiga> | B<rdb>
4003 Amiga \"Rigid Disk Block\" format.
4011 DASD, used on IBM mainframes.
4019 Old Mac partition format. Modern Macs use C<gpt>.
4023 NEC PC-98 format, common in Japan apparently.
4031 ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4032 [InitEmpty, Always, TestRun (
4033 [["part_init"; "/dev/sda"; "mbr"];
4034 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4035 InitEmpty, Always, TestRun (
4036 [["part_init"; "/dev/sda"; "gpt"];
4037 ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4038 ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4039 InitEmpty, Always, TestRun (
4040 [["part_init"; "/dev/sda"; "mbr"];
4041 ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4042 ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4043 ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4044 ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4045 "add a partition to the device",
4047 This command adds a partition to C<device>. If there is no partition
4048 table on the device, call C<guestfs_part_init> first.
4050 The C<prlogex> parameter is the type of partition. Normally you
4051 should pass C<p> or C<primary> here, but MBR partition tables also
4052 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4055 C<startsect> and C<endsect> are the start and end of the partition
4056 in I<sectors>. C<endsect> may be negative, which means it counts
4057 backwards from the end of the disk (C<-1> is the last sector).
4059 Creating a partition which covers the whole disk is not so easy.
4060 Use C<guestfs_part_disk> to do that.");
4062 ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4063 [InitEmpty, Always, TestRun (
4064 [["part_disk"; "/dev/sda"; "mbr"]]);
4065 InitEmpty, Always, TestRun (
4066 [["part_disk"; "/dev/sda"; "gpt"]])],
4067 "partition whole disk with a single primary partition",
4069 This command is simply a combination of C<guestfs_part_init>
4070 followed by C<guestfs_part_add> to create a single primary partition
4071 covering the whole disk.
4073 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4074 but other possible values are described in C<guestfs_part_init>.");
4076 ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4077 [InitEmpty, Always, TestRun (
4078 [["part_disk"; "/dev/sda"; "mbr"];
4079 ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4080 "make a partition bootable",
4082 This sets the bootable flag on partition numbered C<partnum> on
4083 device C<device>. Note that partitions are numbered from 1.
4085 The bootable flag is used by some PC BIOSes to determine which
4086 partition to boot from. It is by no means universally recognized,
4087 and in any case if your operating system installed a boot
4088 sector on the device itself, then that takes precedence.");
4090 ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4091 [InitEmpty, Always, TestRun (
4092 [["part_disk"; "/dev/sda"; "gpt"];
4093 ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4094 "set partition name",
4096 This sets the partition name on partition numbered C<partnum> on
4097 device C<device>. Note that partitions are numbered from 1.
4099 The partition name can only be set on certain types of partition
4100 table. This works on C<gpt> but not on C<mbr> partitions.");
4102 ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4103 [], (* XXX Add a regression test for this. *)
4104 "list partitions on a device",
4106 This command parses the partition table on C<device> and
4107 returns the list of partitions found.
4109 The fields in the returned structure are:
4115 Partition number, counting from 1.
4119 Start of the partition I<in bytes>. To get sectors you have to
4120 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4124 End of the partition in bytes.
4128 Size of the partition in bytes.
4132 ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4133 [InitEmpty, Always, TestOutput (
4134 [["part_disk"; "/dev/sda"; "gpt"];
4135 ["part_get_parttype"; "/dev/sda"]], "gpt")],
4136 "get the partition table type",
4138 This command examines the partition table on C<device> and
4139 returns the partition table type (format) being used.
4141 Common return values include: C<msdos> (a DOS/Windows style MBR
4142 partition table), C<gpt> (a GPT/EFI-style partition table). Other
4143 values are possible, although unusual. See C<guestfs_part_init>
4146 ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [],
4147 [InitBasicFS, Always, TestOutputBuffer (
4148 [["fill"; "0x63"; "10"; "/test"];
4149 ["read_file"; "/test"]], "cccccccccc")],
4150 "fill a file with octets",
4152 This command creates a new file called C<path>. The initial
4153 content of the file is C<len> octets of C<c>, where C<c>
4154 must be a number in the range C<[0..255]>.
4156 To fill a file with zero bytes (sparsely), it is
4157 much more efficient to use C<guestfs_truncate_size>.");
4159 ("available", (RErr, [StringList "groups"]), 216, [],
4160 [InitNone, Always, TestRun [["available"; ""]]],
4161 "test availability of some parts of the API",
4163 This command is used to check the availability of some
4164 groups of functionality in the appliance, which not all builds of
4165 the libguestfs appliance will be able to provide.
4167 The libguestfs groups, and the functions that those
4168 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4170 The argument C<groups> is a list of group names, eg:
4171 C<[\"inotify\", \"augeas\"]> would check for the availability of
4172 the Linux inotify functions and Augeas (configuration file
4175 The command returns no error if I<all> requested groups are available.
4177 It fails with an error if one or more of the requested
4178 groups is unavailable in the appliance.
4180 If an unknown group name is included in the
4181 list of groups then an error is always returned.
4189 You must call C<guestfs_launch> before calling this function.
4191 The reason is because we don't know what groups are
4192 supported by the appliance/daemon until it is running and can
4197 If a group of functions is available, this does not necessarily
4198 mean that they will work. You still have to check for errors
4199 when calling individual API functions even if they are
4204 It is usually the job of distro packagers to build
4205 complete functionality into the libguestfs appliance.
4206 Upstream libguestfs, if built from source with all
4207 requirements satisfied, will support everything.
4211 This call was added in version C<1.0.80>. In previous
4212 versions of libguestfs all you could do would be to speculatively
4213 execute a command to find out if the daemon implemented it.
4214 See also C<guestfs_version>.
4218 ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4219 [InitBasicFS, Always, TestOutputBuffer (
4220 [["write_file"; "/src"; "hello, world"; "0"];
4221 ["dd"; "/src"; "/dest"];
4222 ["read_file"; "/dest"]], "hello, world")],
4223 "copy from source to destination using dd",
4225 This command copies from one source device or file C<src>
4226 to another destination device or file C<dest>. Normally you
4227 would use this to copy to or from a device or partition, for
4228 example to duplicate a filesystem.
4230 If the destination is a device, it must be as large or larger
4231 than the source file or device, otherwise the copy will fail.
4232 This command cannot do partial copies.");
4234 ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4235 [InitBasicFS, Always, TestOutputInt (
4236 [["write_file"; "/file"; "hello, world"; "0"];
4237 ["filesize"; "/file"]], 12)],
4238 "return the size of the file in bytes",
4240 This command returns the size of C<file> in bytes.
4242 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4243 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4244 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4246 ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4247 [InitBasicFSonLVM, Always, TestOutputList (
4248 [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4249 ["lvs"]], ["/dev/VG/LV2"])],
4250 "rename an LVM logical volume",
4252 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4254 ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4255 [InitBasicFSonLVM, Always, TestOutputList (
4257 ["vg_activate"; "false"; "VG"];
4258 ["vgrename"; "VG"; "VG2"];
4259 ["vg_activate"; "true"; "VG2"];
4260 ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4261 ["vgs"]], ["VG2"])],
4262 "rename an LVM volume group",
4264 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4266 ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4267 [InitISOFS, Always, TestOutputBuffer (
4268 [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4269 "list the contents of a single file in an initrd",
4271 This command unpacks the file C<filename> from the initrd file
4272 called C<initrdpath>. The filename must be given I<without> the
4273 initial C</> character.
4275 For example, in guestfish you could use the following command
4276 to examine the boot script (usually called C</init>)
4277 contained in a Linux initrd or initramfs image:
4279 initrd-cat /boot/initrd-<version>.img init
4281 See also C<guestfs_initrd_list>.");
4285 let all_functions = non_daemon_functions @ daemon_functions
4287 (* In some places we want the functions to be displayed sorted
4288 * alphabetically, so this is useful:
4290 let all_functions_sorted =
4291 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
4292 compare n1 n2) all_functions
4294 (* Field types for structures. *)
4296 | FChar (* C 'char' (really, a 7 bit byte). *)
4297 | FString (* nul-terminated ASCII string, NOT NULL. *)
4298 | FBuffer (* opaque buffer of bytes, (char *, int) pair *)
4303 | FBytes (* Any int measure that counts bytes. *)
4304 | FUUID (* 32 bytes long, NOT nul-terminated. *)
4305 | FOptPercent (* [0..100], or -1 meaning "not present". *)
4307 (* Because we generate extra parsing code for LVM command line tools,
4308 * we have to pull out the LVM columns separately here.
4318 "pv_attr", FString (* XXX *);
4319 "pv_pe_count", FInt64;
4320 "pv_pe_alloc_count", FInt64;
4323 "pv_mda_count", FInt64;
4324 "pv_mda_free", FBytes;
4325 (* Not in Fedora 10:
4326 "pv_mda_size", FBytes;
4333 "vg_attr", FString (* XXX *);
4336 "vg_sysid", FString;
4337 "vg_extent_size", FBytes;
4338 "vg_extent_count", FInt64;
4339 "vg_free_count", FInt64;
4344 "snap_count", FInt64;
4347 "vg_mda_count", FInt64;
4348 "vg_mda_free", FBytes;
4349 (* Not in Fedora 10:
4350 "vg_mda_size", FBytes;
4356 "lv_attr", FString (* XXX *);
4359 "lv_kernel_major", FInt64;
4360 "lv_kernel_minor", FInt64;
4362 "seg_count", FInt64;
4364 "snap_percent", FOptPercent;
4365 "copy_percent", FOptPercent;
4368 "mirror_log", FString;
4372 (* Names and fields in all structures (in RStruct and RStructList)
4376 (* The old RIntBool return type, only ever used for aug_defnode. Do
4377 * not use this struct in any new code.
4380 "i", FInt32; (* for historical compatibility *)
4381 "b", FInt32; (* for historical compatibility *)
4384 (* LVM PVs, VGs, LVs. *)
4385 "lvm_pv", lvm_pv_cols;
4386 "lvm_vg", lvm_vg_cols;
4387 "lvm_lv", lvm_lv_cols;
4389 (* Column names and types from stat structures.
4390 * NB. Can't use things like 'st_atime' because glibc header files
4391 * define some of these as macros. Ugh.
4422 (* Column names in dirent structure. *)
4425 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
4430 (* Version numbers. *)
4438 (* Extended attribute. *)
4440 "attrname", FString;
4444 (* Inotify events. *)
4448 "in_cookie", FUInt32;
4452 (* Partition table entry. *)
4455 "part_start", FBytes;
4457 "part_size", FBytes;
4459 ] (* end of structs *)
4461 (* Ugh, Java has to be different ..
4462 * These names are also used by the Haskell bindings.
4464 let java_structs = [
4465 "int_bool", "IntBool";
4470 "statvfs", "StatVFS";
4472 "version", "Version";
4474 "inotify_event", "INotifyEvent";
4475 "partition", "Partition";
4478 (* What structs are actually returned. *)
4479 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
4481 (* Returns a list of RStruct/RStructList structs that are returned
4482 * by any function. Each element of returned list is a pair:
4484 * (structname, RStructOnly)
4485 * == there exists function which returns RStruct (_, structname)
4486 * (structname, RStructListOnly)
4487 * == there exists function which returns RStructList (_, structname)
4488 * (structname, RStructAndList)
4489 * == there are functions returning both RStruct (_, structname)
4490 * and RStructList (_, structname)
4492 let rstructs_used_by functions =
4493 (* ||| is a "logical OR" for rstructs_used_t *)
4497 | _, RStructAndList -> RStructAndList
4498 | RStructOnly, RStructListOnly
4499 | RStructListOnly, RStructOnly -> RStructAndList
4500 | RStructOnly, RStructOnly -> RStructOnly
4501 | RStructListOnly, RStructListOnly -> RStructListOnly
4504 let h = Hashtbl.create 13 in
4506 (* if elem->oldv exists, update entry using ||| operator,
4507 * else just add elem->newv to the hash
4509 let update elem newv =
4510 try let oldv = Hashtbl.find h elem in
4511 Hashtbl.replace h elem (newv ||| oldv)
4512 with Not_found -> Hashtbl.add h elem newv
4516 fun (_, style, _, _, _, _, _) ->
4517 match fst style with
4518 | RStruct (_, structname) -> update structname RStructOnly
4519 | RStructList (_, structname) -> update structname RStructListOnly
4523 (* return key->values as a list of (key,value) *)
4524 Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
4526 (* Used for testing language bindings. *)
4528 | CallString of string
4529 | CallOptString of string option
4530 | CallStringList of string list
4532 | CallInt64 of int64
4535 (* Used to memoize the result of pod2text. *)
4536 let pod2text_memo_filename = "src/.pod2text.data"
4537 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
4539 let chan = open_in pod2text_memo_filename in
4540 let v = input_value chan in
4544 _ -> Hashtbl.create 13
4545 let pod2text_memo_updated () =
4546 let chan = open_out pod2text_memo_filename in
4547 output_value chan pod2text_memo;
4550 (* Useful functions.
4551 * Note we don't want to use any external OCaml libraries which
4552 * makes this a bit harder than it should be.
4554 module StringMap = Map.Make (String)
4556 let failwithf fs = ksprintf failwith fs
4558 let unique = let i = ref 0 in fun () -> incr i; !i
4560 let replace_char s c1 c2 =
4561 let s2 = String.copy s in
4562 let r = ref false in
4563 for i = 0 to String.length s2 - 1 do
4564 if String.unsafe_get s2 i = c1 then (
4565 String.unsafe_set s2 i c2;
4569 if not !r then s else s2
4573 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
4575 let triml ?(test = isspace) str =
4577 let n = ref (String.length str) in
4578 while !n > 0 && test str.[!i]; do
4583 else String.sub str !i !n
4585 let trimr ?(test = isspace) str =
4586 let n = ref (String.length str) in
4587 while !n > 0 && test str.[!n-1]; do
4590 if !n = String.length str then str
4591 else String.sub str 0 !n
4593 let trim ?(test = isspace) str =
4594 trimr ~test (triml ~test str)
4596 let rec find s sub =
4597 let len = String.length s in
4598 let sublen = String.length sub in
4600 if i <= len-sublen then (
4602 if j < sublen then (
4603 if s.[i+j] = sub.[j] then loop2 (j+1)
4609 if r = -1 then loop (i+1) else r
4615 let rec replace_str s s1 s2 =
4616 let len = String.length s in
4617 let sublen = String.length s1 in
4618 let i = find s s1 in
4621 let s' = String.sub s 0 i in
4622 let s'' = String.sub s (i+sublen) (len-i-sublen) in
4623 s' ^ s2 ^ replace_str s'' s1 s2
4626 let rec string_split sep str =
4627 let len = String.length str in
4628 let seplen = String.length sep in
4629 let i = find str sep in
4630 if i = -1 then [str]
4632 let s' = String.sub str 0 i in
4633 let s'' = String.sub str (i+seplen) (len-i-seplen) in
4634 s' :: string_split sep s''
4637 let files_equal n1 n2 =
4638 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
4639 match Sys.command cmd with
4642 | i -> failwithf "%s: failed with error code %d" cmd i
4644 let rec filter_map f = function
4648 | Some y -> y :: filter_map f xs
4649 | None -> filter_map f xs
4651 let rec find_map f = function
4652 | [] -> raise Not_found
4656 | None -> find_map f xs
4659 let rec loop i = function
4661 | x :: xs -> f i x; loop (i+1) xs
4666 let rec loop i = function
4668 | x :: xs -> let r = f i x in r :: loop (i+1) xs
4672 let count_chars c str =
4673 let count = ref 0 in
4674 for i = 0 to String.length str - 1 do
4675 if c = String.unsafe_get str i then incr count
4679 let name_of_argt = function
4680 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
4681 | StringList n | DeviceList n | Bool n | Int n | Int64 n
4682 | FileIn n | FileOut n -> n
4684 let java_name_of_struct typ =
4685 try List.assoc typ java_structs
4688 "java_name_of_struct: no java_structs entry corresponding to %s" typ
4690 let cols_of_struct typ =
4691 try List.assoc typ structs
4693 failwithf "cols_of_struct: unknown struct %s" typ
4695 let seq_of_test = function
4696 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
4697 | TestOutputListOfDevices (s, _)
4698 | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
4699 | TestOutputTrue s | TestOutputFalse s
4700 | TestOutputLength (s, _) | TestOutputBuffer (s, _)
4701 | TestOutputStruct (s, _)
4702 | TestLastFail s -> s
4704 (* Handling for function flags. *)
4705 let protocol_limit_warning =
4706 "Because of the message protocol, there is a transfer limit
4707 of somewhere between 2MB and 4MB. To transfer large files, see
4708 L<guestfs(3)/UPLOADING>."
4710 let danger_will_robinson =
4711 "B<This command is dangerous. Without careful use you
4712 can easily destroy all your data>."
4714 let deprecation_notice flags =
4717 find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
4719 sprintf "This function is deprecated.
4720 In new code, use the C<%s> call instead.
4722 Deprecated functions will not be removed from the API, but the
4723 fact that they are deprecated indicates that there are problems
4724 with correct use of these functions." alt in
4729 (* Create list of optional groups. *)
4731 let h = Hashtbl.create 13 in
4733 fun (name, _, _, flags, _, _, _) ->
4737 let names = try Hashtbl.find h group with Not_found -> [] in
4738 Hashtbl.replace h group (name :: names)
4742 let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
4745 fun group -> group, List.sort compare (Hashtbl.find h group)
4747 List.sort (fun x y -> compare (fst x) (fst y)) groups
4749 (* Check function names etc. for consistency. *)
4750 let check_functions () =
4751 let contains_uppercase str =
4752 let len = String.length str in
4754 if i >= len then false
4757 if c >= 'A' && c <= 'Z' then true
4764 (* Check function names. *)
4766 fun (name, _, _, _, _, _, _) ->
4767 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
4768 failwithf "function name %s does not need 'guestfs' prefix" name;
4770 failwithf "function name is empty";
4771 if name.[0] < 'a' || name.[0] > 'z' then
4772 failwithf "function name %s must start with lowercase a-z" name;
4773 if String.contains name '-' then
4774 failwithf "function name %s should not contain '-', use '_' instead."
4778 (* Check function parameter/return names. *)
4780 fun (name, style, _, _, _, _, _) ->
4781 let check_arg_ret_name n =
4782 if contains_uppercase n then
4783 failwithf "%s param/ret %s should not contain uppercase chars"
4785 if String.contains n '-' || String.contains n '_' then
4786 failwithf "%s param/ret %s should not contain '-' or '_'"
4789 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;
4790 if n = "int" || n = "char" || n = "short" || n = "long" then
4791 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
4792 if n = "i" || n = "n" then
4793 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
4794 if n = "argv" || n = "args" then
4795 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
4797 (* List Haskell, OCaml and C keywords here.
4798 * http://www.haskell.org/haskellwiki/Keywords
4799 * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
4800 * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
4801 * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
4802 * |perl -pe 's/(.+)/"$1";/'|fmt -70
4803 * Omitting _-containing words, since they're handled above.
4804 * Omitting the OCaml reserved word, "val", is ok,
4805 * and saves us from renaming several parameters.
4808 "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
4809 "char"; "class"; "const"; "constraint"; "continue"; "data";
4810 "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
4811 "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
4812 "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
4813 "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
4814 "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
4816 "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
4817 "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
4818 "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
4819 "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
4820 "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
4821 "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
4822 "volatile"; "when"; "where"; "while";
4824 if List.mem n reserved then
4825 failwithf "%s has param/ret using reserved word %s" name n;
4828 (match fst style with
4830 | RInt n | RInt64 n | RBool n
4831 | RConstString n | RConstOptString n | RString n
4832 | RStringList n | RStruct (n, _) | RStructList (n, _)
4833 | RHashtable n | RBufferOut n ->
4834 check_arg_ret_name n
4836 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
4839 (* Check short descriptions. *)
4841 fun (name, _, _, _, _, shortdesc, _) ->
4842 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
4843 failwithf "short description of %s should begin with lowercase." name;
4844 let c = shortdesc.[String.length shortdesc-1] in
4845 if c = '\n' || c = '.' then
4846 failwithf "short description of %s should not end with . or \\n." name
4849 (* Check long dscriptions. *)
4851 fun (name, _, _, _, _, _, longdesc) ->
4852 if longdesc.[String.length longdesc-1] = '\n' then
4853 failwithf "long description of %s should not end with \\n." name
4856 (* Check proc_nrs. *)
4858 fun (name, _, proc_nr, _, _, _, _) ->
4859 if proc_nr <= 0 then
4860 failwithf "daemon function %s should have proc_nr > 0" name
4864 fun (name, _, proc_nr, _, _, _, _) ->
4865 if proc_nr <> -1 then
4866 failwithf "non-daemon function %s should have proc_nr -1" name
4867 ) non_daemon_functions;
4870 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
4873 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
4874 let rec loop = function
4877 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
4879 | (name1,nr1) :: (name2,nr2) :: _ ->
4880 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
4888 (* Ignore functions that have no tests. We generate a
4889 * warning when the user does 'make check' instead.
4891 | name, _, _, _, [], _, _ -> ()
4892 | name, _, _, _, tests, _, _ ->
4896 match seq_of_test test with
4898 failwithf "%s has a test containing an empty sequence" name
4899 | cmds -> List.map List.hd cmds
4901 let funcs = List.flatten funcs in
4903 let tested = List.mem name funcs in
4906 failwithf "function %s has tests but does not test itself" name
4909 (* 'pr' prints to the current output file. *)
4910 let chan = ref Pervasives.stdout
4915 let i = count_chars '\n' str in
4916 lines := !lines + i;
4917 output_string !chan str
4920 let copyright_years =
4921 let this_year = 1900 + (localtime (time ())).tm_year in
4922 if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
4924 (* Generate a header block in a number of standard styles. *)
4925 type comment_style =
4926 CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
4927 type license = GPLv2plus | LGPLv2plus
4929 let generate_header ?(extra_inputs = []) comment license =
4930 let inputs = "src/generator.ml" :: extra_inputs in
4931 let c = match comment with
4932 | CStyle -> pr "/* "; " *"
4933 | CPlusPlusStyle -> pr "// "; "//"
4934 | HashStyle -> pr "# "; "#"
4935 | OCamlStyle -> pr "(* "; " *"
4936 | HaskellStyle -> pr "{- "; " " in
4937 pr "libguestfs generated file\n";
4938 pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
4939 List.iter (pr "%s %s\n" c) inputs;
4940 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
4942 pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
4946 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
4947 pr "%s it under the terms of the GNU General Public License as published by\n" c;
4948 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
4949 pr "%s (at your option) any later version.\n" c;
4951 pr "%s This program is distributed in the hope that it will be useful,\n" c;
4952 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
4953 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
4954 pr "%s GNU General Public License for more details.\n" c;
4956 pr "%s You should have received a copy of the GNU General Public License along\n" c;
4957 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
4958 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
4961 pr "%s This library is free software; you can redistribute it and/or\n" c;
4962 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
4963 pr "%s License as published by the Free Software Foundation; either\n" c;
4964 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
4966 pr "%s This library is distributed in the hope that it will be useful,\n" c;
4967 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
4968 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
4969 pr "%s Lesser General Public License for more details.\n" c;
4971 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
4972 pr "%s License along with this library; if not, write to the Free Software\n" c;
4973 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
4976 | CStyle -> pr " */\n"
4979 | OCamlStyle -> pr " *)\n"
4980 | HaskellStyle -> pr "-}\n"
4984 (* Start of main code generation functions below this line. *)
4986 (* Generate the pod documentation for the C API. *)
4987 let rec generate_actions_pod () =
4989 fun (shortname, style, _, flags, _, _, longdesc) ->
4990 if not (List.mem NotInDocs flags) then (
4991 let name = "guestfs_" ^ shortname in
4992 pr "=head2 %s\n\n" name;
4994 generate_prototype ~extern:false ~handle:"handle" name style;
4996 pr "%s\n\n" longdesc;
4997 (match fst style with
4999 pr "This function returns 0 on success or -1 on error.\n\n"
5001 pr "On error this function returns -1.\n\n"
5003 pr "On error this function returns -1.\n\n"
5005 pr "This function returns a C truth value on success or -1 on error.\n\n"
5007 pr "This function returns a string, or NULL on error.
5008 The string is owned by the guest handle and must I<not> be freed.\n\n"
5009 | RConstOptString _ ->
5010 pr "This function returns a string which may be NULL.
5011 There is way to return an error from this function.
5012 The string is owned by the guest handle and must I<not> be freed.\n\n"
5014 pr "This function returns a string, or NULL on error.
5015 I<The caller must free the returned string after use>.\n\n"
5017 pr "This function returns a NULL-terminated array of strings
5018 (like L<environ(3)>), or NULL if there was an error.
5019 I<The caller must free the strings and the array after use>.\n\n"
5020 | RStruct (_, typ) ->
5021 pr "This function returns a C<struct guestfs_%s *>,
5022 or NULL if there was an error.
5023 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
5024 | RStructList (_, typ) ->
5025 pr "This function returns a C<struct guestfs_%s_list *>
5026 (see E<lt>guestfs-structs.hE<gt>),
5027 or NULL if there was an error.
5028 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
5030 pr "This function returns a NULL-terminated array of
5031 strings, or NULL if there was an error.
5032 The array of strings will always have length C<2n+1>, where
5033 C<n> keys and values alternate, followed by the trailing NULL entry.
5034 I<The caller must free the strings and the array after use>.\n\n"
5036 pr "This function returns a buffer, or NULL on error.
5037 The size of the returned buffer is written to C<*size_r>.
5038 I<The caller must free the returned buffer after use>.\n\n"
5040 if List.mem ProtocolLimitWarning flags then
5041 pr "%s\n\n" protocol_limit_warning;
5042 if List.mem DangerWillRobinson flags then
5043 pr "%s\n\n" danger_will_robinson;
5044 match deprecation_notice flags with
5046 | Some txt -> pr "%s\n\n" txt
5048 ) all_functions_sorted
5050 and generate_structs_pod () =
5051 (* Structs documentation. *)
5054 pr "=head2 guestfs_%s\n" typ;
5056 pr " struct guestfs_%s {\n" typ;
5059 | name, FChar -> pr " char %s;\n" name
5060 | name, FUInt32 -> pr " uint32_t %s;\n" name
5061 | name, FInt32 -> pr " int32_t %s;\n" name
5062 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
5063 | name, FInt64 -> pr " int64_t %s;\n" name
5064 | name, FString -> pr " char *%s;\n" name
5066 pr " /* The next two fields describe a byte array. */\n";
5067 pr " uint32_t %s_len;\n" name;
5068 pr " char *%s;\n" name
5070 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
5071 pr " char %s[32];\n" name
5072 | name, FOptPercent ->
5073 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
5074 pr " float %s;\n" name
5078 pr " struct guestfs_%s_list {\n" typ;
5079 pr " uint32_t len; /* Number of elements in list. */\n";
5080 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
5083 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
5084 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
5089 and generate_availability_pod () =
5090 (* Availability documentation. *)
5094 fun (group, functions) ->
5095 pr "=item B<%s>\n" group;
5097 pr "The following functions:\n";
5098 List.iter (pr "L</guestfs_%s>\n") functions;
5104 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
5105 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
5107 * We have to use an underscore instead of a dash because otherwise
5108 * rpcgen generates incorrect code.
5110 * This header is NOT exported to clients, but see also generate_structs_h.
5112 and generate_xdr () =
5113 generate_header CStyle LGPLv2plus;
5115 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
5116 pr "typedef string str<>;\n";
5119 (* Internal structures. *)
5123 pr "struct guestfs_int_%s {\n" typ;
5125 | name, FChar -> pr " char %s;\n" name
5126 | name, FString -> pr " string %s<>;\n" name
5127 | name, FBuffer -> pr " opaque %s<>;\n" name
5128 | name, FUUID -> pr " opaque %s[32];\n" name
5129 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
5130 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
5131 | name, FOptPercent -> pr " float %s;\n" name
5135 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
5140 fun (shortname, style, _, _, _, _, _) ->
5141 let name = "guestfs_" ^ shortname in
5143 (match snd style with
5146 pr "struct %s_args {\n" name;
5149 | Pathname n | Device n | Dev_or_Path n | String n ->
5150 pr " string %s<>;\n" n
5151 | OptString n -> pr " str *%s;\n" n
5152 | StringList n | DeviceList n -> pr " str %s<>;\n" n
5153 | Bool n -> pr " bool %s;\n" n
5154 | Int n -> pr " int %s;\n" n
5155 | Int64 n -> pr " hyper %s;\n" n
5156 | FileIn _ | FileOut _ -> ()
5160 (match fst style with
5163 pr "struct %s_ret {\n" name;
5167 pr "struct %s_ret {\n" name;
5168 pr " hyper %s;\n" n;
5171 pr "struct %s_ret {\n" name;
5174 | RConstString _ | RConstOptString _ ->
5175 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5177 pr "struct %s_ret {\n" name;
5178 pr " string %s<>;\n" n;
5181 pr "struct %s_ret {\n" name;
5182 pr " str %s<>;\n" n;
5184 | RStruct (n, typ) ->
5185 pr "struct %s_ret {\n" name;
5186 pr " guestfs_int_%s %s;\n" typ n;
5188 | RStructList (n, typ) ->
5189 pr "struct %s_ret {\n" name;
5190 pr " guestfs_int_%s_list %s;\n" typ n;
5193 pr "struct %s_ret {\n" name;
5194 pr " str %s<>;\n" n;
5197 pr "struct %s_ret {\n" name;
5198 pr " opaque %s<>;\n" n;
5203 (* Table of procedure numbers. *)
5204 pr "enum guestfs_procedure {\n";
5206 fun (shortname, _, proc_nr, _, _, _, _) ->
5207 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
5209 pr " GUESTFS_PROC_NR_PROCS\n";
5213 (* Having to choose a maximum message size is annoying for several
5214 * reasons (it limits what we can do in the API), but it (a) makes
5215 * the protocol a lot simpler, and (b) provides a bound on the size
5216 * of the daemon which operates in limited memory space.
5218 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
5221 (* Message header, etc. *)
5223 /* The communication protocol is now documented in the guestfs(3)
5227 const GUESTFS_PROGRAM = 0x2000F5F5;
5228 const GUESTFS_PROTOCOL_VERSION = 1;
5230 /* These constants must be larger than any possible message length. */
5231 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
5232 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
5234 enum guestfs_message_direction {
5235 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
5236 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
5239 enum guestfs_message_status {
5240 GUESTFS_STATUS_OK = 0,
5241 GUESTFS_STATUS_ERROR = 1
5244 const GUESTFS_ERROR_LEN = 256;
5246 struct guestfs_message_error {
5247 string error_message<GUESTFS_ERROR_LEN>;
5250 struct guestfs_message_header {
5251 unsigned prog; /* GUESTFS_PROGRAM */
5252 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
5253 guestfs_procedure proc; /* GUESTFS_PROC_x */
5254 guestfs_message_direction direction;
5255 unsigned serial; /* message serial number */
5256 guestfs_message_status status;
5259 const GUESTFS_MAX_CHUNK_SIZE = 8192;
5261 struct guestfs_chunk {
5262 int cancel; /* if non-zero, transfer is cancelled */
5263 /* data size is 0 bytes if the transfer has finished successfully */
5264 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
5268 (* Generate the guestfs-structs.h file. *)
5269 and generate_structs_h () =
5270 generate_header CStyle LGPLv2plus;
5272 (* This is a public exported header file containing various
5273 * structures. The structures are carefully written to have
5274 * exactly the same in-memory format as the XDR structures that
5275 * we use on the wire to the daemon. The reason for creating
5276 * copies of these structures here is just so we don't have to
5277 * export the whole of guestfs_protocol.h (which includes much
5278 * unrelated and XDR-dependent stuff that we don't want to be
5279 * public, or required by clients).
5281 * To reiterate, we will pass these structures to and from the
5282 * client with a simple assignment or memcpy, so the format
5283 * must be identical to what rpcgen / the RFC defines.
5286 (* Public structures. *)
5289 pr "struct guestfs_%s {\n" typ;
5292 | name, FChar -> pr " char %s;\n" name
5293 | name, FString -> pr " char *%s;\n" name
5295 pr " uint32_t %s_len;\n" name;
5296 pr " char *%s;\n" name
5297 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
5298 | name, FUInt32 -> pr " uint32_t %s;\n" name
5299 | name, FInt32 -> pr " int32_t %s;\n" name
5300 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
5301 | name, FInt64 -> pr " int64_t %s;\n" name
5302 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
5306 pr "struct guestfs_%s_list {\n" typ;
5307 pr " uint32_t len;\n";
5308 pr " struct guestfs_%s *val;\n" typ;
5311 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
5312 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
5316 (* Generate the guestfs-actions.h file. *)
5317 and generate_actions_h () =
5318 generate_header CStyle LGPLv2plus;
5320 fun (shortname, style, _, _, _, _, _) ->
5321 let name = "guestfs_" ^ shortname in
5322 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
5326 (* Generate the guestfs-internal-actions.h file. *)
5327 and generate_internal_actions_h () =
5328 generate_header CStyle LGPLv2plus;
5330 fun (shortname, style, _, _, _, _, _) ->
5331 let name = "guestfs__" ^ shortname in
5332 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
5334 ) non_daemon_functions
5336 (* Generate the client-side dispatch stubs. *)
5337 and generate_client_actions () =
5338 generate_header CStyle LGPLv2plus;
5344 #include <inttypes.h>
5346 #include \"guestfs.h\"
5347 #include \"guestfs-internal.h\"
5348 #include \"guestfs-internal-actions.h\"
5349 #include \"guestfs_protocol.h\"
5351 #define error guestfs_error
5352 //#define perrorf guestfs_perrorf
5353 #define safe_malloc guestfs_safe_malloc
5354 #define safe_realloc guestfs_safe_realloc
5355 //#define safe_strdup guestfs_safe_strdup
5356 #define safe_memdup guestfs_safe_memdup
5358 /* Check the return message from a call for validity. */
5360 check_reply_header (guestfs_h *g,
5361 const struct guestfs_message_header *hdr,
5362 unsigned int proc_nr, unsigned int serial)
5364 if (hdr->prog != GUESTFS_PROGRAM) {
5365 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
5368 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
5369 error (g, \"wrong protocol version (%%d/%%d)\",
5370 hdr->vers, GUESTFS_PROTOCOL_VERSION);
5373 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
5374 error (g, \"unexpected message direction (%%d/%%d)\",
5375 hdr->direction, GUESTFS_DIRECTION_REPLY);
5378 if (hdr->proc != proc_nr) {
5379 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
5382 if (hdr->serial != serial) {
5383 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
5390 /* Check we are in the right state to run a high-level action. */
5392 check_state (guestfs_h *g, const char *caller)
5394 if (!guestfs__is_ready (g)) {
5395 if (guestfs__is_config (g) || guestfs__is_launching (g))
5396 error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
5399 error (g, \"%%s called from the wrong state, %%d != READY\",
5400 caller, guestfs__get_state (g));
5408 (* Generate code to generate guestfish call traces. *)
5409 let trace_call shortname style =
5410 pr " if (guestfs__get_trace (g)) {\n";
5413 List.exists (function
5414 | StringList _ | DeviceList _ -> true
5415 | _ -> false) (snd style) in
5421 pr " printf (\"%s\");\n" shortname;
5424 | String n (* strings *)
5430 (* guestfish doesn't support string escaping, so neither do we *)
5431 pr " printf (\" \\\"%%s\\\"\", %s);\n" n
5432 | OptString n -> (* string option *)
5433 pr " if (%s) printf (\" \\\"%%s\\\"\", %s);\n" n n;
5434 pr " else printf (\" null\");\n"
5436 | DeviceList n -> (* string list *)
5437 pr " putchar (' ');\n";
5438 pr " putchar ('\"');\n";
5439 pr " for (i = 0; %s[i]; ++i) {\n" n;
5440 pr " if (i > 0) putchar (' ');\n";
5441 pr " fputs (%s[i], stdout);\n" n;
5443 pr " putchar ('\"');\n";
5444 | Bool n -> (* boolean *)
5445 pr " fputs (%s ? \" true\" : \" false\", stdout);\n" n
5446 | Int n -> (* int *)
5447 pr " printf (\" %%d\", %s);\n" n
5449 pr " printf (\" %%\" PRIi64, %s);\n" n
5451 pr " putchar ('\\n');\n";
5456 (* For non-daemon functions, generate a wrapper around each function. *)
5458 fun (shortname, style, _, _, _, _, _) ->
5459 let name = "guestfs_" ^ shortname in
5461 generate_prototype ~extern:false ~semicolon:false ~newline:true
5462 ~handle:"g" name style;
5464 trace_call shortname style;
5465 pr " return guestfs__%s " shortname;
5466 generate_c_call_args ~handle:"g" style;
5470 ) non_daemon_functions;
5472 (* Client-side stubs for each function. *)
5474 fun (shortname, style, _, _, _, _, _) ->
5475 let name = "guestfs_" ^ shortname in
5477 (* Generate the action stub. *)
5478 generate_prototype ~extern:false ~semicolon:false ~newline:true
5479 ~handle:"g" name style;
5482 match fst style with
5483 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
5484 | RConstString _ | RConstOptString _ ->
5485 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5486 | RString _ | RStringList _
5487 | RStruct _ | RStructList _
5488 | RHashtable _ | RBufferOut _ ->
5493 (match snd style with
5495 | _ -> pr " struct %s_args args;\n" name
5498 pr " guestfs_message_header hdr;\n";
5499 pr " guestfs_message_error err;\n";
5501 match fst style with
5503 | RConstString _ | RConstOptString _ ->
5504 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5506 | RBool _ | RString _ | RStringList _
5507 | RStruct _ | RStructList _
5508 | RHashtable _ | RBufferOut _ ->
5509 pr " struct %s_ret ret;\n" name;
5512 pr " int serial;\n";
5515 trace_call shortname style;
5516 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
5517 pr " guestfs___set_busy (g);\n";
5520 (* Send the main header and arguments. *)
5521 (match snd style with
5523 pr " serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
5524 (String.uppercase shortname)
5528 | Pathname n | Device n | Dev_or_Path n | String n ->
5529 pr " args.%s = (char *) %s;\n" n n
5531 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
5532 | StringList n | DeviceList n ->
5533 pr " args.%s.%s_val = (char **) %s;\n" n n n;
5534 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
5536 pr " args.%s = %s;\n" n n
5538 pr " args.%s = %s;\n" n n
5540 pr " args.%s = %s;\n" n n
5541 | FileIn _ | FileOut _ -> ()
5543 pr " serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
5544 (String.uppercase shortname);
5545 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
5548 pr " if (serial == -1) {\n";
5549 pr " guestfs___end_busy (g);\n";
5550 pr " return %s;\n" error_code;
5554 (* Send any additional files (FileIn) requested. *)
5555 let need_read_reply_label = ref false in
5559 pr " r = guestfs___send_file (g, %s);\n" n;
5560 pr " if (r == -1) {\n";
5561 pr " guestfs___end_busy (g);\n";
5562 pr " return %s;\n" error_code;
5564 pr " if (r == -2) /* daemon cancelled */\n";
5565 pr " goto read_reply;\n";
5566 need_read_reply_label := true;
5571 (* Wait for the reply from the remote end. *)
5572 if !need_read_reply_label then pr " read_reply:\n";
5573 pr " memset (&hdr, 0, sizeof hdr);\n";
5574 pr " memset (&err, 0, sizeof err);\n";
5575 if has_ret then pr " memset (&ret, 0, sizeof ret);\n";
5577 pr " r = guestfs___recv (g, \"%s\", &hdr, &err,\n " shortname;
5581 pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
5584 pr " if (r == -1) {\n";
5585 pr " guestfs___end_busy (g);\n";
5586 pr " return %s;\n" error_code;
5590 pr " if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
5591 (String.uppercase shortname);
5592 pr " guestfs___end_busy (g);\n";
5593 pr " return %s;\n" error_code;
5597 pr " if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
5598 pr " error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
5599 pr " free (err.error_message);\n";
5600 pr " guestfs___end_busy (g);\n";
5601 pr " return %s;\n" error_code;
5605 (* Expecting to receive further files (FileOut)? *)
5609 pr " if (guestfs___recv_file (g, %s) == -1) {\n" n;
5610 pr " guestfs___end_busy (g);\n";
5611 pr " return %s;\n" error_code;
5617 pr " guestfs___end_busy (g);\n";
5619 (match fst style with
5620 | RErr -> pr " return 0;\n"
5621 | RInt n | RInt64 n | RBool n ->
5622 pr " return ret.%s;\n" n
5623 | RConstString _ | RConstOptString _ ->
5624 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5626 pr " return ret.%s; /* caller will free */\n" n
5627 | RStringList n | RHashtable n ->
5628 pr " /* caller will free this, but we need to add a NULL entry */\n";
5629 pr " ret.%s.%s_val =\n" n n;
5630 pr " safe_realloc (g, ret.%s.%s_val,\n" n n;
5631 pr " sizeof (char *) * (ret.%s.%s_len + 1));\n"
5633 pr " ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
5634 pr " return ret.%s.%s_val;\n" n n
5636 pr " /* caller will free this */\n";
5637 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
5638 | RStructList (n, _) ->
5639 pr " /* caller will free this */\n";
5640 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
5642 pr " /* RBufferOut is tricky: If the buffer is zero-length, then\n";
5643 pr " * _val might be NULL here. To make the API saner for\n";
5644 pr " * callers, we turn this case into a unique pointer (using\n";
5645 pr " * malloc(1)).\n";
5647 pr " if (ret.%s.%s_len > 0) {\n" n n;
5648 pr " *size_r = ret.%s.%s_len;\n" n n;
5649 pr " return ret.%s.%s_val; /* caller will free */\n" n n;
5651 pr " free (ret.%s.%s_val);\n" n n;
5652 pr " char *p = safe_malloc (g, 1);\n";
5653 pr " *size_r = ret.%s.%s_len;\n" n n;
5661 (* Functions to free structures. *)
5662 pr "/* Structure-freeing functions. These rely on the fact that the\n";
5663 pr " * structure format is identical to the XDR format. See note in\n";
5664 pr " * generator.ml.\n";
5671 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
5673 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
5679 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
5681 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
5688 (* Generate daemon/actions.h. *)
5689 and generate_daemon_actions_h () =
5690 generate_header CStyle GPLv2plus;
5692 pr "#include \"../src/guestfs_protocol.h\"\n";
5696 fun (name, style, _, _, _, _, _) ->
5698 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
5702 (* Generate the linker script which controls the visibility of
5703 * symbols in the public ABI and ensures no other symbols get
5704 * exported accidentally.
5706 and generate_linker_script () =
5707 generate_header HashStyle GPLv2plus;
5712 "guestfs_get_error_handler";
5713 "guestfs_get_out_of_memory_handler";
5714 "guestfs_last_error";
5715 "guestfs_set_error_handler";
5716 "guestfs_set_launch_done_callback";
5717 "guestfs_set_log_message_callback";
5718 "guestfs_set_out_of_memory_handler";
5719 "guestfs_set_subprocess_quit_callback";
5721 (* Unofficial parts of the API: the bindings code use these
5722 * functions, so it is useful to export them.
5724 "guestfs_safe_calloc";
5725 "guestfs_safe_malloc";
5728 List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
5732 List.map (fun (typ, _) ->
5733 ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
5736 let globals = List.sort compare (globals @ functions @ structs) in
5740 List.iter (pr " %s;\n") globals;
5747 (* Generate the server-side stubs. *)
5748 and generate_daemon_actions () =
5749 generate_header CStyle GPLv2plus;
5751 pr "#include <config.h>\n";
5753 pr "#include <stdio.h>\n";
5754 pr "#include <stdlib.h>\n";
5755 pr "#include <string.h>\n";
5756 pr "#include <inttypes.h>\n";
5757 pr "#include <rpc/types.h>\n";
5758 pr "#include <rpc/xdr.h>\n";
5760 pr "#include \"daemon.h\"\n";
5761 pr "#include \"c-ctype.h\"\n";
5762 pr "#include \"../src/guestfs_protocol.h\"\n";
5763 pr "#include \"actions.h\"\n";
5767 fun (name, style, _, _, _, _, _) ->
5768 (* Generate server-side stubs. *)
5769 pr "static void %s_stub (XDR *xdr_in)\n" name;
5772 match fst style with
5773 | RErr | RInt _ -> pr " int r;\n"; "-1"
5774 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5775 | RBool _ -> pr " int r;\n"; "-1"
5776 | RConstString _ | RConstOptString _ ->
5777 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5778 | RString _ -> pr " char *r;\n"; "NULL"
5779 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
5780 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
5781 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL"
5783 pr " size_t size = 1;\n";
5787 (match snd style with
5790 pr " struct guestfs_%s_args args;\n" name;
5793 | Device n | Dev_or_Path n
5796 | OptString n -> pr " char *%s;\n" n
5797 | StringList n | DeviceList n -> pr " char **%s;\n" n
5798 | Bool n -> pr " int %s;\n" n
5799 | Int n -> pr " int %s;\n" n
5800 | Int64 n -> pr " int64_t %s;\n" n
5801 | FileIn _ | FileOut _ -> ()
5806 (match snd style with
5809 pr " memset (&args, 0, sizeof args);\n";
5811 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
5812 pr " reply_with_error (\"daemon failed to decode procedure arguments\");\n";
5816 pr " char *%s = args.%s;\n" n n
5818 let pr_list_handling_code n =
5819 pr " %s = realloc (args.%s.%s_val,\n" n n n;
5820 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
5821 pr " if (%s == NULL) {\n" n;
5822 pr " reply_with_perror (\"realloc\");\n";
5825 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
5826 pr " args.%s.%s_val = %s;\n" n n n;
5832 pr " ABS_PATH (%s, goto done);\n" n;
5835 pr " RESOLVE_DEVICE (%s, goto done);\n" n;
5838 pr " REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, goto done);\n" n;
5839 | String n -> pr_args n
5840 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
5842 pr_list_handling_code n;
5844 pr_list_handling_code n;
5845 pr " /* Ensure that each is a device,\n";
5846 pr " * and perform device name translation. */\n";
5847 pr " { int pvi; for (pvi = 0; physvols[pvi] != NULL; ++pvi)\n";
5848 pr " RESOLVE_DEVICE (physvols[pvi], goto done);\n";
5850 | Bool n -> pr " %s = args.%s;\n" n n
5851 | Int n -> pr " %s = args.%s;\n" n n
5852 | Int64 n -> pr " %s = args.%s;\n" n n
5853 | FileIn _ | FileOut _ -> ()
5859 (* this is used at least for do_equal *)
5860 if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
5861 (* Emit NEED_ROOT just once, even when there are two or
5862 more Pathname args *)
5863 pr " NEED_ROOT (goto done);\n";
5866 (* Don't want to call the impl with any FileIn or FileOut
5867 * parameters, since these go "outside" the RPC protocol.
5870 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
5872 pr " r = do_%s " name;
5873 generate_c_call_args (fst style, args');
5876 (match fst style with
5877 | RErr | RInt _ | RInt64 _ | RBool _
5878 | RConstString _ | RConstOptString _
5879 | RString _ | RStringList _ | RHashtable _
5880 | RStruct (_, _) | RStructList (_, _) ->
5881 pr " if (r == %s)\n" error_code;
5882 pr " /* do_%s has already called reply_with_error */\n" name;
5886 pr " /* size == 0 && r == NULL could be a non-error case (just\n";
5887 pr " * an ordinary zero-length buffer), so be careful ...\n";
5889 pr " if (size == 1 && r == %s)\n" error_code;
5890 pr " /* do_%s has already called reply_with_error */\n" name;
5895 (* If there are any FileOut parameters, then the impl must
5896 * send its own reply.
5899 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
5901 pr " /* do_%s has already sent a reply */\n" name
5903 match fst style with
5904 | RErr -> pr " reply (NULL, NULL);\n"
5905 | RInt n | RInt64 n | RBool n ->
5906 pr " struct guestfs_%s_ret ret;\n" name;
5907 pr " ret.%s = r;\n" n;
5908 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5910 | RConstString _ | RConstOptString _ ->
5911 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5913 pr " struct guestfs_%s_ret ret;\n" name;
5914 pr " ret.%s = r;\n" n;
5915 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5918 | RStringList n | RHashtable n ->
5919 pr " struct guestfs_%s_ret ret;\n" name;
5920 pr " ret.%s.%s_len = count_strings (r);\n" n n;
5921 pr " ret.%s.%s_val = r;\n" n n;
5922 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5924 pr " free_strings (r);\n"
5926 pr " struct guestfs_%s_ret ret;\n" name;
5927 pr " ret.%s = *r;\n" n;
5928 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5930 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5932 | RStructList (n, _) ->
5933 pr " struct guestfs_%s_ret ret;\n" name;
5934 pr " ret.%s = *r;\n" n;
5935 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5937 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5940 pr " struct guestfs_%s_ret ret;\n" name;
5941 pr " ret.%s.%s_val = r;\n" n n;
5942 pr " ret.%s.%s_len = size;\n" n n;
5943 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5948 (* Free the args. *)
5949 (match snd style with
5954 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
5961 (* Dispatch function. *)
5962 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
5964 pr " switch (proc_nr) {\n";
5967 fun (name, style, _, _, _, _, _) ->
5968 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
5969 pr " %s_stub (xdr_in);\n" name;
5974 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";
5979 (* LVM columns and tokenization functions. *)
5980 (* XXX This generates crap code. We should rethink how we
5986 pr "static const char *lvm_%s_cols = \"%s\";\n"
5987 typ (String.concat "," (List.map fst cols));
5990 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
5992 pr " char *tok, *p, *next;\n";
5996 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
5999 pr " if (!str) {\n";
6000 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
6003 pr " if (!*str || c_isspace (*str)) {\n";
6004 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
6009 fun (name, coltype) ->
6010 pr " if (!tok) {\n";
6011 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
6014 pr " p = strchrnul (tok, ',');\n";
6015 pr " if (*p) next = p+1; else next = NULL;\n";
6016 pr " *p = '\\0';\n";
6019 pr " r->%s = strdup (tok);\n" name;
6020 pr " if (r->%s == NULL) {\n" name;
6021 pr " perror (\"strdup\");\n";
6025 pr " for (i = j = 0; i < 32; ++j) {\n";
6026 pr " if (tok[j] == '\\0') {\n";
6027 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
6029 pr " } else if (tok[j] != '-')\n";
6030 pr " r->%s[i++] = tok[j];\n" name;
6033 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
6034 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
6038 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
6039 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
6043 pr " if (tok[0] == '\\0')\n";
6044 pr " r->%s = -1;\n" name;
6045 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
6046 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
6049 | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
6050 assert false (* can never be an LVM column *)
6052 pr " tok = next;\n";
6055 pr " if (tok != NULL) {\n";
6056 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
6063 pr "guestfs_int_lvm_%s_list *\n" typ;
6064 pr "parse_command_line_%ss (void)\n" typ;
6066 pr " char *out, *err;\n";
6067 pr " char *p, *pend;\n";
6069 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
6070 pr " void *newp;\n";
6072 pr " ret = malloc (sizeof *ret);\n";
6073 pr " if (!ret) {\n";
6074 pr " reply_with_perror (\"malloc\");\n";
6075 pr " return NULL;\n";
6078 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
6079 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
6081 pr " r = command (&out, &err,\n";
6082 pr " \"/sbin/lvm\", \"%ss\",\n" typ;
6083 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
6084 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
6085 pr " if (r == -1) {\n";
6086 pr " reply_with_error (\"%%s\", err);\n";
6087 pr " free (out);\n";
6088 pr " free (err);\n";
6089 pr " free (ret);\n";
6090 pr " return NULL;\n";
6093 pr " free (err);\n";
6095 pr " /* Tokenize each line of the output. */\n";
6098 pr " while (p) {\n";
6099 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
6100 pr " if (pend) {\n";
6101 pr " *pend = '\\0';\n";
6105 pr " while (*p && c_isspace (*p)) /* Skip any leading whitespace. */\n";
6108 pr " if (!*p) { /* Empty line? Skip it. */\n";
6113 pr " /* Allocate some space to store this next entry. */\n";
6114 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
6115 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
6116 pr " if (newp == NULL) {\n";
6117 pr " reply_with_perror (\"realloc\");\n";
6118 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
6119 pr " free (ret);\n";
6120 pr " free (out);\n";
6121 pr " return NULL;\n";
6123 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
6125 pr " /* Tokenize the next entry. */\n";
6126 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
6127 pr " if (r == -1) {\n";
6128 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
6129 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
6130 pr " free (ret);\n";
6131 pr " free (out);\n";
6132 pr " return NULL;\n";
6139 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
6141 pr " free (out);\n";
6142 pr " return ret;\n";
6145 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
6147 (* Generate a list of function names, for debugging in the daemon.. *)
6148 and generate_daemon_names () =
6149 generate_header CStyle GPLv2plus;
6151 pr "#include <config.h>\n";
6153 pr "#include \"daemon.h\"\n";
6156 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
6157 pr "const char *function_names[] = {\n";
6159 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
6163 (* Generate the optional groups for the daemon to implement
6164 * guestfs_available.
6166 and generate_daemon_optgroups_c () =
6167 generate_header CStyle GPLv2plus;
6169 pr "#include <config.h>\n";
6171 pr "#include \"daemon.h\"\n";
6172 pr "#include \"optgroups.h\"\n";
6175 pr "struct optgroup optgroups[] = {\n";
6178 pr " { \"%s\", optgroup_%s_available },\n" group group
6180 pr " { NULL, NULL }\n";
6183 and generate_daemon_optgroups_h () =
6184 generate_header CStyle GPLv2plus;
6188 pr "extern int optgroup_%s_available (void);\n" group
6191 (* Generate the tests. *)
6192 and generate_tests () =
6193 generate_header CStyle GPLv2plus;
6200 #include <sys/types.h>
6203 #include \"guestfs.h\"
6204 #include \"guestfs-internal.h\"
6206 static guestfs_h *g;
6207 static int suppress_error = 0;
6209 static void print_error (guestfs_h *g, void *data, const char *msg)
6211 if (!suppress_error)
6212 fprintf (stderr, \"%%s\\n\", msg);
6215 /* FIXME: nearly identical code appears in fish.c */
6216 static void print_strings (char *const *argv)
6220 for (argc = 0; argv[argc] != NULL; ++argc)
6221 printf (\"\\t%%s\\n\", argv[argc]);
6225 static void print_table (char const *const *argv)
6229 for (i = 0; argv[i] != NULL; i += 2)
6230 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
6236 (* Generate a list of commands which are not tested anywhere. *)
6237 pr "static void no_test_warnings (void)\n";
6240 let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
6242 fun (_, _, _, _, tests, _, _) ->
6243 let tests = filter_map (
6245 | (_, (Always|If _|Unless _), test) -> Some test
6246 | (_, Disabled, _) -> None
6248 let seq = List.concat (List.map seq_of_test tests) in
6249 let cmds_tested = List.map List.hd seq in
6250 List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
6254 fun (name, _, _, _, _, _, _) ->
6255 if not (Hashtbl.mem hash name) then
6256 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
6262 (* Generate the actual tests. Note that we generate the tests
6263 * in reverse order, deliberately, so that (in general) the
6264 * newest tests run first. This makes it quicker and easier to
6269 fun (name, _, _, flags, tests, _, _) ->
6270 mapi (generate_one_test name flags) tests
6271 ) (List.rev all_functions) in
6272 let test_names = List.concat test_names in
6273 let nr_tests = List.length test_names in
6276 int main (int argc, char *argv[])
6279 unsigned long int n_failed = 0;
6280 const char *filename;
6282 int nr_tests, test_num = 0;
6284 setbuf (stdout, NULL);
6286 no_test_warnings ();
6288 g = guestfs_create ();
6290 printf (\"guestfs_create FAILED\\n\");
6291 exit (EXIT_FAILURE);
6294 guestfs_set_error_handler (g, print_error, NULL);
6296 guestfs_set_path (g, \"../appliance\");
6298 filename = \"test1.img\";
6299 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
6302 exit (EXIT_FAILURE);
6304 if (lseek (fd, %d, SEEK_SET) == -1) {
6308 exit (EXIT_FAILURE);
6310 if (write (fd, &c, 1) == -1) {
6314 exit (EXIT_FAILURE);
6316 if (close (fd) == -1) {
6319 exit (EXIT_FAILURE);
6321 if (guestfs_add_drive (g, filename) == -1) {
6322 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
6323 exit (EXIT_FAILURE);
6326 filename = \"test2.img\";
6327 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
6330 exit (EXIT_FAILURE);
6332 if (lseek (fd, %d, SEEK_SET) == -1) {
6336 exit (EXIT_FAILURE);
6338 if (write (fd, &c, 1) == -1) {
6342 exit (EXIT_FAILURE);
6344 if (close (fd) == -1) {
6347 exit (EXIT_FAILURE);
6349 if (guestfs_add_drive (g, filename) == -1) {
6350 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
6351 exit (EXIT_FAILURE);
6354 filename = \"test3.img\";
6355 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
6358 exit (EXIT_FAILURE);
6360 if (lseek (fd, %d, SEEK_SET) == -1) {
6364 exit (EXIT_FAILURE);
6366 if (write (fd, &c, 1) == -1) {
6370 exit (EXIT_FAILURE);
6372 if (close (fd) == -1) {
6375 exit (EXIT_FAILURE);
6377 if (guestfs_add_drive (g, filename) == -1) {
6378 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
6379 exit (EXIT_FAILURE);
6382 if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
6383 printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
6384 exit (EXIT_FAILURE);
6387 if (guestfs_launch (g) == -1) {
6388 printf (\"guestfs_launch FAILED\\n\");
6389 exit (EXIT_FAILURE);
6392 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
6395 /* Cancel previous alarm. */
6400 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
6404 pr " test_num++;\n";
6405 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
6406 pr " if (%s () == -1) {\n" test_name;
6407 pr " printf (\"%s FAILED\\n\");\n" test_name;
6408 pr " n_failed++;\n";
6413 pr " guestfs_close (g);\n";
6414 pr " unlink (\"test1.img\");\n";
6415 pr " unlink (\"test2.img\");\n";
6416 pr " unlink (\"test3.img\");\n";
6419 pr " if (n_failed > 0) {\n";
6420 pr " printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
6421 pr " exit (EXIT_FAILURE);\n";
6425 pr " exit (EXIT_SUCCESS);\n";
6428 and generate_one_test name flags i (init, prereq, test) =
6429 let test_name = sprintf "test_%s_%d" name i in
6432 static int %s_skip (void)
6436 str = getenv (\"TEST_ONLY\");
6438 return strstr (str, \"%s\") == NULL;
6439 str = getenv (\"SKIP_%s\");
6440 if (str && STREQ (str, \"1\")) return 1;
6441 str = getenv (\"SKIP_TEST_%s\");
6442 if (str && STREQ (str, \"1\")) return 1;
6446 " test_name name (String.uppercase test_name) (String.uppercase name);
6449 | Disabled | Always -> ()
6450 | If code | Unless code ->
6451 pr "static int %s_prereq (void)\n" test_name;
6459 static int %s (void)
6462 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
6466 " test_name test_name test_name;
6468 (* Optional functions should only be tested if the relevant
6469 * support is available in the daemon.
6475 pr " const char *groups[] = { \"%s\", NULL };\n" group;
6477 pr " suppress_error = 1;\n";
6478 pr " r = guestfs_available (g, (char **) groups);\n";
6479 pr " suppress_error = 0;\n";
6480 pr " if (r == -1) {\n";
6481 pr " printf (\" %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", groups[0]);\n" test_name;
6490 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
6492 pr " if (! %s_prereq ()) {\n" test_name;
6493 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
6497 generate_one_test_body name i test_name init test;
6499 pr " if (%s_prereq ()) {\n" test_name;
6500 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
6504 generate_one_test_body name i test_name init test;
6506 generate_one_test_body name i test_name init test
6514 and generate_one_test_body name i test_name init test =
6516 | InitNone (* XXX at some point, InitNone and InitEmpty became
6517 * folded together as the same thing. Really we should
6518 * make InitNone do nothing at all, but the tests may
6519 * need to be checked to make sure this is OK.
6522 pr " /* InitNone|InitEmpty for %s */\n" test_name;
6523 List.iter (generate_test_command_call test_name)
6524 [["blockdev_setrw"; "/dev/sda"];
6528 pr " /* InitPartition for %s: create /dev/sda1 */\n" test_name;
6529 List.iter (generate_test_command_call test_name)
6530 [["blockdev_setrw"; "/dev/sda"];
6533 ["part_disk"; "/dev/sda"; "mbr"]]
6535 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
6536 List.iter (generate_test_command_call test_name)
6537 [["blockdev_setrw"; "/dev/sda"];
6540 ["part_disk"; "/dev/sda"; "mbr"];
6541 ["mkfs"; "ext2"; "/dev/sda1"];
6542 ["mount_options"; ""; "/dev/sda1"; "/"]]
6543 | InitBasicFSonLVM ->
6544 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
6546 List.iter (generate_test_command_call test_name)
6547 [["blockdev_setrw"; "/dev/sda"];
6550 ["part_disk"; "/dev/sda"; "mbr"];
6551 ["pvcreate"; "/dev/sda1"];
6552 ["vgcreate"; "VG"; "/dev/sda1"];
6553 ["lvcreate"; "LV"; "VG"; "8"];
6554 ["mkfs"; "ext2"; "/dev/VG/LV"];
6555 ["mount_options"; ""; "/dev/VG/LV"; "/"]]
6557 pr " /* InitISOFS for %s */\n" test_name;
6558 List.iter (generate_test_command_call test_name)
6559 [["blockdev_setrw"; "/dev/sda"];
6562 ["mount_ro"; "/dev/sdd"; "/"]]
6565 let get_seq_last = function
6567 failwithf "%s: you cannot use [] (empty list) when expecting a command"
6570 let seq = List.rev seq in
6571 List.rev (List.tl seq), List.hd seq
6576 pr " /* TestRun for %s (%d) */\n" name i;
6577 List.iter (generate_test_command_call test_name) seq
6578 | TestOutput (seq, expected) ->
6579 pr " /* TestOutput for %s (%d) */\n" name i;
6580 pr " const char *expected = \"%s\";\n" (c_quote expected);
6581 let seq, last = get_seq_last seq in
6583 pr " if (STRNEQ (r, expected)) {\n";
6584 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
6588 List.iter (generate_test_command_call test_name) seq;
6589 generate_test_command_call ~test test_name last
6590 | TestOutputList (seq, expected) ->
6591 pr " /* TestOutputList for %s (%d) */\n" name i;
6592 let seq, last = get_seq_last seq in
6596 pr " if (!r[%d]) {\n" i;
6597 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
6598 pr " print_strings (r);\n";
6602 pr " const char *expected = \"%s\";\n" (c_quote str);
6603 pr " if (STRNEQ (r[%d], expected)) {\n" i;
6604 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
6609 pr " if (r[%d] != NULL) {\n" (List.length expected);
6610 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
6612 pr " print_strings (r);\n";
6616 List.iter (generate_test_command_call test_name) seq;
6617 generate_test_command_call ~test test_name last
6618 | TestOutputListOfDevices (seq, expected) ->
6619 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
6620 let seq, last = get_seq_last seq in
6624 pr " if (!r[%d]) {\n" i;
6625 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
6626 pr " print_strings (r);\n";
6630 pr " const char *expected = \"%s\";\n" (c_quote str);
6631 pr " r[%d][5] = 's';\n" i;
6632 pr " if (STRNEQ (r[%d], expected)) {\n" i;
6633 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
6638 pr " if (r[%d] != NULL) {\n" (List.length expected);
6639 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
6641 pr " print_strings (r);\n";
6645 List.iter (generate_test_command_call test_name) seq;
6646 generate_test_command_call ~test test_name last
6647 | TestOutputInt (seq, expected) ->
6648 pr " /* TestOutputInt for %s (%d) */\n" name i;
6649 let seq, last = get_seq_last seq in
6651 pr " if (r != %d) {\n" expected;
6652 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
6658 List.iter (generate_test_command_call test_name) seq;
6659 generate_test_command_call ~test test_name last
6660 | TestOutputIntOp (seq, op, expected) ->
6661 pr " /* TestOutputIntOp for %s (%d) */\n" name i;
6662 let seq, last = get_seq_last seq in
6664 pr " if (! (r %s %d)) {\n" op expected;
6665 pr " fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
6666 test_name op expected;
6671 List.iter (generate_test_command_call test_name) seq;
6672 generate_test_command_call ~test test_name last
6673 | TestOutputTrue seq ->
6674 pr " /* TestOutputTrue for %s (%d) */\n" name i;
6675 let seq, last = get_seq_last seq in
6678 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
6683 List.iter (generate_test_command_call test_name) seq;
6684 generate_test_command_call ~test test_name last
6685 | TestOutputFalse seq ->
6686 pr " /* TestOutputFalse for %s (%d) */\n" name i;
6687 let seq, last = get_seq_last seq in
6690 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
6695 List.iter (generate_test_command_call test_name) seq;
6696 generate_test_command_call ~test test_name last
6697 | TestOutputLength (seq, expected) ->
6698 pr " /* TestOutputLength for %s (%d) */\n" name i;
6699 let seq, last = get_seq_last seq in
6702 pr " for (j = 0; j < %d; ++j)\n" expected;
6703 pr " if (r[j] == NULL) {\n";
6704 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
6706 pr " print_strings (r);\n";
6709 pr " if (r[j] != NULL) {\n";
6710 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
6712 pr " print_strings (r);\n";
6716 List.iter (generate_test_command_call test_name) seq;
6717 generate_test_command_call ~test test_name last
6718 | TestOutputBuffer (seq, expected) ->
6719 pr " /* TestOutputBuffer for %s (%d) */\n" name i;
6720 pr " const char *expected = \"%s\";\n" (c_quote expected);
6721 let seq, last = get_seq_last seq in
6722 let len = String.length expected in
6724 pr " if (size != %d) {\n" len;
6725 pr " fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
6728 pr " if (STRNEQLEN (r, expected, size)) {\n";
6729 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
6733 List.iter (generate_test_command_call test_name) seq;
6734 generate_test_command_call ~test test_name last
6735 | TestOutputStruct (seq, checks) ->
6736 pr " /* TestOutputStruct for %s (%d) */\n" name i;
6737 let seq, last = get_seq_last seq in
6741 | CompareWithInt (field, expected) ->
6742 pr " if (r->%s != %d) {\n" field expected;
6743 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
6744 test_name field expected;
6745 pr " (int) r->%s);\n" field;
6748 | CompareWithIntOp (field, op, expected) ->
6749 pr " if (!(r->%s %s %d)) {\n" field op expected;
6750 pr " fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
6751 test_name field op expected;
6752 pr " (int) r->%s);\n" field;
6755 | CompareWithString (field, expected) ->
6756 pr " if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
6757 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
6758 test_name field expected;
6759 pr " r->%s);\n" field;
6762 | CompareFieldsIntEq (field1, field2) ->
6763 pr " if (r->%s != r->%s) {\n" field1 field2;
6764 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
6765 test_name field1 field2;
6766 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
6769 | CompareFieldsStrEq (field1, field2) ->
6770 pr " if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
6771 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
6772 test_name field1 field2;
6773 pr " r->%s, r->%s);\n" field1 field2;
6778 List.iter (generate_test_command_call test_name) seq;
6779 generate_test_command_call ~test test_name last
6780 | TestLastFail seq ->
6781 pr " /* TestLastFail for %s (%d) */\n" name i;
6782 let seq, last = get_seq_last seq in
6783 List.iter (generate_test_command_call test_name) seq;
6784 generate_test_command_call test_name ~expect_error:true last
6786 (* Generate the code to run a command, leaving the result in 'r'.
6787 * If you expect to get an error then you should set expect_error:true.
6789 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
6791 | [] -> assert false
6793 (* Look up the command to find out what args/ret it has. *)
6796 let _, style, _, _, _, _, _ =
6797 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
6800 failwithf "%s: in test, command %s was not found" test_name name in
6802 if List.length (snd style) <> List.length args then
6803 failwithf "%s: in test, wrong number of args given to %s"
6810 | OptString n, "NULL" -> ()
6813 | Dev_or_Path n, arg
6815 | OptString n, arg ->
6816 pr " const char *%s = \"%s\";\n" n (c_quote arg);
6820 | FileIn _, _ | FileOut _, _ -> ()
6821 | StringList n, "" | DeviceList n, "" ->
6822 pr " const char *const %s[1] = { NULL };\n" n
6823 | StringList n, arg | DeviceList n, arg ->
6824 let strs = string_split " " arg in
6827 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
6829 pr " const char *const %s[] = {\n" n;
6831 fun i _ -> pr " %s_%d,\n" n i
6835 ) (List.combine (snd style) args);
6838 match fst style with
6839 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
6840 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6841 | RConstString _ | RConstOptString _ ->
6842 pr " const char *r;\n"; "NULL"
6843 | RString _ -> pr " char *r;\n"; "NULL"
6844 | RStringList _ | RHashtable _ ->
6848 | RStruct (_, typ) ->
6849 pr " struct guestfs_%s *r;\n" typ; "NULL"
6850 | RStructList (_, typ) ->
6851 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
6854 pr " size_t size;\n";
6857 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
6858 pr " r = guestfs_%s (g" name;
6860 (* Generate the parameters. *)
6863 | OptString _, "NULL" -> pr ", NULL"
6865 | Device n, _ | Dev_or_Path n, _
6869 | FileIn _, arg | FileOut _, arg ->
6870 pr ", \"%s\"" (c_quote arg)
6871 | StringList n, _ | DeviceList n, _ ->
6872 pr ", (char **) %s" n
6875 try int_of_string arg
6876 with Failure "int_of_string" ->
6877 failwithf "%s: expecting an int, but got '%s'" test_name arg in
6881 try Int64.of_string arg
6882 with Failure "int_of_string" ->
6883 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
6886 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
6887 ) (List.combine (snd style) args);
6889 (match fst style with
6890 | RBufferOut _ -> pr ", &size"
6896 if not expect_error then
6897 pr " if (r == %s)\n" error_code
6899 pr " if (r != %s)\n" error_code;
6902 (* Insert the test code. *)
6908 (match fst style with
6909 | RErr | RInt _ | RInt64 _ | RBool _
6910 | RConstString _ | RConstOptString _ -> ()
6911 | RString _ | RBufferOut _ -> pr " free (r);\n"
6912 | RStringList _ | RHashtable _ ->
6913 pr " for (i = 0; r[i] != NULL; ++i)\n";
6914 pr " free (r[i]);\n";
6916 | RStruct (_, typ) ->
6917 pr " guestfs_free_%s (r);\n" typ
6918 | RStructList (_, typ) ->
6919 pr " guestfs_free_%s_list (r);\n" typ
6925 let str = replace_str str "\r" "\\r" in
6926 let str = replace_str str "\n" "\\n" in
6927 let str = replace_str str "\t" "\\t" in
6928 let str = replace_str str "\000" "\\0" in
6931 (* Generate a lot of different functions for guestfish. *)
6932 and generate_fish_cmds () =
6933 generate_header CStyle GPLv2plus;
6937 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
6939 let all_functions_sorted =
6941 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
6942 ) all_functions_sorted in
6944 pr "#include <config.h>\n";
6946 pr "#include <stdio.h>\n";
6947 pr "#include <stdlib.h>\n";
6948 pr "#include <string.h>\n";
6949 pr "#include <inttypes.h>\n";
6951 pr "#include <guestfs.h>\n";
6952 pr "#include \"c-ctype.h\"\n";
6953 pr "#include \"full-write.h\"\n";
6954 pr "#include \"xstrtol.h\"\n";
6955 pr "#include \"fish.h\"\n";
6958 (* list_commands function, which implements guestfish -h *)
6959 pr "void list_commands (void)\n";
6961 pr " printf (\" %%-16s %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
6962 pr " list_builtin_commands ();\n";
6964 fun (name, _, _, flags, _, shortdesc, _) ->
6965 let name = replace_char name '_' '-' in
6966 pr " printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
6968 ) all_functions_sorted;
6969 pr " printf (\" %%s\\n\",";
6970 pr " _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
6974 (* display_command function, which implements guestfish -h cmd *)
6975 pr "void display_command (const char *cmd)\n";
6978 fun (name, style, _, flags, _, shortdesc, longdesc) ->
6979 let name2 = replace_char name '_' '-' in
6981 try find_map (function FishAlias n -> Some n | _ -> None) flags
6982 with Not_found -> name in
6983 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
6985 match snd style with
6989 name2 (String.concat " " (List.map name_of_argt args)) in
6992 if List.mem ProtocolLimitWarning flags then
6993 ("\n\n" ^ protocol_limit_warning)
6996 (* For DangerWillRobinson commands, we should probably have
6997 * guestfish prompt before allowing you to use them (especially
6998 * in interactive mode). XXX
7002 if List.mem DangerWillRobinson flags then
7003 ("\n\n" ^ danger_will_robinson)
7008 match deprecation_notice flags with
7010 | Some txt -> "\n\n" ^ txt in
7012 let describe_alias =
7013 if name <> alias then
7014 sprintf "\n\nYou can use '%s' as an alias for this command." alias
7018 pr "STRCASEEQ (cmd, \"%s\")" name;
7019 if name <> name2 then
7020 pr " || STRCASEEQ (cmd, \"%s\")" name2;
7021 if name <> alias then
7022 pr " || STRCASEEQ (cmd, \"%s\")" alias;
7024 pr " pod2text (\"%s\", _(\"%s\"), %S);\n"
7026 ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
7027 "=head1 DESCRIPTION\n\n" ^
7028 longdesc ^ warnings ^ describe_alias);
7031 pr " display_builtin_command (cmd);\n";
7035 let emit_print_list_function typ =
7036 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
7039 pr " unsigned int i;\n";
7041 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
7042 pr " printf (\"[%%d] = {\\n\", i);\n";
7043 pr " print_%s_indent (&%ss->val[i], \" \");\n" typ typ;
7044 pr " printf (\"}\\n\");\n";
7050 (* print_* functions *)
7054 List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
7056 pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
7059 pr " unsigned int i;\n";
7065 pr " printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
7067 pr " printf (\"%%s%s: \", indent);\n" name;
7068 pr " for (i = 0; i < 32; ++i)\n";
7069 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
7070 pr " printf (\"\\n\");\n"
7072 pr " printf (\"%%s%s: \", indent);\n" name;
7073 pr " for (i = 0; i < %s->%s_len; ++i)\n" typ name;
7074 pr " if (c_isprint (%s->%s[i]))\n" typ name;
7075 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
7077 pr " printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
7078 pr " printf (\"\\n\");\n"
7079 | name, (FUInt64|FBytes) ->
7080 pr " printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
7083 pr " printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
7086 pr " printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
7089 pr " printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
7092 pr " printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
7094 | name, FOptPercent ->
7095 pr " if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
7096 typ name name typ name;
7097 pr " else printf (\"%%s%s: \\n\", indent);\n" name
7103 (* Emit a print_TYPE_list function definition only if that function is used. *)
7106 | typ, (RStructListOnly | RStructAndList) ->
7107 (* generate the function for typ *)
7108 emit_print_list_function typ
7109 | typ, _ -> () (* empty *)
7110 ) (rstructs_used_by all_functions);
7112 (* Emit a print_TYPE function definition only if that function is used. *)
7115 | typ, (RStructOnly | RStructAndList) ->
7116 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
7118 pr " print_%s_indent (%s, \"\");\n" typ typ;
7121 | typ, _ -> () (* empty *)
7122 ) (rstructs_used_by all_functions);
7124 (* run_<action> actions *)
7126 fun (name, style, _, flags, _, _, _) ->
7127 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
7129 (match fst style with
7132 | RBool _ -> pr " int r;\n"
7133 | RInt64 _ -> pr " int64_t r;\n"
7134 | RConstString _ | RConstOptString _ -> pr " const char *r;\n"
7135 | RString _ -> pr " char *r;\n"
7136 | RStringList _ | RHashtable _ -> pr " char **r;\n"
7137 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
7138 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
7141 pr " size_t size;\n";
7149 | FileOut n -> pr " const char *%s;\n" n
7151 | Dev_or_Path n -> pr " char *%s;\n" n
7152 | StringList n | DeviceList n -> pr " char **%s;\n" n
7153 | Bool n -> pr " int %s;\n" n
7154 | Int n -> pr " int %s;\n" n
7155 | Int64 n -> pr " int64_t %s;\n" n
7158 (* Check and convert parameters. *)
7159 let argc_expected = List.length (snd style) in
7160 pr " if (argc != %d) {\n" argc_expected;
7161 pr " fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
7163 pr " fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
7167 let parse_integer fn fntyp rtyp range name i =
7169 pr " strtol_error xerr;\n";
7170 pr " %s r;\n" fntyp;
7172 pr " xerr = %s (argv[%d], NULL, 0, &r, \"\");\n" fn i;
7173 pr " if (xerr != LONGINT_OK) {\n";
7174 pr " fprintf (stderr,\n";
7175 pr " _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
7176 pr " cmd, \"%s\", \"%s\", xerr);\n" name fn;
7181 | Some (min, max, comment) ->
7182 pr " /* %s */\n" comment;
7183 pr " if (r < %s || r > %s) {\n" min max;
7184 pr " fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
7188 pr " /* The check above should ensure this assignment does not overflow. */\n";
7190 pr " %s = r;\n" name;
7199 pr " %s = argv[%d];\n" name i
7201 | Dev_or_Path name ->
7202 pr " %s = resolve_win_path (argv[%d]);\n" name i;
7203 pr " if (%s == NULL) return -1;\n" name
7205 pr " %s = STRNEQ (argv[%d], \"\") ? argv[%d] : NULL;\n"
7208 pr " %s = STRNEQ (argv[%d], \"-\") ? argv[%d] : \"/dev/stdin\";\n"
7211 pr " %s = STRNEQ (argv[%d], \"-\") ? argv[%d] : \"/dev/stdout\";\n"
7213 | StringList name | DeviceList name ->
7214 pr " %s = parse_string_list (argv[%d]);\n" name i;
7215 pr " if (%s == NULL) return -1;\n" name;
7217 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
7220 let min = "(-(2LL<<30))"
7221 and max = "((2LL<<30)-1)"
7223 "The Int type in the generator is a signed 31 bit int." in
7224 Some (min, max, comment) in
7225 parse_integer "xstrtol" "long" "int" range name i
7227 parse_integer "xstrtoll" "long long" "int64_t" None name i
7230 (* Call C API function. *)
7232 try find_map (function FishAction n -> Some n | _ -> None) flags
7233 with Not_found -> sprintf "guestfs_%s" name in
7235 generate_c_call_args ~handle:"g" style;
7240 | Device name | String name
7241 | OptString name | FileIn name | FileOut name | Bool name
7242 | Int name | Int64 name -> ()
7243 | Pathname name | Dev_or_Path name ->
7244 pr " free (%s);\n" name
7245 | StringList name | DeviceList name ->
7246 pr " free_strings (%s);\n" name
7249 (* Check return value for errors and display command results. *)
7250 (match fst style with
7251 | RErr -> pr " return r;\n"
7253 pr " if (r == -1) return -1;\n";
7254 pr " printf (\"%%d\\n\", r);\n";
7257 pr " if (r == -1) return -1;\n";
7258 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
7261 pr " if (r == -1) return -1;\n";
7262 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
7265 pr " if (r == NULL) return -1;\n";
7266 pr " printf (\"%%s\\n\", r);\n";
7268 | RConstOptString _ ->
7269 pr " printf (\"%%s\\n\", r ? : \"(null)\");\n";
7272 pr " if (r == NULL) return -1;\n";
7273 pr " printf (\"%%s\\n\", r);\n";
7277 pr " if (r == NULL) return -1;\n";
7278 pr " print_strings (r);\n";
7279 pr " free_strings (r);\n";
7281 | RStruct (_, typ) ->
7282 pr " if (r == NULL) return -1;\n";
7283 pr " print_%s (r);\n" typ;
7284 pr " guestfs_free_%s (r);\n" typ;
7286 | RStructList (_, typ) ->
7287 pr " if (r == NULL) return -1;\n";
7288 pr " print_%s_list (r);\n" typ;
7289 pr " guestfs_free_%s_list (r);\n" typ;
7292 pr " if (r == NULL) return -1;\n";
7293 pr " print_table (r);\n";
7294 pr " free_strings (r);\n";
7297 pr " if (r == NULL) return -1;\n";
7298 pr " if (full_write (1, r, size) != size) {\n";
7299 pr " perror (\"write\");\n";
7310 (* run_action function *)
7311 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
7314 fun (name, _, _, flags, _, _, _) ->
7315 let name2 = replace_char name '_' '-' in
7317 try find_map (function FishAlias n -> Some n | _ -> None) flags
7318 with Not_found -> name in
7320 pr "STRCASEEQ (cmd, \"%s\")" name;
7321 if name <> name2 then
7322 pr " || STRCASEEQ (cmd, \"%s\")" name2;
7323 if name <> alias then
7324 pr " || STRCASEEQ (cmd, \"%s\")" alias;
7326 pr " return run_%s (cmd, argc, argv);\n" name;
7330 pr " fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
7337 (* Readline completion for guestfish. *)
7338 and generate_fish_completion () =
7339 generate_header CStyle GPLv2plus;
7343 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
7353 #ifdef HAVE_LIBREADLINE
7354 #include <readline/readline.h>
7359 #ifdef HAVE_LIBREADLINE
7361 static const char *const commands[] = {
7362 BUILTIN_COMMANDS_FOR_COMPLETION,
7365 (* Get the commands, including the aliases. They don't need to be
7366 * sorted - the generator() function just does a dumb linear search.
7370 fun (name, _, _, flags, _, _, _) ->
7371 let name2 = replace_char name '_' '-' in
7373 try find_map (function FishAlias n -> Some n | _ -> None) flags
7374 with Not_found -> name in
7376 if name <> alias then [name2; alias] else [name2]
7378 let commands = List.flatten commands in
7380 List.iter (pr " \"%s\",\n") commands;
7386 generator (const char *text, int state)
7388 static int index, len;
7393 len = strlen (text);
7396 rl_attempted_completion_over = 1;
7398 while ((name = commands[index]) != NULL) {
7400 if (STRCASEEQLEN (name, text, len))
7401 return strdup (name);
7407 #endif /* HAVE_LIBREADLINE */
7409 char **do_completion (const char *text, int start, int end)
7411 char **matches = NULL;
7413 #ifdef HAVE_LIBREADLINE
7414 rl_completion_append_character = ' ';
7417 matches = rl_completion_matches (text, generator);
7418 else if (complete_dest_paths)
7419 matches = rl_completion_matches (text, complete_dest_paths_generator);
7426 (* Generate the POD documentation for guestfish. *)
7427 and generate_fish_actions_pod () =
7428 let all_functions_sorted =
7430 fun (_, _, _, flags, _, _, _) ->
7431 not (List.mem NotInFish flags || List.mem NotInDocs flags)
7432 ) all_functions_sorted in
7434 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
7437 fun (name, style, _, flags, _, _, longdesc) ->
7439 Str.global_substitute rex (
7442 try Str.matched_group 1 s
7444 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
7445 "C<" ^ replace_char sub '_' '-' ^ ">"
7447 let name = replace_char name '_' '-' in
7449 try find_map (function FishAlias n -> Some n | _ -> None) flags
7450 with Not_found -> name in
7452 pr "=head2 %s" name;
7453 if name <> alias then
7460 | Pathname n | Device n | Dev_or_Path n | String n -> pr " %s" n
7461 | OptString n -> pr " %s" n
7462 | StringList n | DeviceList n -> pr " '%s ...'" n
7463 | Bool _ -> pr " true|false"
7464 | Int n -> pr " %s" n
7465 | Int64 n -> pr " %s" n
7466 | FileIn n | FileOut n -> pr " (%s|-)" n
7470 pr "%s\n\n" longdesc;
7472 if List.exists (function FileIn _ | FileOut _ -> true
7473 | _ -> false) (snd style) then
7474 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
7476 if List.mem ProtocolLimitWarning flags then
7477 pr "%s\n\n" protocol_limit_warning;
7479 if List.mem DangerWillRobinson flags then
7480 pr "%s\n\n" danger_will_robinson;
7482 match deprecation_notice flags with
7484 | Some txt -> pr "%s\n\n" txt
7485 ) all_functions_sorted
7487 (* Generate a C function prototype. *)
7488 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
7489 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
7491 ?handle name style =
7492 if extern then pr "extern ";
7493 if static then pr "static ";
7494 (match fst style with
7496 | RInt _ -> pr "int "
7497 | RInt64 _ -> pr "int64_t "
7498 | RBool _ -> pr "int "
7499 | RConstString _ | RConstOptString _ -> pr "const char *"
7500 | RString _ | RBufferOut _ -> pr "char *"
7501 | RStringList _ | RHashtable _ -> pr "char **"
7502 | RStruct (_, typ) ->
7503 if not in_daemon then pr "struct guestfs_%s *" typ
7504 else pr "guestfs_int_%s *" typ
7505 | RStructList (_, typ) ->
7506 if not in_daemon then pr "struct guestfs_%s_list *" typ
7507 else pr "guestfs_int_%s_list *" typ
7509 let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
7510 pr "%s%s (" prefix name;
7511 if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
7514 let comma = ref false in
7517 | Some handle -> pr "guestfs_h *%s" handle; comma := true
7521 if single_line then pr ", " else pr ",\n\t\t"
7528 | Device n | Dev_or_Path n
7532 pr "const char *%s" n
7533 | StringList n | DeviceList n ->
7535 pr "char *const *%s" n
7536 | Bool n -> next (); pr "int %s" n
7537 | Int n -> next (); pr "int %s" n
7538 | Int64 n -> next (); pr "int64_t %s" n
7541 if not in_daemon then (next (); pr "const char *%s" n)
7543 if is_RBufferOut then (next (); pr "size_t *size_r");
7546 if semicolon then pr ";";
7547 if newline then pr "\n"
7549 (* Generate C call arguments, eg "(handle, foo, bar)" *)
7550 and generate_c_call_args ?handle ?(decl = false) style =
7552 let comma = ref false in
7554 if !comma then pr ", ";
7559 | Some handle -> pr "%s" handle; comma := true
7564 pr "%s" (name_of_argt arg)
7566 (* For RBufferOut calls, add implicit &size parameter. *)
7568 match fst style with
7576 (* Generate the OCaml bindings interface. *)
7577 and generate_ocaml_mli () =
7578 generate_header OCamlStyle LGPLv2plus;
7581 (** For API documentation you should refer to the C API
7582 in the guestfs(3) manual page. The OCaml API uses almost
7583 exactly the same calls. *)
7586 (** A [guestfs_h] handle. *)
7588 exception Error of string
7589 (** This exception is raised when there is an error. *)
7591 exception Handle_closed of string
7592 (** This exception is raised if you use a {!Guestfs.t} handle
7593 after calling {!close} on it. The string is the name of
7596 val create : unit -> t
7597 (** Create a {!Guestfs.t} handle. *)
7599 val close : t -> unit
7600 (** Close the {!Guestfs.t} handle and free up all resources used
7603 Handles are closed by the garbage collector when they become
7604 unreferenced, but callers can call this in order to provide
7605 predictable cleanup. *)
7608 generate_ocaml_structure_decls ();
7612 fun (name, style, _, _, _, shortdesc, _) ->
7613 generate_ocaml_prototype name style;
7614 pr "(** %s *)\n" shortdesc;
7616 ) all_functions_sorted
7618 (* Generate the OCaml bindings implementation. *)
7619 and generate_ocaml_ml () =
7620 generate_header OCamlStyle LGPLv2plus;
7625 exception Error of string
7626 exception Handle_closed of string
7628 external create : unit -> t = \"ocaml_guestfs_create\"
7629 external close : t -> unit = \"ocaml_guestfs_close\"
7631 (* Give the exceptions names, so they can be raised from the C code. *)
7633 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
7634 Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
7638 generate_ocaml_structure_decls ();
7642 fun (name, style, _, _, _, shortdesc, _) ->
7643 generate_ocaml_prototype ~is_external:true name style;
7644 ) all_functions_sorted
7646 (* Generate the OCaml bindings C implementation. *)
7647 and generate_ocaml_c () =
7648 generate_header CStyle LGPLv2plus;
7655 #include <caml/config.h>
7656 #include <caml/alloc.h>
7657 #include <caml/callback.h>
7658 #include <caml/fail.h>
7659 #include <caml/memory.h>
7660 #include <caml/mlvalues.h>
7661 #include <caml/signals.h>
7663 #include <guestfs.h>
7665 #include \"guestfs_c.h\"
7667 /* Copy a hashtable of string pairs into an assoc-list. We return
7668 * the list in reverse order, but hashtables aren't supposed to be
7671 static CAMLprim value
7672 copy_table (char * const * argv)
7675 CAMLlocal5 (rv, pairv, kv, vv, cons);
7679 for (i = 0; argv[i] != NULL; i += 2) {
7680 kv = caml_copy_string (argv[i]);
7681 vv = caml_copy_string (argv[i+1]);
7682 pairv = caml_alloc (2, 0);
7683 Store_field (pairv, 0, kv);
7684 Store_field (pairv, 1, vv);
7685 cons = caml_alloc (2, 0);
7686 Store_field (cons, 1, rv);
7688 Store_field (cons, 0, pairv);
7696 (* Struct copy functions. *)
7698 let emit_ocaml_copy_list_function typ =
7699 pr "static CAMLprim value\n";
7700 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
7702 pr " CAMLparam0 ();\n";
7703 pr " CAMLlocal2 (rv, v);\n";
7704 pr " unsigned int i;\n";
7706 pr " if (%ss->len == 0)\n" typ;
7707 pr " CAMLreturn (Atom (0));\n";
7709 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
7710 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
7711 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
7712 pr " caml_modify (&Field (rv, i), v);\n";
7714 pr " CAMLreturn (rv);\n";
7722 let has_optpercent_col =
7723 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
7725 pr "static CAMLprim value\n";
7726 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
7728 pr " CAMLparam0 ();\n";
7729 if has_optpercent_col then
7730 pr " CAMLlocal3 (rv, v, v2);\n"
7732 pr " CAMLlocal2 (rv, v);\n";
7734 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
7739 pr " v = caml_copy_string (%s->%s);\n" typ name
7741 pr " v = caml_alloc_string (%s->%s_len);\n" typ name;
7742 pr " memcpy (String_val (v), %s->%s, %s->%s_len);\n"
7745 pr " v = caml_alloc_string (32);\n";
7746 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
7747 | name, (FBytes|FInt64|FUInt64) ->
7748 pr " v = caml_copy_int64 (%s->%s);\n" typ name
7749 | name, (FInt32|FUInt32) ->
7750 pr " v = caml_copy_int32 (%s->%s);\n" typ name
7751 | name, FOptPercent ->
7752 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
7753 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
7754 pr " v = caml_alloc (1, 0);\n";
7755 pr " Store_field (v, 0, v2);\n";
7756 pr " } else /* None */\n";
7757 pr " v = Val_int (0);\n";
7759 pr " v = Val_int (%s->%s);\n" typ name
7761 pr " Store_field (rv, %d, v);\n" i
7763 pr " CAMLreturn (rv);\n";
7768 (* Emit a copy_TYPE_list function definition only if that function is used. *)
7771 | typ, (RStructListOnly | RStructAndList) ->
7772 (* generate the function for typ *)
7773 emit_ocaml_copy_list_function typ
7774 | typ, _ -> () (* empty *)
7775 ) (rstructs_used_by all_functions);
7779 fun (name, style, _, _, _, _, _) ->
7780 pr "/* Automatically generated wrapper for function\n";
7782 generate_ocaml_prototype name style;
7787 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
7789 let needs_extra_vs =
7790 match fst style with RConstOptString _ -> true | _ -> false in
7792 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
7793 pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
7794 List.iter (pr ", value %s") (List.tl params); pr ");\n";
7797 pr "CAMLprim value\n";
7798 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
7799 List.iter (pr ", value %s") (List.tl params);
7804 | [p1; p2; p3; p4; p5] ->
7805 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
7806 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
7807 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
7808 pr " CAMLxparam%d (%s);\n"
7809 (List.length rest) (String.concat ", " rest)
7811 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
7813 if not needs_extra_vs then
7814 pr " CAMLlocal1 (rv);\n"
7816 pr " CAMLlocal3 (rv, v, v2);\n";
7819 pr " guestfs_h *g = Guestfs_val (gv);\n";
7820 pr " if (g == NULL)\n";
7821 pr " ocaml_guestfs_raise_closed (\"%s\");\n" name;
7827 | Device n | Dev_or_Path n
7831 pr " const char *%s = String_val (%sv);\n" n n
7833 pr " const char *%s =\n" n;
7834 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
7836 | StringList n | DeviceList n ->
7837 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
7839 pr " int %s = Bool_val (%sv);\n" n n
7841 pr " int %s = Int_val (%sv);\n" n n
7843 pr " int64_t %s = Int64_val (%sv);\n" n n
7846 match fst style with
7847 | RErr -> pr " int r;\n"; "-1"
7848 | RInt _ -> pr " int r;\n"; "-1"
7849 | RInt64 _ -> pr " int64_t r;\n"; "-1"
7850 | RBool _ -> pr " int r;\n"; "-1"
7851 | RConstString _ | RConstOptString _ ->
7852 pr " const char *r;\n"; "NULL"
7853 | RString _ -> pr " char *r;\n"; "NULL"
7858 | RStruct (_, typ) ->
7859 pr " struct guestfs_%s *r;\n" typ; "NULL"
7860 | RStructList (_, typ) ->
7861 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
7868 pr " size_t size;\n";
7872 pr " caml_enter_blocking_section ();\n";
7873 pr " r = guestfs_%s " name;
7874 generate_c_call_args ~handle:"g" style;
7876 pr " caml_leave_blocking_section ();\n";
7880 | StringList n | DeviceList n ->
7881 pr " ocaml_guestfs_free_strings (%s);\n" n;
7882 | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
7883 | Bool _ | Int _ | Int64 _
7884 | FileIn _ | FileOut _ -> ()
7887 pr " if (r == %s)\n" error_code;
7888 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
7891 (match fst style with
7892 | RErr -> pr " rv = Val_unit;\n"
7893 | RInt _ -> pr " rv = Val_int (r);\n"
7895 pr " rv = caml_copy_int64 (r);\n"
7896 | RBool _ -> pr " rv = Val_bool (r);\n"
7898 pr " rv = caml_copy_string (r);\n"
7899 | RConstOptString _ ->
7900 pr " if (r) { /* Some string */\n";
7901 pr " v = caml_alloc (1, 0);\n";
7902 pr " v2 = caml_copy_string (r);\n";
7903 pr " Store_field (v, 0, v2);\n";
7904 pr " } else /* None */\n";
7905 pr " v = Val_int (0);\n";
7907 pr " rv = caml_copy_string (r);\n";
7910 pr " rv = caml_copy_string_array ((const char **) r);\n";
7911 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
7913 | RStruct (_, typ) ->
7914 pr " rv = copy_%s (r);\n" typ;
7915 pr " guestfs_free_%s (r);\n" typ;
7916 | RStructList (_, typ) ->
7917 pr " rv = copy_%s_list (r);\n" typ;
7918 pr " guestfs_free_%s_list (r);\n" typ;
7920 pr " rv = copy_table (r);\n";
7921 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
7924 pr " rv = caml_alloc_string (size);\n";
7925 pr " memcpy (String_val (rv), r, size);\n";
7928 pr " CAMLreturn (rv);\n";
7932 if List.length params > 5 then (
7933 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
7934 pr "CAMLprim value ";
7935 pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
7936 pr "CAMLprim value\n";
7937 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
7939 pr " return ocaml_guestfs_%s (argv[0]" name;
7940 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
7945 ) all_functions_sorted
7947 and generate_ocaml_structure_decls () =
7950 pr "type %s = {\n" typ;
7953 | name, FString -> pr " %s : string;\n" name
7954 | name, FBuffer -> pr " %s : string;\n" name
7955 | name, FUUID -> pr " %s : string;\n" name
7956 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
7957 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
7958 | name, FChar -> pr " %s : char;\n" name
7959 | name, FOptPercent -> pr " %s : float option;\n" name
7965 and generate_ocaml_prototype ?(is_external = false) name style =
7966 if is_external then pr "external " else pr "val ";
7967 pr "%s : t -> " name;
7970 | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _ -> pr "string -> "
7971 | OptString _ -> pr "string option -> "
7972 | StringList _ | DeviceList _ -> pr "string array -> "
7973 | Bool _ -> pr "bool -> "
7974 | Int _ -> pr "int -> "
7975 | Int64 _ -> pr "int64 -> "
7977 (match fst style with
7978 | RErr -> pr "unit" (* all errors are turned into exceptions *)
7979 | RInt _ -> pr "int"
7980 | RInt64 _ -> pr "int64"
7981 | RBool _ -> pr "bool"
7982 | RConstString _ -> pr "string"
7983 | RConstOptString _ -> pr "string option"
7984 | RString _ | RBufferOut _ -> pr "string"
7985 | RStringList _ -> pr "string array"
7986 | RStruct (_, typ) -> pr "%s" typ
7987 | RStructList (_, typ) -> pr "%s array" typ
7988 | RHashtable _ -> pr "(string * string) list"
7990 if is_external then (
7992 if List.length (snd style) + 1 > 5 then
7993 pr "\"ocaml_guestfs_%s_byte\" " name;
7994 pr "\"ocaml_guestfs_%s\"" name
7998 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
7999 and generate_perl_xs () =
8000 generate_header CStyle LGPLv2plus;
8003 #include \"EXTERN.h\"
8007 #include <guestfs.h>
8010 #define PRId64 \"lld\"
8014 my_newSVll(long long val) {
8015 #ifdef USE_64_BIT_ALL
8016 return newSViv(val);
8020 len = snprintf(buf, 100, \"%%\" PRId64, val);
8021 return newSVpv(buf, len);
8026 #define PRIu64 \"llu\"
8030 my_newSVull(unsigned long long val) {
8031 #ifdef USE_64_BIT_ALL
8032 return newSVuv(val);
8036 len = snprintf(buf, 100, \"%%\" PRIu64, val);
8037 return newSVpv(buf, len);
8041 /* http://www.perlmonks.org/?node_id=680842 */
8043 XS_unpack_charPtrPtr (SV *arg) {
8048 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
8049 croak (\"array reference expected\");
8051 av = (AV *)SvRV (arg);
8052 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
8054 croak (\"malloc failed\");
8056 for (i = 0; i <= av_len (av); i++) {
8057 SV **elem = av_fetch (av, i, 0);
8059 if (!elem || !*elem)
8060 croak (\"missing element in list\");
8062 ret[i] = SvPV_nolen (*elem);
8070 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
8077 RETVAL = guestfs_create ();
8079 croak (\"could not create guestfs handle\");
8080 guestfs_set_error_handler (RETVAL, NULL, NULL);
8093 fun (name, style, _, _, _, _, _) ->
8094 (match fst style with
8095 | RErr -> pr "void\n"
8096 | RInt _ -> pr "SV *\n"
8097 | RInt64 _ -> pr "SV *\n"
8098 | RBool _ -> pr "SV *\n"
8099 | RConstString _ -> pr "SV *\n"
8100 | RConstOptString _ -> pr "SV *\n"
8101 | RString _ -> pr "SV *\n"
8102 | RBufferOut _ -> pr "SV *\n"
8104 | RStruct _ | RStructList _
8106 pr "void\n" (* all lists returned implictly on the stack *)
8108 (* Call and arguments. *)
8110 generate_c_call_args ~handle:"g" ~decl:true style;
8112 pr " guestfs_h *g;\n";
8116 | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
8119 (* http://www.perlmonks.org/?node_id=554277
8120 * Note that the implicit handle argument means we have
8121 * to add 1 to the ST(x) operator.
8123 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
8124 | StringList n | DeviceList n -> pr " char **%s;\n" n
8125 | Bool n -> pr " int %s;\n" n
8126 | Int n -> pr " int %s;\n" n
8127 | Int64 n -> pr " int64_t %s;\n" n
8130 let do_cleanups () =
8133 | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
8134 | Bool _ | Int _ | Int64 _
8135 | FileIn _ | FileOut _ -> ()
8136 | StringList n | DeviceList n -> pr " free (%s);\n" n
8141 (match fst style with
8146 pr " r = guestfs_%s " name;
8147 generate_c_call_args ~handle:"g" style;
8150 pr " if (r == -1)\n";
8151 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8157 pr " %s = guestfs_%s " n name;
8158 generate_c_call_args ~handle:"g" style;
8161 pr " if (%s == -1)\n" n;
8162 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8163 pr " RETVAL = newSViv (%s);\n" n;
8168 pr " int64_t %s;\n" n;
8170 pr " %s = guestfs_%s " n name;
8171 generate_c_call_args ~handle:"g" style;
8174 pr " if (%s == -1)\n" n;
8175 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8176 pr " RETVAL = my_newSVll (%s);\n" n;
8181 pr " const char *%s;\n" n;
8183 pr " %s = guestfs_%s " n name;
8184 generate_c_call_args ~handle:"g" style;
8187 pr " if (%s == NULL)\n" n;
8188 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8189 pr " RETVAL = newSVpv (%s, 0);\n" n;
8192 | RConstOptString n ->
8194 pr " const char *%s;\n" n;
8196 pr " %s = guestfs_%s " n name;
8197 generate_c_call_args ~handle:"g" style;
8200 pr " if (%s == NULL)\n" n;
8201 pr " RETVAL = &PL_sv_undef;\n";
8203 pr " RETVAL = newSVpv (%s, 0);\n" n;
8208 pr " char *%s;\n" n;
8210 pr " %s = guestfs_%s " n name;
8211 generate_c_call_args ~handle:"g" style;
8214 pr " if (%s == NULL)\n" n;
8215 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8216 pr " RETVAL = newSVpv (%s, 0);\n" n;
8217 pr " free (%s);\n" n;
8220 | RStringList n | RHashtable n ->
8222 pr " char **%s;\n" n;
8225 pr " %s = guestfs_%s " n name;
8226 generate_c_call_args ~handle:"g" style;
8229 pr " if (%s == NULL)\n" n;
8230 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8231 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
8232 pr " EXTEND (SP, n);\n";
8233 pr " for (i = 0; i < n; ++i) {\n";
8234 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
8235 pr " free (%s[i]);\n" n;
8237 pr " free (%s);\n" n;
8238 | RStruct (n, typ) ->
8239 let cols = cols_of_struct typ in
8240 generate_perl_struct_code typ cols name style n do_cleanups
8241 | RStructList (n, typ) ->
8242 let cols = cols_of_struct typ in
8243 generate_perl_struct_list_code typ cols name style n do_cleanups
8246 pr " char *%s;\n" n;
8247 pr " size_t size;\n";
8249 pr " %s = guestfs_%s " n name;
8250 generate_c_call_args ~handle:"g" style;
8253 pr " if (%s == NULL)\n" n;
8254 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8255 pr " RETVAL = newSVpv (%s, size);\n" n;
8256 pr " free (%s);\n" n;
8264 and generate_perl_struct_list_code typ cols name style n do_cleanups =
8266 pr " struct guestfs_%s_list *%s;\n" typ n;
8270 pr " %s = guestfs_%s " n name;
8271 generate_c_call_args ~handle:"g" style;
8274 pr " if (%s == NULL)\n" n;
8275 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8276 pr " EXTEND (SP, %s->len);\n" n;
8277 pr " for (i = 0; i < %s->len; ++i) {\n" n;
8278 pr " hv = newHV ();\n";
8282 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
8283 name (String.length name) n name
8285 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
8286 name (String.length name) n name
8288 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
8289 name (String.length name) n name n name
8290 | name, (FBytes|FUInt64) ->
8291 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
8292 name (String.length name) n name
8294 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
8295 name (String.length name) n name
8296 | name, (FInt32|FUInt32) ->
8297 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
8298 name (String.length name) n name
8300 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
8301 name (String.length name) n name
8302 | name, FOptPercent ->
8303 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
8304 name (String.length name) n name
8306 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
8308 pr " guestfs_free_%s_list (%s);\n" typ n
8310 and generate_perl_struct_code typ cols name style n do_cleanups =
8312 pr " struct guestfs_%s *%s;\n" typ n;
8314 pr " %s = guestfs_%s " n name;
8315 generate_c_call_args ~handle:"g" style;
8318 pr " if (%s == NULL)\n" n;
8319 pr " croak (\"%%s\", guestfs_last_error (g));\n";
8320 pr " EXTEND (SP, 2 * %d);\n" (List.length cols);
8322 fun ((name, _) as col) ->
8323 pr " PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
8327 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
8330 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, %s->%s_len)));\n"
8333 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
8335 | name, (FBytes|FUInt64) ->
8336 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
8339 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
8341 | name, (FInt32|FUInt32) ->
8342 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
8345 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
8347 | name, FOptPercent ->
8348 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
8351 pr " free (%s);\n" n
8353 (* Generate Sys/Guestfs.pm. *)
8354 and generate_perl_pm () =
8355 generate_header HashStyle LGPLv2plus;
8362 Sys::Guestfs - Perl bindings for libguestfs
8368 my $h = Sys::Guestfs->new ();
8369 $h->add_drive ('guest.img');
8371 $h->mount ('/dev/sda1', '/');
8372 $h->touch ('/hello');
8377 The C<Sys::Guestfs> module provides a Perl XS binding to the
8378 libguestfs API for examining and modifying virtual machine
8381 Amongst the things this is good for: making batch configuration
8382 changes to guests, getting disk used/free statistics (see also:
8383 virt-df), migrating between virtualization systems (see also:
8384 virt-p2v), performing partial backups, performing partial guest
8385 clones, cloning guests and changing registry/UUID/hostname info, and
8388 Libguestfs uses Linux kernel and qemu code, and can access any type of
8389 guest filesystem that Linux and qemu can, including but not limited
8390 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
8391 schemes, qcow, qcow2, vmdk.
8393 Libguestfs provides ways to enumerate guest storage (eg. partitions,
8394 LVs, what filesystem is in each LV, etc.). It can also run commands
8395 in the context of the guest. Also you can access filesystems over
8398 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
8399 functions for using libguestfs from Perl, including integration
8404 All errors turn into calls to C<croak> (see L<Carp(3)>).
8412 package Sys::Guestfs;
8418 XSLoader::load ('Sys::Guestfs');
8420 =item $h = Sys::Guestfs->new ();
8422 Create a new guestfs handle.
8428 my $class = ref ($proto) || $proto;
8430 my $self = Sys::Guestfs::_create ();
8431 bless $self, $class;
8437 (* Actions. We only need to print documentation for these as
8438 * they are pulled in from the XS code automatically.
8441 fun (name, style, _, flags, _, _, longdesc) ->
8442 if not (List.mem NotInDocs flags) then (
8443 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
8445 generate_perl_prototype name style;
8447 pr "%s\n\n" longdesc;
8448 if List.mem ProtocolLimitWarning flags then
8449 pr "%s\n\n" protocol_limit_warning;
8450 if List.mem DangerWillRobinson flags then
8451 pr "%s\n\n" danger_will_robinson;
8452 match deprecation_notice flags with
8454 | Some txt -> pr "%s\n\n" txt
8456 ) all_functions_sorted;
8468 Copyright (C) %s Red Hat Inc.
8472 Please see the file COPYING.LIB for the full license.
8478 L<http://libguestfs.org>,
8479 L<Sys::Guestfs::Lib(3)>.
8484 and generate_perl_prototype name style =
8485 (match fst style with
8493 | RBufferOut n -> pr "$%s = " n
8495 | RHashtable n -> pr "%%%s = " n
8497 | RStructList (n,_) -> pr "@%s = " n
8500 let comma = ref false in
8503 if !comma then pr ", ";
8506 | Pathname n | Device n | Dev_or_Path n | String n
8507 | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n ->
8509 | StringList n | DeviceList n ->
8514 (* Generate Python C module. *)
8515 and generate_python_c () =
8516 generate_header CStyle LGPLv2plus;
8525 #include \"guestfs.h\"
8533 get_handle (PyObject *obj)
8536 assert (obj != Py_None);
8537 return ((Pyguestfs_Object *) obj)->g;
8541 put_handle (guestfs_h *g)
8545 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
8548 /* This list should be freed (but not the strings) after use. */
8550 get_string_list (PyObject *obj)
8557 if (!PyList_Check (obj)) {
8558 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
8562 len = PyList_Size (obj);
8563 r = malloc (sizeof (char *) * (len+1));
8565 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
8569 for (i = 0; i < len; ++i)
8570 r[i] = PyString_AsString (PyList_GetItem (obj, i));
8577 put_string_list (char * const * const argv)
8582 for (argc = 0; argv[argc] != NULL; ++argc)
8585 list = PyList_New (argc);
8586 for (i = 0; i < argc; ++i)
8587 PyList_SetItem (list, i, PyString_FromString (argv[i]));
8593 put_table (char * const * const argv)
8595 PyObject *list, *item;
8598 for (argc = 0; argv[argc] != NULL; ++argc)
8601 list = PyList_New (argc >> 1);
8602 for (i = 0; i < argc; i += 2) {
8603 item = PyTuple_New (2);
8604 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
8605 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
8606 PyList_SetItem (list, i >> 1, item);
8613 free_strings (char **argv)
8617 for (argc = 0; argv[argc] != NULL; ++argc)
8623 py_guestfs_create (PyObject *self, PyObject *args)
8627 g = guestfs_create ();
8629 PyErr_SetString (PyExc_RuntimeError,
8630 \"guestfs.create: failed to allocate handle\");
8633 guestfs_set_error_handler (g, NULL, NULL);
8634 return put_handle (g);
8638 py_guestfs_close (PyObject *self, PyObject *args)
8643 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
8645 g = get_handle (py_g);
8649 Py_INCREF (Py_None);
8655 let emit_put_list_function typ =
8656 pr "static PyObject *\n";
8657 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
8659 pr " PyObject *list;\n";
8662 pr " list = PyList_New (%ss->len);\n" typ;
8663 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
8664 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
8665 pr " return list;\n";
8670 (* Structures, turned into Python dictionaries. *)
8673 pr "static PyObject *\n";
8674 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
8676 pr " PyObject *dict;\n";
8678 pr " dict = PyDict_New ();\n";
8682 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8683 pr " PyString_FromString (%s->%s));\n"
8686 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8687 pr " PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
8690 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8691 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
8693 | name, (FBytes|FUInt64) ->
8694 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8695 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
8698 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8699 pr " PyLong_FromLongLong (%s->%s));\n"
8702 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8703 pr " PyLong_FromUnsignedLong (%s->%s));\n"
8706 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8707 pr " PyLong_FromLong (%s->%s));\n"
8709 | name, FOptPercent ->
8710 pr " if (%s->%s >= 0)\n" typ name;
8711 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8712 pr " PyFloat_FromDouble ((double) %s->%s));\n"
8715 pr " Py_INCREF (Py_None);\n";
8716 pr " PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
8719 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
8720 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
8722 pr " return dict;\n";
8728 (* Emit a put_TYPE_list function definition only if that function is used. *)
8731 | typ, (RStructListOnly | RStructAndList) ->
8732 (* generate the function for typ *)
8733 emit_put_list_function typ
8734 | typ, _ -> () (* empty *)
8735 ) (rstructs_used_by all_functions);
8737 (* Python wrapper functions. *)
8739 fun (name, style, _, _, _, _, _) ->
8740 pr "static PyObject *\n";
8741 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
8744 pr " PyObject *py_g;\n";
8745 pr " guestfs_h *g;\n";
8746 pr " PyObject *py_r;\n";
8749 match fst style with
8750 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
8751 | RInt64 _ -> pr " int64_t r;\n"; "-1"
8752 | RConstString _ | RConstOptString _ ->
8753 pr " const char *r;\n"; "NULL"
8754 | RString _ -> pr " char *r;\n"; "NULL"
8755 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
8756 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
8757 | RStructList (_, typ) ->
8758 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
8761 pr " size_t size;\n";
8766 | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
8767 pr " const char *%s;\n" n
8768 | OptString n -> pr " const char *%s;\n" n
8769 | StringList n | DeviceList n ->
8770 pr " PyObject *py_%s;\n" n;
8771 pr " char **%s;\n" n
8772 | Bool n -> pr " int %s;\n" n
8773 | Int n -> pr " int %s;\n" n
8774 | Int64 n -> pr " long long %s;\n" n
8779 (* Convert the parameters. *)
8780 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
8783 | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _ -> pr "s"
8784 | OptString _ -> pr "z"
8785 | StringList _ | DeviceList _ -> pr "O"
8786 | Bool _ -> pr "i" (* XXX Python has booleans? *)
8788 | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
8789 * emulate C's int/long/long long in Python?
8792 pr ":guestfs_%s\",\n" name;
8796 | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n -> pr ", &%s" n
8797 | OptString n -> pr ", &%s" n
8798 | StringList n | DeviceList n -> pr ", &py_%s" n
8799 | Bool n -> pr ", &%s" n
8800 | Int n -> pr ", &%s" n
8801 | Int64 n -> pr ", &%s" n
8805 pr " return NULL;\n";
8807 pr " g = get_handle (py_g);\n";
8810 | Pathname _ | Device _ | Dev_or_Path _ | String _
8811 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
8812 | StringList n | DeviceList n ->
8813 pr " %s = get_string_list (py_%s);\n" n n;
8814 pr " if (!%s) return NULL;\n" n
8819 pr " r = guestfs_%s " name;
8820 generate_c_call_args ~handle:"g" style;
8825 | Pathname _ | Device _ | Dev_or_Path _ | String _
8826 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
8827 | StringList n | DeviceList n ->
8828 pr " free (%s);\n" n
8831 pr " if (r == %s) {\n" error_code;
8832 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
8833 pr " return NULL;\n";
8837 (match fst style with
8839 pr " Py_INCREF (Py_None);\n";
8840 pr " py_r = Py_None;\n"
8842 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
8843 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
8844 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
8845 | RConstOptString _ ->
8847 pr " py_r = PyString_FromString (r);\n";
8849 pr " Py_INCREF (Py_None);\n";
8850 pr " py_r = Py_None;\n";
8853 pr " py_r = PyString_FromString (r);\n";
8856 pr " py_r = put_string_list (r);\n";
8857 pr " free_strings (r);\n"
8858 | RStruct (_, typ) ->
8859 pr " py_r = put_%s (r);\n" typ;
8860 pr " guestfs_free_%s (r);\n" typ
8861 | RStructList (_, typ) ->
8862 pr " py_r = put_%s_list (r);\n" typ;
8863 pr " guestfs_free_%s_list (r);\n" typ
8865 pr " py_r = put_table (r);\n";
8866 pr " free_strings (r);\n"
8868 pr " py_r = PyString_FromStringAndSize (r, size);\n";
8872 pr " return py_r;\n";
8877 (* Table of functions. *)
8878 pr "static PyMethodDef methods[] = {\n";
8879 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
8880 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
8882 fun (name, _, _, _, _, _, _) ->
8883 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
8886 pr " { NULL, NULL, 0, NULL }\n";
8890 (* Init function. *)
8893 initlibguestfsmod (void)
8895 static int initialized = 0;
8897 if (initialized) return;
8898 Py_InitModule ((char *) \"libguestfsmod\", methods);
8903 (* Generate Python module. *)
8904 and generate_python_py () =
8905 generate_header HashStyle LGPLv2plus;
8908 u\"\"\"Python bindings for libguestfs
8911 g = guestfs.GuestFS ()
8912 g.add_drive (\"guest.img\")
8914 parts = g.list_partitions ()
8916 The guestfs module provides a Python binding to the libguestfs API
8917 for examining and modifying virtual machine disk images.
8919 Amongst the things this is good for: making batch configuration
8920 changes to guests, getting disk used/free statistics (see also:
8921 virt-df), migrating between virtualization systems (see also:
8922 virt-p2v), performing partial backups, performing partial guest
8923 clones, cloning guests and changing registry/UUID/hostname info, and
8926 Libguestfs uses Linux kernel and qemu code, and can access any type of
8927 guest filesystem that Linux and qemu can, including but not limited
8928 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
8929 schemes, qcow, qcow2, vmdk.
8931 Libguestfs provides ways to enumerate guest storage (eg. partitions,
8932 LVs, what filesystem is in each LV, etc.). It can also run commands
8933 in the context of the guest. Also you can access filesystems over
8936 Errors which happen while using the API are turned into Python
8937 RuntimeError exceptions.
8939 To create a guestfs handle you usually have to perform the following
8942 # Create the handle, call add_drive at least once, and possibly
8943 # several times if the guest has multiple block devices:
8944 g = guestfs.GuestFS ()
8945 g.add_drive (\"guest.img\")
8947 # Launch the qemu subprocess and wait for it to become ready:
8950 # Now you can issue commands, for example:
8955 import libguestfsmod
8958 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
8960 def __init__ (self):
8961 \"\"\"Create a new libguestfs handle.\"\"\"
8962 self._o = libguestfsmod.create ()
8965 libguestfsmod.close (self._o)
8970 fun (name, style, _, flags, _, _, longdesc) ->
8972 generate_py_call_args ~handle:"self" (snd style);
8975 if not (List.mem NotInDocs flags) then (
8976 let doc = replace_str longdesc "C<guestfs_" "C<g." in
8978 match fst style with
8979 | RErr | RInt _ | RInt64 _ | RBool _
8980 | RConstOptString _ | RConstString _
8981 | RString _ | RBufferOut _ -> doc
8983 doc ^ "\n\nThis function returns a list of strings."
8984 | RStruct (_, typ) ->
8985 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
8986 | RStructList (_, typ) ->
8987 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
8989 doc ^ "\n\nThis function returns a dictionary." in
8991 if List.mem ProtocolLimitWarning flags then
8992 doc ^ "\n\n" ^ protocol_limit_warning
8995 if List.mem DangerWillRobinson flags then
8996 doc ^ "\n\n" ^ danger_will_robinson
8999 match deprecation_notice flags with
9001 | Some txt -> doc ^ "\n\n" ^ txt in
9002 let doc = pod2text ~width:60 name doc in
9003 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
9004 let doc = String.concat "\n " doc in
9005 pr " u\"\"\"%s\"\"\"\n" doc;
9007 pr " return libguestfsmod.%s " name;
9008 generate_py_call_args ~handle:"self._o" (snd style);
9013 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
9014 and generate_py_call_args ~handle args =
9016 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
9019 (* Useful if you need the longdesc POD text as plain text. Returns a
9022 * Because this is very slow (the slowest part of autogeneration),
9023 * we memoize the results.
9025 and pod2text ~width name longdesc =
9026 let key = width, name, longdesc in
9027 try Hashtbl.find pod2text_memo key
9029 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
9030 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
9032 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
9033 let chan = open_process_in cmd in
9034 let lines = ref [] in
9036 let line = input_line chan in
9037 if i = 1 then (* discard the first line of output *)
9040 let line = triml line in
9041 lines := line :: !lines;
9044 let lines = try loop 1 with End_of_file -> List.rev !lines in
9046 (match close_process_in chan with
9049 failwithf "pod2text: process exited with non-zero status (%d)" i
9050 | WSIGNALED i | WSTOPPED i ->
9051 failwithf "pod2text: process signalled or stopped by signal %d" i
9053 Hashtbl.add pod2text_memo key lines;
9054 pod2text_memo_updated ();
9057 (* Generate ruby bindings. *)
9058 and generate_ruby_c () =
9059 generate_header CStyle LGPLv2plus;
9067 #include \"guestfs.h\"
9069 #include \"extconf.h\"
9071 /* For Ruby < 1.9 */
9073 #define RARRAY_LEN(r) (RARRAY((r))->len)
9076 static VALUE m_guestfs; /* guestfs module */
9077 static VALUE c_guestfs; /* guestfs_h handle */
9078 static VALUE e_Error; /* used for all errors */
9080 static void ruby_guestfs_free (void *p)
9083 guestfs_close ((guestfs_h *) p);
9086 static VALUE ruby_guestfs_create (VALUE m)
9090 g = guestfs_create ();
9092 rb_raise (e_Error, \"failed to create guestfs handle\");
9094 /* Don't print error messages to stderr by default. */
9095 guestfs_set_error_handler (g, NULL, NULL);
9097 /* Wrap it, and make sure the close function is called when the
9100 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
9103 static VALUE ruby_guestfs_close (VALUE gv)
9106 Data_Get_Struct (gv, guestfs_h, g);
9108 ruby_guestfs_free (g);
9109 DATA_PTR (gv) = NULL;
9117 fun (name, style, _, _, _, _, _) ->
9118 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
9119 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
9122 pr " guestfs_h *g;\n";
9123 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
9125 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
9131 | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
9132 pr " Check_Type (%sv, T_STRING);\n" n;
9133 pr " const char *%s = StringValueCStr (%sv);\n" n n;
9135 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
9136 pr " \"%s\", \"%s\");\n" n name
9138 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
9139 | StringList n | DeviceList n ->
9140 pr " char **%s;\n" n;
9141 pr " Check_Type (%sv, T_ARRAY);\n" n;
9143 pr " int i, len;\n";
9144 pr " len = RARRAY_LEN (%sv);\n" n;
9145 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
9147 pr " for (i = 0; i < len; ++i) {\n";
9148 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
9149 pr " %s[i] = StringValueCStr (v);\n" n;
9151 pr " %s[len] = NULL;\n" n;
9154 pr " int %s = RTEST (%sv);\n" n n
9156 pr " int %s = NUM2INT (%sv);\n" n n
9158 pr " long long %s = NUM2LL (%sv);\n" n n
9163 match fst style with
9164 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
9165 | RInt64 _ -> pr " int64_t r;\n"; "-1"
9166 | RConstString _ | RConstOptString _ ->
9167 pr " const char *r;\n"; "NULL"
9168 | RString _ -> pr " char *r;\n"; "NULL"
9169 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
9170 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
9171 | RStructList (_, typ) ->
9172 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
9175 pr " size_t size;\n";
9179 pr " r = guestfs_%s " name;
9180 generate_c_call_args ~handle:"g" style;
9185 | Pathname _ | Device _ | Dev_or_Path _ | String _
9186 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
9187 | StringList n | DeviceList n ->
9188 pr " free (%s);\n" n
9191 pr " if (r == %s)\n" error_code;
9192 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
9195 (match fst style with
9197 pr " return Qnil;\n"
9198 | RInt _ | RBool _ ->
9199 pr " return INT2NUM (r);\n"
9201 pr " return ULL2NUM (r);\n"
9203 pr " return rb_str_new2 (r);\n";
9204 | RConstOptString _ ->
9206 pr " return rb_str_new2 (r);\n";
9208 pr " return Qnil;\n";
9210 pr " VALUE rv = rb_str_new2 (r);\n";
9214 pr " int i, len = 0;\n";
9215 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
9216 pr " VALUE rv = rb_ary_new2 (len);\n";
9217 pr " for (i = 0; r[i] != NULL; ++i) {\n";
9218 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
9219 pr " free (r[i]);\n";
9223 | RStruct (_, typ) ->
9224 let cols = cols_of_struct typ in
9225 generate_ruby_struct_code typ cols
9226 | RStructList (_, typ) ->
9227 let cols = cols_of_struct typ in
9228 generate_ruby_struct_list_code typ cols
9230 pr " VALUE rv = rb_hash_new ();\n";
9232 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
9233 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
9234 pr " free (r[i]);\n";
9235 pr " free (r[i+1]);\n";
9240 pr " VALUE rv = rb_str_new (r, size);\n";
9250 /* Initialize the module. */
9251 void Init__guestfs ()
9253 m_guestfs = rb_define_module (\"Guestfs\");
9254 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
9255 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
9257 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
9258 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
9261 (* Define the rest of the methods. *)
9263 fun (name, style, _, _, _, _, _) ->
9264 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
9265 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
9270 (* Ruby code to return a struct. *)
9271 and generate_ruby_struct_code typ cols =
9272 pr " VALUE rv = rb_hash_new ();\n";
9276 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
9278 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
9280 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
9281 | name, (FBytes|FUInt64) ->
9282 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
9284 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
9286 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
9288 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
9289 | name, FOptPercent ->
9290 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
9291 | name, FChar -> (* XXX wrong? *)
9292 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
9294 pr " guestfs_free_%s (r);\n" typ;
9297 (* Ruby code to return a struct list. *)
9298 and generate_ruby_struct_list_code typ cols =
9299 pr " VALUE rv = rb_ary_new2 (r->len);\n";
9301 pr " for (i = 0; i < r->len; ++i) {\n";
9302 pr " VALUE hv = rb_hash_new ();\n";
9306 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
9308 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, r->val[i].%s_len));\n" name name name
9310 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
9311 | name, (FBytes|FUInt64) ->
9312 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
9314 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
9316 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
9318 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
9319 | name, FOptPercent ->
9320 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
9321 | name, FChar -> (* XXX wrong? *)
9322 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
9324 pr " rb_ary_push (rv, hv);\n";
9326 pr " guestfs_free_%s_list (r);\n" typ;
9329 (* Generate Java bindings GuestFS.java file. *)
9330 and generate_java_java () =
9331 generate_header CStyle LGPLv2plus;
9334 package com.redhat.et.libguestfs;
9336 import java.util.HashMap;
9337 import com.redhat.et.libguestfs.LibGuestFSException;
9338 import com.redhat.et.libguestfs.PV;
9339 import com.redhat.et.libguestfs.VG;
9340 import com.redhat.et.libguestfs.LV;
9341 import com.redhat.et.libguestfs.Stat;
9342 import com.redhat.et.libguestfs.StatVFS;
9343 import com.redhat.et.libguestfs.IntBool;
9344 import com.redhat.et.libguestfs.Dirent;
9347 * The GuestFS object is a libguestfs handle.
9351 public class GuestFS {
9352 // Load the native code.
9354 System.loadLibrary (\"guestfs_jni\");
9358 * The native guestfs_h pointer.
9363 * Create a libguestfs handle.
9365 * @throws LibGuestFSException
9367 public GuestFS () throws LibGuestFSException
9371 private native long _create () throws LibGuestFSException;
9374 * Close a libguestfs handle.
9376 * You can also leave handles to be collected by the garbage
9377 * collector, but this method ensures that the resources used
9378 * by the handle are freed up immediately. If you call any
9379 * other methods after closing the handle, you will get an
9382 * @throws LibGuestFSException
9384 public void close () throws LibGuestFSException
9390 private native void _close (long g) throws LibGuestFSException;
9392 public void finalize () throws LibGuestFSException
9400 fun (name, style, _, flags, _, shortdesc, longdesc) ->
9401 if not (List.mem NotInDocs flags); then (
9402 let doc = replace_str longdesc "C<guestfs_" "C<g." in
9404 if List.mem ProtocolLimitWarning flags then
9405 doc ^ "\n\n" ^ protocol_limit_warning
9408 if List.mem DangerWillRobinson flags then
9409 doc ^ "\n\n" ^ danger_will_robinson
9412 match deprecation_notice flags with
9414 | Some txt -> doc ^ "\n\n" ^ txt in
9415 let doc = pod2text ~width:60 name doc in
9416 let doc = List.map ( (* RHBZ#501883 *)
9419 | nonempty -> nonempty
9421 let doc = String.concat "\n * " doc in
9424 pr " * %s\n" shortdesc;
9427 pr " * @throws LibGuestFSException\n";
9431 generate_java_prototype ~public:true ~semicolon:false name style;
9434 pr " if (g == 0)\n";
9435 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
9438 if fst style <> RErr then pr "return ";
9440 generate_java_call_args ~handle:"g" (snd style);
9444 generate_java_prototype ~privat:true ~native:true name style;
9451 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
9452 and generate_java_call_args ~handle args =
9454 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
9457 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
9458 ?(semicolon=true) name style =
9459 if privat then pr "private ";
9460 if public then pr "public ";
9461 if native then pr "native ";
9464 (match fst style with
9465 | RErr -> pr "void ";
9466 | RInt _ -> pr "int ";
9467 | RInt64 _ -> pr "long ";
9468 | RBool _ -> pr "boolean ";
9469 | RConstString _ | RConstOptString _ | RString _
9470 | RBufferOut _ -> pr "String ";
9471 | RStringList _ -> pr "String[] ";
9472 | RStruct (_, typ) ->
9473 let name = java_name_of_struct typ in
9475 | RStructList (_, typ) ->
9476 let name = java_name_of_struct typ in
9478 | RHashtable _ -> pr "HashMap<String,String> ";
9481 if native then pr "_%s " name else pr "%s " name;
9483 let needs_comma = ref false in
9492 if !needs_comma then pr ", ";
9493 needs_comma := true;
9497 | Device n | Dev_or_Path n
9503 | StringList n | DeviceList n ->
9514 pr " throws LibGuestFSException";
9515 if semicolon then pr ";"
9517 and generate_java_struct jtyp cols () =
9518 generate_header CStyle LGPLv2plus;
9521 package com.redhat.et.libguestfs;
9524 * Libguestfs %s structure.
9536 | name, FBuffer -> pr " public String %s;\n" name
9537 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
9538 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
9539 | name, FChar -> pr " public char %s;\n" name
9540 | name, FOptPercent ->
9541 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
9542 pr " public float %s;\n" name
9547 and generate_java_c () =
9548 generate_header CStyle LGPLv2plus;
9555 #include \"com_redhat_et_libguestfs_GuestFS.h\"
9556 #include \"guestfs.h\"
9558 /* Note that this function returns. The exception is not thrown
9559 * until after the wrapper function returns.
9562 throw_exception (JNIEnv *env, const char *msg)
9565 cl = (*env)->FindClass (env,
9566 \"com/redhat/et/libguestfs/LibGuestFSException\");
9567 (*env)->ThrowNew (env, cl, msg);
9570 JNIEXPORT jlong JNICALL
9571 Java_com_redhat_et_libguestfs_GuestFS__1create
9572 (JNIEnv *env, jobject obj)
9576 g = guestfs_create ();
9578 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
9581 guestfs_set_error_handler (g, NULL, NULL);
9582 return (jlong) (long) g;
9585 JNIEXPORT void JNICALL
9586 Java_com_redhat_et_libguestfs_GuestFS__1close
9587 (JNIEnv *env, jobject obj, jlong jg)
9589 guestfs_h *g = (guestfs_h *) (long) jg;
9596 fun (name, style, _, _, _, _, _) ->
9598 (match fst style with
9599 | RErr -> pr "void ";
9600 | RInt _ -> pr "jint ";
9601 | RInt64 _ -> pr "jlong ";
9602 | RBool _ -> pr "jboolean ";
9603 | RConstString _ | RConstOptString _ | RString _
9604 | RBufferOut _ -> pr "jstring ";
9605 | RStruct _ | RHashtable _ ->
9607 | RStringList _ | RStructList _ ->
9611 pr "Java_com_redhat_et_libguestfs_GuestFS_";
9612 pr "%s" (replace_str ("_" ^ name) "_" "_1");
9614 pr " (JNIEnv *env, jobject obj, jlong jg";
9618 | Device n | Dev_or_Path n
9623 pr ", jstring j%s" n
9624 | StringList n | DeviceList n ->
9625 pr ", jobjectArray j%s" n
9627 pr ", jboolean j%s" n
9635 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
9636 let error_code, no_ret =
9637 match fst style with
9638 | RErr -> pr " int r;\n"; "-1", ""
9640 | RInt _ -> pr " int r;\n"; "-1", "0"
9641 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
9642 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
9643 | RConstOptString _ -> pr " const char *r;\n"; "NULL", "NULL"
9645 pr " jstring jr;\n";
9646 pr " char *r;\n"; "NULL", "NULL"
9648 pr " jobjectArray jr;\n";
9651 pr " jstring jstr;\n";
9652 pr " char **r;\n"; "NULL", "NULL"
9653 | RStruct (_, typ) ->
9654 pr " jobject jr;\n";
9656 pr " jfieldID fl;\n";
9657 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
9658 | RStructList (_, typ) ->
9659 pr " jobjectArray jr;\n";
9661 pr " jfieldID fl;\n";
9662 pr " jobject jfl;\n";
9663 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
9664 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL"
9666 pr " jstring jr;\n";
9668 pr " size_t size;\n";
9673 | Device n | Dev_or_Path n
9678 pr " const char *%s;\n" n
9679 | StringList n | DeviceList n ->
9680 pr " int %s_len;\n" n;
9681 pr " const char **%s;\n" n
9686 pr " int64_t %s;\n" n
9690 (match fst style with
9691 | RStringList _ | RStructList _ -> true
9692 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
9694 | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
9695 List.exists (function
9696 | StringList _ -> true
9697 | DeviceList _ -> true
9698 | _ -> false) (snd style) in
9704 (* Get the parameters. *)
9708 | Device n | Dev_or_Path n
9712 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
9714 (* This is completely undocumented, but Java null becomes
9717 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
9718 | StringList n | DeviceList n ->
9719 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
9720 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
9721 pr " for (i = 0; i < %s_len; ++i) {\n" n;
9722 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
9724 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
9726 pr " %s[%s_len] = NULL;\n" n n;
9730 pr " %s = j%s;\n" n n
9733 (* Make the call. *)
9734 pr " r = guestfs_%s " name;
9735 generate_c_call_args ~handle:"g" style;
9738 (* Release the parameters. *)
9742 | Device n | Dev_or_Path n
9746 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
9749 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
9750 | StringList n | DeviceList n ->
9751 pr " for (i = 0; i < %s_len; ++i) {\n" n;
9752 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
9754 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
9756 pr " free (%s);\n" n
9762 (* Check for errors. *)
9763 pr " if (r == %s) {\n" error_code;
9764 pr " throw_exception (env, guestfs_last_error (g));\n";
9765 pr " return %s;\n" no_ret;
9769 (match fst style with
9771 | RInt _ -> pr " return (jint) r;\n"
9772 | RBool _ -> pr " return (jboolean) r;\n"
9773 | RInt64 _ -> pr " return (jlong) r;\n"
9774 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
9775 | RConstOptString _ ->
9776 pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
9778 pr " jr = (*env)->NewStringUTF (env, r);\n";
9782 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
9783 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
9784 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
9785 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
9786 pr " for (i = 0; i < r_len; ++i) {\n";
9787 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
9788 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
9789 pr " free (r[i]);\n";
9793 | RStruct (_, typ) ->
9794 let jtyp = java_name_of_struct typ in
9795 let cols = cols_of_struct typ in
9796 generate_java_struct_return typ jtyp cols
9797 | RStructList (_, typ) ->
9798 let jtyp = java_name_of_struct typ in
9799 let cols = cols_of_struct typ in
9800 generate_java_struct_list_return typ jtyp cols
9803 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
9804 pr " return NULL;\n"
9806 pr " jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
9815 and generate_java_struct_return typ jtyp cols =
9816 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
9817 pr " jr = (*env)->AllocObject (env, cl);\n";
9821 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9822 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
9825 pr " char s[33];\n";
9826 pr " memcpy (s, r->%s, 32);\n" name;
9828 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9829 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
9833 pr " int len = r->%s_len;\n" name;
9834 pr " char s[len+1];\n";
9835 pr " memcpy (s, r->%s, len);\n" name;
9836 pr " s[len] = 0;\n";
9837 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9838 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
9840 | name, (FBytes|FUInt64|FInt64) ->
9841 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
9842 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9843 | name, (FUInt32|FInt32) ->
9844 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
9845 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9846 | name, FOptPercent ->
9847 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
9848 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
9850 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
9851 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9856 and generate_java_struct_list_return typ jtyp cols =
9857 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
9858 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
9859 pr " for (i = 0; i < r->len; ++i) {\n";
9860 pr " jfl = (*env)->AllocObject (env, cl);\n";
9864 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9865 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
9868 pr " char s[33];\n";
9869 pr " memcpy (s, r->val[i].%s, 32);\n" name;
9871 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9872 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
9876 pr " int len = r->val[i].%s_len;\n" name;
9877 pr " char s[len+1];\n";
9878 pr " memcpy (s, r->val[i].%s, len);\n" name;
9879 pr " s[len] = 0;\n";
9880 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9881 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
9883 | name, (FBytes|FUInt64|FInt64) ->
9884 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
9885 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9886 | name, (FUInt32|FInt32) ->
9887 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
9888 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9889 | name, FOptPercent ->
9890 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
9891 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
9893 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
9894 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9896 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
9898 pr " guestfs_free_%s_list (r);\n" typ;
9901 and generate_java_makefile_inc () =
9902 generate_header HashStyle GPLv2plus;
9904 pr "java_built_sources = \\\n";
9907 pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
9909 pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
9911 and generate_haskell_hs () =
9912 generate_header HaskellStyle LGPLv2plus;
9914 (* XXX We only know how to generate partial FFI for Haskell
9915 * at the moment. Please help out!
9917 let can_generate style =
9921 | RInt64 _, _ -> true
9924 | RConstOptString _, _
9930 | RBufferOut _, _ -> false in
9933 {-# INCLUDE <guestfs.h> #-}
9934 {-# LANGUAGE ForeignFunctionInterface #-}
9939 (* List out the names of the actions we want to export. *)
9941 fun (name, style, _, _, _, _, _) ->
9942 if can_generate style then pr ",\n %s" name
9948 -- Unfortunately some symbols duplicate ones already present
9949 -- in Prelude. We don't know which, so we hard-code a list
9951 import Prelude hiding (truncate)
9955 import Foreign.C.Types
9957 import Control.Exception
9958 import Data.Typeable
9960 data GuestfsS = GuestfsS -- represents the opaque C struct
9961 type GuestfsP = Ptr GuestfsS -- guestfs_h *
9962 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
9964 -- XXX define properly later XXX
9968 data IntBool = IntBool
9970 data StatVFS = StatVFS
9971 data Hashtable = Hashtable
9973 foreign import ccall unsafe \"guestfs_create\" c_create
9975 foreign import ccall unsafe \"&guestfs_close\" c_close
9976 :: FunPtr (GuestfsP -> IO ())
9977 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
9978 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
9980 create :: IO GuestfsH
9983 c_set_error_handler p nullPtr nullPtr
9984 h <- newForeignPtr c_close p
9987 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
9988 :: GuestfsP -> IO CString
9990 -- last_error :: GuestfsH -> IO (Maybe String)
9991 -- last_error h = do
9992 -- str <- withForeignPtr h (\\p -> c_last_error p)
9993 -- maybePeek peekCString str
9995 last_error :: GuestfsH -> IO (String)
9997 str <- withForeignPtr h (\\p -> c_last_error p)
9999 then return \"no error\"
10000 else peekCString str
10004 (* Generate wrappers for each foreign function. *)
10006 fun (name, style, _, _, _, _, _) ->
10007 if can_generate style then (
10008 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
10010 generate_haskell_prototype ~handle:"GuestfsP" style;
10014 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
10016 pr "%s %s = do\n" name
10017 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
10019 (* Convert pointer arguments using with* functions. *)
10024 | Pathname n | Device n | Dev_or_Path n | String n -> pr "withCString %s $ \\%s -> " n n
10025 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
10026 | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
10027 | Bool _ | Int _ | Int64 _ -> ()
10029 (* Convert integer arguments. *)
10033 | Bool n -> sprintf "(fromBool %s)" n
10034 | Int n -> sprintf "(fromIntegral %s)" n
10035 | Int64 n -> sprintf "(fromIntegral %s)" n
10036 | FileIn n | FileOut n
10037 | Pathname n | Device n | Dev_or_Path n | String n | OptString n | StringList n | DeviceList n -> n
10039 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
10040 (String.concat " " ("p" :: args));
10041 (match fst style with
10042 | RErr | RInt _ | RInt64 _ | RBool _ ->
10043 pr " if (r == -1)\n";
10045 pr " err <- last_error h\n";
10047 | RConstString _ | RConstOptString _ | RString _
10048 | RStringList _ | RStruct _
10049 | RStructList _ | RHashtable _ | RBufferOut _ ->
10050 pr " if (r == nullPtr)\n";
10052 pr " err <- last_error h\n";
10055 (match fst style with
10057 pr " else return ()\n"
10059 pr " else return (fromIntegral r)\n"
10061 pr " else return (fromIntegral r)\n"
10063 pr " else return (toBool r)\n"
10065 | RConstOptString _
10072 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
10078 and generate_haskell_prototype ~handle ?(hs = false) style =
10079 pr "%s -> " handle;
10080 let string = if hs then "String" else "CString" in
10081 let int = if hs then "Int" else "CInt" in
10082 let bool = if hs then "Bool" else "CInt" in
10083 let int64 = if hs then "Integer" else "Int64" in
10087 | Pathname _ | Device _ | Dev_or_Path _ | String _ -> pr "%s" string
10088 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
10089 | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
10090 | Bool _ -> pr "%s" bool
10091 | Int _ -> pr "%s" int
10092 | Int64 _ -> pr "%s" int
10093 | FileIn _ -> pr "%s" string
10094 | FileOut _ -> pr "%s" string
10099 (match fst style with
10100 | RErr -> if not hs then pr "CInt"
10101 | RInt _ -> pr "%s" int
10102 | RInt64 _ -> pr "%s" int64
10103 | RBool _ -> pr "%s" bool
10104 | RConstString _ -> pr "%s" string
10105 | RConstOptString _ -> pr "Maybe %s" string
10106 | RString _ -> pr "%s" string
10107 | RStringList _ -> pr "[%s]" string
10108 | RStruct (_, typ) ->
10109 let name = java_name_of_struct typ in
10111 | RStructList (_, typ) ->
10112 let name = java_name_of_struct typ in
10114 | RHashtable _ -> pr "Hashtable"
10115 | RBufferOut _ -> pr "%s" string
10119 and generate_csharp () =
10120 generate_header CPlusPlusStyle LGPLv2plus;
10122 (* XXX Make this configurable by the C# assembly users. *)
10123 let library = "libguestfs.so.0" in
10126 // These C# bindings are highly experimental at present.
10128 // Firstly they only work on Linux (ie. Mono). In order to get them
10129 // to work on Windows (ie. .Net) you would need to port the library
10130 // itself to Windows first.
10132 // The second issue is that some calls are known to be incorrect and
10133 // can cause Mono to segfault. Particularly: calls which pass or
10134 // return string[], or return any structure value. This is because
10135 // we haven't worked out the correct way to do this from C#.
10137 // The third issue is that when compiling you get a lot of warnings.
10138 // We are not sure whether the warnings are important or not.
10140 // Fourthly we do not routinely build or test these bindings as part
10141 // of the make && make check cycle, which means that regressions might
10144 // Suggestions and patches are welcome.
10148 // gmcs Libguestfs.cs
10149 // mono Libguestfs.exe
10151 // (You'll probably want to add a Test class / static main function
10152 // otherwise this won't do anything useful).
10156 using System.Runtime.InteropServices;
10157 using System.Runtime.Serialization;
10158 using System.Collections;
10162 class Error : System.ApplicationException
10164 public Error (string message) : base (message) {}
10165 protected Error (SerializationInfo info, StreamingContext context) {}
10172 [DllImport (\"%s\")]
10173 static extern IntPtr guestfs_create ();
10177 _handle = guestfs_create ();
10178 if (_handle == IntPtr.Zero)
10179 throw new Error (\"could not create guestfs handle\");
10182 [DllImport (\"%s\")]
10183 static extern void guestfs_close (IntPtr h);
10187 guestfs_close (_handle);
10190 [DllImport (\"%s\")]
10191 static extern string guestfs_last_error (IntPtr h);
10193 " library library library;
10195 (* Generate C# structure bindings. We prefix struct names with
10196 * underscore because C# cannot have conflicting struct names and
10197 * method names (eg. "class stat" and "stat").
10201 pr " [StructLayout (LayoutKind.Sequential)]\n";
10202 pr " public class _%s {\n" typ;
10205 | name, FChar -> pr " char %s;\n" name
10206 | name, FString -> pr " string %s;\n" name
10208 pr " uint %s_len;\n" name;
10209 pr " string %s;\n" name
10211 pr " [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
10212 pr " string %s;\n" name
10213 | name, FUInt32 -> pr " uint %s;\n" name
10214 | name, FInt32 -> pr " int %s;\n" name
10215 | name, (FUInt64|FBytes) -> pr " ulong %s;\n" name
10216 | name, FInt64 -> pr " long %s;\n" name
10217 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
10223 (* Generate C# function bindings. *)
10225 fun (name, style, _, _, _, shortdesc, _) ->
10226 let rec csharp_return_type () =
10227 match fst style with
10229 | RBool n -> "bool"
10231 | RInt64 n -> "long"
10233 | RConstOptString n
10235 | RBufferOut n -> "string"
10236 | RStruct (_,n) -> "_" ^ n
10237 | RHashtable n -> "Hashtable"
10238 | RStringList n -> "string[]"
10239 | RStructList (_,n) -> sprintf "_%s[]" n
10241 and c_return_type () =
10242 match fst style with
10246 | RInt64 _ -> "long"
10248 | RConstOptString _
10250 | RBufferOut _ -> "string"
10251 | RStruct (_,n) -> "_" ^ n
10253 | RStringList _ -> "string[]"
10254 | RStructList (_,n) -> sprintf "_%s[]" n
10256 and c_error_comparison () =
10257 match fst style with
10261 | RInt64 _ -> "== -1"
10263 | RConstOptString _
10269 | RStructList (_,_) -> "== null"
10271 and generate_extern_prototype () =
10272 pr " static extern %s guestfs_%s (IntPtr h"
10273 (c_return_type ()) name;
10276 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
10277 | FileIn n | FileOut n ->
10278 pr ", [In] string %s" n
10279 | StringList n | DeviceList n ->
10280 pr ", [In] string[] %s" n
10290 and generate_public_prototype () =
10291 pr " public %s %s (" (csharp_return_type ()) name;
10292 let comma = ref false in
10294 if !comma then pr ", ";
10299 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
10300 | FileIn n | FileOut n ->
10301 next (); pr "string %s" n
10302 | StringList n | DeviceList n ->
10303 next (); pr "string[] %s" n
10305 next (); pr "bool %s" n
10307 next (); pr "int %s" n
10309 next (); pr "long %s" n
10313 and generate_call () =
10314 pr "guestfs_%s (_handle" name;
10315 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
10319 pr " [DllImport (\"%s\")]\n" library;
10320 generate_extern_prototype ();
10322 pr " /// <summary>\n";
10323 pr " /// %s\n" shortdesc;
10324 pr " /// </summary>\n";
10325 generate_public_prototype ();
10327 pr " %s r;\n" (c_return_type ());
10330 pr " if (r %s)\n" (c_error_comparison ());
10331 pr " throw new Error (guestfs_last_error (_handle));\n";
10332 (match fst style with
10335 pr " return r != 0 ? true : false;\n"
10337 pr " Hashtable rr = new Hashtable ();\n";
10338 pr " for (int i = 0; i < r.Length; i += 2)\n";
10339 pr " rr.Add (r[i], r[i+1]);\n";
10341 | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
10342 | RString _ | RBufferOut _ | RStruct _ | RStringList _
10348 ) all_functions_sorted;
10354 and generate_bindtests () =
10355 generate_header CStyle LGPLv2plus;
10359 #include <stdlib.h>
10360 #include <inttypes.h>
10361 #include <string.h>
10363 #include \"guestfs.h\"
10364 #include \"guestfs-internal.h\"
10365 #include \"guestfs-internal-actions.h\"
10366 #include \"guestfs_protocol.h\"
10368 #define error guestfs_error
10369 #define safe_calloc guestfs_safe_calloc
10370 #define safe_malloc guestfs_safe_malloc
10373 print_strings (char *const *argv)
10378 for (argc = 0; argv[argc] != NULL; ++argc) {
10379 if (argc > 0) printf (\", \");
10380 printf (\"\\\"%%s\\\"\", argv[argc]);
10385 /* The test0 function prints its parameters to stdout. */
10389 match test_functions with
10390 | [] -> assert false
10391 | test0 :: tests -> test0, tests in
10394 let (name, style, _, _, _, _, _) = test0 in
10395 generate_prototype ~extern:false ~semicolon:false ~newline:true
10396 ~handle:"g" ~prefix:"guestfs__" name style;
10401 | Device n | Dev_or_Path n
10404 | FileOut n -> pr " printf (\"%%s\\n\", %s);\n" n
10405 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
10406 | StringList n | DeviceList n -> pr " print_strings (%s);\n" n
10407 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
10408 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
10409 | Int64 n -> pr " printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
10411 pr " /* Java changes stdout line buffering so we need this: */\n";
10412 pr " fflush (stdout);\n";
10418 fun (name, style, _, _, _, _, _) ->
10419 if String.sub name (String.length name - 3) 3 <> "err" then (
10420 pr "/* Test normal return. */\n";
10421 generate_prototype ~extern:false ~semicolon:false ~newline:true
10422 ~handle:"g" ~prefix:"guestfs__" name style;
10424 (match fst style with
10429 pr " sscanf (val, \"%%d\", &r);\n";
10432 pr " int64_t r;\n";
10433 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
10436 pr " return STREQ (val, \"true\");\n"
10438 | RConstOptString _ ->
10439 (* Can't return the input string here. Return a static
10440 * string so we ensure we get a segfault if the caller
10441 * tries to free it.
10443 pr " return \"static string\";\n"
10445 pr " return strdup (val);\n"
10447 pr " char **strs;\n";
10449 pr " sscanf (val, \"%%d\", &n);\n";
10450 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
10451 pr " for (i = 0; i < n; ++i) {\n";
10452 pr " strs[i] = safe_malloc (g, 16);\n";
10453 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
10455 pr " strs[n] = NULL;\n";
10456 pr " return strs;\n"
10457 | RStruct (_, typ) ->
10458 pr " struct guestfs_%s *r;\n" typ;
10459 pr " r = safe_calloc (g, sizeof *r, 1);\n";
10461 | RStructList (_, typ) ->
10462 pr " struct guestfs_%s_list *r;\n" typ;
10463 pr " r = safe_calloc (g, sizeof *r, 1);\n";
10464 pr " sscanf (val, \"%%d\", &r->len);\n";
10465 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
10468 pr " char **strs;\n";
10470 pr " sscanf (val, \"%%d\", &n);\n";
10471 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
10472 pr " for (i = 0; i < n; ++i) {\n";
10473 pr " strs[i*2] = safe_malloc (g, 16);\n";
10474 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
10475 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
10476 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
10478 pr " strs[n*2] = NULL;\n";
10479 pr " return strs;\n"
10481 pr " return strdup (val);\n"
10486 pr "/* Test error return. */\n";
10487 generate_prototype ~extern:false ~semicolon:false ~newline:true
10488 ~handle:"g" ~prefix:"guestfs__" name style;
10490 pr " error (g, \"error\");\n";
10491 (match fst style with
10492 | RErr | RInt _ | RInt64 _ | RBool _ ->
10494 | RConstString _ | RConstOptString _
10495 | RString _ | RStringList _ | RStruct _
10499 pr " return NULL;\n"
10506 and generate_ocaml_bindtests () =
10507 generate_header OCamlStyle GPLv2plus;
10511 let g = Guestfs.create () in
10515 String.concat " " (
10518 | CallString s -> "\"" ^ s ^ "\""
10519 | CallOptString None -> "None"
10520 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
10521 | CallStringList xs ->
10522 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
10523 | CallInt i when i >= 0 -> string_of_int i
10524 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
10525 | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
10526 | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
10527 | CallBool b -> string_of_bool b
10532 generate_lang_bindtests (
10533 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
10536 pr "print_endline \"EOF\"\n"
10538 and generate_perl_bindtests () =
10539 pr "#!/usr/bin/perl -w\n";
10540 generate_header HashStyle GPLv2plus;
10547 my $g = Sys::Guestfs->new ();
10551 String.concat ", " (
10554 | CallString s -> "\"" ^ s ^ "\""
10555 | CallOptString None -> "undef"
10556 | CallOptString (Some s) -> sprintf "\"%s\"" s
10557 | CallStringList xs ->
10558 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
10559 | CallInt i -> string_of_int i
10560 | CallInt64 i -> Int64.to_string i
10561 | CallBool b -> if b then "1" else "0"
10566 generate_lang_bindtests (
10567 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
10570 pr "print \"EOF\\n\"\n"
10572 and generate_python_bindtests () =
10573 generate_header HashStyle GPLv2plus;
10578 g = guestfs.GuestFS ()
10582 String.concat ", " (
10585 | CallString s -> "\"" ^ s ^ "\""
10586 | CallOptString None -> "None"
10587 | CallOptString (Some s) -> sprintf "\"%s\"" s
10588 | CallStringList xs ->
10589 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
10590 | CallInt i -> string_of_int i
10591 | CallInt64 i -> Int64.to_string i
10592 | CallBool b -> if b then "1" else "0"
10597 generate_lang_bindtests (
10598 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
10601 pr "print \"EOF\"\n"
10603 and generate_ruby_bindtests () =
10604 generate_header HashStyle GPLv2plus;
10609 g = Guestfs::create()
10613 String.concat ", " (
10616 | CallString s -> "\"" ^ s ^ "\""
10617 | CallOptString None -> "nil"
10618 | CallOptString (Some s) -> sprintf "\"%s\"" s
10619 | CallStringList xs ->
10620 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
10621 | CallInt i -> string_of_int i
10622 | CallInt64 i -> Int64.to_string i
10623 | CallBool b -> string_of_bool b
10628 generate_lang_bindtests (
10629 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
10632 pr "print \"EOF\\n\"\n"
10634 and generate_java_bindtests () =
10635 generate_header CStyle GPLv2plus;
10638 import com.redhat.et.libguestfs.*;
10640 public class Bindtests {
10641 public static void main (String[] argv)
10644 GuestFS g = new GuestFS ();
10648 String.concat ", " (
10651 | CallString s -> "\"" ^ s ^ "\""
10652 | CallOptString None -> "null"
10653 | CallOptString (Some s) -> sprintf "\"%s\"" s
10654 | CallStringList xs ->
10656 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
10657 | CallInt i -> string_of_int i
10658 | CallInt64 i -> Int64.to_string i
10659 | CallBool b -> string_of_bool b
10664 generate_lang_bindtests (
10665 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
10669 System.out.println (\"EOF\");
10671 catch (Exception exn) {
10672 System.err.println (exn);
10679 and generate_haskell_bindtests () =
10680 generate_header HaskellStyle GPLv2plus;
10683 module Bindtests where
10684 import qualified Guestfs
10687 g <- Guestfs.create
10691 String.concat " " (
10694 | CallString s -> "\"" ^ s ^ "\""
10695 | CallOptString None -> "Nothing"
10696 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
10697 | CallStringList xs ->
10698 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
10699 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
10700 | CallInt i -> string_of_int i
10701 | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
10702 | CallInt64 i -> Int64.to_string i
10703 | CallBool true -> "True"
10704 | CallBool false -> "False"
10709 generate_lang_bindtests (
10710 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
10713 pr " putStrLn \"EOF\"\n"
10715 (* Language-independent bindings tests - we do it this way to
10716 * ensure there is parity in testing bindings across all languages.
10718 and generate_lang_bindtests call =
10719 call "test0" [CallString "abc"; CallOptString (Some "def");
10720 CallStringList []; CallBool false;
10721 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10722 call "test0" [CallString "abc"; CallOptString None;
10723 CallStringList []; CallBool false;
10724 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10725 call "test0" [CallString ""; CallOptString (Some "def");
10726 CallStringList []; CallBool false;
10727 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10728 call "test0" [CallString ""; CallOptString (Some "");
10729 CallStringList []; CallBool false;
10730 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10731 call "test0" [CallString "abc"; CallOptString (Some "def");
10732 CallStringList ["1"]; CallBool false;
10733 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10734 call "test0" [CallString "abc"; CallOptString (Some "def");
10735 CallStringList ["1"; "2"]; CallBool false;
10736 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10737 call "test0" [CallString "abc"; CallOptString (Some "def");
10738 CallStringList ["1"]; CallBool true;
10739 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
10740 call "test0" [CallString "abc"; CallOptString (Some "def");
10741 CallStringList ["1"]; CallBool false;
10742 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456"];
10743 call "test0" [CallString "abc"; CallOptString (Some "def");
10744 CallStringList ["1"]; CallBool false;
10745 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456"];
10746 call "test0" [CallString "abc"; CallOptString (Some "def");
10747 CallStringList ["1"]; CallBool false;
10748 CallInt 1; CallInt64 1L; CallString "123"; CallString "456"];
10749 call "test0" [CallString "abc"; CallOptString (Some "def");
10750 CallStringList ["1"]; CallBool false;
10751 CallInt 2; CallInt64 2L; CallString "123"; CallString "456"];
10752 call "test0" [CallString "abc"; CallOptString (Some "def");
10753 CallStringList ["1"]; CallBool false;
10754 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456"];
10755 call "test0" [CallString "abc"; CallOptString (Some "def");
10756 CallStringList ["1"]; CallBool false;
10757 CallInt 0; CallInt64 0L; CallString ""; CallString ""]
10759 (* XXX Add here tests of the return and error functions. *)
10761 (* Code to generator bindings for virt-inspector. Currently only
10762 * implemented for OCaml code (for virt-p2v 2.0).
10764 let rng_input = "inspector/virt-inspector.rng"
10766 (* Read the input file and parse it into internal structures. This is
10767 * by no means a complete RELAX NG parser, but is just enough to be
10768 * able to parse the specific input file.
10771 | Element of string * rng list (* <element name=name/> *)
10772 | Attribute of string * rng list (* <attribute name=name/> *)
10773 | Interleave of rng list (* <interleave/> *)
10774 | ZeroOrMore of rng (* <zeroOrMore/> *)
10775 | OneOrMore of rng (* <oneOrMore/> *)
10776 | Optional of rng (* <optional/> *)
10777 | Choice of string list (* <choice><value/>*</choice> *)
10778 | Value of string (* <value>str</value> *)
10779 | Text (* <text/> *)
10781 let rec string_of_rng = function
10782 | Element (name, xs) ->
10783 "Element (\"" ^ name ^ "\", (" ^ string_of_rng_list xs ^ "))"
10784 | Attribute (name, xs) ->
10785 "Attribute (\"" ^ name ^ "\", (" ^ string_of_rng_list xs ^ "))"
10786 | Interleave xs -> "Interleave (" ^ string_of_rng_list xs ^ ")"
10787 | ZeroOrMore rng -> "ZeroOrMore (" ^ string_of_rng rng ^ ")"
10788 | OneOrMore rng -> "OneOrMore (" ^ string_of_rng rng ^ ")"
10789 | Optional rng -> "Optional (" ^ string_of_rng rng ^ ")"
10790 | Choice values -> "Choice [" ^ String.concat ", " values ^ "]"
10791 | Value value -> "Value \"" ^ value ^ "\""
10794 and string_of_rng_list xs =
10795 String.concat ", " (List.map string_of_rng xs)
10797 let rec parse_rng ?defines context = function
10799 | Xml.Element ("element", ["name", name], children) :: rest ->
10800 Element (name, parse_rng ?defines context children)
10801 :: parse_rng ?defines context rest
10802 | Xml.Element ("attribute", ["name", name], children) :: rest ->
10803 Attribute (name, parse_rng ?defines context children)
10804 :: parse_rng ?defines context rest
10805 | Xml.Element ("interleave", [], children) :: rest ->
10806 Interleave (parse_rng ?defines context children)
10807 :: parse_rng ?defines context rest
10808 | Xml.Element ("zeroOrMore", [], [child]) :: rest ->
10809 let rng = parse_rng ?defines context [child] in
10811 | [child] -> ZeroOrMore child :: parse_rng ?defines context rest
10813 failwithf "%s: <zeroOrMore> contains more than one child element"
10816 | Xml.Element ("oneOrMore", [], [child]) :: rest ->
10817 let rng = parse_rng ?defines context [child] in
10819 | [child] -> OneOrMore child :: parse_rng ?defines context rest
10821 failwithf "%s: <oneOrMore> contains more than one child element"
10824 | Xml.Element ("optional", [], [child]) :: rest ->
10825 let rng = parse_rng ?defines context [child] in
10827 | [child] -> Optional child :: parse_rng ?defines context rest
10829 failwithf "%s: <optional> contains more than one child element"
10832 | Xml.Element ("choice", [], children) :: rest ->
10833 let values = List.map (
10834 function Xml.Element ("value", [], [Xml.PCData value]) -> value
10836 failwithf "%s: can't handle anything except <value> in <choice>"
10840 :: parse_rng ?defines context rest
10841 | Xml.Element ("value", [], [Xml.PCData value]) :: rest ->
10842 Value value :: parse_rng ?defines context rest
10843 | Xml.Element ("text", [], []) :: rest ->
10844 Text :: parse_rng ?defines context rest
10845 | Xml.Element ("ref", ["name", name], []) :: rest ->
10846 (* Look up the reference. Because of limitations in this parser,
10847 * we can't handle arbitrarily nested <ref> yet. You can only
10848 * use <ref> from inside <start>.
10850 (match defines with
10852 failwithf "%s: contains <ref>, but no refs are defined yet" context
10854 let rng = StringMap.find name map in
10855 rng @ parse_rng ?defines context rest
10858 failwithf "%s: can't handle '%s' in schema" context (Xml.to_string x)
10861 let xml = Xml.parse_file rng_input in
10863 | Xml.Element ("grammar", _,
10864 Xml.Element ("start", _, gram) :: defines) ->
10865 (* The <define/> elements are referenced in the <start> section,
10866 * so build a map of those first.
10868 let defines = List.fold_left (
10870 function Xml.Element ("define", ["name", name], defn) ->
10871 StringMap.add name defn map
10873 failwithf "%s: expected <define name=name/>" rng_input
10874 ) StringMap.empty defines in
10875 let defines = StringMap.mapi parse_rng defines in
10877 (* Parse the <start> clause, passing the defines. *)
10878 parse_rng ~defines "<start>" gram
10880 failwithf "%s: input is not <grammar><start/><define>*</grammar>"
10883 let name_of_field = function
10884 | Element (name, _) | Attribute (name, _)
10885 | ZeroOrMore (Element (name, _))
10886 | OneOrMore (Element (name, _))
10887 | Optional (Element (name, _)) -> name
10888 | Optional (Attribute (name, _)) -> name
10889 | Text -> (* an unnamed field in an element *)
10892 failwithf "name_of_field failed at: %s" (string_of_rng rng)
10894 (* At the moment this function only generates OCaml types. However we
10895 * should parameterize it later so it can generate types/structs in a
10896 * variety of languages.
10898 let generate_types xs =
10899 (* A simple type is one that can be printed out directly, eg.
10900 * "string option". A complex type is one which has a name and has
10901 * to be defined via another toplevel definition, eg. a struct.
10903 * generate_type generates code for either simple or complex types.
10904 * In the simple case, it returns the string ("string option"). In
10905 * the complex case, it returns the name ("mountpoint"). In the
10906 * complex case it has to print out the definition before returning,
10907 * so it should only be called when we are at the beginning of a
10908 * new line (BOL context).
10910 let rec generate_type = function
10911 | Text -> (* string *)
10913 | Choice values -> (* [`val1|`val2|...] *)
10914 "[" ^ String.concat "|" (List.map ((^)"`") values) ^ "]", true
10915 | ZeroOrMore rng -> (* <rng> list *)
10916 let t, is_simple = generate_type rng in
10917 t ^ " list (* 0 or more *)", is_simple
10918 | OneOrMore rng -> (* <rng> list *)
10919 let t, is_simple = generate_type rng in
10920 t ^ " list (* 1 or more *)", is_simple
10921 (* virt-inspector hack: bool *)
10922 | Optional (Attribute (name, [Value "1"])) ->
10924 | Optional rng -> (* <rng> list *)
10925 let t, is_simple = generate_type rng in
10926 t ^ " option", is_simple
10927 (* type name = { fields ... } *)
10928 | Element (name, fields) when is_attrs_interleave fields ->
10929 generate_type_struct name (get_attrs_interleave fields)
10930 | Element (name, [field]) (* type name = field *)
10931 | Attribute (name, [field]) ->
10932 let t, is_simple = generate_type field in
10933 if is_simple then (t, true)
10935 pr "type %s = %s\n" name t;
10938 | Element (name, fields) -> (* type name = { fields ... } *)
10939 generate_type_struct name fields
10941 failwithf "generate_type failed at: %s" (string_of_rng rng)
10943 and is_attrs_interleave = function
10944 | [Interleave _] -> true
10945 | Attribute _ :: fields -> is_attrs_interleave fields
10946 | Optional (Attribute _) :: fields -> is_attrs_interleave fields
10949 and get_attrs_interleave = function
10950 | [Interleave fields] -> fields
10951 | ((Attribute _) as field) :: fields
10952 | ((Optional (Attribute _)) as field) :: fields ->
10953 field :: get_attrs_interleave fields
10954 | _ -> assert false
10956 and generate_types xs =
10957 List.iter (fun x -> ignore (generate_type x)) xs
10959 and generate_type_struct name fields =
10960 (* Calculate the types of the fields first. We have to do this
10961 * before printing anything so we are still in BOL context.
10963 let types = List.map fst (List.map generate_type fields) in
10965 (* Special case of a struct containing just a string and another
10966 * field. Turn it into an assoc list.
10969 | ["string"; other] ->
10970 let fname1, fname2 =
10972 | [f1; f2] -> name_of_field f1, name_of_field f2
10973 | _ -> assert false in
10974 pr "type %s = string * %s (* %s -> %s *)\n" name other fname1 fname2;
10978 pr "type %s = {\n" name;
10980 fun (field, ftype) ->
10981 let fname = name_of_field field in
10982 pr " %s_%s : %s;\n" name fname ftype
10983 ) (List.combine fields types);
10985 (* Return the name of this type, and
10986 * false because it's not a simple type.
10993 let generate_parsers xs =
10994 (* As for generate_type above, generate_parser makes a parser for
10995 * some type, and returns the name of the parser it has generated.
10996 * Because it (may) need to print something, it should always be
10997 * called in BOL context.
10999 let rec generate_parser = function
11000 | Text -> (* string *)
11001 "string_child_or_empty"
11002 | Choice values -> (* [`val1|`val2|...] *)
11003 sprintf "(fun x -> match Xml.pcdata (first_child x) with %s | str -> failwith (\"unexpected field value: \" ^ str))"
11005 (List.map (fun v -> sprintf "%S -> `%s" v v) values))
11006 | ZeroOrMore rng -> (* <rng> list *)
11007 let pa = generate_parser rng in
11008 sprintf "(fun x -> List.map %s (Xml.children x))" pa
11009 | OneOrMore rng -> (* <rng> list *)
11010 let pa = generate_parser rng in
11011 sprintf "(fun x -> List.map %s (Xml.children x))" pa
11012 (* virt-inspector hack: bool *)
11013 | Optional (Attribute (name, [Value "1"])) ->
11014 sprintf "(fun x -> try ignore (Xml.attrib x %S); true with Xml.No_attribute _ -> false)" name
11015 | Optional rng -> (* <rng> list *)
11016 let pa = generate_parser rng in
11017 sprintf "(function None -> None | Some x -> Some (%s x))" pa
11018 (* type name = { fields ... } *)
11019 | Element (name, fields) when is_attrs_interleave fields ->
11020 generate_parser_struct name (get_attrs_interleave fields)
11021 | Element (name, [field]) -> (* type name = field *)
11022 let pa = generate_parser field in
11023 let parser_name = sprintf "parse_%s_%d" name (unique ()) in
11024 pr "let %s =\n" parser_name;
11026 pr "let parse_%s = %s\n" name parser_name;
11028 | Attribute (name, [field]) ->
11029 let pa = generate_parser field in
11030 let parser_name = sprintf "parse_%s_%d" name (unique ()) in
11031 pr "let %s =\n" parser_name;
11033 pr "let parse_%s = %s\n" name parser_name;
11035 | Element (name, fields) -> (* type name = { fields ... } *)
11036 generate_parser_struct name ([], fields)
11038 failwithf "generate_parser failed at: %s" (string_of_rng rng)
11040 and is_attrs_interleave = function
11041 | [Interleave _] -> true
11042 | Attribute _ :: fields -> is_attrs_interleave fields
11043 | Optional (Attribute _) :: fields -> is_attrs_interleave fields
11046 and get_attrs_interleave = function
11047 | [Interleave fields] -> [], fields
11048 | ((Attribute _) as field) :: fields
11049 | ((Optional (Attribute _)) as field) :: fields ->
11050 let attrs, interleaves = get_attrs_interleave fields in
11051 (field :: attrs), interleaves
11052 | _ -> assert false
11054 and generate_parsers xs =
11055 List.iter (fun x -> ignore (generate_parser x)) xs
11057 and generate_parser_struct name (attrs, interleaves) =
11058 (* Generate parsers for the fields first. We have to do this
11059 * before printing anything so we are still in BOL context.
11061 let fields = attrs @ interleaves in
11062 let pas = List.map generate_parser fields in
11064 (* Generate an intermediate tuple from all the fields first.
11065 * If the type is just a string + another field, then we will
11066 * return this directly, otherwise it is turned into a record.
11068 * RELAX NG note: This code treats <interleave> and plain lists of
11069 * fields the same. In other words, it doesn't bother enforcing
11070 * any ordering of fields in the XML.
11072 pr "let parse_%s x =\n" name;
11073 pr " let t = (\n ";
11074 let comma = ref false in
11077 if !comma then pr ",\n ";
11080 | Optional (Attribute (fname, [field])), pa ->
11082 | Optional (Element (fname, [field])), pa ->
11083 pr "%s (optional_child %S x)" pa fname
11084 | Attribute (fname, [Text]), _ ->
11085 pr "attribute %S x" fname
11086 | (ZeroOrMore _ | OneOrMore _), pa ->
11091 let fname = name_of_field field in
11092 pr "%s (child %S x)" pa fname
11093 ) (List.combine fields pas);
11097 | [Element (_, [Text]) | Attribute (_, [Text]); _] ->
11101 pr " (Obj.magic t : %s)\n" name
11105 | (Optional (Attribute (fname, [field])), pa) ->
11106 pr " %s_%s =\n" name fname;
11108 | (Optional (Element (fname, [field])), pa) ->
11109 pr " %s_%s =\n" name fname;
11110 pr " (let x = optional_child %S x in\n" fname;
11113 let fname = name_of_field field in
11114 pr " %s_%s =\n" name fname;
11115 pr " (let x = child %S x in\n" fname;
11117 ) (List.combine fields pas);
11121 sprintf "parse_%s" name
11124 generate_parsers xs
11126 (* Generate ocaml/guestfs_inspector.mli. *)
11127 let generate_ocaml_inspector_mli () =
11128 generate_header ~extra_inputs:[rng_input] OCamlStyle LGPLv2plus;
11131 (** This is an OCaml language binding to the external [virt-inspector]
11134 For more information, please read the man page [virt-inspector(1)].
11139 generate_types grammar;
11140 pr "(** The nested information returned from the {!inspect} function. *)\n";
11144 val inspect : ?connect:string -> ?xml:string -> string list -> operatingsystems
11145 (** To inspect a libvirt domain called [name], pass a singleton
11146 list: [inspect [name]]. When using libvirt only, you may
11147 optionally pass a libvirt URI using [inspect ~connect:uri ...].
11149 To inspect a disk image or images, pass a list of the filenames
11150 of the disk images: [inspect filenames]
11152 This function inspects the given guest or disk images and
11153 returns a list of operating system(s) found and a large amount
11154 of information about them. In the vast majority of cases,
11155 a virtual machine only contains a single operating system.
11157 If the optional [~xml] parameter is given, then this function
11158 skips running the external virt-inspector program and just
11159 parses the given XML directly (which is expected to be XML
11160 produced from a previous run of virt-inspector). The list of
11161 names and connect URI are ignored in this case.
11163 This function can throw a wide variety of exceptions, for example
11164 if the external virt-inspector program cannot be found, or if
11165 it doesn't generate valid XML.
11169 (* Generate ocaml/guestfs_inspector.ml. *)
11170 let generate_ocaml_inspector_ml () =
11171 generate_header ~extra_inputs:[rng_input] OCamlStyle LGPLv2plus;
11176 generate_types grammar;
11180 (* Misc functions which are used by the parser code below. *)
11181 let first_child = function
11182 | Xml.Element (_, _, c::_) -> c
11183 | Xml.Element (name, _, []) ->
11184 failwith (\"expected <\" ^ name ^ \"/> to have a child node\")
11185 | Xml.PCData str ->
11186 failwith (\"expected XML tag, but read PCDATA '\" ^ str ^ \"' instead\")
11188 let string_child_or_empty = function
11189 | Xml.Element (_, _, [Xml.PCData s]) -> s
11190 | Xml.Element (_, _, []) -> \"\"
11191 | Xml.Element (x, _, _) ->
11192 failwith (\"expected XML tag with a single PCDATA child, but got \" ^
11194 | Xml.PCData str ->
11195 failwith (\"expected XML tag, but read PCDATA '\" ^ str ^ \"' instead\")
11197 let optional_child name xml =
11198 let children = Xml.children xml in
11200 Some (List.find (function
11201 | Xml.Element (n, _, _) when n = name -> true
11202 | _ -> false) children)
11206 let child name xml =
11207 match optional_child name xml with
11210 failwith (\"mandatory field <\" ^ name ^ \"/> missing in XML output\")
11212 let attribute name xml =
11213 try Xml.attrib xml name
11214 with Xml.No_attribute _ ->
11215 failwith (\"mandatory attribute \" ^ name ^ \" missing in XML output\")
11219 generate_parsers grammar;
11223 (* Run external virt-inspector, then use parser to parse the XML. *)
11224 let inspect ?connect ?xml names =
11228 if names = [] then invalid_arg \"inspect: no names given\";
11229 let cmd = [ \"virt-inspector\"; \"--xml\" ] @
11230 (match connect with None -> [] | Some uri -> [ \"--connect\"; uri ]) @
11232 let cmd = List.map Filename.quote cmd in
11233 let cmd = String.concat \" \" cmd in
11234 let chan = open_process_in cmd in
11235 let xml = Xml.parse_in chan in
11236 (match close_process_in chan with
11238 | WEXITED _ -> failwith \"external virt-inspector command failed\"
11239 | WSIGNALED i | WSTOPPED i ->
11240 failwith (\"external virt-inspector command died or stopped on sig \" ^
11245 Xml.parse_string doc in
11246 parse_operatingsystems xml
11249 (* This is used to generate the src/MAX_PROC_NR file which
11250 * contains the maximum procedure number, a surrogate for the
11251 * ABI version number. See src/Makefile.am for the details.
11253 and generate_max_proc_nr () =
11254 let proc_nrs = List.map (
11255 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
11256 ) daemon_functions in
11258 let max_proc_nr = List.fold_left max 0 proc_nrs in
11260 pr "%d\n" max_proc_nr
11262 let output_to filename k =
11263 let filename_new = filename ^ ".new" in
11264 chan := open_out filename_new;
11267 chan := Pervasives.stdout;
11269 (* Is the new file different from the current file? *)
11270 if Sys.file_exists filename && files_equal filename filename_new then
11271 unlink filename_new (* same, so skip it *)
11273 (* different, overwrite old one *)
11274 (try chmod filename 0o644 with Unix_error _ -> ());
11275 rename filename_new filename;
11276 chmod filename 0o444;
11277 printf "written %s\n%!" filename;
11280 let perror msg = function
11281 | Unix_error (err, _, _) ->
11282 eprintf "%s: %s\n" msg (error_message err)
11284 eprintf "%s: %s\n" msg (Printexc.to_string exn)
11286 (* Main program. *)
11289 try openfile "HACKING" [O_RDWR] 0
11291 | Unix_error (ENOENT, _, _) ->
11293 You are probably running this from the wrong directory.
11294 Run it from the top source directory using the command
11299 perror "open: HACKING" exn;
11302 (* Acquire a lock so parallel builds won't try to run the generator
11303 * twice at the same time. Subsequent builds will wait for the first
11304 * one to finish. Note the lock is released implicitly when the
11307 (try lockf lock_fd F_LOCK 1
11309 perror "lock: HACKING" exn;
11312 check_functions ();
11314 output_to "src/guestfs_protocol.x" generate_xdr;
11315 output_to "src/guestfs-structs.h" generate_structs_h;
11316 output_to "src/guestfs-actions.h" generate_actions_h;
11317 output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
11318 output_to "src/guestfs-actions.c" generate_client_actions;
11319 output_to "src/guestfs-bindtests.c" generate_bindtests;
11320 output_to "src/guestfs-structs.pod" generate_structs_pod;
11321 output_to "src/guestfs-actions.pod" generate_actions_pod;
11322 output_to "src/guestfs-availability.pod" generate_availability_pod;
11323 output_to "src/MAX_PROC_NR" generate_max_proc_nr;
11324 output_to "src/libguestfs.syms" generate_linker_script;
11325 output_to "daemon/actions.h" generate_daemon_actions_h;
11326 output_to "daemon/stubs.c" generate_daemon_actions;
11327 output_to "daemon/names.c" generate_daemon_names;
11328 output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
11329 output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
11330 output_to "capitests/tests.c" generate_tests;
11331 output_to "fish/cmds.c" generate_fish_cmds;
11332 output_to "fish/completion.c" generate_fish_completion;
11333 output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
11334 output_to "ocaml/guestfs.mli" generate_ocaml_mli;
11335 output_to "ocaml/guestfs.ml" generate_ocaml_ml;
11336 output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
11337 output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
11338 output_to "ocaml/guestfs_inspector.mli" generate_ocaml_inspector_mli;
11339 output_to "ocaml/guestfs_inspector.ml" generate_ocaml_inspector_ml;
11340 output_to "perl/Guestfs.xs" generate_perl_xs;
11341 output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
11342 output_to "perl/bindtests.pl" generate_perl_bindtests;
11343 output_to "python/guestfs-py.c" generate_python_c;
11344 output_to "python/guestfs.py" generate_python_py;
11345 output_to "python/bindtests.py" generate_python_bindtests;
11346 output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
11347 output_to "ruby/bindtests.rb" generate_ruby_bindtests;
11348 output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
11352 let cols = cols_of_struct typ in
11353 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
11354 output_to filename (generate_java_struct jtyp cols);
11357 output_to "java/Makefile.inc" generate_java_makefile_inc;
11358 output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
11359 output_to "java/Bindtests.java" generate_java_bindtests;
11360 output_to "haskell/Guestfs.hs" generate_haskell_hs;
11361 output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
11362 output_to "csharp/Libguestfs.cs" generate_csharp;
11364 (* Always generate this file last, and unconditionally. It's used
11365 * by the Makefile to know when we must re-run the generator.
11367 let chan = open_out "src/stamp-generator" in
11368 fprintf chan "1\n";
11371 printf "generated %d lines of code\n" !lines