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 #directory "+../pkg-lib/xml-light";; (* for GODI users *)
46 #load "xml-light.cma";;
51 type style = ret * args
53 (* "RErr" as a return value means an int used as a simple error
54 * indication, ie. 0 or -1.
58 (* "RInt" as a return value means an int which is -1 for error
59 * or any value >= 0 on success. Only use this for smallish
60 * positive ints (0 <= i < 2^30).
64 (* "RInt64" is the same as RInt, but is guaranteed to be able
65 * to return a full 64 bit value, _except_ that -1 means error
66 * (so -1 cannot be a valid, non-error return value).
70 (* "RBool" is a bool return value which can be true/false or
75 (* "RConstString" is a string that refers to a constant value.
76 * The return value must NOT be NULL (since NULL indicates
79 * Try to avoid using this. In particular you cannot use this
80 * for values returned from the daemon, because there is no
81 * thread-safe way to return them in the C API.
83 | RConstString of string
85 (* "RConstOptString" is an even more broken version of
86 * "RConstString". The returned string may be NULL and there
87 * is no way to return an error indication. Avoid using this!
89 | RConstOptString of string
91 (* "RString" is a returned string. It must NOT be NULL, since
92 * a NULL return indicates an error. The caller frees this.
96 (* "RStringList" is a list of strings. No string in the list
97 * can be NULL. The caller frees the strings and the array.
99 | RStringList of string
101 (* "RStruct" is a function which returns a single named structure
102 * or an error indication (in C, a struct, and in other languages
103 * with varying representations, but usually very efficient). See
104 * after the function list below for the structures.
106 | RStruct of string * string (* name of retval, name of struct *)
108 (* "RStructList" is a function which returns either a list/array
109 * of structures (could be zero-length), or an error indication.
111 | RStructList of string * string (* name of retval, name of struct *)
113 (* Key-value pairs of untyped strings. Turns into a hashtable or
114 * dictionary in languages which support it. DON'T use this as a
115 * general "bucket" for results. Prefer a stronger typed return
116 * value if one is available, or write a custom struct. Don't use
117 * this if the list could potentially be very long, since it is
118 * inefficient. Keys should be unique. NULLs are not permitted.
120 | RHashtable of string
122 (* "RBufferOut" is handled almost exactly like RString, but
123 * it allows the string to contain arbitrary 8 bit data including
124 * ASCII NUL. In the C API this causes an implicit extra parameter
125 * to be added of type <size_t *size_r>. The extra parameter
126 * returns the actual size of the return buffer in bytes.
128 * Other programming languages support strings with arbitrary 8 bit
131 * At the RPC layer we have to use the opaque<> type instead of
132 * string<>. Returned data is still limited to the max message
135 | RBufferOut of string
137 and args = argt list (* Function parameters, guestfs handle is implicit. *)
139 (* Note in future we should allow a "variable args" parameter as
140 * the final parameter, to allow commands like
141 * chmod mode file [file(s)...]
142 * This is not implemented yet, but many commands (such as chmod)
143 * are currently defined with the argument order keeping this future
144 * possibility in mind.
147 | String of string (* const char *name, cannot be NULL *)
148 | Device of string (* /dev device name, cannot be NULL *)
149 | Pathname of string (* file name, cannot be NULL *)
150 | Dev_or_Path of string (* /dev device name or Pathname, cannot be NULL *)
151 | OptString of string (* const char *name, may be NULL *)
152 | StringList of string(* list of strings (each string cannot be NULL) *)
153 | DeviceList of string(* list of Device names (each cannot be NULL) *)
154 | Bool of string (* boolean *)
155 | Int of string (* int (smallish ints, signed, <= 31 bits) *)
156 | Int64 of string (* any 64 bit int *)
157 (* These are treated as filenames (simple string parameters) in
158 * the C API and bindings. But in the RPC protocol, we transfer
159 * the actual file content up to or down from the daemon.
160 * FileIn: local machine -> daemon (in request)
161 * FileOut: daemon -> local machine (in reply)
162 * In guestfish (only), the special name "-" means read from
163 * stdin or write to stdout.
167 (* Opaque buffer which can contain arbitrary 8 bit data.
168 * In the C API, this is expressed as <const char *, size_t> 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.
177 (* Key material / passphrase. Eventually we should treat this
178 * as sensitive and mlock it into physical RAM. However this
179 * is highly complex because of all the places that XDR-encoded
180 * strings can end up. So currently the only difference from
181 * 'String' is the way that guestfish requests these parameters
187 | ProtocolLimitWarning (* display warning about protocol size limits *)
188 | DangerWillRobinson (* flags particularly dangerous commands *)
189 | FishAlias of string (* provide an alias for this cmd in guestfish *)
190 | FishOutput of fish_output_t (* how to display output in guestfish *)
191 | NotInFish (* do not export via guestfish *)
192 | NotInDocs (* do not add this function to documentation *)
193 | DeprecatedBy of string (* function is deprecated, use .. instead *)
194 | Optional of string (* function is part of an optional group *)
197 | FishOutputOctal (* for int return, print in octal *)
198 | FishOutputHexadecimal (* for int return, print in hex *)
200 (* You can supply zero or as many tests as you want per API call.
202 * Note that the test environment has 3 block devices, of size 500MB,
203 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
204 * a fourth ISO block device with some known files on it (/dev/sdd).
206 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
207 * Number of cylinders was 63 for IDE emulated disks with precisely
208 * the same size. How exactly this is calculated is a mystery.
210 * The ISO block device (/dev/sdd) comes from images/test.iso.
212 * To be able to run the tests in a reasonable amount of time,
213 * the virtual machine and block devices are reused between tests.
214 * So don't try testing kill_subprocess :-x
216 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
218 * Don't assume anything about the previous contents of the block
219 * devices. Use 'Init*' to create some initial scenarios.
221 * You can add a prerequisite clause to any individual test. This
222 * is a run-time check, which, if it fails, causes the test to be
223 * skipped. Useful if testing a command which might not work on
224 * all variations of libguestfs builds. A test that has prerequisite
225 * of 'Always' is run unconditionally.
227 * In addition, packagers can skip individual tests by setting the
228 * environment variables: eg:
229 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
230 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
232 type tests = (test_init * test_prereq * test) list
234 (* Run the command sequence and just expect nothing to fail. *)
237 (* Run the command sequence and expect the output of the final
238 * command to be the string.
240 | TestOutput of seq * string
242 (* Run the command sequence and expect the output of the final
243 * command to be the list of strings.
245 | TestOutputList of seq * string list
247 (* Run the command sequence and expect the output of the final
248 * command to be the list of block devices (could be either
249 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
250 * character of each string).
252 | TestOutputListOfDevices of seq * string list
254 (* Run the command sequence and expect the output of the final
255 * command to be the integer.
257 | TestOutputInt of seq * int
259 (* Run the command sequence and expect the output of the final
260 * command to be <op> <int>, eg. ">=", "1".
262 | TestOutputIntOp of seq * string * int
264 (* Run the command sequence and expect the output of the final
265 * command to be a true value (!= 0 or != NULL).
267 | TestOutputTrue of seq
269 (* Run the command sequence and expect the output of the final
270 * command to be a false value (== 0 or == NULL, but not an error).
272 | TestOutputFalse of seq
274 (* Run the command sequence and expect the output of the final
275 * command to be a list of the given length (but don't care about
278 | TestOutputLength of seq * int
280 (* Run the command sequence and expect the output of the final
281 * command to be a buffer (RBufferOut), ie. string + size.
283 | TestOutputBuffer of seq * string
285 (* Run the command sequence and expect the output of the final
286 * command to be a structure.
288 | TestOutputStruct of seq * test_field_compare list
290 (* Run the command sequence and expect the final command (only)
293 | TestLastFail of seq
295 and test_field_compare =
296 | CompareWithInt of string * int
297 | CompareWithIntOp of string * string * int
298 | CompareWithString of string * string
299 | CompareFieldsIntEq of string * string
300 | CompareFieldsStrEq of string * string
302 (* Test prerequisites. *)
304 (* Test always runs. *)
307 (* Test is currently disabled - eg. it fails, or it tests some
308 * unimplemented feature.
312 (* 'string' is some C code (a function body) that should return
313 * true or false. The test will run if the code returns true.
317 (* As for 'If' but the test runs _unless_ the code returns true. *)
320 (* Run the test only if 'string' is available in the daemon. *)
321 | IfAvailable of string
323 (* Some initial scenarios for testing. *)
325 (* Do nothing, block devices could contain random stuff including
326 * LVM PVs, and some filesystems might be mounted. This is usually
331 (* Block devices are empty and no filesystems are mounted. *)
334 (* /dev/sda contains a single partition /dev/sda1, with random
335 * content. /dev/sdb and /dev/sdc may have random content.
340 (* /dev/sda contains a single partition /dev/sda1, which is formatted
341 * as ext2, empty [except for lost+found] and mounted on /.
342 * /dev/sdb and /dev/sdc may have random content.
348 * /dev/sda1 (is a PV):
349 * /dev/VG/LV (size 8MB):
350 * formatted as ext2, empty [except for lost+found], mounted on /
351 * /dev/sdb and /dev/sdc may have random content.
355 (* /dev/sdd (the ISO, see images/ directory in source)
360 (* Sequence of commands for testing. *)
362 and cmd = string list
364 (* Note about long descriptions: When referring to another
365 * action, use the format C<guestfs_other> (ie. the full name of
366 * the C function). This will be replaced as appropriate in other
369 * Apart from that, long descriptions are just perldoc paragraphs.
372 (* Generate a random UUID (used in tests). *)
374 let chan = open_process_in "uuidgen" in
375 let uuid = input_line chan in
376 (match close_process_in chan with
379 failwith "uuidgen: process exited with non-zero status"
380 | WSIGNALED _ | WSTOPPED _ ->
381 failwith "uuidgen: process signalled or stopped by signal"
385 (* These test functions are used in the language binding tests. *)
387 let test_all_args = [
390 StringList "strlist";
399 let test_all_rets = [
400 (* except for RErr, which is tested thoroughly elsewhere *)
401 "test0rint", RInt "valout";
402 "test0rint64", RInt64 "valout";
403 "test0rbool", RBool "valout";
404 "test0rconststring", RConstString "valout";
405 "test0rconstoptstring", RConstOptString "valout";
406 "test0rstring", RString "valout";
407 "test0rstringlist", RStringList "valout";
408 "test0rstruct", RStruct ("valout", "lvm_pv");
409 "test0rstructlist", RStructList ("valout", "lvm_pv");
410 "test0rhashtable", RHashtable "valout";
413 let test_functions = [
414 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
416 "internal test function - do not use",
418 This is an internal test function which is used to test whether
419 the automatically generated bindings can handle every possible
420 parameter type correctly.
422 It echos the contents of each parameter to stdout.
424 You probably don't want to call this function.");
428 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
430 "internal test function - do not use",
432 This is an internal test function which is used to test whether
433 the automatically generated bindings can handle every possible
434 return type correctly.
436 It converts string C<val> to the return type.
438 You probably don't want to call this function.");
439 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
441 "internal test function - do not use",
443 This is an internal test function which is used to test whether
444 the automatically generated bindings can handle every possible
445 return type correctly.
447 This function always returns an error.
449 You probably don't want to call this function.")]
453 (* non_daemon_functions are any functions which don't get processed
454 * in the daemon, eg. functions for setting and getting local
455 * configuration values.
458 let non_daemon_functions = test_functions @ [
459 ("launch", (RErr, []), -1, [FishAlias "run"],
461 "launch the qemu subprocess",
463 Internally libguestfs is implemented by running a virtual machine
466 You should call this after configuring the handle
467 (eg. adding drives) but before performing any actions.");
469 ("wait_ready", (RErr, []), -1, [NotInFish],
471 "wait until the qemu subprocess launches (no op)",
473 This function is a no op.
475 In versions of the API E<lt> 1.0.71 you had to call this function
476 just after calling C<guestfs_launch> to wait for the launch
477 to complete. However this is no longer necessary because
478 C<guestfs_launch> now does the waiting.
480 If you see any calls to this function in code then you can just
481 remove them, unless you want to retain compatibility with older
482 versions of the API.");
484 ("kill_subprocess", (RErr, []), -1, [],
486 "kill the qemu subprocess",
488 This kills the qemu subprocess. You should never need to call this.");
490 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
492 "add an image to examine or modify",
494 This function adds a virtual machine disk image C<filename> to the
495 guest. The first time you call this function, the disk appears as IDE
496 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
499 You don't necessarily need to be root when using libguestfs. However
500 you obviously do need sufficient permissions to access the filename
501 for whatever operations you want to perform (ie. read access if you
502 just want to read the image or write access if you want to modify the
505 This is equivalent to the qemu parameter
506 C<-drive file=filename,cache=off,if=...>.
508 C<cache=off> is omitted in cases where it is not supported by
509 the underlying filesystem.
511 C<if=...> is set at compile time by the configuration option
512 C<./configure --with-drive-if=...>. In the rare case where you
513 might need to change this at run time, use C<guestfs_add_drive_with_if>
514 or C<guestfs_add_drive_ro_with_if>.
516 Note that this call checks for the existence of C<filename>. This
517 stops you from specifying other types of drive which are supported
518 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
519 the general C<guestfs_config> call instead.");
521 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
523 "add a CD-ROM disk image to examine",
525 This function adds a virtual CD-ROM disk image to the guest.
527 This is equivalent to the qemu parameter C<-cdrom filename>.
535 This call checks for the existence of C<filename>. This
536 stops you from specifying other types of drive which are supported
537 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
538 the general C<guestfs_config> call instead.
542 If you just want to add an ISO file (often you use this as an
543 efficient way to transfer large files into the guest), then you
544 should probably use C<guestfs_add_drive_ro> instead.
548 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
550 "add a drive in snapshot mode (read-only)",
552 This adds a drive in snapshot mode, making it effectively
555 Note that writes to the device are allowed, and will be seen for
556 the duration of the guestfs handle, but they are written
557 to a temporary file which is discarded as soon as the guestfs
558 handle is closed. We don't currently have any method to enable
559 changes to be committed, although qemu can support this.
561 This is equivalent to the qemu parameter
562 C<-drive file=filename,snapshot=on,if=...>.
564 C<if=...> is set at compile time by the configuration option
565 C<./configure --with-drive-if=...>. In the rare case where you
566 might need to change this at run time, use C<guestfs_add_drive_with_if>
567 or C<guestfs_add_drive_ro_with_if>.
569 Note that this call checks for the existence of C<filename>. This
570 stops you from specifying other types of drive which are supported
571 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
572 the general C<guestfs_config> call instead.");
574 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
576 "add qemu parameters",
578 This can be used to add arbitrary qemu command line parameters
579 of the form C<-param value>. Actually it's not quite arbitrary - we
580 prevent you from setting some parameters which would interfere with
581 parameters that we use.
583 The first character of C<param> string must be a C<-> (dash).
585 C<value> can be NULL.");
587 ("set_qemu", (RErr, [OptString "qemu"]), -1, [FishAlias "qemu"],
589 "set the qemu binary",
591 Set the qemu binary that we will use.
593 The default is chosen when the library was compiled by the
596 You can also override this by setting the C<LIBGUESTFS_QEMU>
597 environment variable.
599 Setting C<qemu> to C<NULL> restores the default qemu binary.
601 Note that you should call this function as early as possible
602 after creating the handle. This is because some pre-launch
603 operations depend on testing qemu features (by running C<qemu -help>).
604 If the qemu binary changes, we don't retest features, and
605 so you might see inconsistent results. Using the environment
606 variable C<LIBGUESTFS_QEMU> is safest of all since that picks
607 the qemu binary at the same time as the handle is created.");
609 ("get_qemu", (RConstString "qemu", []), -1, [],
610 [InitNone, Always, TestRun (
612 "get the qemu binary",
614 Return the current qemu binary.
616 This is always non-NULL. If it wasn't set already, then this will
617 return the default qemu binary name.");
619 ("set_path", (RErr, [OptString "searchpath"]), -1, [FishAlias "path"],
621 "set the search path",
623 Set the path that libguestfs searches for kernel and initrd.img.
625 The default is C<$libdir/guestfs> unless overridden by setting
626 C<LIBGUESTFS_PATH> environment variable.
628 Setting C<path> to C<NULL> restores the default path.");
630 ("get_path", (RConstString "path", []), -1, [],
631 [InitNone, Always, TestRun (
633 "get the search path",
635 Return the current search path.
637 This is always non-NULL. If it wasn't set already, then this will
638 return the default path.");
640 ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
642 "add options to kernel command line",
644 This function is used to add additional options to the
645 guest kernel command line.
647 The default is C<NULL> unless overridden by setting
648 C<LIBGUESTFS_APPEND> environment variable.
650 Setting C<append> to C<NULL> means I<no> additional options
651 are passed (libguestfs always adds a few of its own).");
653 ("get_append", (RConstOptString "append", []), -1, [],
654 (* This cannot be tested with the current framework. The
655 * function can return NULL in normal operations, which the
656 * test framework interprets as an error.
659 "get the additional kernel options",
661 Return the additional kernel options which are added to the
662 guest kernel command line.
664 If C<NULL> then no options are added.");
666 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
670 If C<autosync> is true, this enables autosync. Libguestfs will make a
671 best effort attempt to run C<guestfs_umount_all> followed by
672 C<guestfs_sync> when the handle is closed
673 (also if the program exits without closing handles).
675 This is disabled by default (except in guestfish where it is
676 enabled by default).");
678 ("get_autosync", (RBool "autosync", []), -1, [],
679 [InitNone, Always, TestRun (
680 [["get_autosync"]])],
683 Get the autosync flag.");
685 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
689 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
691 Verbose messages are disabled unless the environment variable
692 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
694 ("get_verbose", (RBool "verbose", []), -1, [],
698 This returns the verbose messages flag.");
700 ("is_ready", (RBool "ready", []), -1, [],
701 [InitNone, Always, TestOutputTrue (
703 "is ready to accept commands",
705 This returns true iff this handle is ready to accept commands
706 (in the C<READY> state).
708 For more information on states, see L<guestfs(3)>.");
710 ("is_config", (RBool "config", []), -1, [],
711 [InitNone, Always, TestOutputFalse (
713 "is in configuration state",
715 This returns true iff this handle is being configured
716 (in the C<CONFIG> state).
718 For more information on states, see L<guestfs(3)>.");
720 ("is_launching", (RBool "launching", []), -1, [],
721 [InitNone, Always, TestOutputFalse (
722 [["is_launching"]])],
723 "is launching subprocess",
725 This returns true iff this handle is launching the subprocess
726 (in the C<LAUNCHING> state).
728 For more information on states, see L<guestfs(3)>.");
730 ("is_busy", (RBool "busy", []), -1, [],
731 [InitNone, Always, TestOutputFalse (
733 "is busy processing a command",
735 This returns true iff this handle is busy processing a command
736 (in the C<BUSY> state).
738 For more information on states, see L<guestfs(3)>.");
740 ("get_state", (RInt "state", []), -1, [],
742 "get the current state",
744 This returns the current state as an opaque integer. This is
745 only useful for printing debug and internal error messages.
747 For more information on states, see L<guestfs(3)>.");
749 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
750 [InitNone, Always, TestOutputInt (
751 [["set_memsize"; "500"];
752 ["get_memsize"]], 500)],
753 "set memory allocated to the qemu subprocess",
755 This sets the memory size in megabytes allocated to the
756 qemu subprocess. This only has any effect if called before
759 You can also change this by setting the environment
760 variable C<LIBGUESTFS_MEMSIZE> before the handle is
763 For more information on the architecture of libguestfs,
764 see L<guestfs(3)>.");
766 ("get_memsize", (RInt "memsize", []), -1, [],
767 [InitNone, Always, TestOutputIntOp (
768 [["get_memsize"]], ">=", 256)],
769 "get memory allocated to the qemu subprocess",
771 This gets the memory size in megabytes allocated to the
774 If C<guestfs_set_memsize> was not called
775 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
776 then this returns the compiled-in default value for memsize.
778 For more information on the architecture of libguestfs,
779 see L<guestfs(3)>.");
781 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
782 [InitNone, Always, TestOutputIntOp (
783 [["get_pid"]], ">=", 1)],
784 "get PID of qemu subprocess",
786 Return the process ID of the qemu subprocess. If there is no
787 qemu subprocess, then this will return an error.
789 This is an internal call used for debugging and testing.");
791 ("version", (RStruct ("version", "version"), []), -1, [],
792 [InitNone, Always, TestOutputStruct (
793 [["version"]], [CompareWithInt ("major", 1)])],
794 "get the library version number",
796 Return the libguestfs version number that the program is linked
799 Note that because of dynamic linking this is not necessarily
800 the version of libguestfs that you compiled against. You can
801 compile the program, and then at runtime dynamically link
802 against a completely different C<libguestfs.so> library.
804 This call was added in version C<1.0.58>. In previous
805 versions of libguestfs there was no way to get the version
806 number. From C code you can use dynamic linker functions
807 to find out if this symbol exists (if it doesn't, then
808 it's an earlier version).
810 The call returns a structure with four elements. The first
811 three (C<major>, C<minor> and C<release>) are numbers and
812 correspond to the usual version triplet. The fourth element
813 (C<extra>) is a string and is normally empty, but may be
814 used for distro-specific information.
816 To construct the original version string:
817 C<$major.$minor.$release$extra>
819 See also: L<guestfs(3)/LIBGUESTFS VERSION NUMBERS>.
821 I<Note:> Don't use this call to test for availability
822 of features. In enterprise distributions we backport
823 features from later versions into earlier versions,
824 making this an unreliable way to test for features.
825 Use C<guestfs_available> instead.");
827 ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
828 [InitNone, Always, TestOutputTrue (
829 [["set_selinux"; "true"];
831 "set SELinux enabled or disabled at appliance boot",
833 This sets the selinux flag that is passed to the appliance
834 at boot time. The default is C<selinux=0> (disabled).
836 Note that if SELinux is enabled, it is always in
837 Permissive mode (C<enforcing=0>).
839 For more information on the architecture of libguestfs,
840 see L<guestfs(3)>.");
842 ("get_selinux", (RBool "selinux", []), -1, [],
844 "get SELinux enabled flag",
846 This returns the current setting of the selinux flag which
847 is passed to the appliance at boot time. See C<guestfs_set_selinux>.
849 For more information on the architecture of libguestfs,
850 see L<guestfs(3)>.");
852 ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
853 [InitNone, Always, TestOutputFalse (
854 [["set_trace"; "false"];
856 "enable or disable command traces",
858 If the command trace flag is set to 1, then commands are
859 printed on stderr before they are executed in a format
860 which is very similar to the one used by guestfish. In
861 other words, you can run a program with this enabled, and
862 you will get out a script which you can feed to guestfish
863 to perform the same set of actions.
865 If you want to trace C API calls into libguestfs (and
866 other libraries) then possibly a better way is to use
867 the external ltrace(1) command.
869 Command traces are disabled unless the environment variable
870 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
872 ("get_trace", (RBool "trace", []), -1, [],
874 "get command trace enabled flag",
876 Return the command trace flag.");
878 ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
879 [InitNone, Always, TestOutputFalse (
880 [["set_direct"; "false"];
882 "enable or disable direct appliance mode",
884 If the direct appliance mode flag is enabled, then stdin and
885 stdout are passed directly through to the appliance once it
888 One consequence of this is that log messages aren't caught
889 by the library and handled by C<guestfs_set_log_message_callback>,
890 but go straight to stdout.
892 You probably don't want to use this unless you know what you
895 The default is disabled.");
897 ("get_direct", (RBool "direct", []), -1, [],
899 "get direct appliance mode flag",
901 Return the direct appliance mode flag.");
903 ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
904 [InitNone, Always, TestOutputTrue (
905 [["set_recovery_proc"; "true"];
906 ["get_recovery_proc"]])],
907 "enable or disable the recovery process",
909 If this is called with the parameter C<false> then
910 C<guestfs_launch> does not create a recovery process. The
911 purpose of the recovery process is to stop runaway qemu
912 processes in the case where the main program aborts abruptly.
914 This only has any effect if called before C<guestfs_launch>,
915 and the default is true.
917 About the only time when you would want to disable this is
918 if the main process will fork itself into the background
919 (\"daemonize\" itself). In this case the recovery process
920 thinks that the main program has disappeared and so kills
921 qemu, which is not very helpful.");
923 ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
925 "get recovery process enabled flag",
927 Return the recovery process enabled flag.");
929 ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
931 "add a drive specifying the QEMU block emulation to use",
933 This is the same as C<guestfs_add_drive> but it allows you
934 to specify the QEMU interface emulation to use at run time.");
936 ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
938 "add a drive read-only specifying the QEMU block emulation to use",
940 This is the same as C<guestfs_add_drive_ro> but it allows you
941 to specify the QEMU interface emulation to use at run time.");
943 ("file_architecture", (RString "arch", [Pathname "filename"]), -1, [],
944 [InitISOFS, Always, TestOutput (
945 [["file_architecture"; "/bin-i586-dynamic"]], "i386");
946 InitISOFS, Always, TestOutput (
947 [["file_architecture"; "/bin-sparc-dynamic"]], "sparc");
948 InitISOFS, Always, TestOutput (
949 [["file_architecture"; "/bin-win32.exe"]], "i386");
950 InitISOFS, Always, TestOutput (
951 [["file_architecture"; "/bin-win64.exe"]], "x86_64");
952 InitISOFS, Always, TestOutput (
953 [["file_architecture"; "/bin-x86_64-dynamic"]], "x86_64");
954 InitISOFS, Always, TestOutput (
955 [["file_architecture"; "/lib-i586.so"]], "i386");
956 InitISOFS, Always, TestOutput (
957 [["file_architecture"; "/lib-sparc.so"]], "sparc");
958 InitISOFS, Always, TestOutput (
959 [["file_architecture"; "/lib-win32.dll"]], "i386");
960 InitISOFS, Always, TestOutput (
961 [["file_architecture"; "/lib-win64.dll"]], "x86_64");
962 InitISOFS, Always, TestOutput (
963 [["file_architecture"; "/lib-x86_64.so"]], "x86_64");
964 InitISOFS, Always, TestOutput (
965 [["file_architecture"; "/initrd-x86_64.img"]], "x86_64");
966 InitISOFS, Always, TestOutput (
967 [["file_architecture"; "/initrd-x86_64.img.gz"]], "x86_64");],
968 "detect the architecture of a binary file",
970 This detects the architecture of the binary C<filename>,
971 and returns it if known.
973 Currently defined architectures are:
979 This string is returned for all 32 bit i386, i486, i586, i686 binaries
980 irrespective of the precise processor requirements of the binary.
992 64 bit SPARC V9 and above.
1008 Libguestfs may return other architecture strings in future.
1010 The function works on at least the following types of files:
1016 many types of Un*x and Linux binary
1020 many types of Un*x and Linux shared library
1024 Windows Win32 and Win64 binaries
1028 Windows Win32 and Win64 DLLs
1030 Win32 binaries and DLLs return C<i386>.
1032 Win64 binaries and DLLs return C<x86_64>.
1036 Linux kernel modules
1040 Linux new-style initrd images
1044 some non-x86 Linux vmlinuz kernels
1048 What it can't do currently:
1054 static libraries (libfoo.a)
1058 Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
1062 x86 Linux vmlinuz kernels
1064 x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and
1065 compressed code, and are horribly hard to unpack. If you want to find
1066 the architecture of a kernel, use the architecture of the associated
1067 initrd or kernel module(s) instead.
1071 ("inspect_os", (RStringList "roots", []), -1, [],
1073 "inspect disk and return list of operating systems found",
1075 This function uses other libguestfs functions and certain
1076 heuristics to inspect the disk(s) (usually disks belonging to
1077 a virtual machine), looking for operating systems.
1079 The list returned is empty if no operating systems were found.
1081 If one operating system was found, then this returns a list with
1082 a single element, which is the name of the root filesystem of
1083 this operating system. It is also possible for this function
1084 to return a list containing more than one element, indicating
1085 a dual-boot or multi-boot virtual machine, with each element being
1086 the root filesystem of one of the operating systems.
1088 You can pass the root string(s) returned to other
1089 C<guestfs_inspect_get_*> functions in order to query further
1090 information about each operating system, such as the name
1093 This function uses other libguestfs features such as
1094 C<guestfs_mount_ro> and C<guestfs_umount_all> in order to mount
1095 and unmount filesystems and look at the contents. This should
1096 be called with no disks currently mounted. The function may also
1097 use Augeas, so any existing Augeas handle will be closed.
1099 This function cannot decrypt encrypted disks. The caller
1100 must do that first (supplying the necessary keys) if the
1103 Please read L<guestfs(3)/INSPECTION> for more details.");
1105 ("inspect_get_type", (RString "name", [Device "root"]), -1, [],
1107 "get type of inspected operating system",
1109 This function should only be called with a root device string
1110 as returned by C<guestfs_inspect_os>.
1112 This returns the type of the inspected operating system.
1113 Currently defined types are:
1119 Any Linux-based operating system.
1123 Any Microsoft Windows operating system.
1127 The operating system type could not be determined.
1131 Future versions of libguestfs may return other strings here.
1132 The caller should be prepared to handle any string.
1134 Please read L<guestfs(3)/INSPECTION> for more details.");
1136 ("inspect_get_arch", (RString "arch", [Device "root"]), -1, [],
1138 "get architecture of inspected operating system",
1140 This function should only be called with a root device string
1141 as returned by C<guestfs_inspect_os>.
1143 This returns the architecture of the inspected operating system.
1144 The possible return values are listed under
1145 C<guestfs_file_architecture>.
1147 If the architecture could not be determined, then the
1148 string C<unknown> is returned.
1150 Please read L<guestfs(3)/INSPECTION> for more details.");
1152 ("inspect_get_distro", (RString "distro", [Device "root"]), -1, [],
1154 "get distro of inspected operating system",
1156 This function should only be called with a root device string
1157 as returned by C<guestfs_inspect_os>.
1159 This returns the distro (distribution) of the inspected operating
1162 Currently defined distros are:
1168 Debian or a Debian-derived distro such as Ubuntu.
1174 =item \"redhat-based\"
1176 Some Red Hat-derived distro.
1180 Red Hat Enterprise Linux and some derivatives.
1184 Windows does not have distributions. This string is
1185 returned if the OS type is Windows.
1189 The distro could not be determined.
1193 Future versions of libguestfs may return other strings here.
1194 The caller should be prepared to handle any string.
1196 Please read L<guestfs(3)/INSPECTION> for more details.");
1198 ("inspect_get_major_version", (RInt "major", [Device "root"]), -1, [],
1200 "get major version of inspected operating system",
1202 This function should only be called with a root device string
1203 as returned by C<guestfs_inspect_os>.
1205 This returns the major version number of the inspected operating
1208 Windows uses a consistent versioning scheme which is I<not>
1209 reflected in the popular public names used by the operating system.
1210 Notably the operating system known as \"Windows 7\" is really
1211 version 6.1 (ie. major = 6, minor = 1). You can find out the
1212 real versions corresponding to releases of Windows by consulting
1215 If the version could not be determined, then C<0> is returned.
1217 Please read L<guestfs(3)/INSPECTION> for more details.");
1219 ("inspect_get_minor_version", (RInt "minor", [Device "root"]), -1, [],
1221 "get minor version of inspected operating system",
1223 This function should only be called with a root device string
1224 as returned by C<guestfs_inspect_os>.
1226 This returns the minor version number of the inspected operating
1229 If the version could not be determined, then C<0> is returned.
1231 Please read L<guestfs(3)/INSPECTION> for more details.
1232 See also C<guestfs_inspect_get_major_version>.");
1234 ("inspect_get_product_name", (RString "product", [Device "root"]), -1, [],
1236 "get product name of inspected operating system",
1238 This function should only be called with a root device string
1239 as returned by C<guestfs_inspect_os>.
1241 This returns the product name of the inspected operating
1242 system. The product name is generally some freeform string
1243 which can be displayed to the user, but should not be
1246 If the product name could not be determined, then the
1247 string C<unknown> is returned.
1249 Please read L<guestfs(3)/INSPECTION> for more details.");
1251 ("inspect_get_mountpoints", (RHashtable "mountpoints", [Device "root"]), -1, [],
1253 "get mountpoints of inspected operating system",
1255 This function should only be called with a root device string
1256 as returned by C<guestfs_inspect_os>.
1258 This returns a hash of where we think the filesystems
1259 associated with this operating system should be mounted.
1260 Callers should note that this is at best an educated guess
1261 made by reading configuration files such as C</etc/fstab>.
1263 Each element in the returned hashtable has a key which
1264 is the path of the mountpoint (eg. C</boot>) and a value
1265 which is the filesystem that would be mounted there
1268 Non-mounted devices such as swap devices are I<not>
1269 returned in this list.
1271 Please read L<guestfs(3)/INSPECTION> for more details.
1272 See also C<guestfs_inspect_get_filesystems>.");
1274 ("inspect_get_filesystems", (RStringList "filesystems", [Device "root"]), -1, [],
1276 "get filesystems associated with inspected operating system",
1278 This function should only be called with a root device string
1279 as returned by C<guestfs_inspect_os>.
1281 This returns a list of all the filesystems that we think
1282 are associated with this operating system. This includes
1283 the root filesystem, other ordinary filesystems, and
1284 non-mounted devices like swap partitions.
1286 In the case of a multi-boot virtual machine, it is possible
1287 for a filesystem to be shared between operating systems.
1289 Please read L<guestfs(3)/INSPECTION> for more details.
1290 See also C<guestfs_inspect_get_mountpoints>.");
1292 ("set_network", (RErr, [Bool "network"]), -1, [FishAlias "network"],
1294 "set enable network flag",
1296 If C<network> is true, then the network is enabled in the
1297 libguestfs appliance. The default is false.
1299 This affects whether commands are able to access the network
1300 (see L<guestfs(3)/RUNNING COMMANDS>).
1302 You must call this before calling C<guestfs_launch>, otherwise
1303 it has no effect.");
1305 ("get_network", (RBool "network", []), -1, [],
1307 "get enable network flag",
1309 This returns the enable network flag.");
1313 (* daemon_functions are any functions which cause some action
1314 * to take place in the daemon.
1317 let daemon_functions = [
1318 ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
1319 [InitEmpty, Always, TestOutput (
1320 [["part_disk"; "/dev/sda"; "mbr"];
1321 ["mkfs"; "ext2"; "/dev/sda1"];
1322 ["mount"; "/dev/sda1"; "/"];
1323 ["write"; "/new"; "new file contents"];
1324 ["cat"; "/new"]], "new file contents")],
1325 "mount a guest disk at a position in the filesystem",
1327 Mount a guest disk at a position in the filesystem. Block devices
1328 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
1329 the guest. If those block devices contain partitions, they will have
1330 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
1333 The rules are the same as for L<mount(2)>: A filesystem must
1334 first be mounted on C</> before others can be mounted. Other
1335 filesystems can only be mounted on directories which already
1338 The mounted filesystem is writable, if we have sufficient permissions
1339 on the underlying device.
1342 When you use this call, the filesystem options C<sync> and C<noatime>
1343 are set implicitly. This was originally done because we thought it
1344 would improve reliability, but it turns out that I<-o sync> has a
1345 very large negative performance impact and negligible effect on
1346 reliability. Therefore we recommend that you avoid using
1347 C<guestfs_mount> in any code that needs performance, and instead
1348 use C<guestfs_mount_options> (use an empty string for the first
1349 parameter if you don't want any options).");
1351 ("sync", (RErr, []), 2, [],
1352 [ InitEmpty, Always, TestRun [["sync"]]],
1353 "sync disks, writes are flushed through to the disk image",
1355 This syncs the disk, so that any writes are flushed through to the
1356 underlying disk image.
1358 You should always call this if you have modified a disk image, before
1359 closing the handle.");
1361 ("touch", (RErr, [Pathname "path"]), 3, [],
1362 [InitBasicFS, Always, TestOutputTrue (
1364 ["exists"; "/new"]])],
1365 "update file timestamps or create a new file",
1367 Touch acts like the L<touch(1)> command. It can be used to
1368 update the timestamps on a file, or, if the file does not exist,
1369 to create a new zero-length file.
1371 This command only works on regular files, and will fail on other
1372 file types such as directories, symbolic links, block special etc.");
1374 ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
1375 [InitISOFS, Always, TestOutput (
1376 [["cat"; "/known-2"]], "abcdef\n")],
1377 "list the contents of a file",
1379 Return the contents of the file named C<path>.
1381 Note that this function cannot correctly handle binary files
1382 (specifically, files containing C<\\0> character which is treated
1383 as end of string). For those you need to use the C<guestfs_read_file>
1384 or C<guestfs_download> functions which have a more complex interface.");
1386 ("ll", (RString "listing", [Pathname "directory"]), 5, [],
1387 [], (* XXX Tricky to test because it depends on the exact format
1388 * of the 'ls -l' command, which changes between F10 and F11.
1390 "list the files in a directory (long format)",
1392 List the files in C<directory> (relative to the root directory,
1393 there is no cwd) in the format of 'ls -la'.
1395 This command is mostly useful for interactive sessions. It
1396 is I<not> intended that you try to parse the output string.");
1398 ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
1399 [InitBasicFS, Always, TestOutputList (
1401 ["touch"; "/newer"];
1402 ["touch"; "/newest"];
1403 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
1404 "list the files in a directory",
1406 List the files in C<directory> (relative to the root directory,
1407 there is no cwd). The '.' and '..' entries are not returned, but
1408 hidden files are shown.
1410 This command is mostly useful for interactive sessions. Programs
1411 should probably use C<guestfs_readdir> instead.");
1413 ("list_devices", (RStringList "devices", []), 7, [],
1414 [InitEmpty, Always, TestOutputListOfDevices (
1415 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1416 "list the block devices",
1418 List all the block devices.
1420 The full block device names are returned, eg. C</dev/sda>");
1422 ("list_partitions", (RStringList "partitions", []), 8, [],
1423 [InitBasicFS, Always, TestOutputListOfDevices (
1424 [["list_partitions"]], ["/dev/sda1"]);
1425 InitEmpty, Always, TestOutputListOfDevices (
1426 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1427 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1428 "list the partitions",
1430 List all the partitions detected on all block devices.
1432 The full partition device names are returned, eg. C</dev/sda1>
1434 This does not return logical volumes. For that you will need to
1435 call C<guestfs_lvs>.");
1437 ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1438 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1439 [["pvs"]], ["/dev/sda1"]);
1440 InitEmpty, Always, TestOutputListOfDevices (
1441 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1442 ["pvcreate"; "/dev/sda1"];
1443 ["pvcreate"; "/dev/sda2"];
1444 ["pvcreate"; "/dev/sda3"];
1445 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1446 "list the LVM physical volumes (PVs)",
1448 List all the physical volumes detected. This is the equivalent
1449 of the L<pvs(8)> command.
1451 This returns a list of just the device names that contain
1452 PVs (eg. C</dev/sda2>).
1454 See also C<guestfs_pvs_full>.");
1456 ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1457 [InitBasicFSonLVM, Always, TestOutputList (
1459 InitEmpty, Always, TestOutputList (
1460 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1461 ["pvcreate"; "/dev/sda1"];
1462 ["pvcreate"; "/dev/sda2"];
1463 ["pvcreate"; "/dev/sda3"];
1464 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1465 ["vgcreate"; "VG2"; "/dev/sda3"];
1466 ["vgs"]], ["VG1"; "VG2"])],
1467 "list the LVM volume groups (VGs)",
1469 List all the volumes groups detected. This is the equivalent
1470 of the L<vgs(8)> command.
1472 This returns a list of just the volume group names that were
1473 detected (eg. C<VolGroup00>).
1475 See also C<guestfs_vgs_full>.");
1477 ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1478 [InitBasicFSonLVM, Always, TestOutputList (
1479 [["lvs"]], ["/dev/VG/LV"]);
1480 InitEmpty, Always, TestOutputList (
1481 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1482 ["pvcreate"; "/dev/sda1"];
1483 ["pvcreate"; "/dev/sda2"];
1484 ["pvcreate"; "/dev/sda3"];
1485 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1486 ["vgcreate"; "VG2"; "/dev/sda3"];
1487 ["lvcreate"; "LV1"; "VG1"; "50"];
1488 ["lvcreate"; "LV2"; "VG1"; "50"];
1489 ["lvcreate"; "LV3"; "VG2"; "50"];
1490 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1491 "list the LVM logical volumes (LVs)",
1493 List all the logical volumes detected. This is the equivalent
1494 of the L<lvs(8)> command.
1496 This returns a list of the logical volume device names
1497 (eg. C</dev/VolGroup00/LogVol00>).
1499 See also C<guestfs_lvs_full>.");
1501 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1502 [], (* XXX how to test? *)
1503 "list the LVM physical volumes (PVs)",
1505 List all the physical volumes detected. This is the equivalent
1506 of the L<pvs(8)> command. The \"full\" version includes all fields.");
1508 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1509 [], (* XXX how to test? *)
1510 "list the LVM volume groups (VGs)",
1512 List all the volumes groups detected. This is the equivalent
1513 of the L<vgs(8)> command. The \"full\" version includes all fields.");
1515 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1516 [], (* XXX how to test? *)
1517 "list the LVM logical volumes (LVs)",
1519 List all the logical volumes detected. This is the equivalent
1520 of the L<lvs(8)> command. The \"full\" version includes all fields.");
1522 ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1523 [InitISOFS, Always, TestOutputList (
1524 [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1525 InitISOFS, Always, TestOutputList (
1526 [["read_lines"; "/empty"]], [])],
1527 "read file as lines",
1529 Return the contents of the file named C<path>.
1531 The file contents are returned as a list of lines. Trailing
1532 C<LF> and C<CRLF> character sequences are I<not> returned.
1534 Note that this function cannot correctly handle binary files
1535 (specifically, files containing C<\\0> character which is treated
1536 as end of line). For those you need to use the C<guestfs_read_file>
1537 function which has a more complex interface.");
1539 ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1540 [], (* XXX Augeas code needs tests. *)
1541 "create a new Augeas handle",
1543 Create a new Augeas handle for editing configuration files.
1544 If there was any previous Augeas handle associated with this
1545 guestfs session, then it is closed.
1547 You must call this before using any other C<guestfs_aug_*>
1550 C<root> is the filesystem root. C<root> must not be NULL,
1553 The flags are the same as the flags defined in
1554 E<lt>augeas.hE<gt>, the logical I<or> of the following
1559 =item C<AUG_SAVE_BACKUP> = 1
1561 Keep the original file with a C<.augsave> extension.
1563 =item C<AUG_SAVE_NEWFILE> = 2
1565 Save changes into a file with extension C<.augnew>, and
1566 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
1568 =item C<AUG_TYPE_CHECK> = 4
1570 Typecheck lenses (can be expensive).
1572 =item C<AUG_NO_STDINC> = 8
1574 Do not use standard load path for modules.
1576 =item C<AUG_SAVE_NOOP> = 16
1578 Make save a no-op, just record what would have been changed.
1580 =item C<AUG_NO_LOAD> = 32
1582 Do not load the tree in C<guestfs_aug_init>.
1586 To close the handle, you can call C<guestfs_aug_close>.
1588 To find out more about Augeas, see L<http://augeas.net/>.");
1590 ("aug_close", (RErr, []), 26, [Optional "augeas"],
1591 [], (* XXX Augeas code needs tests. *)
1592 "close the current Augeas handle",
1594 Close the current Augeas handle and free up any resources
1595 used by it. After calling this, you have to call
1596 C<guestfs_aug_init> again before you can use any other
1597 Augeas functions.");
1599 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1600 [], (* XXX Augeas code needs tests. *)
1601 "define an Augeas variable",
1603 Defines an Augeas variable C<name> whose value is the result
1604 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
1607 On success this returns the number of nodes in C<expr>, or
1608 C<0> if C<expr> evaluates to something which is not a nodeset.");
1610 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1611 [], (* XXX Augeas code needs tests. *)
1612 "define an Augeas node",
1614 Defines a variable C<name> whose value is the result of
1617 If C<expr> evaluates to an empty nodeset, a node is created,
1618 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1619 C<name> will be the nodeset containing that single node.
1621 On success this returns a pair containing the
1622 number of nodes in the nodeset, and a boolean flag
1623 if a node was created.");
1625 ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1626 [], (* XXX Augeas code needs tests. *)
1627 "look up the value of an Augeas path",
1629 Look up the value associated with C<path>. If C<path>
1630 matches exactly one node, the C<value> is returned.");
1632 ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1633 [], (* XXX Augeas code needs tests. *)
1634 "set Augeas path to value",
1636 Set the value associated with C<path> to C<val>.
1638 In the Augeas API, it is possible to clear a node by setting
1639 the value to NULL. Due to an oversight in the libguestfs API
1640 you cannot do that with this call. Instead you must use the
1641 C<guestfs_aug_clear> call.");
1643 ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1644 [], (* XXX Augeas code needs tests. *)
1645 "insert a sibling Augeas node",
1647 Create a new sibling C<label> for C<path>, inserting it into
1648 the tree before or after C<path> (depending on the boolean
1651 C<path> must match exactly one existing node in the tree, and
1652 C<label> must be a label, ie. not contain C</>, C<*> or end
1653 with a bracketed index C<[N]>.");
1655 ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1656 [], (* XXX Augeas code needs tests. *)
1657 "remove an Augeas path",
1659 Remove C<path> and all of its children.
1661 On success this returns the number of entries which were removed.");
1663 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1664 [], (* XXX Augeas code needs tests. *)
1667 Move the node C<src> to C<dest>. C<src> must match exactly
1668 one node. C<dest> is overwritten if it exists.");
1670 ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1671 [], (* XXX Augeas code needs tests. *)
1672 "return Augeas nodes which match augpath",
1674 Returns a list of paths which match the path expression C<path>.
1675 The returned paths are sufficiently qualified so that they match
1676 exactly one node in the current tree.");
1678 ("aug_save", (RErr, []), 25, [Optional "augeas"],
1679 [], (* XXX Augeas code needs tests. *)
1680 "write all pending Augeas changes to disk",
1682 This writes all pending changes to disk.
1684 The flags which were passed to C<guestfs_aug_init> affect exactly
1685 how files are saved.");
1687 ("aug_load", (RErr, []), 27, [Optional "augeas"],
1688 [], (* XXX Augeas code needs tests. *)
1689 "load files into the tree",
1691 Load files into the tree.
1693 See C<aug_load> in the Augeas documentation for the full gory
1696 ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1697 [], (* XXX Augeas code needs tests. *)
1698 "list Augeas nodes under augpath",
1700 This is just a shortcut for listing C<guestfs_aug_match>
1701 C<path/*> and sorting the resulting nodes into alphabetical order.");
1703 ("rm", (RErr, [Pathname "path"]), 29, [],
1704 [InitBasicFS, Always, TestRun
1707 InitBasicFS, Always, TestLastFail
1709 InitBasicFS, Always, TestLastFail
1714 Remove the single file C<path>.");
1716 ("rmdir", (RErr, [Pathname "path"]), 30, [],
1717 [InitBasicFS, Always, TestRun
1720 InitBasicFS, Always, TestLastFail
1721 [["rmdir"; "/new"]];
1722 InitBasicFS, Always, TestLastFail
1724 ["rmdir"; "/new"]]],
1725 "remove a directory",
1727 Remove the single directory C<path>.");
1729 ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1730 [InitBasicFS, Always, TestOutputFalse
1732 ["mkdir"; "/new/foo"];
1733 ["touch"; "/new/foo/bar"];
1735 ["exists"; "/new"]]],
1736 "remove a file or directory recursively",
1738 Remove the file or directory C<path>, recursively removing the
1739 contents if its a directory. This is like the C<rm -rf> shell
1742 ("mkdir", (RErr, [Pathname "path"]), 32, [],
1743 [InitBasicFS, Always, TestOutputTrue
1745 ["is_dir"; "/new"]];
1746 InitBasicFS, Always, TestLastFail
1747 [["mkdir"; "/new/foo/bar"]]],
1748 "create a directory",
1750 Create a directory named C<path>.");
1752 ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1753 [InitBasicFS, Always, TestOutputTrue
1754 [["mkdir_p"; "/new/foo/bar"];
1755 ["is_dir"; "/new/foo/bar"]];
1756 InitBasicFS, Always, TestOutputTrue
1757 [["mkdir_p"; "/new/foo/bar"];
1758 ["is_dir"; "/new/foo"]];
1759 InitBasicFS, Always, TestOutputTrue
1760 [["mkdir_p"; "/new/foo/bar"];
1761 ["is_dir"; "/new"]];
1762 (* Regression tests for RHBZ#503133: *)
1763 InitBasicFS, Always, TestRun
1765 ["mkdir_p"; "/new"]];
1766 InitBasicFS, Always, TestLastFail
1768 ["mkdir_p"; "/new"]]],
1769 "create a directory and parents",
1771 Create a directory named C<path>, creating any parent directories
1772 as necessary. This is like the C<mkdir -p> shell command.");
1774 ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1775 [], (* XXX Need stat command to test *)
1778 Change the mode (permissions) of C<path> to C<mode>. Only
1779 numeric modes are supported.
1781 I<Note>: When using this command from guestfish, C<mode>
1782 by default would be decimal, unless you prefix it with
1783 C<0> to get octal, ie. use C<0700> not C<700>.
1785 The mode actually set is affected by the umask.");
1787 ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1788 [], (* XXX Need stat command to test *)
1789 "change file owner and group",
1791 Change the file owner to C<owner> and group to C<group>.
1793 Only numeric uid and gid are supported. If you want to use
1794 names, you will need to locate and parse the password file
1795 yourself (Augeas support makes this relatively easy).");
1797 ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1798 [InitISOFS, Always, TestOutputTrue (
1799 [["exists"; "/empty"]]);
1800 InitISOFS, Always, TestOutputTrue (
1801 [["exists"; "/directory"]])],
1802 "test if file or directory exists",
1804 This returns C<true> if and only if there is a file, directory
1805 (or anything) with the given C<path> name.
1807 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1809 ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1810 [InitISOFS, Always, TestOutputTrue (
1811 [["is_file"; "/known-1"]]);
1812 InitISOFS, Always, TestOutputFalse (
1813 [["is_file"; "/directory"]])],
1814 "test if file exists",
1816 This returns C<true> if and only if there is a file
1817 with the given C<path> name. Note that it returns false for
1818 other objects like directories.
1820 See also C<guestfs_stat>.");
1822 ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1823 [InitISOFS, Always, TestOutputFalse (
1824 [["is_dir"; "/known-3"]]);
1825 InitISOFS, Always, TestOutputTrue (
1826 [["is_dir"; "/directory"]])],
1827 "test if file exists",
1829 This returns C<true> if and only if there is a directory
1830 with the given C<path> name. Note that it returns false for
1831 other objects like files.
1833 See also C<guestfs_stat>.");
1835 ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1836 [InitEmpty, Always, TestOutputListOfDevices (
1837 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1838 ["pvcreate"; "/dev/sda1"];
1839 ["pvcreate"; "/dev/sda2"];
1840 ["pvcreate"; "/dev/sda3"];
1841 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1842 "create an LVM physical volume",
1844 This creates an LVM physical volume on the named C<device>,
1845 where C<device> should usually be a partition name such
1848 ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1849 [InitEmpty, Always, TestOutputList (
1850 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1851 ["pvcreate"; "/dev/sda1"];
1852 ["pvcreate"; "/dev/sda2"];
1853 ["pvcreate"; "/dev/sda3"];
1854 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1855 ["vgcreate"; "VG2"; "/dev/sda3"];
1856 ["vgs"]], ["VG1"; "VG2"])],
1857 "create an LVM volume group",
1859 This creates an LVM volume group called C<volgroup>
1860 from the non-empty list of physical volumes C<physvols>.");
1862 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1863 [InitEmpty, Always, TestOutputList (
1864 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1865 ["pvcreate"; "/dev/sda1"];
1866 ["pvcreate"; "/dev/sda2"];
1867 ["pvcreate"; "/dev/sda3"];
1868 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1869 ["vgcreate"; "VG2"; "/dev/sda3"];
1870 ["lvcreate"; "LV1"; "VG1"; "50"];
1871 ["lvcreate"; "LV2"; "VG1"; "50"];
1872 ["lvcreate"; "LV3"; "VG2"; "50"];
1873 ["lvcreate"; "LV4"; "VG2"; "50"];
1874 ["lvcreate"; "LV5"; "VG2"; "50"];
1876 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1877 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1878 "create an LVM logical volume",
1880 This creates an LVM logical volume called C<logvol>
1881 on the volume group C<volgroup>, with C<size> megabytes.");
1883 ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1884 [InitEmpty, Always, TestOutput (
1885 [["part_disk"; "/dev/sda"; "mbr"];
1886 ["mkfs"; "ext2"; "/dev/sda1"];
1887 ["mount_options"; ""; "/dev/sda1"; "/"];
1888 ["write"; "/new"; "new file contents"];
1889 ["cat"; "/new"]], "new file contents")],
1890 "make a filesystem",
1892 This creates a filesystem on C<device> (usually a partition
1893 or LVM logical volume). The filesystem type is C<fstype>, for
1896 ("sfdisk", (RErr, [Device "device";
1897 Int "cyls"; Int "heads"; Int "sectors";
1898 StringList "lines"]), 43, [DangerWillRobinson],
1900 "create partitions on a block device",
1902 This is a direct interface to the L<sfdisk(8)> program for creating
1903 partitions on block devices.
1905 C<device> should be a block device, for example C</dev/sda>.
1907 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1908 and sectors on the device, which are passed directly to sfdisk as
1909 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1910 of these, then the corresponding parameter is omitted. Usually for
1911 'large' disks, you can just pass C<0> for these, but for small
1912 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1913 out the right geometry and you will need to tell it.
1915 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1916 information refer to the L<sfdisk(8)> manpage.
1918 To create a single partition occupying the whole disk, you would
1919 pass C<lines> as a single element list, when the single element being
1920 the string C<,> (comma).
1922 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1923 C<guestfs_part_init>");
1925 ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning; DeprecatedBy "write"],
1926 (* Regression test for RHBZ#597135. *)
1927 [InitBasicFS, Always, TestLastFail
1928 [["write_file"; "/new"; "abc"; "10000"]]],
1931 This call creates a file called C<path>. The contents of the
1932 file is the string C<content> (which can contain any 8 bit data),
1933 with length C<size>.
1935 As a special case, if C<size> is C<0>
1936 then the length is calculated using C<strlen> (so in this case
1937 the content cannot contain embedded ASCII NULs).
1939 I<NB.> Owing to a bug, writing content containing ASCII NUL
1940 characters does I<not> work, even if the length is specified.");
1942 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1943 [InitEmpty, Always, TestOutputListOfDevices (
1944 [["part_disk"; "/dev/sda"; "mbr"];
1945 ["mkfs"; "ext2"; "/dev/sda1"];
1946 ["mount_options"; ""; "/dev/sda1"; "/"];
1947 ["mounts"]], ["/dev/sda1"]);
1948 InitEmpty, Always, TestOutputList (
1949 [["part_disk"; "/dev/sda"; "mbr"];
1950 ["mkfs"; "ext2"; "/dev/sda1"];
1951 ["mount_options"; ""; "/dev/sda1"; "/"];
1954 "unmount a filesystem",
1956 This unmounts the given filesystem. The filesystem may be
1957 specified either by its mountpoint (path) or the device which
1958 contains the filesystem.");
1960 ("mounts", (RStringList "devices", []), 46, [],
1961 [InitBasicFS, Always, TestOutputListOfDevices (
1962 [["mounts"]], ["/dev/sda1"])],
1963 "show mounted filesystems",
1965 This returns the list of currently mounted filesystems. It returns
1966 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1968 Some internal mounts are not shown.
1970 See also: C<guestfs_mountpoints>");
1972 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1973 [InitBasicFS, Always, TestOutputList (
1976 (* check that umount_all can unmount nested mounts correctly: *)
1977 InitEmpty, Always, TestOutputList (
1978 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1979 ["mkfs"; "ext2"; "/dev/sda1"];
1980 ["mkfs"; "ext2"; "/dev/sda2"];
1981 ["mkfs"; "ext2"; "/dev/sda3"];
1982 ["mount_options"; ""; "/dev/sda1"; "/"];
1984 ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1985 ["mkdir"; "/mp1/mp2"];
1986 ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1987 ["mkdir"; "/mp1/mp2/mp3"];
1990 "unmount all filesystems",
1992 This unmounts all mounted filesystems.
1994 Some internal mounts are not unmounted by this call.");
1996 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1998 "remove all LVM LVs, VGs and PVs",
2000 This command removes all LVM logical volumes, volume groups
2001 and physical volumes.");
2003 ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
2004 [InitISOFS, Always, TestOutput (
2005 [["file"; "/empty"]], "empty");
2006 InitISOFS, Always, TestOutput (
2007 [["file"; "/known-1"]], "ASCII text");
2008 InitISOFS, Always, TestLastFail (
2009 [["file"; "/notexists"]]);
2010 InitISOFS, Always, TestOutput (
2011 [["file"; "/abssymlink"]], "symbolic link");
2012 InitISOFS, Always, TestOutput (
2013 [["file"; "/directory"]], "directory")],
2014 "determine file type",
2016 This call uses the standard L<file(1)> command to determine
2017 the type or contents of the file.
2019 This call will also transparently look inside various types
2022 The exact command which runs is C<file -zb path>. Note in
2023 particular that the filename is not prepended to the output
2026 This command can also be used on C</dev/> devices
2027 (and partitions, LV names). You can for example use this
2028 to determine if a device contains a filesystem, although
2029 it's usually better to use C<guestfs_vfs_type>.
2031 If the C<path> does not begin with C</dev/> then
2032 this command only works for the content of regular files.
2033 For other file types (directory, symbolic link etc) it
2034 will just return the string C<directory> etc.");
2036 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
2037 [InitBasicFS, Always, TestOutput (
2038 [["upload"; "test-command"; "/test-command"];
2039 ["chmod"; "0o755"; "/test-command"];
2040 ["command"; "/test-command 1"]], "Result1");
2041 InitBasicFS, Always, TestOutput (
2042 [["upload"; "test-command"; "/test-command"];
2043 ["chmod"; "0o755"; "/test-command"];
2044 ["command"; "/test-command 2"]], "Result2\n");
2045 InitBasicFS, Always, TestOutput (
2046 [["upload"; "test-command"; "/test-command"];
2047 ["chmod"; "0o755"; "/test-command"];
2048 ["command"; "/test-command 3"]], "\nResult3");
2049 InitBasicFS, Always, TestOutput (
2050 [["upload"; "test-command"; "/test-command"];
2051 ["chmod"; "0o755"; "/test-command"];
2052 ["command"; "/test-command 4"]], "\nResult4\n");
2053 InitBasicFS, Always, TestOutput (
2054 [["upload"; "test-command"; "/test-command"];
2055 ["chmod"; "0o755"; "/test-command"];
2056 ["command"; "/test-command 5"]], "\nResult5\n\n");
2057 InitBasicFS, Always, TestOutput (
2058 [["upload"; "test-command"; "/test-command"];
2059 ["chmod"; "0o755"; "/test-command"];
2060 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
2061 InitBasicFS, Always, TestOutput (
2062 [["upload"; "test-command"; "/test-command"];
2063 ["chmod"; "0o755"; "/test-command"];
2064 ["command"; "/test-command 7"]], "");
2065 InitBasicFS, Always, TestOutput (
2066 [["upload"; "test-command"; "/test-command"];
2067 ["chmod"; "0o755"; "/test-command"];
2068 ["command"; "/test-command 8"]], "\n");
2069 InitBasicFS, Always, TestOutput (
2070 [["upload"; "test-command"; "/test-command"];
2071 ["chmod"; "0o755"; "/test-command"];
2072 ["command"; "/test-command 9"]], "\n\n");
2073 InitBasicFS, Always, TestOutput (
2074 [["upload"; "test-command"; "/test-command"];
2075 ["chmod"; "0o755"; "/test-command"];
2076 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
2077 InitBasicFS, Always, TestOutput (
2078 [["upload"; "test-command"; "/test-command"];
2079 ["chmod"; "0o755"; "/test-command"];
2080 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
2081 InitBasicFS, Always, TestLastFail (
2082 [["upload"; "test-command"; "/test-command"];
2083 ["chmod"; "0o755"; "/test-command"];
2084 ["command"; "/test-command"]])],
2085 "run a command from the guest filesystem",
2087 This call runs a command from the guest filesystem. The
2088 filesystem must be mounted, and must contain a compatible
2089 operating system (ie. something Linux, with the same
2090 or compatible processor architecture).
2092 The single parameter is an argv-style list of arguments.
2093 The first element is the name of the program to run.
2094 Subsequent elements are parameters. The list must be
2095 non-empty (ie. must contain a program name). Note that
2096 the command runs directly, and is I<not> invoked via
2097 the shell (see C<guestfs_sh>).
2099 The return value is anything printed to I<stdout> by
2102 If the command returns a non-zero exit status, then
2103 this function returns an error message. The error message
2104 string is the content of I<stderr> from the command.
2106 The C<$PATH> environment variable will contain at least
2107 C</usr/bin> and C</bin>. If you require a program from
2108 another location, you should provide the full path in the
2111 Shared libraries and data files required by the program
2112 must be available on filesystems which are mounted in the
2113 correct places. It is the caller's responsibility to ensure
2114 all filesystems that are needed are mounted at the right
2117 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
2118 [InitBasicFS, Always, TestOutputList (
2119 [["upload"; "test-command"; "/test-command"];
2120 ["chmod"; "0o755"; "/test-command"];
2121 ["command_lines"; "/test-command 1"]], ["Result1"]);
2122 InitBasicFS, Always, TestOutputList (
2123 [["upload"; "test-command"; "/test-command"];
2124 ["chmod"; "0o755"; "/test-command"];
2125 ["command_lines"; "/test-command 2"]], ["Result2"]);
2126 InitBasicFS, Always, TestOutputList (
2127 [["upload"; "test-command"; "/test-command"];
2128 ["chmod"; "0o755"; "/test-command"];
2129 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
2130 InitBasicFS, Always, TestOutputList (
2131 [["upload"; "test-command"; "/test-command"];
2132 ["chmod"; "0o755"; "/test-command"];
2133 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
2134 InitBasicFS, Always, TestOutputList (
2135 [["upload"; "test-command"; "/test-command"];
2136 ["chmod"; "0o755"; "/test-command"];
2137 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
2138 InitBasicFS, Always, TestOutputList (
2139 [["upload"; "test-command"; "/test-command"];
2140 ["chmod"; "0o755"; "/test-command"];
2141 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
2142 InitBasicFS, Always, TestOutputList (
2143 [["upload"; "test-command"; "/test-command"];
2144 ["chmod"; "0o755"; "/test-command"];
2145 ["command_lines"; "/test-command 7"]], []);
2146 InitBasicFS, Always, TestOutputList (
2147 [["upload"; "test-command"; "/test-command"];
2148 ["chmod"; "0o755"; "/test-command"];
2149 ["command_lines"; "/test-command 8"]], [""]);
2150 InitBasicFS, Always, TestOutputList (
2151 [["upload"; "test-command"; "/test-command"];
2152 ["chmod"; "0o755"; "/test-command"];
2153 ["command_lines"; "/test-command 9"]], ["";""]);
2154 InitBasicFS, Always, TestOutputList (
2155 [["upload"; "test-command"; "/test-command"];
2156 ["chmod"; "0o755"; "/test-command"];
2157 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
2158 InitBasicFS, Always, TestOutputList (
2159 [["upload"; "test-command"; "/test-command"];
2160 ["chmod"; "0o755"; "/test-command"];
2161 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
2162 "run a command, returning lines",
2164 This is the same as C<guestfs_command>, but splits the
2165 result into a list of lines.
2167 See also: C<guestfs_sh_lines>");
2169 ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
2170 [InitISOFS, Always, TestOutputStruct (
2171 [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
2172 "get file information",
2174 Returns file information for the given C<path>.
2176 This is the same as the C<stat(2)> system call.");
2178 ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
2179 [InitISOFS, Always, TestOutputStruct (
2180 [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
2181 "get file information for a symbolic link",
2183 Returns file information for the given C<path>.
2185 This is the same as C<guestfs_stat> except that if C<path>
2186 is a symbolic link, then the link is stat-ed, not the file it
2189 This is the same as the C<lstat(2)> system call.");
2191 ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
2192 [InitISOFS, Always, TestOutputStruct (
2193 [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
2194 "get file system statistics",
2196 Returns file system statistics for any mounted file system.
2197 C<path> should be a file or directory in the mounted file system
2198 (typically it is the mount point itself, but it doesn't need to be).
2200 This is the same as the C<statvfs(2)> system call.");
2202 ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
2204 "get ext2/ext3/ext4 superblock details",
2206 This returns the contents of the ext2, ext3 or ext4 filesystem
2207 superblock on C<device>.
2209 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
2210 manpage for more details. The list of fields returned isn't
2211 clearly defined, and depends on both the version of C<tune2fs>
2212 that libguestfs was built against, and the filesystem itself.");
2214 ("blockdev_setro", (RErr, [Device "device"]), 56, [],
2215 [InitEmpty, Always, TestOutputTrue (
2216 [["blockdev_setro"; "/dev/sda"];
2217 ["blockdev_getro"; "/dev/sda"]])],
2218 "set block device to read-only",
2220 Sets the block device named C<device> to read-only.
2222 This uses the L<blockdev(8)> command.");
2224 ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
2225 [InitEmpty, Always, TestOutputFalse (
2226 [["blockdev_setrw"; "/dev/sda"];
2227 ["blockdev_getro"; "/dev/sda"]])],
2228 "set block device to read-write",
2230 Sets the block device named C<device> to read-write.
2232 This uses the L<blockdev(8)> command.");
2234 ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
2235 [InitEmpty, Always, TestOutputTrue (
2236 [["blockdev_setro"; "/dev/sda"];
2237 ["blockdev_getro"; "/dev/sda"]])],
2238 "is block device set to read-only",
2240 Returns a boolean indicating if the block device is read-only
2241 (true if read-only, false if not).
2243 This uses the L<blockdev(8)> command.");
2245 ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
2246 [InitEmpty, Always, TestOutputInt (
2247 [["blockdev_getss"; "/dev/sda"]], 512)],
2248 "get sectorsize of block device",
2250 This returns the size of sectors on a block device.
2251 Usually 512, but can be larger for modern devices.
2253 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
2256 This uses the L<blockdev(8)> command.");
2258 ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
2259 [InitEmpty, Always, TestOutputInt (
2260 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
2261 "get blocksize of block device",
2263 This returns the block size of a device.
2265 (Note this is different from both I<size in blocks> and
2266 I<filesystem block size>).
2268 This uses the L<blockdev(8)> command.");
2270 ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
2272 "set blocksize of block device",
2274 This sets the block size of a device.
2276 (Note this is different from both I<size in blocks> and
2277 I<filesystem block size>).
2279 This uses the L<blockdev(8)> command.");
2281 ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
2282 [InitEmpty, Always, TestOutputInt (
2283 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
2284 "get total size of device in 512-byte sectors",
2286 This returns the size of the device in units of 512-byte sectors
2287 (even if the sectorsize isn't 512 bytes ... weird).
2289 See also C<guestfs_blockdev_getss> for the real sector size of
2290 the device, and C<guestfs_blockdev_getsize64> for the more
2291 useful I<size in bytes>.
2293 This uses the L<blockdev(8)> command.");
2295 ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
2296 [InitEmpty, Always, TestOutputInt (
2297 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
2298 "get total size of device in bytes",
2300 This returns the size of the device in bytes.
2302 See also C<guestfs_blockdev_getsz>.
2304 This uses the L<blockdev(8)> command.");
2306 ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
2307 [InitEmpty, Always, TestRun
2308 [["blockdev_flushbufs"; "/dev/sda"]]],
2309 "flush device buffers",
2311 This tells the kernel to flush internal buffers associated
2314 This uses the L<blockdev(8)> command.");
2316 ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
2317 [InitEmpty, Always, TestRun
2318 [["blockdev_rereadpt"; "/dev/sda"]]],
2319 "reread partition table",
2321 Reread the partition table on C<device>.
2323 This uses the L<blockdev(8)> command.");
2325 ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
2326 [InitBasicFS, Always, TestOutput (
2327 (* Pick a file from cwd which isn't likely to change. *)
2328 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2329 ["checksum"; "md5"; "/COPYING.LIB"]],
2330 Digest.to_hex (Digest.file "COPYING.LIB"))],
2331 "upload a file from the local machine",
2333 Upload local file C<filename> to C<remotefilename> on the
2336 C<filename> can also be a named pipe.
2338 See also C<guestfs_download>.");
2340 ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [],
2341 [InitBasicFS, Always, TestOutput (
2342 (* Pick a file from cwd which isn't likely to change. *)
2343 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2344 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
2345 ["upload"; "testdownload.tmp"; "/upload"];
2346 ["checksum"; "md5"; "/upload"]],
2347 Digest.to_hex (Digest.file "COPYING.LIB"))],
2348 "download a file to the local machine",
2350 Download file C<remotefilename> and save it as C<filename>
2351 on the local machine.
2353 C<filename> can also be a named pipe.
2355 See also C<guestfs_upload>, C<guestfs_cat>.");
2357 ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
2358 [InitISOFS, Always, TestOutput (
2359 [["checksum"; "crc"; "/known-3"]], "2891671662");
2360 InitISOFS, Always, TestLastFail (
2361 [["checksum"; "crc"; "/notexists"]]);
2362 InitISOFS, Always, TestOutput (
2363 [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
2364 InitISOFS, Always, TestOutput (
2365 [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
2366 InitISOFS, Always, TestOutput (
2367 [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
2368 InitISOFS, Always, TestOutput (
2369 [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
2370 InitISOFS, Always, TestOutput (
2371 [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
2372 InitISOFS, Always, TestOutput (
2373 [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6");
2374 (* Test for RHBZ#579608, absolute symbolic links. *)
2375 InitISOFS, Always, TestOutput (
2376 [["checksum"; "sha512"; "/abssymlink"]], "5f57d0639bc95081c53afc63a449403883818edc64da48930ad6b1a4fb49be90404686877743fbcd7c99811f3def7df7bc22635c885c6a8cf79c806b43451c1a")],
2377 "compute MD5, SHAx or CRC checksum of file",
2379 This call computes the MD5, SHAx or CRC checksum of the
2382 The type of checksum to compute is given by the C<csumtype>
2383 parameter which must have one of the following values:
2389 Compute the cyclic redundancy check (CRC) specified by POSIX
2390 for the C<cksum> command.
2394 Compute the MD5 hash (using the C<md5sum> program).
2398 Compute the SHA1 hash (using the C<sha1sum> program).
2402 Compute the SHA224 hash (using the C<sha224sum> program).
2406 Compute the SHA256 hash (using the C<sha256sum> program).
2410 Compute the SHA384 hash (using the C<sha384sum> program).
2414 Compute the SHA512 hash (using the C<sha512sum> program).
2418 The checksum is returned as a printable string.
2420 To get the checksum for a device, use C<guestfs_checksum_device>.
2422 To get the checksums for many files, use C<guestfs_checksums_out>.");
2424 ("tar_in", (RErr, [FileIn "tarfile"; Pathname "directory"]), 69, [],
2425 [InitBasicFS, Always, TestOutput (
2426 [["tar_in"; "../images/helloworld.tar"; "/"];
2427 ["cat"; "/hello"]], "hello\n")],
2428 "unpack tarfile to directory",
2430 This command uploads and unpacks local file C<tarfile> (an
2431 I<uncompressed> tar file) into C<directory>.
2433 To upload a compressed tarball, use C<guestfs_tgz_in>
2434 or C<guestfs_txz_in>.");
2436 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2438 "pack directory into tarfile",
2440 This command packs the contents of C<directory> and downloads
2441 it to local file C<tarfile>.
2443 To download a compressed tarball, use C<guestfs_tgz_out>
2444 or C<guestfs_txz_out>.");
2446 ("tgz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 71, [],
2447 [InitBasicFS, Always, TestOutput (
2448 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2449 ["cat"; "/hello"]], "hello\n")],
2450 "unpack compressed tarball to directory",
2452 This command uploads and unpacks local file C<tarball> (a
2453 I<gzip compressed> tar file) into C<directory>.
2455 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2457 ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2459 "pack directory into compressed tarball",
2461 This command packs the contents of C<directory> and downloads
2462 it to local file C<tarball>.
2464 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2466 ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2467 [InitBasicFS, Always, TestLastFail (
2469 ["mount_ro"; "/dev/sda1"; "/"];
2470 ["touch"; "/new"]]);
2471 InitBasicFS, Always, TestOutput (
2472 [["write"; "/new"; "data"];
2474 ["mount_ro"; "/dev/sda1"; "/"];
2475 ["cat"; "/new"]], "data")],
2476 "mount a guest disk, read-only",
2478 This is the same as the C<guestfs_mount> command, but it
2479 mounts the filesystem with the read-only (I<-o ro>) flag.");
2481 ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2483 "mount a guest disk with mount options",
2485 This is the same as the C<guestfs_mount> command, but it
2486 allows you to set the mount options as for the
2487 L<mount(8)> I<-o> flag.
2489 If the C<options> parameter is an empty string, then
2490 no options are passed (all options default to whatever
2491 the filesystem uses).");
2493 ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2495 "mount a guest disk with mount options and vfstype",
2497 This is the same as the C<guestfs_mount> command, but it
2498 allows you to set both the mount options and the vfstype
2499 as for the L<mount(8)> I<-o> and I<-t> flags.");
2501 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2503 "debugging and internals",
2505 The C<guestfs_debug> command exposes some internals of
2506 C<guestfsd> (the guestfs daemon) that runs inside the
2509 There is no comprehensive help for this command. You have
2510 to look at the file C<daemon/debug.c> in the libguestfs source
2511 to find out what you can do.");
2513 ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2514 [InitEmpty, Always, TestOutputList (
2515 [["part_disk"; "/dev/sda"; "mbr"];
2516 ["pvcreate"; "/dev/sda1"];
2517 ["vgcreate"; "VG"; "/dev/sda1"];
2518 ["lvcreate"; "LV1"; "VG"; "50"];
2519 ["lvcreate"; "LV2"; "VG"; "50"];
2520 ["lvremove"; "/dev/VG/LV1"];
2521 ["lvs"]], ["/dev/VG/LV2"]);
2522 InitEmpty, Always, TestOutputList (
2523 [["part_disk"; "/dev/sda"; "mbr"];
2524 ["pvcreate"; "/dev/sda1"];
2525 ["vgcreate"; "VG"; "/dev/sda1"];
2526 ["lvcreate"; "LV1"; "VG"; "50"];
2527 ["lvcreate"; "LV2"; "VG"; "50"];
2528 ["lvremove"; "/dev/VG"];
2530 InitEmpty, Always, TestOutputList (
2531 [["part_disk"; "/dev/sda"; "mbr"];
2532 ["pvcreate"; "/dev/sda1"];
2533 ["vgcreate"; "VG"; "/dev/sda1"];
2534 ["lvcreate"; "LV1"; "VG"; "50"];
2535 ["lvcreate"; "LV2"; "VG"; "50"];
2536 ["lvremove"; "/dev/VG"];
2538 "remove an LVM logical volume",
2540 Remove an LVM logical volume C<device>, where C<device> is
2541 the path to the LV, such as C</dev/VG/LV>.
2543 You can also remove all LVs in a volume group by specifying
2544 the VG name, C</dev/VG>.");
2546 ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2547 [InitEmpty, Always, TestOutputList (
2548 [["part_disk"; "/dev/sda"; "mbr"];
2549 ["pvcreate"; "/dev/sda1"];
2550 ["vgcreate"; "VG"; "/dev/sda1"];
2551 ["lvcreate"; "LV1"; "VG"; "50"];
2552 ["lvcreate"; "LV2"; "VG"; "50"];
2555 InitEmpty, Always, TestOutputList (
2556 [["part_disk"; "/dev/sda"; "mbr"];
2557 ["pvcreate"; "/dev/sda1"];
2558 ["vgcreate"; "VG"; "/dev/sda1"];
2559 ["lvcreate"; "LV1"; "VG"; "50"];
2560 ["lvcreate"; "LV2"; "VG"; "50"];
2563 "remove an LVM volume group",
2565 Remove an LVM volume group C<vgname>, (for example C<VG>).
2567 This also forcibly removes all logical volumes in the volume
2570 ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2571 [InitEmpty, Always, TestOutputListOfDevices (
2572 [["part_disk"; "/dev/sda"; "mbr"];
2573 ["pvcreate"; "/dev/sda1"];
2574 ["vgcreate"; "VG"; "/dev/sda1"];
2575 ["lvcreate"; "LV1"; "VG"; "50"];
2576 ["lvcreate"; "LV2"; "VG"; "50"];
2578 ["pvremove"; "/dev/sda1"];
2580 InitEmpty, Always, TestOutputListOfDevices (
2581 [["part_disk"; "/dev/sda"; "mbr"];
2582 ["pvcreate"; "/dev/sda1"];
2583 ["vgcreate"; "VG"; "/dev/sda1"];
2584 ["lvcreate"; "LV1"; "VG"; "50"];
2585 ["lvcreate"; "LV2"; "VG"; "50"];
2587 ["pvremove"; "/dev/sda1"];
2589 InitEmpty, Always, TestOutputListOfDevices (
2590 [["part_disk"; "/dev/sda"; "mbr"];
2591 ["pvcreate"; "/dev/sda1"];
2592 ["vgcreate"; "VG"; "/dev/sda1"];
2593 ["lvcreate"; "LV1"; "VG"; "50"];
2594 ["lvcreate"; "LV2"; "VG"; "50"];
2596 ["pvremove"; "/dev/sda1"];
2598 "remove an LVM physical volume",
2600 This wipes a physical volume C<device> so that LVM will no longer
2603 The implementation uses the C<pvremove> command which refuses to
2604 wipe physical volumes that contain any volume groups, so you have
2605 to remove those first.");
2607 ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2608 [InitBasicFS, Always, TestOutput (
2609 [["set_e2label"; "/dev/sda1"; "testlabel"];
2610 ["get_e2label"; "/dev/sda1"]], "testlabel")],
2611 "set the ext2/3/4 filesystem label",
2613 This sets the ext2/3/4 filesystem label of the filesystem on
2614 C<device> to C<label>. Filesystem labels are limited to
2617 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2618 to return the existing label on a filesystem.");
2620 ("get_e2label", (RString "label", [Device "device"]), 81, [DeprecatedBy "vfs_label"],
2622 "get the ext2/3/4 filesystem label",
2624 This returns the ext2/3/4 filesystem label of the filesystem on
2627 ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2628 (let uuid = uuidgen () in
2629 [InitBasicFS, Always, TestOutput (
2630 [["set_e2uuid"; "/dev/sda1"; uuid];
2631 ["get_e2uuid"; "/dev/sda1"]], uuid);
2632 InitBasicFS, Always, TestOutput (
2633 [["set_e2uuid"; "/dev/sda1"; "clear"];
2634 ["get_e2uuid"; "/dev/sda1"]], "");
2635 (* We can't predict what UUIDs will be, so just check the commands run. *)
2636 InitBasicFS, Always, TestRun (
2637 [["set_e2uuid"; "/dev/sda1"; "random"]]);
2638 InitBasicFS, Always, TestRun (
2639 [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2640 "set the ext2/3/4 filesystem UUID",
2642 This sets the ext2/3/4 filesystem UUID of the filesystem on
2643 C<device> to C<uuid>. The format of the UUID and alternatives
2644 such as C<clear>, C<random> and C<time> are described in the
2645 L<tune2fs(8)> manpage.
2647 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2648 to return the existing UUID of a filesystem.");
2650 ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [DeprecatedBy "vfs_uuid"],
2651 (* Regression test for RHBZ#597112. *)
2652 (let uuid = uuidgen () in
2653 [InitBasicFS, Always, TestOutput (
2654 [["mke2journal"; "1024"; "/dev/sdb"];
2655 ["set_e2uuid"; "/dev/sdb"; uuid];
2656 ["get_e2uuid"; "/dev/sdb"]], uuid)]),
2657 "get the ext2/3/4 filesystem UUID",
2659 This returns the ext2/3/4 filesystem UUID of the filesystem on
2662 ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [FishOutput FishOutputHexadecimal],
2663 [InitBasicFS, Always, TestOutputInt (
2664 [["umount"; "/dev/sda1"];
2665 ["fsck"; "ext2"; "/dev/sda1"]], 0);
2666 InitBasicFS, Always, TestOutputInt (
2667 [["umount"; "/dev/sda1"];
2668 ["zero"; "/dev/sda1"];
2669 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2670 "run the filesystem checker",
2672 This runs the filesystem checker (fsck) on C<device> which
2673 should have filesystem type C<fstype>.
2675 The returned integer is the status. See L<fsck(8)> for the
2676 list of status codes from C<fsck>.
2684 Multiple status codes can be summed together.
2688 A non-zero return code can mean \"success\", for example if
2689 errors have been corrected on the filesystem.
2693 Checking or repairing NTFS volumes is not supported
2698 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2700 ("zero", (RErr, [Device "device"]), 85, [],
2701 [InitBasicFS, Always, TestOutput (
2702 [["umount"; "/dev/sda1"];
2703 ["zero"; "/dev/sda1"];
2704 ["file"; "/dev/sda1"]], "data")],
2705 "write zeroes to the device",
2707 This command writes zeroes over the first few blocks of C<device>.
2709 How many blocks are zeroed isn't specified (but it's I<not> enough
2710 to securely wipe the device). It should be sufficient to remove
2711 any partition tables, filesystem superblocks and so on.
2713 See also: C<guestfs_zero_device>, C<guestfs_scrub_device>.");
2715 ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2717 * https://bugzilla.redhat.com/show_bug.cgi?id=484986
2718 * https://bugzilla.redhat.com/show_bug.cgi?id=479760
2720 [InitBasicFS, Always, TestOutputTrue (
2721 [["mkdir_p"; "/boot/grub"];
2722 ["write"; "/boot/grub/device.map"; "(hd0) /dev/vda"];
2723 ["grub_install"; "/"; "/dev/vda"];
2724 ["is_dir"; "/boot"]])],
2727 This command installs GRUB (the Grand Unified Bootloader) on
2728 C<device>, with the root directory being C<root>.
2730 Note: If grub-install reports the error
2731 \"No suitable drive was found in the generated device map.\"
2732 it may be that you need to create a C</boot/grub/device.map>
2733 file first that contains the mapping between grub device names
2734 and Linux device names. It is usually sufficient to create
2739 replacing C</dev/vda> with the name of the installation device.");
2741 ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2742 [InitBasicFS, Always, TestOutput (
2743 [["write"; "/old"; "file content"];
2744 ["cp"; "/old"; "/new"];
2745 ["cat"; "/new"]], "file content");
2746 InitBasicFS, Always, TestOutputTrue (
2747 [["write"; "/old"; "file content"];
2748 ["cp"; "/old"; "/new"];
2749 ["is_file"; "/old"]]);
2750 InitBasicFS, Always, TestOutput (
2751 [["write"; "/old"; "file content"];
2753 ["cp"; "/old"; "/dir/new"];
2754 ["cat"; "/dir/new"]], "file content")],
2757 This copies a file from C<src> to C<dest> where C<dest> is
2758 either a destination filename or destination directory.");
2760 ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2761 [InitBasicFS, Always, TestOutput (
2762 [["mkdir"; "/olddir"];
2763 ["mkdir"; "/newdir"];
2764 ["write"; "/olddir/file"; "file content"];
2765 ["cp_a"; "/olddir"; "/newdir"];
2766 ["cat"; "/newdir/olddir/file"]], "file content")],
2767 "copy a file or directory recursively",
2769 This copies a file or directory from C<src> to C<dest>
2770 recursively using the C<cp -a> command.");
2772 ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2773 [InitBasicFS, Always, TestOutput (
2774 [["write"; "/old"; "file content"];
2775 ["mv"; "/old"; "/new"];
2776 ["cat"; "/new"]], "file content");
2777 InitBasicFS, Always, TestOutputFalse (
2778 [["write"; "/old"; "file content"];
2779 ["mv"; "/old"; "/new"];
2780 ["is_file"; "/old"]])],
2783 This moves a file from C<src> to C<dest> where C<dest> is
2784 either a destination filename or destination directory.");
2786 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2787 [InitEmpty, Always, TestRun (
2788 [["drop_caches"; "3"]])],
2789 "drop kernel page cache, dentries and inodes",
2791 This instructs the guest kernel to drop its page cache,
2792 and/or dentries and inode caches. The parameter C<whattodrop>
2793 tells the kernel what precisely to drop, see
2794 L<http://linux-mm.org/Drop_Caches>
2796 Setting C<whattodrop> to 3 should drop everything.
2798 This automatically calls L<sync(2)> before the operation,
2799 so that the maximum guest memory is freed.");
2801 ("dmesg", (RString "kmsgs", []), 91, [],
2802 [InitEmpty, Always, TestRun (
2804 "return kernel messages",
2806 This returns the kernel messages (C<dmesg> output) from
2807 the guest kernel. This is sometimes useful for extended
2808 debugging of problems.
2810 Another way to get the same information is to enable
2811 verbose messages with C<guestfs_set_verbose> or by setting
2812 the environment variable C<LIBGUESTFS_DEBUG=1> before
2813 running the program.");
2815 ("ping_daemon", (RErr, []), 92, [],
2816 [InitEmpty, Always, TestRun (
2817 [["ping_daemon"]])],
2818 "ping the guest daemon",
2820 This is a test probe into the guestfs daemon running inside
2821 the qemu subprocess. Calling this function checks that the
2822 daemon responds to the ping message, without affecting the daemon
2823 or attached block device(s) in any other way.");
2825 ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2826 [InitBasicFS, Always, TestOutputTrue (
2827 [["write"; "/file1"; "contents of a file"];
2828 ["cp"; "/file1"; "/file2"];
2829 ["equal"; "/file1"; "/file2"]]);
2830 InitBasicFS, Always, TestOutputFalse (
2831 [["write"; "/file1"; "contents of a file"];
2832 ["write"; "/file2"; "contents of another file"];
2833 ["equal"; "/file1"; "/file2"]]);
2834 InitBasicFS, Always, TestLastFail (
2835 [["equal"; "/file1"; "/file2"]])],
2836 "test if two files have equal contents",
2838 This compares the two files C<file1> and C<file2> and returns
2839 true if their content is exactly equal, or false otherwise.
2841 The external L<cmp(1)> program is used for the comparison.");
2843 ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2844 [InitISOFS, Always, TestOutputList (
2845 [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2846 InitISOFS, Always, TestOutputList (
2847 [["strings"; "/empty"]], []);
2848 (* Test for RHBZ#579608, absolute symbolic links. *)
2849 InitISOFS, Always, TestRun (
2850 [["strings"; "/abssymlink"]])],
2851 "print the printable strings in a file",
2853 This runs the L<strings(1)> command on a file and returns
2854 the list of printable strings found.");
2856 ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2857 [InitISOFS, Always, TestOutputList (
2858 [["strings_e"; "b"; "/known-5"]], []);
2859 InitBasicFS, Always, TestOutputList (
2860 [["write"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"];
2861 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2862 "print the printable strings in a file",
2864 This is like the C<guestfs_strings> command, but allows you to
2865 specify the encoding of strings that are looked for in
2866 the source file C<path>.
2868 Allowed encodings are:
2874 Single 7-bit-byte characters like ASCII and the ASCII-compatible
2875 parts of ISO-8859-X (this is what C<guestfs_strings> uses).
2879 Single 8-bit-byte characters.
2883 16-bit big endian strings such as those encoded in
2884 UTF-16BE or UCS-2BE.
2886 =item l (lower case letter L)
2888 16-bit little endian such as UTF-16LE and UCS-2LE.
2889 This is useful for examining binaries in Windows guests.
2893 32-bit big endian such as UCS-4BE.
2897 32-bit little endian such as UCS-4LE.
2901 The returned strings are transcoded to UTF-8.");
2903 ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2904 [InitISOFS, Always, TestOutput (
2905 [["hexdump"; "/known-4"]], "00000000 61 62 63 0a 64 65 66 0a 67 68 69 |abc.def.ghi|\n0000000b\n");
2906 (* Test for RHBZ#501888c2 regression which caused large hexdump
2907 * commands to segfault.
2909 InitISOFS, Always, TestRun (
2910 [["hexdump"; "/100krandom"]]);
2911 (* Test for RHBZ#579608, absolute symbolic links. *)
2912 InitISOFS, Always, TestRun (
2913 [["hexdump"; "/abssymlink"]])],
2914 "dump a file in hexadecimal",
2916 This runs C<hexdump -C> on the given C<path>. The result is
2917 the human-readable, canonical hex dump of the file.");
2919 ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2920 [InitNone, Always, TestOutput (
2921 [["part_disk"; "/dev/sda"; "mbr"];
2922 ["mkfs"; "ext3"; "/dev/sda1"];
2923 ["mount_options"; ""; "/dev/sda1"; "/"];
2924 ["write"; "/new"; "test file"];
2925 ["umount"; "/dev/sda1"];
2926 ["zerofree"; "/dev/sda1"];
2927 ["mount_options"; ""; "/dev/sda1"; "/"];
2928 ["cat"; "/new"]], "test file")],
2929 "zero unused inodes and disk blocks on ext2/3 filesystem",
2931 This runs the I<zerofree> program on C<device>. This program
2932 claims to zero unused inodes and disk blocks on an ext2/3
2933 filesystem, thus making it possible to compress the filesystem
2936 You should B<not> run this program if the filesystem is
2939 It is possible that using this program can damage the filesystem
2940 or data on the filesystem.");
2942 ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2944 "resize an LVM physical volume",
2946 This resizes (expands or shrinks) an existing LVM physical
2947 volume to match the new size of the underlying device.");
2949 ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2950 Int "cyls"; Int "heads"; Int "sectors";
2951 String "line"]), 99, [DangerWillRobinson],
2953 "modify a single partition on a block device",
2955 This runs L<sfdisk(8)> option to modify just the single
2956 partition C<n> (note: C<n> counts from 1).
2958 For other parameters, see C<guestfs_sfdisk>. You should usually
2959 pass C<0> for the cyls/heads/sectors parameters.
2961 See also: C<guestfs_part_add>");
2963 ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2965 "display the partition table",
2967 This displays the partition table on C<device>, in the
2968 human-readable output of the L<sfdisk(8)> command. It is
2969 not intended to be parsed.
2971 See also: C<guestfs_part_list>");
2973 ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2975 "display the kernel geometry",
2977 This displays the kernel's idea of the geometry of C<device>.
2979 The result is in human-readable format, and not designed to
2982 ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2984 "display the disk geometry from the partition table",
2986 This displays the disk geometry of C<device> read from the
2987 partition table. Especially in the case where the underlying
2988 block device has been resized, this can be different from the
2989 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2991 The result is in human-readable format, and not designed to
2994 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2996 "activate or deactivate all volume groups",
2998 This command activates or (if C<activate> is false) deactivates
2999 all logical volumes in all volume groups.
3000 If activated, then they are made known to the
3001 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
3002 then those devices disappear.
3004 This command is the same as running C<vgchange -a y|n>");
3006 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
3008 "activate or deactivate some volume groups",
3010 This command activates or (if C<activate> is false) deactivates
3011 all logical volumes in the listed volume groups C<volgroups>.
3012 If activated, then they are made known to the
3013 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
3014 then those devices disappear.
3016 This command is the same as running C<vgchange -a y|n volgroups...>
3018 Note that if C<volgroups> is an empty list then B<all> volume groups
3019 are activated or deactivated.");
3021 ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
3022 [InitNone, Always, TestOutput (
3023 [["part_disk"; "/dev/sda"; "mbr"];
3024 ["pvcreate"; "/dev/sda1"];
3025 ["vgcreate"; "VG"; "/dev/sda1"];
3026 ["lvcreate"; "LV"; "VG"; "10"];
3027 ["mkfs"; "ext2"; "/dev/VG/LV"];
3028 ["mount_options"; ""; "/dev/VG/LV"; "/"];
3029 ["write"; "/new"; "test content"];
3031 ["lvresize"; "/dev/VG/LV"; "20"];
3032 ["e2fsck_f"; "/dev/VG/LV"];
3033 ["resize2fs"; "/dev/VG/LV"];
3034 ["mount_options"; ""; "/dev/VG/LV"; "/"];
3035 ["cat"; "/new"]], "test content");
3036 InitNone, Always, TestRun (
3037 (* Make an LV smaller to test RHBZ#587484. *)
3038 [["part_disk"; "/dev/sda"; "mbr"];
3039 ["pvcreate"; "/dev/sda1"];
3040 ["vgcreate"; "VG"; "/dev/sda1"];
3041 ["lvcreate"; "LV"; "VG"; "20"];
3042 ["lvresize"; "/dev/VG/LV"; "10"]])],
3043 "resize an LVM logical volume",
3045 This resizes (expands or shrinks) an existing LVM logical
3046 volume to C<mbytes>. When reducing, data in the reduced part
3049 ("resize2fs", (RErr, [Device "device"]), 106, [],
3050 [], (* lvresize tests this *)
3051 "resize an ext2, ext3 or ext4 filesystem",
3053 This resizes an ext2, ext3 or ext4 filesystem to match the size of
3054 the underlying device.
3056 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
3057 on the C<device> before calling this command. For unknown reasons
3058 C<resize2fs> sometimes gives an error about this and sometimes not.
3059 In any case, it is always safe to call C<guestfs_e2fsck_f> before
3060 calling this function.");
3062 ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
3063 [InitBasicFS, Always, TestOutputList (
3064 [["find"; "/"]], ["lost+found"]);
3065 InitBasicFS, Always, TestOutputList (
3069 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
3070 InitBasicFS, Always, TestOutputList (
3071 [["mkdir_p"; "/a/b/c"];
3072 ["touch"; "/a/b/c/d"];
3073 ["find"; "/a/b/"]], ["c"; "c/d"])],
3074 "find all files and directories",
3076 This command lists out all files and directories, recursively,
3077 starting at C<directory>. It is essentially equivalent to
3078 running the shell command C<find directory -print> but some
3079 post-processing happens on the output, described below.
3081 This returns a list of strings I<without any prefix>. Thus
3082 if the directory structure was:
3088 then the returned list from C<guestfs_find> C</tmp> would be
3096 If C<directory> is not a directory, then this command returns
3099 The returned list is sorted.
3101 See also C<guestfs_find0>.");
3103 ("e2fsck_f", (RErr, [Device "device"]), 108, [],
3104 [], (* lvresize tests this *)
3105 "check an ext2/ext3 filesystem",
3107 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
3108 filesystem checker on C<device>, noninteractively (C<-p>),
3109 even if the filesystem appears to be clean (C<-f>).
3111 This command is only needed because of C<guestfs_resize2fs>
3112 (q.v.). Normally you should use C<guestfs_fsck>.");
3114 ("sleep", (RErr, [Int "secs"]), 109, [],
3115 [InitNone, Always, TestRun (
3117 "sleep for some seconds",
3119 Sleep for C<secs> seconds.");
3121 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
3122 [InitNone, Always, TestOutputInt (
3123 [["part_disk"; "/dev/sda"; "mbr"];
3124 ["mkfs"; "ntfs"; "/dev/sda1"];
3125 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
3126 InitNone, Always, TestOutputInt (
3127 [["part_disk"; "/dev/sda"; "mbr"];
3128 ["mkfs"; "ext2"; "/dev/sda1"];
3129 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
3130 "probe NTFS volume",
3132 This command runs the L<ntfs-3g.probe(8)> command which probes
3133 an NTFS C<device> for mountability. (Not all NTFS volumes can
3134 be mounted read-write, and some cannot be mounted at all).
3136 C<rw> is a boolean flag. Set it to true if you want to test
3137 if the volume can be mounted read-write. Set it to false if
3138 you want to test if the volume can be mounted read-only.
3140 The return value is an integer which C<0> if the operation
3141 would succeed, or some non-zero value documented in the
3142 L<ntfs-3g.probe(8)> manual page.");
3144 ("sh", (RString "output", [String "command"]), 111, [],
3145 [], (* XXX needs tests *)
3146 "run a command via the shell",
3148 This call runs a command from the guest filesystem via the
3151 This is like C<guestfs_command>, but passes the command to:
3153 /bin/sh -c \"command\"
3155 Depending on the guest's shell, this usually results in
3156 wildcards being expanded, shell expressions being interpolated
3159 All the provisos about C<guestfs_command> apply to this call.");
3161 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
3162 [], (* XXX needs tests *)
3163 "run a command via the shell returning lines",
3165 This is the same as C<guestfs_sh>, but splits the result
3166 into a list of lines.
3168 See also: C<guestfs_command_lines>");
3170 ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
3171 (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
3172 * code in stubs.c, since all valid glob patterns must start with "/".
3173 * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
3175 [InitBasicFS, Always, TestOutputList (
3176 [["mkdir_p"; "/a/b/c"];
3177 ["touch"; "/a/b/c/d"];
3178 ["touch"; "/a/b/c/e"];
3179 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3180 InitBasicFS, Always, TestOutputList (
3181 [["mkdir_p"; "/a/b/c"];
3182 ["touch"; "/a/b/c/d"];
3183 ["touch"; "/a/b/c/e"];
3184 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3185 InitBasicFS, Always, TestOutputList (
3186 [["mkdir_p"; "/a/b/c"];
3187 ["touch"; "/a/b/c/d"];
3188 ["touch"; "/a/b/c/e"];
3189 ["glob_expand"; "/a/*/x/*"]], [])],
3190 "expand a wildcard path",
3192 This command searches for all the pathnames matching
3193 C<pattern> according to the wildcard expansion rules
3196 If no paths match, then this returns an empty list
3197 (note: not an error).
3199 It is just a wrapper around the C L<glob(3)> function
3200 with flags C<GLOB_MARK|GLOB_BRACE>.
3201 See that manual page for more details.");
3203 ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
3204 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
3205 [["scrub_device"; "/dev/sdc"]])],
3206 "scrub (securely wipe) a device",
3208 This command writes patterns over C<device> to make data retrieval
3211 It is an interface to the L<scrub(1)> program. See that
3212 manual page for more details.");
3214 ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
3215 [InitBasicFS, Always, TestRun (
3216 [["write"; "/file"; "content"];
3217 ["scrub_file"; "/file"]])],
3218 "scrub (securely wipe) a file",
3220 This command writes patterns over a file to make data retrieval
3223 The file is I<removed> after scrubbing.
3225 It is an interface to the L<scrub(1)> program. See that
3226 manual page for more details.");
3228 ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
3229 [], (* XXX needs testing *)
3230 "scrub (securely wipe) free space",
3232 This command creates the directory C<dir> and then fills it
3233 with files until the filesystem is full, and scrubs the files
3234 as for C<guestfs_scrub_file>, and deletes them.
3235 The intention is to scrub any free space on the partition
3238 It is an interface to the L<scrub(1)> program. See that
3239 manual page for more details.");
3241 ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
3242 [InitBasicFS, Always, TestRun (
3244 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
3245 "create a temporary directory",
3247 This command creates a temporary directory. The
3248 C<template> parameter should be a full pathname for the
3249 temporary directory name with the final six characters being
3252 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
3253 the second one being suitable for Windows filesystems.
3255 The name of the temporary directory that was created
3258 The temporary directory is created with mode 0700
3259 and is owned by root.
3261 The caller is responsible for deleting the temporary
3262 directory and its contents after use.
3264 See also: L<mkdtemp(3)>");
3266 ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
3267 [InitISOFS, Always, TestOutputInt (
3268 [["wc_l"; "/10klines"]], 10000);
3269 (* Test for RHBZ#579608, absolute symbolic links. *)
3270 InitISOFS, Always, TestOutputInt (
3271 [["wc_l"; "/abssymlink"]], 10000)],
3272 "count lines in a file",
3274 This command counts the lines in a file, using the
3275 C<wc -l> external command.");
3277 ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
3278 [InitISOFS, Always, TestOutputInt (
3279 [["wc_w"; "/10klines"]], 10000)],
3280 "count words in a file",
3282 This command counts the words in a file, using the
3283 C<wc -w> external command.");
3285 ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
3286 [InitISOFS, Always, TestOutputInt (
3287 [["wc_c"; "/100kallspaces"]], 102400)],
3288 "count characters in a file",
3290 This command counts the characters in a file, using the
3291 C<wc -c> external command.");
3293 ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
3294 [InitISOFS, Always, TestOutputList (
3295 [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"]);
3296 (* Test for RHBZ#579608, absolute symbolic links. *)
3297 InitISOFS, Always, TestOutputList (
3298 [["head"; "/abssymlink"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
3299 "return first 10 lines of a file",
3301 This command returns up to the first 10 lines of a file as
3302 a list of strings.");
3304 ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
3305 [InitISOFS, Always, TestOutputList (
3306 [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3307 InitISOFS, Always, TestOutputList (
3308 [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3309 InitISOFS, Always, TestOutputList (
3310 [["head_n"; "0"; "/10klines"]], [])],
3311 "return first N lines of a file",
3313 If the parameter C<nrlines> is a positive number, this returns the first
3314 C<nrlines> lines of the file C<path>.
3316 If the parameter C<nrlines> is a negative number, this returns lines
3317 from the file C<path>, excluding the last C<nrlines> lines.
3319 If the parameter C<nrlines> is zero, this returns an empty list.");
3321 ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
3322 [InitISOFS, Always, TestOutputList (
3323 [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
3324 "return last 10 lines of a file",
3326 This command returns up to the last 10 lines of a file as
3327 a list of strings.");
3329 ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
3330 [InitISOFS, Always, TestOutputList (
3331 [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3332 InitISOFS, Always, TestOutputList (
3333 [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3334 InitISOFS, Always, TestOutputList (
3335 [["tail_n"; "0"; "/10klines"]], [])],
3336 "return last N lines of a file",
3338 If the parameter C<nrlines> is a positive number, this returns the last
3339 C<nrlines> lines of the file C<path>.
3341 If the parameter C<nrlines> is a negative number, this returns lines
3342 from the file C<path>, starting with the C<-nrlines>th line.
3344 If the parameter C<nrlines> is zero, this returns an empty list.");
3346 ("df", (RString "output", []), 125, [],
3347 [], (* XXX Tricky to test because it depends on the exact format
3348 * of the 'df' command and other imponderables.
3350 "report file system disk space usage",
3352 This command runs the C<df> command to report disk space used.
3354 This command is mostly useful for interactive sessions. It
3355 is I<not> intended that you try to parse the output string.
3356 Use C<statvfs> from programs.");
3358 ("df_h", (RString "output", []), 126, [],
3359 [], (* XXX Tricky to test because it depends on the exact format
3360 * of the 'df' command and other imponderables.
3362 "report file system disk space usage (human readable)",
3364 This command runs the C<df -h> command to report disk space used
3365 in human-readable format.
3367 This command is mostly useful for interactive sessions. It
3368 is I<not> intended that you try to parse the output string.
3369 Use C<statvfs> from programs.");
3371 ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
3372 [InitISOFS, Always, TestOutputInt (
3373 [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
3374 "estimate file space usage",
3376 This command runs the C<du -s> command to estimate file space
3379 C<path> can be a file or a directory. If C<path> is a directory
3380 then the estimate includes the contents of the directory and all
3381 subdirectories (recursively).
3383 The result is the estimated size in I<kilobytes>
3384 (ie. units of 1024 bytes).");
3386 ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
3387 [InitISOFS, Always, TestOutputList (
3388 [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
3389 "list files in an initrd",
3391 This command lists out files contained in an initrd.
3393 The files are listed without any initial C</> character. The
3394 files are listed in the order they appear (not necessarily
3395 alphabetical). Directory names are listed as separate items.
3397 Old Linux kernels (2.4 and earlier) used a compressed ext2
3398 filesystem as initrd. We I<only> support the newer initramfs
3399 format (compressed cpio files).");
3401 ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
3403 "mount a file using the loop device",
3405 This command lets you mount C<file> (a filesystem image
3406 in a file) on a mount point. It is entirely equivalent to
3407 the command C<mount -o loop file mountpoint>.");
3409 ("mkswap", (RErr, [Device "device"]), 130, [],
3410 [InitEmpty, Always, TestRun (
3411 [["part_disk"; "/dev/sda"; "mbr"];
3412 ["mkswap"; "/dev/sda1"]])],
3413 "create a swap partition",
3415 Create a swap partition on C<device>.");
3417 ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
3418 [InitEmpty, Always, TestRun (
3419 [["part_disk"; "/dev/sda"; "mbr"];
3420 ["mkswap_L"; "hello"; "/dev/sda1"]])],
3421 "create a swap partition with a label",
3423 Create a swap partition on C<device> with label C<label>.
3425 Note that you cannot attach a swap label to a block device
3426 (eg. C</dev/sda>), just to a partition. This appears to be
3427 a limitation of the kernel or swap tools.");
3429 ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
3430 (let uuid = uuidgen () in
3431 [InitEmpty, Always, TestRun (
3432 [["part_disk"; "/dev/sda"; "mbr"];
3433 ["mkswap_U"; uuid; "/dev/sda1"]])]),
3434 "create a swap partition with an explicit UUID",
3436 Create a swap partition on C<device> with UUID C<uuid>.");
3438 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
3439 [InitBasicFS, Always, TestOutputStruct (
3440 [["mknod"; "0o10777"; "0"; "0"; "/node"];
3441 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
3442 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
3443 InitBasicFS, Always, TestOutputStruct (
3444 [["mknod"; "0o60777"; "66"; "99"; "/node"];
3445 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3446 "make block, character or FIFO devices",
3448 This call creates block or character special devices, or
3449 named pipes (FIFOs).
3451 The C<mode> parameter should be the mode, using the standard
3452 constants. C<devmajor> and C<devminor> are the
3453 device major and minor numbers, only used when creating block
3454 and character special devices.
3456 Note that, just like L<mknod(2)>, the mode must be bitwise
3457 OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
3458 just creates a regular file). These constants are
3459 available in the standard Linux header files, or you can use
3460 C<guestfs_mknod_b>, C<guestfs_mknod_c> or C<guestfs_mkfifo>
3461 which are wrappers around this command which bitwise OR
3462 in the appropriate constant for you.
3464 The mode actually set is affected by the umask.");
3466 ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
3467 [InitBasicFS, Always, TestOutputStruct (
3468 [["mkfifo"; "0o777"; "/node"];
3469 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
3470 "make FIFO (named pipe)",
3472 This call creates a FIFO (named pipe) called C<path> with
3473 mode C<mode>. It is just a convenient wrapper around
3476 The mode actually set is affected by the umask.");
3478 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
3479 [InitBasicFS, Always, TestOutputStruct (
3480 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
3481 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3482 "make block device node",
3484 This call creates a block device node called C<path> with
3485 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3486 It is just a convenient wrapper around C<guestfs_mknod>.
3488 The mode actually set is affected by the umask.");
3490 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
3491 [InitBasicFS, Always, TestOutputStruct (
3492 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
3493 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
3494 "make char device node",
3496 This call creates a char device node called C<path> with
3497 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3498 It is just a convenient wrapper around C<guestfs_mknod>.
3500 The mode actually set is affected by the umask.");
3502 ("umask", (RInt "oldmask", [Int "mask"]), 137, [FishOutput FishOutputOctal],
3503 [InitEmpty, Always, TestOutputInt (
3504 [["umask"; "0o22"]], 0o22)],
3505 "set file mode creation mask (umask)",
3507 This function sets the mask used for creating new files and
3508 device nodes to C<mask & 0777>.
3510 Typical umask values would be C<022> which creates new files
3511 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3512 C<002> which creates new files with permissions like
3513 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3515 The default umask is C<022>. This is important because it
3516 means that directories and device nodes will be created with
3517 C<0644> or C<0755> mode even if you specify C<0777>.
3519 See also C<guestfs_get_umask>,
3520 L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3522 This call returns the previous umask.");
3524 ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3526 "read directories entries",
3528 This returns the list of directory entries in directory C<dir>.
3530 All entries in the directory are returned, including C<.> and
3531 C<..>. The entries are I<not> sorted, but returned in the same
3532 order as the underlying filesystem.
3534 Also this call returns basic file type information about each
3535 file. The C<ftyp> field will contain one of the following characters:
3573 The L<readdir(3)> call returned a C<d_type> field with an
3578 This function is primarily intended for use by programs. To
3579 get a simple list of names, use C<guestfs_ls>. To get a printable
3580 directory for human consumption, use C<guestfs_ll>.");
3582 ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3584 "create partitions on a block device",
3586 This is a simplified interface to the C<guestfs_sfdisk>
3587 command, where partition sizes are specified in megabytes
3588 only (rounded to the nearest cylinder) and you don't need
3589 to specify the cyls, heads and sectors parameters which
3590 were rarely if ever used anyway.
3592 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3593 and C<guestfs_part_disk>");
3595 ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3597 "determine file type inside a compressed file",
3599 This command runs C<file> after first decompressing C<path>
3602 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3604 Since 1.0.63, use C<guestfs_file> instead which can now
3605 process compressed files.");
3607 ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3609 "list extended attributes of a file or directory",
3611 This call lists the extended attributes of the file or directory
3614 At the system call level, this is a combination of the
3615 L<listxattr(2)> and L<getxattr(2)> calls.
3617 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3619 ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3621 "list extended attributes of a file or directory",
3623 This is the same as C<guestfs_getxattrs>, but if C<path>
3624 is a symbolic link, then it returns the extended attributes
3625 of the link itself.");
3627 ("setxattr", (RErr, [String "xattr";
3628 String "val"; Int "vallen"; (* will be BufferIn *)
3629 Pathname "path"]), 143, [Optional "linuxxattrs"],
3631 "set extended attribute of a file or directory",
3633 This call sets the extended attribute named C<xattr>
3634 of the file C<path> to the value C<val> (of length C<vallen>).
3635 The value is arbitrary 8 bit data.
3637 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3639 ("lsetxattr", (RErr, [String "xattr";
3640 String "val"; Int "vallen"; (* will be BufferIn *)
3641 Pathname "path"]), 144, [Optional "linuxxattrs"],
3643 "set extended attribute of a file or directory",
3645 This is the same as C<guestfs_setxattr>, but if C<path>
3646 is a symbolic link, then it sets an extended attribute
3647 of the link itself.");
3649 ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3651 "remove extended attribute of a file or directory",
3653 This call removes the extended attribute named C<xattr>
3654 of the file C<path>.
3656 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3658 ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3660 "remove extended attribute of a file or directory",
3662 This is the same as C<guestfs_removexattr>, but if C<path>
3663 is a symbolic link, then it removes an extended attribute
3664 of the link itself.");
3666 ("mountpoints", (RHashtable "mps", []), 147, [],
3670 This call is similar to C<guestfs_mounts>. That call returns
3671 a list of devices. This one returns a hash table (map) of
3672 device name to directory where the device is mounted.");
3674 ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3675 (* This is a special case: while you would expect a parameter
3676 * of type "Pathname", that doesn't work, because it implies
3677 * NEED_ROOT in the generated calling code in stubs.c, and
3678 * this function cannot use NEED_ROOT.
3681 "create a mountpoint",
3683 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3684 specialized calls that can be used to create extra mountpoints
3685 before mounting the first filesystem.
3687 These calls are I<only> necessary in some very limited circumstances,
3688 mainly the case where you want to mount a mix of unrelated and/or
3689 read-only filesystems together.
3691 For example, live CDs often contain a \"Russian doll\" nest of
3692 filesystems, an ISO outer layer, with a squashfs image inside, with
3693 an ext2/3 image inside that. You can unpack this as follows
3696 add-ro Fedora-11-i686-Live.iso
3699 mkmountpoint /squash
3702 mount-loop /cd/LiveOS/squashfs.img /squash
3703 mount-loop /squash/LiveOS/ext3fs.img /ext3
3705 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3707 ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3709 "remove a mountpoint",
3711 This calls removes a mountpoint that was previously created
3712 with C<guestfs_mkmountpoint>. See C<guestfs_mkmountpoint>
3713 for full details.");
3715 ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3716 [InitISOFS, Always, TestOutputBuffer (
3717 [["read_file"; "/known-4"]], "abc\ndef\nghi");
3718 (* Test various near large, large and too large files (RHBZ#589039). *)
3719 InitBasicFS, Always, TestLastFail (
3721 ["truncate_size"; "/a"; "4194303"]; (* GUESTFS_MESSAGE_MAX - 1 *)
3722 ["read_file"; "/a"]]);
3723 InitBasicFS, Always, TestLastFail (
3725 ["truncate_size"; "/a"; "4194304"]; (* GUESTFS_MESSAGE_MAX *)
3726 ["read_file"; "/a"]]);
3727 InitBasicFS, Always, TestLastFail (
3729 ["truncate_size"; "/a"; "41943040"]; (* GUESTFS_MESSAGE_MAX * 10 *)
3730 ["read_file"; "/a"]])],
3733 This calls returns the contents of the file C<path> as a
3736 Unlike C<guestfs_cat>, this function can correctly
3737 handle files that contain embedded ASCII NUL characters.
3738 However unlike C<guestfs_download>, this function is limited
3739 in the total size of file that can be handled.");
3741 ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3742 [InitISOFS, Always, TestOutputList (
3743 [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3744 InitISOFS, Always, TestOutputList (
3745 [["grep"; "nomatch"; "/test-grep.txt"]], []);
3746 (* Test for RHBZ#579608, absolute symbolic links. *)
3747 InitISOFS, Always, TestOutputList (
3748 [["grep"; "nomatch"; "/abssymlink"]], [])],
3749 "return lines matching a pattern",
3751 This calls the external C<grep> program and returns the
3754 ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3755 [InitISOFS, Always, TestOutputList (
3756 [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3757 "return lines matching a pattern",
3759 This calls the external C<egrep> program and returns the
3762 ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3763 [InitISOFS, Always, TestOutputList (
3764 [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3765 "return lines matching a pattern",
3767 This calls the external C<fgrep> program and returns the
3770 ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3771 [InitISOFS, Always, TestOutputList (
3772 [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3773 "return lines matching a pattern",
3775 This calls the external C<grep -i> program and returns the
3778 ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3779 [InitISOFS, Always, TestOutputList (
3780 [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3781 "return lines matching a pattern",
3783 This calls the external C<egrep -i> program and returns the
3786 ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3787 [InitISOFS, Always, TestOutputList (
3788 [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3789 "return lines matching a pattern",
3791 This calls the external C<fgrep -i> program and returns the
3794 ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3795 [InitISOFS, Always, TestOutputList (
3796 [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3797 "return lines matching a pattern",
3799 This calls the external C<zgrep> program and returns the
3802 ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3803 [InitISOFS, Always, TestOutputList (
3804 [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3805 "return lines matching a pattern",
3807 This calls the external C<zegrep> program and returns the
3810 ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3811 [InitISOFS, Always, TestOutputList (
3812 [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3813 "return lines matching a pattern",
3815 This calls the external C<zfgrep> program and returns the
3818 ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3819 [InitISOFS, Always, TestOutputList (
3820 [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3821 "return lines matching a pattern",
3823 This calls the external C<zgrep -i> program and returns the
3826 ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3827 [InitISOFS, Always, TestOutputList (
3828 [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3829 "return lines matching a pattern",
3831 This calls the external C<zegrep -i> program and returns the
3834 ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3835 [InitISOFS, Always, TestOutputList (
3836 [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3837 "return lines matching a pattern",
3839 This calls the external C<zfgrep -i> program and returns the
3842 ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3843 [InitISOFS, Always, TestOutput (
3844 [["realpath"; "/../directory"]], "/directory")],
3845 "canonicalized absolute pathname",
3847 Return the canonicalized absolute pathname of C<path>. The
3848 returned path has no C<.>, C<..> or symbolic link path elements.");
3850 ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3851 [InitBasicFS, Always, TestOutputStruct (
3854 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3855 "create a hard link",
3857 This command creates a hard link using the C<ln> command.");
3859 ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3860 [InitBasicFS, Always, TestOutputStruct (
3863 ["ln_f"; "/a"; "/b"];
3864 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3865 "create a hard link",
3867 This command creates a hard link using the C<ln -f> command.
3868 The C<-f> option removes the link (C<linkname>) if it exists already.");
3870 ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3871 [InitBasicFS, Always, TestOutputStruct (
3873 ["ln_s"; "a"; "/b"];
3874 ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3875 "create a symbolic link",
3877 This command creates a symbolic link using the C<ln -s> command.");
3879 ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3880 [InitBasicFS, Always, TestOutput (
3881 [["mkdir_p"; "/a/b"];
3882 ["touch"; "/a/b/c"];
3883 ["ln_sf"; "../d"; "/a/b/c"];
3884 ["readlink"; "/a/b/c"]], "../d")],
3885 "create a symbolic link",
3887 This command creates a symbolic link using the C<ln -sf> command,
3888 The C<-f> option removes the link (C<linkname>) if it exists already.");
3890 ("readlink", (RString "link", [Pathname "path"]), 168, [],
3891 [] (* XXX tested above *),
3892 "read the target of a symbolic link",
3894 This command reads the target of a symbolic link.");
3896 ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [DeprecatedBy "fallocate64"],
3897 [InitBasicFS, Always, TestOutputStruct (
3898 [["fallocate"; "/a"; "1000000"];
3899 ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3900 "preallocate a file in the guest filesystem",
3902 This command preallocates a file (containing zero bytes) named
3903 C<path> of size C<len> bytes. If the file exists already, it
3906 Do not confuse this with the guestfish-specific
3907 C<alloc> command which allocates a file in the host and
3908 attaches it as a device.");
3910 ("swapon_device", (RErr, [Device "device"]), 170, [],
3911 [InitPartition, Always, TestRun (
3912 [["mkswap"; "/dev/sda1"];
3913 ["swapon_device"; "/dev/sda1"];
3914 ["swapoff_device"; "/dev/sda1"]])],
3915 "enable swap on device",
3917 This command enables the libguestfs appliance to use the
3918 swap device or partition named C<device>. The increased
3919 memory is made available for all commands, for example
3920 those run using C<guestfs_command> or C<guestfs_sh>.
3922 Note that you should not swap to existing guest swap
3923 partitions unless you know what you are doing. They may
3924 contain hibernation information, or other information that
3925 the guest doesn't want you to trash. You also risk leaking
3926 information about the host to the guest this way. Instead,
3927 attach a new host device to the guest and swap on that.");
3929 ("swapoff_device", (RErr, [Device "device"]), 171, [],
3930 [], (* XXX tested by swapon_device *)
3931 "disable swap on device",
3933 This command disables the libguestfs appliance swap
3934 device or partition named C<device>.
3935 See C<guestfs_swapon_device>.");
3937 ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3938 [InitBasicFS, Always, TestRun (
3939 [["fallocate"; "/swap"; "8388608"];
3940 ["mkswap_file"; "/swap"];
3941 ["swapon_file"; "/swap"];
3942 ["swapoff_file"; "/swap"]])],
3943 "enable swap on file",
3945 This command enables swap to a file.
3946 See C<guestfs_swapon_device> for other notes.");
3948 ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3949 [], (* XXX tested by swapon_file *)
3950 "disable swap on file",
3952 This command disables the libguestfs appliance swap on file.");
3954 ("swapon_label", (RErr, [String "label"]), 174, [],
3955 [InitEmpty, Always, TestRun (
3956 [["part_disk"; "/dev/sdb"; "mbr"];
3957 ["mkswap_L"; "swapit"; "/dev/sdb1"];
3958 ["swapon_label"; "swapit"];
3959 ["swapoff_label"; "swapit"];
3960 ["zero"; "/dev/sdb"];
3961 ["blockdev_rereadpt"; "/dev/sdb"]])],
3962 "enable swap on labeled swap partition",
3964 This command enables swap to a labeled swap partition.
3965 See C<guestfs_swapon_device> for other notes.");
3967 ("swapoff_label", (RErr, [String "label"]), 175, [],
3968 [], (* XXX tested by swapon_label *)
3969 "disable swap on labeled swap partition",
3971 This command disables the libguestfs appliance swap on
3972 labeled swap partition.");
3974 ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3975 (let uuid = uuidgen () in
3976 [InitEmpty, Always, TestRun (
3977 [["mkswap_U"; uuid; "/dev/sdb"];
3978 ["swapon_uuid"; uuid];
3979 ["swapoff_uuid"; uuid]])]),
3980 "enable swap on swap partition by UUID",
3982 This command enables swap to a swap partition with the given UUID.
3983 See C<guestfs_swapon_device> for other notes.");
3985 ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3986 [], (* XXX tested by swapon_uuid *)
3987 "disable swap on swap partition by UUID",
3989 This command disables the libguestfs appliance swap partition
3990 with the given UUID.");
3992 ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3993 [InitBasicFS, Always, TestRun (
3994 [["fallocate"; "/swap"; "8388608"];
3995 ["mkswap_file"; "/swap"]])],
3996 "create a swap file",
4000 This command just writes a swap file signature to an existing
4001 file. To create the file itself, use something like C<guestfs_fallocate>.");
4003 ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
4004 [InitISOFS, Always, TestRun (
4005 [["inotify_init"; "0"]])],
4006 "create an inotify handle",
4008 This command creates a new inotify handle.
4009 The inotify subsystem can be used to notify events which happen to
4010 objects in the guest filesystem.
4012 C<maxevents> is the maximum number of events which will be
4013 queued up between calls to C<guestfs_inotify_read> or
4014 C<guestfs_inotify_files>.
4015 If this is passed as C<0>, then the kernel (or previously set)
4016 default is used. For Linux 2.6.29 the default was 16384 events.
4017 Beyond this limit, the kernel throws away events, but records
4018 the fact that it threw them away by setting a flag
4019 C<IN_Q_OVERFLOW> in the returned structure list (see
4020 C<guestfs_inotify_read>).
4022 Before any events are generated, you have to add some
4023 watches to the internal watch list. See:
4024 C<guestfs_inotify_add_watch>,
4025 C<guestfs_inotify_rm_watch> and
4026 C<guestfs_inotify_watch_all>.
4028 Queued up events should be read periodically by calling
4029 C<guestfs_inotify_read>
4030 (or C<guestfs_inotify_files> which is just a helpful
4031 wrapper around C<guestfs_inotify_read>). If you don't
4032 read the events out often enough then you risk the internal
4035 The handle should be closed after use by calling
4036 C<guestfs_inotify_close>. This also removes any
4037 watches automatically.
4039 See also L<inotify(7)> for an overview of the inotify interface
4040 as exposed by the Linux kernel, which is roughly what we expose
4041 via libguestfs. Note that there is one global inotify handle
4042 per libguestfs instance.");
4044 ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
4045 [InitBasicFS, Always, TestOutputList (
4046 [["inotify_init"; "0"];
4047 ["inotify_add_watch"; "/"; "1073741823"];
4050 ["inotify_files"]], ["a"; "b"])],
4051 "add an inotify watch",
4053 Watch C<path> for the events listed in C<mask>.
4055 Note that if C<path> is a directory then events within that
4056 directory are watched, but this does I<not> happen recursively
4057 (in subdirectories).
4059 Note for non-C or non-Linux callers: the inotify events are
4060 defined by the Linux kernel ABI and are listed in
4061 C</usr/include/sys/inotify.h>.");
4063 ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
4065 "remove an inotify watch",
4067 Remove a previously defined inotify watch.
4068 See C<guestfs_inotify_add_watch>.");
4070 ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
4072 "return list of inotify events",
4074 Return the complete queue of events that have happened
4075 since the previous read call.
4077 If no events have happened, this returns an empty list.
4079 I<Note>: In order to make sure that all events have been
4080 read, you must call this function repeatedly until it
4081 returns an empty list. The reason is that the call will
4082 read events up to the maximum appliance-to-host message
4083 size and leave remaining events in the queue.");
4085 ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
4087 "return list of watched files that had events",
4089 This function is a helpful wrapper around C<guestfs_inotify_read>
4090 which just returns a list of pathnames of objects that were
4091 touched. The returned pathnames are sorted and deduplicated.");
4093 ("inotify_close", (RErr, []), 184, [Optional "inotify"],
4095 "close the inotify handle",
4097 This closes the inotify handle which was previously
4098 opened by inotify_init. It removes all watches, throws
4099 away any pending events, and deallocates all resources.");
4101 ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
4103 "set SELinux security context",
4105 This sets the SELinux security context of the daemon
4106 to the string C<context>.
4108 See the documentation about SELINUX in L<guestfs(3)>.");
4110 ("getcon", (RString "context", []), 186, [Optional "selinux"],
4112 "get SELinux security context",
4114 This gets the SELinux security context of the daemon.
4116 See the documentation about SELINUX in L<guestfs(3)>,
4117 and C<guestfs_setcon>");
4119 ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
4120 [InitEmpty, Always, TestOutput (
4121 [["part_disk"; "/dev/sda"; "mbr"];
4122 ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
4123 ["mount_options"; ""; "/dev/sda1"; "/"];
4124 ["write"; "/new"; "new file contents"];
4125 ["cat"; "/new"]], "new file contents");
4126 InitEmpty, Always, TestRun (
4127 [["part_disk"; "/dev/sda"; "mbr"];
4128 ["mkfs_b"; "vfat"; "32768"; "/dev/sda1"]]);
4129 InitEmpty, Always, TestLastFail (
4130 [["part_disk"; "/dev/sda"; "mbr"];
4131 ["mkfs_b"; "vfat"; "32769"; "/dev/sda1"]]);
4132 InitEmpty, Always, TestLastFail (
4133 [["part_disk"; "/dev/sda"; "mbr"];
4134 ["mkfs_b"; "vfat"; "33280"; "/dev/sda1"]]);
4135 InitEmpty, IfAvailable "ntfsprogs", TestRun (
4136 [["part_disk"; "/dev/sda"; "mbr"];
4137 ["mkfs_b"; "ntfs"; "32768"; "/dev/sda1"]])],
4138 "make a filesystem with block size",
4140 This call is similar to C<guestfs_mkfs>, but it allows you to
4141 control the block size of the resulting filesystem. Supported
4142 block sizes depend on the filesystem type, but typically they
4143 are C<1024>, C<2048> or C<4096> only.
4145 For VFAT and NTFS the C<blocksize> parameter is treated as
4146 the requested cluster size.");
4148 ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
4149 [InitEmpty, Always, TestOutput (
4150 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4151 ["mke2journal"; "4096"; "/dev/sda1"];
4152 ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
4153 ["mount_options"; ""; "/dev/sda2"; "/"];
4154 ["write"; "/new"; "new file contents"];
4155 ["cat"; "/new"]], "new file contents")],
4156 "make ext2/3/4 external journal",
4158 This creates an ext2 external journal on C<device>. It is equivalent
4161 mke2fs -O journal_dev -b blocksize device");
4163 ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
4164 [InitEmpty, Always, TestOutput (
4165 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4166 ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
4167 ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
4168 ["mount_options"; ""; "/dev/sda2"; "/"];
4169 ["write"; "/new"; "new file contents"];
4170 ["cat"; "/new"]], "new file contents")],
4171 "make ext2/3/4 external journal with label",
4173 This creates an ext2 external journal on C<device> with label C<label>.");
4175 ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
4176 (let uuid = uuidgen () in
4177 [InitEmpty, Always, TestOutput (
4178 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4179 ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
4180 ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
4181 ["mount_options"; ""; "/dev/sda2"; "/"];
4182 ["write"; "/new"; "new file contents"];
4183 ["cat"; "/new"]], "new file contents")]),
4184 "make ext2/3/4 external journal with UUID",
4186 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
4188 ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
4190 "make ext2/3/4 filesystem with external journal",
4192 This creates an ext2/3/4 filesystem on C<device> with
4193 an external journal on C<journal>. It is equivalent
4196 mke2fs -t fstype -b blocksize -J device=<journal> <device>
4198 See also C<guestfs_mke2journal>.");
4200 ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
4202 "make ext2/3/4 filesystem with external journal",
4204 This creates an ext2/3/4 filesystem on C<device> with
4205 an external journal on the journal labeled C<label>.
4207 See also C<guestfs_mke2journal_L>.");
4209 ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
4211 "make ext2/3/4 filesystem with external journal",
4213 This creates an ext2/3/4 filesystem on C<device> with
4214 an external journal on the journal with UUID C<uuid>.
4216 See also C<guestfs_mke2journal_U>.");
4218 ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
4219 [InitNone, Always, TestRun [["modprobe"; "fat"]]],
4220 "load a kernel module",
4222 This loads a kernel module in the appliance.
4224 The kernel module must have been whitelisted when libguestfs
4225 was built (see C<appliance/kmod.whitelist.in> in the source).");
4227 ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
4228 [InitNone, Always, TestOutput (
4229 [["echo_daemon"; "This is a test"]], "This is a test"
4231 "echo arguments back to the client",
4233 This command concatenates the list of C<words> passed with single spaces
4234 between them and returns the resulting string.
4236 You can use this command to test the connection through to the daemon.
4238 See also C<guestfs_ping_daemon>.");
4240 ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
4241 [], (* There is a regression test for this. *)
4242 "find all files and directories, returning NUL-separated list",
4244 This command lists out all files and directories, recursively,
4245 starting at C<directory>, placing the resulting list in the
4246 external file called C<files>.
4248 This command works the same way as C<guestfs_find> with the
4249 following exceptions:
4255 The resulting list is written to an external file.
4259 Items (filenames) in the result are separated
4260 by C<\\0> characters. See L<find(1)> option I<-print0>.
4264 This command is not limited in the number of names that it
4269 The result list is not sorted.
4273 ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
4274 [InitISOFS, Always, TestOutput (
4275 [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
4276 InitISOFS, Always, TestOutput (
4277 [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
4278 InitISOFS, Always, TestOutput (
4279 [["case_sensitive_path"; "/Known-1"]], "/known-1");
4280 InitISOFS, Always, TestLastFail (
4281 [["case_sensitive_path"; "/Known-1/"]]);
4282 InitBasicFS, Always, TestOutput (
4284 ["mkdir"; "/a/bbb"];
4285 ["touch"; "/a/bbb/c"];
4286 ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
4287 InitBasicFS, Always, TestOutput (
4289 ["mkdir"; "/a/bbb"];
4290 ["touch"; "/a/bbb/c"];
4291 ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
4292 InitBasicFS, Always, TestLastFail (
4294 ["mkdir"; "/a/bbb"];
4295 ["touch"; "/a/bbb/c"];
4296 ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
4297 "return true path on case-insensitive filesystem",
4299 This can be used to resolve case insensitive paths on
4300 a filesystem which is case sensitive. The use case is
4301 to resolve paths which you have read from Windows configuration
4302 files or the Windows Registry, to the true path.
4304 The command handles a peculiarity of the Linux ntfs-3g
4305 filesystem driver (and probably others), which is that although
4306 the underlying filesystem is case-insensitive, the driver
4307 exports the filesystem to Linux as case-sensitive.
4309 One consequence of this is that special directories such
4310 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
4311 (or other things) depending on the precise details of how
4312 they were created. In Windows itself this would not be
4315 Bug or feature? You decide:
4316 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
4318 This function resolves the true case of each element in the
4319 path and returns the case-sensitive path.
4321 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
4322 might return C<\"/WINDOWS/system32\"> (the exact return value
4323 would depend on details of how the directories were originally
4324 created under Windows).
4327 This function does not handle drive names, backslashes etc.
4329 See also C<guestfs_realpath>.");
4331 ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
4332 [InitBasicFS, Always, TestOutput (
4333 [["vfs_type"; "/dev/sda1"]], "ext2")],
4334 "get the Linux VFS type corresponding to a mounted device",
4336 This command gets the filesystem type corresponding to
4337 the filesystem on C<device>.
4339 For most filesystems, the result is the name of the Linux
4340 VFS module which would be used to mount this filesystem
4341 if you mounted it without specifying the filesystem type.
4342 For example a string such as C<ext3> or C<ntfs>.");
4344 ("truncate", (RErr, [Pathname "path"]), 199, [],
4345 [InitBasicFS, Always, TestOutputStruct (
4346 [["write"; "/test"; "some stuff so size is not zero"];
4347 ["truncate"; "/test"];
4348 ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
4349 "truncate a file to zero size",
4351 This command truncates C<path> to a zero-length file. The
4352 file must exist already.");
4354 ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
4355 [InitBasicFS, Always, TestOutputStruct (
4356 [["touch"; "/test"];
4357 ["truncate_size"; "/test"; "1000"];
4358 ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
4359 "truncate a file to a particular size",
4361 This command truncates C<path> to size C<size> bytes. The file
4364 If the current file size is less than C<size> then
4365 the file is extended to the required size with zero bytes.
4366 This creates a sparse file (ie. disk blocks are not allocated
4367 for the file until you write to it). To create a non-sparse
4368 file of zeroes, use C<guestfs_fallocate64> instead.");
4370 ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
4371 [InitBasicFS, Always, TestOutputStruct (
4372 [["touch"; "/test"];
4373 ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
4374 ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
4375 "set timestamp of a file with nanosecond precision",
4377 This command sets the timestamps of a file with nanosecond
4380 C<atsecs, atnsecs> are the last access time (atime) in secs and
4381 nanoseconds from the epoch.
4383 C<mtsecs, mtnsecs> are the last modification time (mtime) in
4384 secs and nanoseconds from the epoch.
4386 If the C<*nsecs> field contains the special value C<-1> then
4387 the corresponding timestamp is set to the current time. (The
4388 C<*secs> field is ignored in this case).
4390 If the C<*nsecs> field contains the special value C<-2> then
4391 the corresponding timestamp is left unchanged. (The
4392 C<*secs> field is ignored in this case).");
4394 ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
4395 [InitBasicFS, Always, TestOutputStruct (
4396 [["mkdir_mode"; "/test"; "0o111"];
4397 ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
4398 "create a directory with a particular mode",
4400 This command creates a directory, setting the initial permissions
4401 of the directory to C<mode>.
4403 For common Linux filesystems, the actual mode which is set will
4404 be C<mode & ~umask & 01777>. Non-native-Linux filesystems may
4405 interpret the mode in other ways.
4407 See also C<guestfs_mkdir>, C<guestfs_umask>");
4409 ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
4411 "change file owner and group",
4413 Change the file owner to C<owner> and group to C<group>.
4414 This is like C<guestfs_chown> but if C<path> is a symlink then
4415 the link itself is changed, not the target.
4417 Only numeric uid and gid are supported. If you want to use
4418 names, you will need to locate and parse the password file
4419 yourself (Augeas support makes this relatively easy).");
4421 ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
4423 "lstat on multiple files",
4425 This call allows you to perform the C<guestfs_lstat> operation
4426 on multiple files, where all files are in the directory C<path>.
4427 C<names> is the list of files from this directory.
4429 On return you get a list of stat structs, with a one-to-one
4430 correspondence to the C<names> list. If any name did not exist
4431 or could not be lstat'd, then the C<ino> field of that structure
4434 This call is intended for programs that want to efficiently
4435 list a directory contents without making many round-trips.
4436 See also C<guestfs_lxattrlist> for a similarly efficient call
4437 for getting extended attributes. Very long directory listings
4438 might cause the protocol message size to be exceeded, causing
4439 this call to fail. The caller must split up such requests
4440 into smaller groups of names.");
4442 ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
4444 "lgetxattr on multiple files",
4446 This call allows you to get the extended attributes
4447 of multiple files, where all files are in the directory C<path>.
4448 C<names> is the list of files from this directory.
4450 On return you get a flat list of xattr structs which must be
4451 interpreted sequentially. The first xattr struct always has a zero-length
4452 C<attrname>. C<attrval> in this struct is zero-length
4453 to indicate there was an error doing C<lgetxattr> for this
4454 file, I<or> is a C string which is a decimal number
4455 (the number of following attributes for this file, which could
4456 be C<\"0\">). Then after the first xattr struct are the
4457 zero or more attributes for the first named file.
4458 This repeats for the second and subsequent files.
4460 This call is intended for programs that want to efficiently
4461 list a directory contents without making many round-trips.
4462 See also C<guestfs_lstatlist> for a similarly efficient call
4463 for getting standard stats. Very long directory listings
4464 might cause the protocol message size to be exceeded, causing
4465 this call to fail. The caller must split up such requests
4466 into smaller groups of names.");
4468 ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
4470 "readlink on multiple files",
4472 This call allows you to do a C<readlink> operation
4473 on multiple files, where all files are in the directory C<path>.
4474 C<names> is the list of files from this directory.
4476 On return you get a list of strings, with a one-to-one
4477 correspondence to the C<names> list. Each string is the
4478 value of the symbolic link.
4480 If the C<readlink(2)> operation fails on any name, then
4481 the corresponding result string is the empty string C<\"\">.
4482 However the whole operation is completed even if there
4483 were C<readlink(2)> errors, and so you can call this
4484 function with names where you don't know if they are
4485 symbolic links already (albeit slightly less efficient).
4487 This call is intended for programs that want to efficiently
4488 list a directory contents without making many round-trips.
4489 Very long directory listings might cause the protocol
4490 message size to be exceeded, causing
4491 this call to fail. The caller must split up such requests
4492 into smaller groups of names.");
4494 ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
4495 [InitISOFS, Always, TestOutputBuffer (
4496 [["pread"; "/known-4"; "1"; "3"]], "\n");
4497 InitISOFS, Always, TestOutputBuffer (
4498 [["pread"; "/empty"; "0"; "100"]], "")],
4499 "read part of a file",
4501 This command lets you read part of a file. It reads C<count>
4502 bytes of the file, starting at C<offset>, from file C<path>.
4504 This may read fewer bytes than requested. For further details
4505 see the L<pread(2)> system call.
4507 See also C<guestfs_pwrite>.");
4509 ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
4510 [InitEmpty, Always, TestRun (
4511 [["part_init"; "/dev/sda"; "gpt"]])],
4512 "create an empty partition table",
4514 This creates an empty partition table on C<device> of one of the
4515 partition types listed below. Usually C<parttype> should be
4516 either C<msdos> or C<gpt> (for large disks).
4518 Initially there are no partitions. Following this, you should
4519 call C<guestfs_part_add> for each partition required.
4521 Possible values for C<parttype> are:
4525 =item B<efi> | B<gpt>
4527 Intel EFI / GPT partition table.
4529 This is recommended for >= 2 TB partitions that will be accessed
4530 from Linux and Intel-based Mac OS X. It also has limited backwards
4531 compatibility with the C<mbr> format.
4533 =item B<mbr> | B<msdos>
4535 The standard PC \"Master Boot Record\" (MBR) format used
4536 by MS-DOS and Windows. This partition type will B<only> work
4537 for device sizes up to 2 TB. For large disks we recommend
4542 Other partition table types that may work but are not
4551 =item B<amiga> | B<rdb>
4553 Amiga \"Rigid Disk Block\" format.
4561 DASD, used on IBM mainframes.
4569 Old Mac partition format. Modern Macs use C<gpt>.
4573 NEC PC-98 format, common in Japan apparently.
4581 ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4582 [InitEmpty, Always, TestRun (
4583 [["part_init"; "/dev/sda"; "mbr"];
4584 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4585 InitEmpty, Always, TestRun (
4586 [["part_init"; "/dev/sda"; "gpt"];
4587 ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4588 ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4589 InitEmpty, Always, TestRun (
4590 [["part_init"; "/dev/sda"; "mbr"];
4591 ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4592 ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4593 ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4594 ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4595 "add a partition to the device",
4597 This command adds a partition to C<device>. If there is no partition
4598 table on the device, call C<guestfs_part_init> first.
4600 The C<prlogex> parameter is the type of partition. Normally you
4601 should pass C<p> or C<primary> here, but MBR partition tables also
4602 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4605 C<startsect> and C<endsect> are the start and end of the partition
4606 in I<sectors>. C<endsect> may be negative, which means it counts
4607 backwards from the end of the disk (C<-1> is the last sector).
4609 Creating a partition which covers the whole disk is not so easy.
4610 Use C<guestfs_part_disk> to do that.");
4612 ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4613 [InitEmpty, Always, TestRun (
4614 [["part_disk"; "/dev/sda"; "mbr"]]);
4615 InitEmpty, Always, TestRun (
4616 [["part_disk"; "/dev/sda"; "gpt"]])],
4617 "partition whole disk with a single primary partition",
4619 This command is simply a combination of C<guestfs_part_init>
4620 followed by C<guestfs_part_add> to create a single primary partition
4621 covering the whole disk.
4623 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4624 but other possible values are described in C<guestfs_part_init>.");
4626 ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4627 [InitEmpty, Always, TestRun (
4628 [["part_disk"; "/dev/sda"; "mbr"];
4629 ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4630 "make a partition bootable",
4632 This sets the bootable flag on partition numbered C<partnum> on
4633 device C<device>. Note that partitions are numbered from 1.
4635 The bootable flag is used by some operating systems (notably
4636 Windows) to determine which partition to boot from. It is by
4637 no means universally recognized.");
4639 ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4640 [InitEmpty, Always, TestRun (
4641 [["part_disk"; "/dev/sda"; "gpt"];
4642 ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4643 "set partition name",
4645 This sets the partition name on partition numbered C<partnum> on
4646 device C<device>. Note that partitions are numbered from 1.
4648 The partition name can only be set on certain types of partition
4649 table. This works on C<gpt> but not on C<mbr> partitions.");
4651 ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4652 [], (* XXX Add a regression test for this. *)
4653 "list partitions on a device",
4655 This command parses the partition table on C<device> and
4656 returns the list of partitions found.
4658 The fields in the returned structure are:
4664 Partition number, counting from 1.
4668 Start of the partition I<in bytes>. To get sectors you have to
4669 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4673 End of the partition in bytes.
4677 Size of the partition in bytes.
4681 ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4682 [InitEmpty, Always, TestOutput (
4683 [["part_disk"; "/dev/sda"; "gpt"];
4684 ["part_get_parttype"; "/dev/sda"]], "gpt")],
4685 "get the partition table type",
4687 This command examines the partition table on C<device> and
4688 returns the partition table type (format) being used.
4690 Common return values include: C<msdos> (a DOS/Windows style MBR
4691 partition table), C<gpt> (a GPT/EFI-style partition table). Other
4692 values are possible, although unusual. See C<guestfs_part_init>
4695 ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [],
4696 [InitBasicFS, Always, TestOutputBuffer (
4697 [["fill"; "0x63"; "10"; "/test"];
4698 ["read_file"; "/test"]], "cccccccccc")],
4699 "fill a file with octets",
4701 This command creates a new file called C<path>. The initial
4702 content of the file is C<len> octets of C<c>, where C<c>
4703 must be a number in the range C<[0..255]>.
4705 To fill a file with zero bytes (sparsely), it is
4706 much more efficient to use C<guestfs_truncate_size>.
4707 To create a file with a pattern of repeating bytes
4708 use C<guestfs_fill_pattern>.");
4710 ("available", (RErr, [StringList "groups"]), 216, [],
4711 [InitNone, Always, TestRun [["available"; ""]]],
4712 "test availability of some parts of the API",
4714 This command is used to check the availability of some
4715 groups of functionality in the appliance, which not all builds of
4716 the libguestfs appliance will be able to provide.
4718 The libguestfs groups, and the functions that those
4719 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4720 You can also fetch this list at runtime by calling
4721 C<guestfs_available_all_groups>.
4723 The argument C<groups> is a list of group names, eg:
4724 C<[\"inotify\", \"augeas\"]> would check for the availability of
4725 the Linux inotify functions and Augeas (configuration file
4728 The command returns no error if I<all> requested groups are available.
4730 It fails with an error if one or more of the requested
4731 groups is unavailable in the appliance.
4733 If an unknown group name is included in the
4734 list of groups then an error is always returned.
4742 You must call C<guestfs_launch> before calling this function.
4744 The reason is because we don't know what groups are
4745 supported by the appliance/daemon until it is running and can
4750 If a group of functions is available, this does not necessarily
4751 mean that they will work. You still have to check for errors
4752 when calling individual API functions even if they are
4757 It is usually the job of distro packagers to build
4758 complete functionality into the libguestfs appliance.
4759 Upstream libguestfs, if built from source with all
4760 requirements satisfied, will support everything.
4764 This call was added in version C<1.0.80>. In previous
4765 versions of libguestfs all you could do would be to speculatively
4766 execute a command to find out if the daemon implemented it.
4767 See also C<guestfs_version>.
4771 ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4772 [InitBasicFS, Always, TestOutputBuffer (
4773 [["write"; "/src"; "hello, world"];
4774 ["dd"; "/src"; "/dest"];
4775 ["read_file"; "/dest"]], "hello, world")],
4776 "copy from source to destination using dd",
4778 This command copies from one source device or file C<src>
4779 to another destination device or file C<dest>. Normally you
4780 would use this to copy to or from a device or partition, for
4781 example to duplicate a filesystem.
4783 If the destination is a device, it must be as large or larger
4784 than the source file or device, otherwise the copy will fail.
4785 This command cannot do partial copies (see C<guestfs_copy_size>).");
4787 ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4788 [InitBasicFS, Always, TestOutputInt (
4789 [["write"; "/file"; "hello, world"];
4790 ["filesize"; "/file"]], 12)],
4791 "return the size of the file in bytes",
4793 This command returns the size of C<file> in bytes.
4795 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4796 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4797 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4799 ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4800 [InitBasicFSonLVM, Always, TestOutputList (
4801 [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4802 ["lvs"]], ["/dev/VG/LV2"])],
4803 "rename an LVM logical volume",
4805 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4807 ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4808 [InitBasicFSonLVM, Always, TestOutputList (
4810 ["vg_activate"; "false"; "VG"];
4811 ["vgrename"; "VG"; "VG2"];
4812 ["vg_activate"; "true"; "VG2"];
4813 ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4814 ["vgs"]], ["VG2"])],
4815 "rename an LVM volume group",
4817 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4819 ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4820 [InitISOFS, Always, TestOutputBuffer (
4821 [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4822 "list the contents of a single file in an initrd",
4824 This command unpacks the file C<filename> from the initrd file
4825 called C<initrdpath>. The filename must be given I<without> the
4826 initial C</> character.
4828 For example, in guestfish you could use the following command
4829 to examine the boot script (usually called C</init>)
4830 contained in a Linux initrd or initramfs image:
4832 initrd-cat /boot/initrd-<version>.img init
4834 See also C<guestfs_initrd_list>.");
4836 ("pvuuid", (RString "uuid", [Device "device"]), 222, [],
4838 "get the UUID of a physical volume",
4840 This command returns the UUID of the LVM PV C<device>.");
4842 ("vguuid", (RString "uuid", [String "vgname"]), 223, [],
4844 "get the UUID of a volume group",
4846 This command returns the UUID of the LVM VG named C<vgname>.");
4848 ("lvuuid", (RString "uuid", [Device "device"]), 224, [],
4850 "get the UUID of a logical volume",
4852 This command returns the UUID of the LVM LV C<device>.");
4854 ("vgpvuuids", (RStringList "uuids", [String "vgname"]), 225, [],
4856 "get the PV UUIDs containing the volume group",
4858 Given a VG called C<vgname>, this returns the UUIDs of all
4859 the physical volumes that this volume group resides on.
4861 You can use this along with C<guestfs_pvs> and C<guestfs_pvuuid>
4862 calls to associate physical volumes and volume groups.
4864 See also C<guestfs_vglvuuids>.");
4866 ("vglvuuids", (RStringList "uuids", [String "vgname"]), 226, [],
4868 "get the LV UUIDs of all LVs in the volume group",
4870 Given a VG called C<vgname>, this returns the UUIDs of all
4871 the logical volumes created in this volume group.
4873 You can use this along with C<guestfs_lvs> and C<guestfs_lvuuid>
4874 calls to associate logical volumes and volume groups.
4876 See also C<guestfs_vgpvuuids>.");
4878 ("copy_size", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"; Int64 "size"]), 227, [],
4879 [InitBasicFS, Always, TestOutputBuffer (
4880 [["write"; "/src"; "hello, world"];
4881 ["copy_size"; "/src"; "/dest"; "5"];
4882 ["read_file"; "/dest"]], "hello")],
4883 "copy size bytes from source to destination using dd",
4885 This command copies exactly C<size> bytes from one source device
4886 or file C<src> to another destination device or file C<dest>.
4888 Note this will fail if the source is too short or if the destination
4889 is not large enough.");
4891 ("zero_device", (RErr, [Device "device"]), 228, [DangerWillRobinson],
4892 [InitBasicFSonLVM, Always, TestRun (
4893 [["zero_device"; "/dev/VG/LV"]])],
4894 "write zeroes to an entire device",
4896 This command writes zeroes over the entire C<device>. Compare
4897 with C<guestfs_zero> which just zeroes the first few blocks of
4900 ("txz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 229, [Optional "xz"],
4901 [InitBasicFS, Always, TestOutput (
4902 [["txz_in"; "../images/helloworld.tar.xz"; "/"];
4903 ["cat"; "/hello"]], "hello\n")],
4904 "unpack compressed tarball to directory",
4906 This command uploads and unpacks local file C<tarball> (an
4907 I<xz compressed> tar file) into C<directory>.");
4909 ("txz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 230, [Optional "xz"],
4911 "pack directory into compressed tarball",
4913 This command packs the contents of C<directory> and downloads
4914 it to local file C<tarball> (as an xz compressed tar archive).");
4916 ("ntfsresize", (RErr, [Device "device"]), 231, [Optional "ntfsprogs"],
4918 "resize an NTFS filesystem",
4920 This command resizes an NTFS filesystem, expanding or
4921 shrinking it to the size of the underlying device.
4922 See also L<ntfsresize(8)>.");
4924 ("vgscan", (RErr, []), 232, [],
4925 [InitEmpty, Always, TestRun (
4927 "rescan for LVM physical volumes, volume groups and logical volumes",
4929 This rescans all block devices and rebuilds the list of LVM
4930 physical volumes, volume groups and logical volumes.");
4932 ("part_del", (RErr, [Device "device"; Int "partnum"]), 233, [],
4933 [InitEmpty, Always, TestRun (
4934 [["part_init"; "/dev/sda"; "mbr"];
4935 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4936 ["part_del"; "/dev/sda"; "1"]])],
4937 "delete a partition",
4939 This command deletes the partition numbered C<partnum> on C<device>.
4941 Note that in the case of MBR partitioning, deleting an
4942 extended partition also deletes any logical partitions
4945 ("part_get_bootable", (RBool "bootable", [Device "device"; Int "partnum"]), 234, [],
4946 [InitEmpty, Always, TestOutputTrue (
4947 [["part_init"; "/dev/sda"; "mbr"];
4948 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4949 ["part_set_bootable"; "/dev/sda"; "1"; "true"];
4950 ["part_get_bootable"; "/dev/sda"; "1"]])],
4951 "return true if a partition is bootable",
4953 This command returns true if the partition C<partnum> on
4954 C<device> has the bootable flag set.
4956 See also C<guestfs_part_set_bootable>.");
4958 ("part_get_mbr_id", (RInt "idbyte", [Device "device"; Int "partnum"]), 235, [FishOutput FishOutputHexadecimal],
4959 [InitEmpty, Always, TestOutputInt (
4960 [["part_init"; "/dev/sda"; "mbr"];
4961 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4962 ["part_set_mbr_id"; "/dev/sda"; "1"; "0x7f"];
4963 ["part_get_mbr_id"; "/dev/sda"; "1"]], 0x7f)],
4964 "get the MBR type byte (ID byte) from a partition",
4966 Returns the MBR type byte (also known as the ID byte) from
4967 the numbered partition C<partnum>.
4969 Note that only MBR (old DOS-style) partitions have type bytes.
4970 You will get undefined results for other partition table
4971 types (see C<guestfs_part_get_parttype>).");
4973 ("part_set_mbr_id", (RErr, [Device "device"; Int "partnum"; Int "idbyte"]), 236, [],
4974 [], (* tested by part_get_mbr_id *)
4975 "set the MBR type byte (ID byte) of a partition",
4977 Sets the MBR type byte (also known as the ID byte) of
4978 the numbered partition C<partnum> to C<idbyte>. Note
4979 that the type bytes quoted in most documentation are
4980 in fact hexadecimal numbers, but usually documented
4981 without any leading \"0x\" which might be confusing.
4983 Note that only MBR (old DOS-style) partitions have type bytes.
4984 You will get undefined results for other partition table
4985 types (see C<guestfs_part_get_parttype>).");
4987 ("checksum_device", (RString "checksum", [String "csumtype"; Device "device"]), 237, [],
4988 [InitISOFS, Always, TestOutput (
4989 [["checksum_device"; "md5"; "/dev/sdd"]],
4990 (Digest.to_hex (Digest.file "images/test.iso")))],
4991 "compute MD5, SHAx or CRC checksum of the contents of a device",
4993 This call computes the MD5, SHAx or CRC checksum of the
4994 contents of the device named C<device>. For the types of
4995 checksums supported see the C<guestfs_checksum> command.");
4997 ("lvresize_free", (RErr, [Device "lv"; Int "percent"]), 238, [Optional "lvm2"],
4998 [InitNone, Always, TestRun (
4999 [["part_disk"; "/dev/sda"; "mbr"];
5000 ["pvcreate"; "/dev/sda1"];
5001 ["vgcreate"; "VG"; "/dev/sda1"];
5002 ["lvcreate"; "LV"; "VG"; "10"];
5003 ["lvresize_free"; "/dev/VG/LV"; "100"]])],
5004 "expand an LV to fill free space",
5006 This expands an existing logical volume C<lv> so that it fills
5007 C<pc>% of the remaining free space in the volume group. Commonly
5008 you would call this with pc = 100 which expands the logical volume
5009 as much as possible, using all remaining free space in the volume
5012 ("aug_clear", (RErr, [String "augpath"]), 239, [Optional "augeas"],
5013 [], (* XXX Augeas code needs tests. *)
5014 "clear Augeas path",
5016 Set the value associated with C<path> to C<NULL>. This
5017 is the same as the L<augtool(1)> C<clear> command.");
5019 ("get_umask", (RInt "mask", []), 240, [FishOutput FishOutputOctal],
5020 [InitEmpty, Always, TestOutputInt (
5021 [["get_umask"]], 0o22)],
5022 "get the current umask",
5024 Return the current umask. By default the umask is C<022>
5025 unless it has been set by calling C<guestfs_umask>.");
5027 ("debug_upload", (RErr, [FileIn "filename"; String "tmpname"; Int "mode"]), 241, [],
5029 "upload a file to the appliance (internal use only)",
5031 The C<guestfs_debug_upload> command uploads a file to
5032 the libguestfs appliance.
5034 There is no comprehensive help for this command. You have
5035 to look at the file C<daemon/debug.c> in the libguestfs source
5036 to find out what it is for.");
5038 ("base64_in", (RErr, [FileIn "base64file"; Pathname "filename"]), 242, [],
5039 [InitBasicFS, Always, TestOutput (
5040 [["base64_in"; "../images/hello.b64"; "/hello"];
5041 ["cat"; "/hello"]], "hello\n")],
5042 "upload base64-encoded data to file",
5044 This command uploads base64-encoded data from C<base64file>
5047 ("base64_out", (RErr, [Pathname "filename"; FileOut "base64file"]), 243, [],
5049 "download file and encode as base64",
5051 This command downloads the contents of C<filename>, writing
5052 it out to local file C<base64file> encoded as base64.");
5054 ("checksums_out", (RErr, [String "csumtype"; Pathname "directory"; FileOut "sumsfile"]), 244, [],
5056 "compute MD5, SHAx or CRC checksum of files in a directory",
5058 This command computes the checksums of all regular files in
5059 C<directory> and then emits a list of those checksums to
5060 the local output file C<sumsfile>.
5062 This can be used for verifying the integrity of a virtual
5063 machine. However to be properly secure you should pay
5064 attention to the output of the checksum command (it uses
5065 the ones from GNU coreutils). In particular when the
5066 filename is not printable, coreutils uses a special
5067 backslash syntax. For more information, see the GNU
5068 coreutils info file.");
5070 ("fill_pattern", (RErr, [String "pattern"; Int "len"; Pathname "path"]), 245, [],
5071 [InitBasicFS, Always, TestOutputBuffer (
5072 [["fill_pattern"; "abcdefghijklmnopqrstuvwxyz"; "28"; "/test"];
5073 ["read_file"; "/test"]], "abcdefghijklmnopqrstuvwxyzab")],
5074 "fill a file with a repeating pattern of bytes",
5076 This function is like C<guestfs_fill> except that it creates
5077 a new file of length C<len> containing the repeating pattern
5078 of bytes in C<pattern>. The pattern is truncated if necessary
5079 to ensure the length of the file is exactly C<len> bytes.");
5081 ("write", (RErr, [Pathname "path"; BufferIn "content"]), 246, [ProtocolLimitWarning],
5082 [InitBasicFS, Always, TestOutput (
5083 [["write"; "/new"; "new file contents"];
5084 ["cat"; "/new"]], "new file contents");
5085 InitBasicFS, Always, TestOutput (
5086 [["write"; "/new"; "\nnew file contents\n"];
5087 ["cat"; "/new"]], "\nnew file contents\n");
5088 InitBasicFS, Always, TestOutput (
5089 [["write"; "/new"; "\n\n"];
5090 ["cat"; "/new"]], "\n\n");
5091 InitBasicFS, Always, TestOutput (
5092 [["write"; "/new"; ""];
5093 ["cat"; "/new"]], "");
5094 InitBasicFS, Always, TestOutput (
5095 [["write"; "/new"; "\n\n\n"];
5096 ["cat"; "/new"]], "\n\n\n");
5097 InitBasicFS, Always, TestOutput (
5098 [["write"; "/new"; "\n"];
5099 ["cat"; "/new"]], "\n")],
5100 "create a new file",
5102 This call creates a file called C<path>. The content of the
5103 file is the string C<content> (which can contain any 8 bit data).");
5105 ("pwrite", (RInt "nbytes", [Pathname "path"; BufferIn "content"; Int64 "offset"]), 247, [ProtocolLimitWarning],
5106 [InitBasicFS, Always, TestOutput (
5107 [["write"; "/new"; "new file contents"];
5108 ["pwrite"; "/new"; "data"; "4"];
5109 ["cat"; "/new"]], "new data contents");
5110 InitBasicFS, Always, TestOutput (
5111 [["write"; "/new"; "new file contents"];
5112 ["pwrite"; "/new"; "is extended"; "9"];
5113 ["cat"; "/new"]], "new file is extended");
5114 InitBasicFS, Always, TestOutput (
5115 [["write"; "/new"; "new file contents"];
5116 ["pwrite"; "/new"; ""; "4"];
5117 ["cat"; "/new"]], "new file contents")],
5118 "write to part of a file",
5120 This command writes to part of a file. It writes the data
5121 buffer C<content> to the file C<path> starting at offset C<offset>.
5123 This command implements the L<pwrite(2)> system call, and like
5124 that system call it may not write the full data requested. The
5125 return value is the number of bytes that were actually written
5126 to the file. This could even be 0, although short writes are
5127 unlikely for regular files in ordinary circumstances.
5129 See also C<guestfs_pread>.");
5131 ("resize2fs_size", (RErr, [Device "device"; Int64 "size"]), 248, [],
5133 "resize an ext2, ext3 or ext4 filesystem (with size)",
5135 This command is the same as C<guestfs_resize2fs> except that it
5136 allows you to specify the new size (in bytes) explicitly.");
5138 ("pvresize_size", (RErr, [Device "device"; Int64 "size"]), 249, [Optional "lvm2"],
5140 "resize an LVM physical volume (with size)",
5142 This command is the same as C<guestfs_pvresize> except that it
5143 allows you to specify the new size (in bytes) explicitly.");
5145 ("ntfsresize_size", (RErr, [Device "device"; Int64 "size"]), 250, [Optional "ntfsprogs"],
5147 "resize an NTFS filesystem (with size)",
5149 This command is the same as C<guestfs_ntfsresize> except that it
5150 allows you to specify the new size (in bytes) explicitly.");
5152 ("available_all_groups", (RStringList "groups", []), 251, [],
5153 [InitNone, Always, TestRun [["available_all_groups"]]],
5154 "return a list of all optional groups",
5156 This command returns a list of all optional groups that this
5157 daemon knows about. Note this returns both supported and unsupported
5158 groups. To find out which ones the daemon can actually support
5159 you have to call C<guestfs_available> on each member of the
5162 See also C<guestfs_available> and L<guestfs(3)/AVAILABILITY>.");
5164 ("fallocate64", (RErr, [Pathname "path"; Int64 "len"]), 252, [],
5165 [InitBasicFS, Always, TestOutputStruct (
5166 [["fallocate64"; "/a"; "1000000"];
5167 ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
5168 "preallocate a file in the guest filesystem",
5170 This command preallocates a file (containing zero bytes) named
5171 C<path> of size C<len> bytes. If the file exists already, it
5174 Note that this call allocates disk blocks for the file.
5175 To create a sparse file use C<guestfs_truncate_size> instead.
5177 The deprecated call C<guestfs_fallocate> does the same,
5178 but owing to an oversight it only allowed 30 bit lengths
5179 to be specified, effectively limiting the maximum size
5180 of files created through that call to 1GB.
5182 Do not confuse this with the guestfish-specific
5183 C<alloc> and C<sparse> commands which create
5184 a file in the host and attach it as a device.");
5186 ("vfs_label", (RString "label", [Device "device"]), 253, [],
5187 [InitBasicFS, Always, TestOutput (
5188 [["set_e2label"; "/dev/sda1"; "LTEST"];
5189 ["vfs_label"; "/dev/sda1"]], "LTEST")],
5190 "get the filesystem label",
5192 This returns the filesystem label of the filesystem on
5195 If the filesystem is unlabeled, this returns the empty string.
5197 To find a filesystem from the label, use C<guestfs_findfs_label>.");
5199 ("vfs_uuid", (RString "uuid", [Device "device"]), 254, [],
5200 (let uuid = uuidgen () in
5201 [InitBasicFS, Always, TestOutput (
5202 [["set_e2uuid"; "/dev/sda1"; uuid];
5203 ["vfs_uuid"; "/dev/sda1"]], uuid)]),
5204 "get the filesystem UUID",
5206 This returns the filesystem UUID of the filesystem on
5209 If the filesystem does not have a UUID, this returns the empty string.
5211 To find a filesystem from the UUID, use C<guestfs_findfs_uuid>.");
5213 ("lvm_set_filter", (RErr, [DeviceList "devices"]), 255, [Optional "lvm2"],
5214 (* Can't be tested with the current framework because
5215 * the VG is being used by the mounted filesystem, so
5216 * the vgchange -an command we do first will fail.
5219 "set LVM device filter",
5221 This sets the LVM device filter so that LVM will only be
5222 able to \"see\" the block devices in the list C<devices>,
5223 and will ignore all other attached block devices.
5225 Where disk image(s) contain duplicate PVs or VGs, this
5226 command is useful to get LVM to ignore the duplicates, otherwise
5227 LVM can get confused. Note also there are two types
5228 of duplication possible: either cloned PVs/VGs which have
5229 identical UUIDs; or VGs that are not cloned but just happen
5230 to have the same name. In normal operation you cannot
5231 create this situation, but you can do it outside LVM, eg.
5232 by cloning disk images or by bit twiddling inside the LVM
5235 This command also clears the LVM cache and performs a volume
5238 You can filter whole block devices or individual partitions.
5240 You cannot use this if any VG is currently in use (eg.
5241 contains a mounted filesystem), even if you are not
5242 filtering out that VG.");
5244 ("lvm_clear_filter", (RErr, []), 256, [],
5245 [], (* see note on lvm_set_filter *)
5246 "clear LVM device filter",
5248 This undoes the effect of C<guestfs_lvm_set_filter>. LVM
5249 will be able to see every block device.
5251 This command also clears the LVM cache and performs a volume
5254 ("luks_open", (RErr, [Device "device"; Key "key"; String "mapname"]), 257, [Optional "luks"],
5256 "open a LUKS-encrypted block device",
5258 This command opens a block device which has been encrypted
5259 according to the Linux Unified Key Setup (LUKS) standard.
5261 C<device> is the encrypted block device or partition.
5263 The caller must supply one of the keys associated with the
5264 LUKS block device, in the C<key> parameter.
5266 This creates a new block device called C</dev/mapper/mapname>.
5267 Reads and writes to this block device are decrypted from and
5268 encrypted to the underlying C<device> respectively.
5270 If this block device contains LVM volume groups, then
5271 calling C<guestfs_vgscan> followed by C<guestfs_vg_activate_all>
5272 will make them visible.");
5274 ("luks_open_ro", (RErr, [Device "device"; Key "key"; String "mapname"]), 258, [Optional "luks"],
5276 "open a LUKS-encrypted block device read-only",
5278 This is the same as C<guestfs_luks_open> except that a read-only
5279 mapping is created.");
5281 ("luks_close", (RErr, [Device "device"]), 259, [Optional "luks"],
5283 "close a LUKS device",
5285 This closes a LUKS device that was created earlier by
5286 C<guestfs_luks_open> or C<guestfs_luks_open_ro>. The
5287 C<device> parameter must be the name of the LUKS mapping
5288 device (ie. C</dev/mapper/mapname>) and I<not> the name
5289 of the underlying block device.");
5291 ("luks_format", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 260, [Optional "luks"; DangerWillRobinson],
5293 "format a block device as a LUKS encrypted device",
5295 This command erases existing data on C<device> and formats
5296 the device as a LUKS encrypted device. C<key> is the
5297 initial key, which is added to key slot C<slot>. (LUKS
5298 supports 8 key slots, numbered 0-7).");
5300 ("luks_format_cipher", (RErr, [Device "device"; Key "key"; Int "keyslot"; String "cipher"]), 261, [Optional "luks"; DangerWillRobinson],
5302 "format a block device as a LUKS encrypted device",
5304 This command is the same as C<guestfs_luks_format> but
5305 it also allows you to set the C<cipher> used.");
5307 ("luks_add_key", (RErr, [Device "device"; Key "key"; Key "newkey"; Int "keyslot"]), 262, [Optional "luks"],
5309 "add a key on a LUKS encrypted device",
5311 This command adds a new key on LUKS device C<device>.
5312 C<key> is any existing key, and is used to access the device.
5313 C<newkey> is the new key to add. C<keyslot> is the key slot
5314 that will be replaced.
5316 Note that if C<keyslot> already contains a key, then this
5317 command will fail. You have to use C<guestfs_luks_kill_slot>
5318 first to remove that key.");
5320 ("luks_kill_slot", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 263, [Optional "luks"],
5322 "remove a key from a LUKS encrypted device",
5324 This command deletes the key in key slot C<keyslot> from the
5325 encrypted LUKS device C<device>. C<key> must be one of the
5328 ("is_lv", (RBool "lvflag", [Device "device"]), 264, [Optional "lvm2"],
5329 [InitBasicFSonLVM, IfAvailable "lvm2", TestOutputTrue (
5330 [["is_lv"; "/dev/VG/LV"]]);
5331 InitBasicFSonLVM, IfAvailable "lvm2", TestOutputFalse (
5332 [["is_lv"; "/dev/sda1"]])],
5333 "test if device is a logical volume",
5335 This command tests whether C<device> is a logical volume, and
5336 returns true iff this is the case.");
5338 ("findfs_uuid", (RString "device", [String "uuid"]), 265, [],
5340 "find a filesystem by UUID",
5342 This command searches the filesystems and returns the one
5343 which has the given UUID. An error is returned if no such
5344 filesystem can be found.
5346 To find the UUID of a filesystem, use C<guestfs_vfs_uuid>.");
5348 ("findfs_label", (RString "device", [String "label"]), 266, [],
5350 "find a filesystem by label",
5352 This command searches the filesystems and returns the one
5353 which has the given label. An error is returned if no such
5354 filesystem can be found.
5356 To find the label of a filesystem, use C<guestfs_vfs_label>.");
5360 let all_functions = non_daemon_functions @ daemon_functions
5362 (* In some places we want the functions to be displayed sorted
5363 * alphabetically, so this is useful:
5365 let all_functions_sorted =
5366 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
5367 compare n1 n2) all_functions
5369 (* This is used to generate the src/MAX_PROC_NR file which
5370 * contains the maximum procedure number, a surrogate for the
5371 * ABI version number. See src/Makefile.am for the details.
5374 let proc_nrs = List.map (
5375 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
5376 ) daemon_functions in
5377 List.fold_left max 0 proc_nrs
5379 (* Field types for structures. *)
5381 | FChar (* C 'char' (really, a 7 bit byte). *)
5382 | FString (* nul-terminated ASCII string, NOT NULL. *)
5383 | FBuffer (* opaque buffer of bytes, (char *, int) pair *)
5388 | FBytes (* Any int measure that counts bytes. *)
5389 | FUUID (* 32 bytes long, NOT nul-terminated. *)
5390 | FOptPercent (* [0..100], or -1 meaning "not present". *)
5392 (* Because we generate extra parsing code for LVM command line tools,
5393 * we have to pull out the LVM columns separately here.
5403 "pv_attr", FString (* XXX *);
5404 "pv_pe_count", FInt64;
5405 "pv_pe_alloc_count", FInt64;
5408 "pv_mda_count", FInt64;
5409 "pv_mda_free", FBytes;
5410 (* Not in Fedora 10:
5411 "pv_mda_size", FBytes;
5418 "vg_attr", FString (* XXX *);
5421 "vg_sysid", FString;
5422 "vg_extent_size", FBytes;
5423 "vg_extent_count", FInt64;
5424 "vg_free_count", FInt64;
5429 "snap_count", FInt64;
5432 "vg_mda_count", FInt64;
5433 "vg_mda_free", FBytes;
5434 (* Not in Fedora 10:
5435 "vg_mda_size", FBytes;
5441 "lv_attr", FString (* XXX *);
5444 "lv_kernel_major", FInt64;
5445 "lv_kernel_minor", FInt64;
5447 "seg_count", FInt64;
5449 "snap_percent", FOptPercent;
5450 "copy_percent", FOptPercent;
5453 "mirror_log", FString;
5457 (* Names and fields in all structures (in RStruct and RStructList)
5461 (* The old RIntBool return type, only ever used for aug_defnode. Do
5462 * not use this struct in any new code.
5465 "i", FInt32; (* for historical compatibility *)
5466 "b", FInt32; (* for historical compatibility *)
5469 (* LVM PVs, VGs, LVs. *)
5470 "lvm_pv", lvm_pv_cols;
5471 "lvm_vg", lvm_vg_cols;
5472 "lvm_lv", lvm_lv_cols;
5474 (* Column names and types from stat structures.
5475 * NB. Can't use things like 'st_atime' because glibc header files
5476 * define some of these as macros. Ugh.
5507 (* Column names in dirent structure. *)
5510 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
5515 (* Version numbers. *)
5523 (* Extended attribute. *)
5525 "attrname", FString;
5529 (* Inotify events. *)
5533 "in_cookie", FUInt32;
5537 (* Partition table entry. *)
5540 "part_start", FBytes;
5542 "part_size", FBytes;
5544 ] (* end of structs *)
5546 (* Ugh, Java has to be different ..
5547 * These names are also used by the Haskell bindings.
5549 let java_structs = [
5550 "int_bool", "IntBool";
5555 "statvfs", "StatVFS";
5557 "version", "Version";
5559 "inotify_event", "INotifyEvent";
5560 "partition", "Partition";
5563 (* What structs are actually returned. *)
5564 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
5566 (* Returns a list of RStruct/RStructList structs that are returned
5567 * by any function. Each element of returned list is a pair:
5569 * (structname, RStructOnly)
5570 * == there exists function which returns RStruct (_, structname)
5571 * (structname, RStructListOnly)
5572 * == there exists function which returns RStructList (_, structname)
5573 * (structname, RStructAndList)
5574 * == there are functions returning both RStruct (_, structname)
5575 * and RStructList (_, structname)
5577 let rstructs_used_by functions =
5578 (* ||| is a "logical OR" for rstructs_used_t *)
5582 | _, RStructAndList -> RStructAndList
5583 | RStructOnly, RStructListOnly
5584 | RStructListOnly, RStructOnly -> RStructAndList
5585 | RStructOnly, RStructOnly -> RStructOnly
5586 | RStructListOnly, RStructListOnly -> RStructListOnly
5589 let h = Hashtbl.create 13 in
5591 (* if elem->oldv exists, update entry using ||| operator,
5592 * else just add elem->newv to the hash
5594 let update elem newv =
5595 try let oldv = Hashtbl.find h elem in
5596 Hashtbl.replace h elem (newv ||| oldv)
5597 with Not_found -> Hashtbl.add h elem newv
5601 fun (_, style, _, _, _, _, _) ->
5602 match fst style with
5603 | RStruct (_, structname) -> update structname RStructOnly
5604 | RStructList (_, structname) -> update structname RStructListOnly
5608 (* return key->values as a list of (key,value) *)
5609 Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
5611 (* Used for testing language bindings. *)
5613 | CallString of string
5614 | CallOptString of string option
5615 | CallStringList of string list
5617 | CallInt64 of int64
5619 | CallBuffer of string
5621 (* Used to memoize the result of pod2text. *)
5622 let pod2text_memo_filename = "src/.pod2text.data"
5623 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
5625 let chan = open_in pod2text_memo_filename in
5626 let v = input_value chan in
5630 _ -> Hashtbl.create 13
5631 let pod2text_memo_updated () =
5632 let chan = open_out pod2text_memo_filename in
5633 output_value chan pod2text_memo;
5636 (* Useful functions.
5637 * Note we don't want to use any external OCaml libraries which
5638 * makes this a bit harder than it should be.
5640 module StringMap = Map.Make (String)
5642 let failwithf fs = ksprintf failwith fs
5644 let unique = let i = ref 0 in fun () -> incr i; !i
5646 let replace_char s c1 c2 =
5647 let s2 = String.copy s in
5648 let r = ref false in
5649 for i = 0 to String.length s2 - 1 do
5650 if String.unsafe_get s2 i = c1 then (
5651 String.unsafe_set s2 i c2;
5655 if not !r then s else s2
5659 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
5661 let triml ?(test = isspace) str =
5663 let n = ref (String.length str) in
5664 while !n > 0 && test str.[!i]; do
5669 else String.sub str !i !n
5671 let trimr ?(test = isspace) str =
5672 let n = ref (String.length str) in
5673 while !n > 0 && test str.[!n-1]; do
5676 if !n = String.length str then str
5677 else String.sub str 0 !n
5679 let trim ?(test = isspace) str =
5680 trimr ~test (triml ~test str)
5682 let rec find s sub =
5683 let len = String.length s in
5684 let sublen = String.length sub in
5686 if i <= len-sublen then (
5688 if j < sublen then (
5689 if s.[i+j] = sub.[j] then loop2 (j+1)
5695 if r = -1 then loop (i+1) else r
5701 let rec replace_str s s1 s2 =
5702 let len = String.length s in
5703 let sublen = String.length s1 in
5704 let i = find s s1 in
5707 let s' = String.sub s 0 i in
5708 let s'' = String.sub s (i+sublen) (len-i-sublen) in
5709 s' ^ s2 ^ replace_str s'' s1 s2
5712 let rec string_split sep str =
5713 let len = String.length str in
5714 let seplen = String.length sep in
5715 let i = find str sep in
5716 if i = -1 then [str]
5718 let s' = String.sub str 0 i in
5719 let s'' = String.sub str (i+seplen) (len-i-seplen) in
5720 s' :: string_split sep s''
5723 let files_equal n1 n2 =
5724 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
5725 match Sys.command cmd with
5728 | i -> failwithf "%s: failed with error code %d" cmd i
5730 let rec filter_map f = function
5734 | Some y -> y :: filter_map f xs
5735 | None -> filter_map f xs
5737 let rec find_map f = function
5738 | [] -> raise Not_found
5742 | None -> find_map f xs
5745 let rec loop i = function
5747 | x :: xs -> f i x; loop (i+1) xs
5752 let rec loop i = function
5754 | x :: xs -> let r = f i x in r :: loop (i+1) xs
5758 let count_chars c str =
5759 let count = ref 0 in
5760 for i = 0 to String.length str - 1 do
5761 if c = String.unsafe_get str i then incr count
5767 for i = 0 to String.length str - 1 do
5768 let c = String.unsafe_get str i in
5773 let map_chars f str =
5774 List.map f (explode str)
5776 let name_of_argt = function
5777 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
5778 | StringList n | DeviceList n | Bool n | Int n | Int64 n
5779 | FileIn n | FileOut n | BufferIn n | Key n -> n
5781 let java_name_of_struct typ =
5782 try List.assoc typ java_structs
5785 "java_name_of_struct: no java_structs entry corresponding to %s" typ
5787 let cols_of_struct typ =
5788 try List.assoc typ structs
5790 failwithf "cols_of_struct: unknown struct %s" typ
5792 let seq_of_test = function
5793 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
5794 | TestOutputListOfDevices (s, _)
5795 | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
5796 | TestOutputTrue s | TestOutputFalse s
5797 | TestOutputLength (s, _) | TestOutputBuffer (s, _)
5798 | TestOutputStruct (s, _)
5799 | TestLastFail s -> s
5801 (* Handling for function flags. *)
5802 let protocol_limit_warning =
5803 "Because of the message protocol, there is a transfer limit
5804 of somewhere between 2MB and 4MB. See L<guestfs(3)/PROTOCOL LIMITS>."
5806 let danger_will_robinson =
5807 "B<This command is dangerous. Without careful use you
5808 can easily destroy all your data>."
5810 let deprecation_notice flags =
5813 find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
5815 sprintf "This function is deprecated.
5816 In new code, use the C<%s> call instead.
5818 Deprecated functions will not be removed from the API, but the
5819 fact that they are deprecated indicates that there are problems
5820 with correct use of these functions." alt in
5825 (* Create list of optional groups. *)
5827 let h = Hashtbl.create 13 in
5829 fun (name, _, _, flags, _, _, _) ->
5833 let names = try Hashtbl.find h group with Not_found -> [] in
5834 Hashtbl.replace h group (name :: names)
5838 let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
5841 fun group -> group, List.sort compare (Hashtbl.find h group)
5843 List.sort (fun x y -> compare (fst x) (fst y)) groups
5845 (* Check function names etc. for consistency. *)
5846 let check_functions () =
5847 let contains_uppercase str =
5848 let len = String.length str in
5850 if i >= len then false
5853 if c >= 'A' && c <= 'Z' then true
5860 (* Check function names. *)
5862 fun (name, _, _, _, _, _, _) ->
5863 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
5864 failwithf "function name %s does not need 'guestfs' prefix" name;
5866 failwithf "function name is empty";
5867 if name.[0] < 'a' || name.[0] > 'z' then
5868 failwithf "function name %s must start with lowercase a-z" name;
5869 if String.contains name '-' then
5870 failwithf "function name %s should not contain '-', use '_' instead."
5874 (* Check function parameter/return names. *)
5876 fun (name, style, _, _, _, _, _) ->
5877 let check_arg_ret_name n =
5878 if contains_uppercase n then
5879 failwithf "%s param/ret %s should not contain uppercase chars"
5881 if String.contains n '-' || String.contains n '_' then
5882 failwithf "%s param/ret %s should not contain '-' or '_'"
5885 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;
5886 if n = "int" || n = "char" || n = "short" || n = "long" then
5887 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
5888 if n = "i" || n = "n" then
5889 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
5890 if n = "argv" || n = "args" then
5891 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
5893 (* List Haskell, OCaml and C keywords here.
5894 * http://www.haskell.org/haskellwiki/Keywords
5895 * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
5896 * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
5897 * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
5898 * |perl -pe 's/(.+)/"$1";/'|fmt -70
5899 * Omitting _-containing words, since they're handled above.
5900 * Omitting the OCaml reserved word, "val", is ok,
5901 * and saves us from renaming several parameters.
5904 "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
5905 "char"; "class"; "const"; "constraint"; "continue"; "data";
5906 "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
5907 "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
5908 "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
5909 "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
5910 "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
5912 "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
5913 "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
5914 "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
5915 "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
5916 "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
5917 "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
5918 "volatile"; "when"; "where"; "while";
5920 if List.mem n reserved then
5921 failwithf "%s has param/ret using reserved word %s" name n;
5924 (match fst style with
5926 | RInt n | RInt64 n | RBool n
5927 | RConstString n | RConstOptString n | RString n
5928 | RStringList n | RStruct (n, _) | RStructList (n, _)
5929 | RHashtable n | RBufferOut n ->
5930 check_arg_ret_name n
5932 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
5935 (* Check short descriptions. *)
5937 fun (name, _, _, _, _, shortdesc, _) ->
5938 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
5939 failwithf "short description of %s should begin with lowercase." name;
5940 let c = shortdesc.[String.length shortdesc-1] in
5941 if c = '\n' || c = '.' then
5942 failwithf "short description of %s should not end with . or \\n." name
5945 (* Check long descriptions. *)
5947 fun (name, _, _, _, _, _, longdesc) ->
5948 if longdesc.[String.length longdesc-1] = '\n' then
5949 failwithf "long description of %s should not end with \\n." name
5952 (* Check proc_nrs. *)
5954 fun (name, _, proc_nr, _, _, _, _) ->
5955 if proc_nr <= 0 then
5956 failwithf "daemon function %s should have proc_nr > 0" name
5960 fun (name, _, proc_nr, _, _, _, _) ->
5961 if proc_nr <> -1 then
5962 failwithf "non-daemon function %s should have proc_nr -1" name
5963 ) non_daemon_functions;
5966 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
5969 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
5970 let rec loop = function
5973 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
5975 | (name1,nr1) :: (name2,nr2) :: _ ->
5976 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
5984 (* Ignore functions that have no tests. We generate a
5985 * warning when the user does 'make check' instead.
5987 | name, _, _, _, [], _, _ -> ()
5988 | name, _, _, _, tests, _, _ ->
5992 match seq_of_test test with
5994 failwithf "%s has a test containing an empty sequence" name
5995 | cmds -> List.map List.hd cmds
5997 let funcs = List.flatten funcs in
5999 let tested = List.mem name funcs in
6002 failwithf "function %s has tests but does not test itself" name
6005 (* 'pr' prints to the current output file. *)
6006 let chan = ref Pervasives.stdout
6011 let i = count_chars '\n' str in
6012 lines := !lines + i;
6013 output_string !chan str
6016 let copyright_years =
6017 let this_year = 1900 + (localtime (time ())).tm_year in
6018 if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
6020 (* Generate a header block in a number of standard styles. *)
6021 type comment_style =
6022 CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
6023 type license = GPLv2plus | LGPLv2plus
6025 let generate_header ?(extra_inputs = []) comment license =
6026 let inputs = "src/generator.ml" :: extra_inputs in
6027 let c = match comment with
6028 | CStyle -> pr "/* "; " *"
6029 | CPlusPlusStyle -> pr "// "; "//"
6030 | HashStyle -> pr "# "; "#"
6031 | OCamlStyle -> pr "(* "; " *"
6032 | HaskellStyle -> pr "{- "; " " in
6033 pr "libguestfs generated file\n";
6034 pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
6035 List.iter (pr "%s %s\n" c) inputs;
6036 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
6038 pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
6042 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
6043 pr "%s it under the terms of the GNU General Public License as published by\n" c;
6044 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
6045 pr "%s (at your option) any later version.\n" c;
6047 pr "%s This program is distributed in the hope that it will be useful,\n" c;
6048 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6049 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
6050 pr "%s GNU General Public License for more details.\n" c;
6052 pr "%s You should have received a copy of the GNU General Public License along\n" c;
6053 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
6054 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
6057 pr "%s This library is free software; you can redistribute it and/or\n" c;
6058 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
6059 pr "%s License as published by the Free Software Foundation; either\n" c;
6060 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
6062 pr "%s This library is distributed in the hope that it will be useful,\n" c;
6063 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6064 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
6065 pr "%s Lesser General Public License for more details.\n" c;
6067 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
6068 pr "%s License along with this library; if not, write to the Free Software\n" c;
6069 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
6072 | CStyle -> pr " */\n"
6075 | OCamlStyle -> pr " *)\n"
6076 | HaskellStyle -> pr "-}\n"
6080 (* Start of main code generation functions below this line. *)
6082 (* Generate the pod documentation for the C API. *)
6083 let rec generate_actions_pod () =
6085 fun (shortname, style, _, flags, _, _, longdesc) ->
6086 if not (List.mem NotInDocs flags) then (
6087 let name = "guestfs_" ^ shortname in
6088 pr "=head2 %s\n\n" name;
6090 generate_prototype ~extern:false ~handle:"g" name style;
6092 pr "%s\n\n" longdesc;
6093 (match fst style with
6095 pr "This function returns 0 on success or -1 on error.\n\n"
6097 pr "On error this function returns -1.\n\n"
6099 pr "On error this function returns -1.\n\n"
6101 pr "This function returns a C truth value on success or -1 on error.\n\n"
6103 pr "This function returns a string, or NULL on error.
6104 The string is owned by the guest handle and must I<not> be freed.\n\n"
6105 | RConstOptString _ ->
6106 pr "This function returns a string which may be NULL.
6107 There is no way to return an error from this function.
6108 The string is owned by the guest handle and must I<not> be freed.\n\n"
6110 pr "This function returns a string, or NULL on error.
6111 I<The caller must free the returned string after use>.\n\n"
6113 pr "This function returns a NULL-terminated array of strings
6114 (like L<environ(3)>), or NULL if there was an error.
6115 I<The caller must free the strings and the array after use>.\n\n"
6116 | RStruct (_, typ) ->
6117 pr "This function returns a C<struct guestfs_%s *>,
6118 or NULL if there was an error.
6119 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
6120 | RStructList (_, typ) ->
6121 pr "This function returns a C<struct guestfs_%s_list *>
6122 (see E<lt>guestfs-structs.hE<gt>),
6123 or NULL if there was an error.
6124 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
6126 pr "This function returns a NULL-terminated array of
6127 strings, or NULL if there was an error.
6128 The array of strings will always have length C<2n+1>, where
6129 C<n> keys and values alternate, followed by the trailing NULL entry.
6130 I<The caller must free the strings and the array after use>.\n\n"
6132 pr "This function returns a buffer, or NULL on error.
6133 The size of the returned buffer is written to C<*size_r>.
6134 I<The caller must free the returned buffer after use>.\n\n"
6136 if List.mem ProtocolLimitWarning flags then
6137 pr "%s\n\n" protocol_limit_warning;
6138 if List.mem DangerWillRobinson flags then
6139 pr "%s\n\n" danger_will_robinson;
6140 if List.exists (function Key _ -> true | _ -> false) (snd style) then
6141 pr "This function takes a key or passphrase parameter which
6142 could contain sensitive material. Read the section
6143 L</KEYS AND PASSPHRASES> for more information.\n\n";
6144 match deprecation_notice flags with
6146 | Some txt -> pr "%s\n\n" txt
6148 ) all_functions_sorted
6150 and generate_structs_pod () =
6151 (* Structs documentation. *)
6154 pr "=head2 guestfs_%s\n" typ;
6156 pr " struct guestfs_%s {\n" typ;
6159 | name, FChar -> pr " char %s;\n" name
6160 | name, FUInt32 -> pr " uint32_t %s;\n" name
6161 | name, FInt32 -> pr " int32_t %s;\n" name
6162 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
6163 | name, FInt64 -> pr " int64_t %s;\n" name
6164 | name, FString -> pr " char *%s;\n" name
6166 pr " /* The next two fields describe a byte array. */\n";
6167 pr " uint32_t %s_len;\n" name;
6168 pr " char *%s;\n" name
6170 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
6171 pr " char %s[32];\n" name
6172 | name, FOptPercent ->
6173 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
6174 pr " float %s;\n" name
6178 pr " struct guestfs_%s_list {\n" typ;
6179 pr " uint32_t len; /* Number of elements in list. */\n";
6180 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
6183 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
6184 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
6189 and generate_availability_pod () =
6190 (* Availability documentation. *)
6194 fun (group, functions) ->
6195 pr "=item B<%s>\n" group;
6197 pr "The following functions:\n";
6198 List.iter (pr "L</guestfs_%s>\n") functions;
6204 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
6205 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
6207 * We have to use an underscore instead of a dash because otherwise
6208 * rpcgen generates incorrect code.
6210 * This header is NOT exported to clients, but see also generate_structs_h.
6212 and generate_xdr () =
6213 generate_header CStyle LGPLv2plus;
6215 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
6216 pr "typedef string str<>;\n";
6219 (* Internal structures. *)
6223 pr "struct guestfs_int_%s {\n" typ;
6225 | name, FChar -> pr " char %s;\n" name
6226 | name, FString -> pr " string %s<>;\n" name
6227 | name, FBuffer -> pr " opaque %s<>;\n" name
6228 | name, FUUID -> pr " opaque %s[32];\n" name
6229 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
6230 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
6231 | name, FOptPercent -> pr " float %s;\n" name
6235 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
6240 fun (shortname, style, _, _, _, _, _) ->
6241 let name = "guestfs_" ^ shortname in
6243 (match snd style with
6246 pr "struct %s_args {\n" name;
6249 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6250 pr " string %s<>;\n" n
6251 | OptString n -> pr " str *%s;\n" n
6252 | StringList n | DeviceList n -> pr " str %s<>;\n" n
6253 | Bool n -> pr " bool %s;\n" n
6254 | Int n -> pr " int %s;\n" n
6255 | Int64 n -> pr " hyper %s;\n" n
6257 pr " opaque %s<>;\n" n
6258 | FileIn _ | FileOut _ -> ()
6262 (match fst style with
6265 pr "struct %s_ret {\n" name;
6269 pr "struct %s_ret {\n" name;
6270 pr " hyper %s;\n" n;
6273 pr "struct %s_ret {\n" name;
6276 | RConstString _ | RConstOptString _ ->
6277 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6279 pr "struct %s_ret {\n" name;
6280 pr " string %s<>;\n" n;
6283 pr "struct %s_ret {\n" name;
6284 pr " str %s<>;\n" n;
6286 | RStruct (n, typ) ->
6287 pr "struct %s_ret {\n" name;
6288 pr " guestfs_int_%s %s;\n" typ n;
6290 | RStructList (n, typ) ->
6291 pr "struct %s_ret {\n" name;
6292 pr " guestfs_int_%s_list %s;\n" typ n;
6295 pr "struct %s_ret {\n" name;
6296 pr " str %s<>;\n" n;
6299 pr "struct %s_ret {\n" name;
6300 pr " opaque %s<>;\n" n;
6305 (* Table of procedure numbers. *)
6306 pr "enum guestfs_procedure {\n";
6308 fun (shortname, _, proc_nr, _, _, _, _) ->
6309 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
6311 pr " GUESTFS_PROC_NR_PROCS\n";
6315 (* Having to choose a maximum message size is annoying for several
6316 * reasons (it limits what we can do in the API), but it (a) makes
6317 * the protocol a lot simpler, and (b) provides a bound on the size
6318 * of the daemon which operates in limited memory space.
6320 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
6323 (* Message header, etc. *)
6325 /* The communication protocol is now documented in the guestfs(3)
6329 const GUESTFS_PROGRAM = 0x2000F5F5;
6330 const GUESTFS_PROTOCOL_VERSION = 1;
6332 /* These constants must be larger than any possible message length. */
6333 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
6334 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
6336 enum guestfs_message_direction {
6337 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
6338 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
6341 enum guestfs_message_status {
6342 GUESTFS_STATUS_OK = 0,
6343 GUESTFS_STATUS_ERROR = 1
6348 pr "const GUESTFS_ERROR_LEN = %d;\n" (64 * 1024);
6352 struct guestfs_message_error {
6353 int linux_errno; /* Linux errno if available. */
6354 string error_message<GUESTFS_ERROR_LEN>;
6357 struct guestfs_message_header {
6358 unsigned prog; /* GUESTFS_PROGRAM */
6359 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
6360 guestfs_procedure proc; /* GUESTFS_PROC_x */
6361 guestfs_message_direction direction;
6362 unsigned serial; /* message serial number */
6363 guestfs_message_status status;
6366 const GUESTFS_MAX_CHUNK_SIZE = 8192;
6368 struct guestfs_chunk {
6369 int cancel; /* if non-zero, transfer is cancelled */
6370 /* data size is 0 bytes if the transfer has finished successfully */
6371 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
6375 (* Generate the guestfs-structs.h file. *)
6376 and generate_structs_h () =
6377 generate_header CStyle LGPLv2plus;
6379 (* This is a public exported header file containing various
6380 * structures. The structures are carefully written to have
6381 * exactly the same in-memory format as the XDR structures that
6382 * we use on the wire to the daemon. The reason for creating
6383 * copies of these structures here is just so we don't have to
6384 * export the whole of guestfs_protocol.h (which includes much
6385 * unrelated and XDR-dependent stuff that we don't want to be
6386 * public, or required by clients).
6388 * To reiterate, we will pass these structures to and from the
6389 * client with a simple assignment or memcpy, so the format
6390 * must be identical to what rpcgen / the RFC defines.
6393 (* Public structures. *)
6396 pr "struct guestfs_%s {\n" typ;
6399 | name, FChar -> pr " char %s;\n" name
6400 | name, FString -> pr " char *%s;\n" name
6402 pr " uint32_t %s_len;\n" name;
6403 pr " char *%s;\n" name
6404 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
6405 | name, FUInt32 -> pr " uint32_t %s;\n" name
6406 | name, FInt32 -> pr " int32_t %s;\n" name
6407 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
6408 | name, FInt64 -> pr " int64_t %s;\n" name
6409 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
6413 pr "struct guestfs_%s_list {\n" typ;
6414 pr " uint32_t len;\n";
6415 pr " struct guestfs_%s *val;\n" typ;
6418 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
6419 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
6423 (* Generate the guestfs-actions.h file. *)
6424 and generate_actions_h () =
6425 generate_header CStyle LGPLv2plus;
6427 fun (shortname, style, _, _, _, _, _) ->
6428 let name = "guestfs_" ^ shortname in
6429 generate_prototype ~single_line:true ~newline:true ~handle:"g"
6433 (* Generate the guestfs-internal-actions.h file. *)
6434 and generate_internal_actions_h () =
6435 generate_header CStyle LGPLv2plus;
6437 fun (shortname, style, _, _, _, _, _) ->
6438 let name = "guestfs__" ^ shortname in
6439 generate_prototype ~single_line:true ~newline:true ~handle:"g"
6441 ) non_daemon_functions
6443 (* Generate the client-side dispatch stubs. *)
6444 and generate_client_actions () =
6445 generate_header CStyle LGPLv2plus;
6452 #include <inttypes.h>
6454 #include \"guestfs.h\"
6455 #include \"guestfs-internal.h\"
6456 #include \"guestfs-internal-actions.h\"
6457 #include \"guestfs_protocol.h\"
6459 /* Check the return message from a call for validity. */
6461 check_reply_header (guestfs_h *g,
6462 const struct guestfs_message_header *hdr,
6463 unsigned int proc_nr, unsigned int serial)
6465 if (hdr->prog != GUESTFS_PROGRAM) {
6466 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
6469 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
6470 error (g, \"wrong protocol version (%%d/%%d)\",
6471 hdr->vers, GUESTFS_PROTOCOL_VERSION);
6474 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
6475 error (g, \"unexpected message direction (%%d/%%d)\",
6476 hdr->direction, GUESTFS_DIRECTION_REPLY);
6479 if (hdr->proc != proc_nr) {
6480 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
6483 if (hdr->serial != serial) {
6484 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
6491 /* Check we are in the right state to run a high-level action. */
6493 check_state (guestfs_h *g, const char *caller)
6495 if (!guestfs__is_ready (g)) {
6496 if (guestfs__is_config (g) || guestfs__is_launching (g))
6497 error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
6500 error (g, \"%%s called from the wrong state, %%d != READY\",
6501 caller, guestfs__get_state (g));
6509 let error_code_of = function
6510 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
6511 | RConstString _ | RConstOptString _
6512 | RString _ | RStringList _
6513 | RStruct _ | RStructList _
6514 | RHashtable _ | RBufferOut _ -> "NULL"
6517 (* Generate code to check String-like parameters are not passed in
6518 * as NULL (returning an error if they are).
6520 let check_null_strings shortname style =
6521 let pr_newline = ref false in
6524 (* parameters which should not be NULL *)
6535 pr " if (%s == NULL) {\n" n;
6536 pr " error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
6537 pr " \"%s\", \"%s\");\n" shortname n;
6538 pr " return %s;\n" (error_code_of (fst style));
6545 (* not applicable *)
6551 if !pr_newline then pr "\n";
6554 (* Generate code to generate guestfish call traces. *)
6555 let trace_call shortname style =
6556 pr " if (guestfs__get_trace (g)) {\n";
6559 List.exists (function
6560 | StringList _ | DeviceList _ -> true
6561 | _ -> false) (snd style) in
6567 pr " fprintf (stderr, \"%s\");\n" shortname;
6570 | String n (* strings *)
6578 (* guestfish doesn't support string escaping, so neither do we *)
6579 pr " fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
6580 | OptString n -> (* string option *)
6581 pr " if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
6582 pr " else fprintf (stderr, \" null\");\n"
6584 | DeviceList n -> (* string list *)
6585 pr " fputc (' ', stderr);\n";
6586 pr " fputc ('\"', stderr);\n";
6587 pr " for (i = 0; %s[i]; ++i) {\n" n;
6588 pr " if (i > 0) fputc (' ', stderr);\n";
6589 pr " fputs (%s[i], stderr);\n" n;
6591 pr " fputc ('\"', stderr);\n";
6592 | Bool n -> (* boolean *)
6593 pr " fputs (%s ? \" true\" : \" false\", stderr);\n" n
6594 | Int n -> (* int *)
6595 pr " fprintf (stderr, \" %%d\", %s);\n" n
6597 pr " fprintf (stderr, \" %%\" PRIi64, %s);\n" n
6599 pr " fputc ('\\n', stderr);\n";
6604 (* For non-daemon functions, generate a wrapper around each function. *)
6606 fun (shortname, style, _, _, _, _, _) ->
6607 let name = "guestfs_" ^ shortname in
6609 generate_prototype ~extern:false ~semicolon:false ~newline:true
6610 ~handle:"g" name style;
6612 check_null_strings shortname style;
6613 trace_call shortname style;
6614 pr " return guestfs__%s " shortname;
6615 generate_c_call_args ~handle:"g" style;
6619 ) non_daemon_functions;
6621 (* Client-side stubs for each function. *)
6623 fun (shortname, style, _, _, _, _, _) ->
6624 let name = "guestfs_" ^ shortname in
6625 let error_code = error_code_of (fst style) in
6627 (* Generate the action stub. *)
6628 generate_prototype ~extern:false ~semicolon:false ~newline:true
6629 ~handle:"g" name style;
6633 (match snd style with
6635 | _ -> pr " struct %s_args args;\n" name
6638 pr " guestfs_message_header hdr;\n";
6639 pr " guestfs_message_error err;\n";
6641 match fst style with
6643 | RConstString _ | RConstOptString _ ->
6644 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6646 | RBool _ | RString _ | RStringList _
6647 | RStruct _ | RStructList _
6648 | RHashtable _ | RBufferOut _ ->
6649 pr " struct %s_ret ret;\n" name;
6652 pr " int serial;\n";
6655 check_null_strings shortname style;
6656 trace_call shortname style;
6657 pr " if (check_state (g, \"%s\") == -1) return %s;\n"
6658 shortname error_code;
6659 pr " guestfs___set_busy (g);\n";
6662 (* Send the main header and arguments. *)
6663 (match snd style with
6665 pr " serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
6666 (String.uppercase shortname)
6670 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6671 pr " args.%s = (char *) %s;\n" n n
6673 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
6674 | StringList n | DeviceList n ->
6675 pr " args.%s.%s_val = (char **) %s;\n" n n n;
6676 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
6678 pr " args.%s = %s;\n" n n
6680 pr " args.%s = %s;\n" n n
6682 pr " args.%s = %s;\n" n n
6683 | FileIn _ | FileOut _ -> ()
6685 pr " /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
6686 pr " if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
6687 pr " error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
6689 pr " guestfs___end_busy (g);\n";
6690 pr " return %s;\n" error_code;
6692 pr " args.%s.%s_val = (char *) %s;\n" n n n;
6693 pr " args.%s.%s_len = %s_size;\n" n n n
6695 pr " serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
6696 (String.uppercase shortname);
6697 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
6700 pr " if (serial == -1) {\n";
6701 pr " guestfs___end_busy (g);\n";
6702 pr " return %s;\n" error_code;
6706 (* Send any additional files (FileIn) requested. *)
6707 let need_read_reply_label = ref false in
6711 pr " r = guestfs___send_file (g, %s);\n" n;
6712 pr " if (r == -1) {\n";
6713 pr " guestfs___end_busy (g);\n";
6714 pr " return %s;\n" error_code;
6716 pr " if (r == -2) /* daemon cancelled */\n";
6717 pr " goto read_reply;\n";
6718 need_read_reply_label := true;
6723 (* Wait for the reply from the remote end. *)
6724 if !need_read_reply_label then pr " read_reply:\n";
6725 pr " memset (&hdr, 0, sizeof hdr);\n";
6726 pr " memset (&err, 0, sizeof err);\n";
6727 if has_ret then pr " memset (&ret, 0, sizeof ret);\n";
6729 pr " r = guestfs___recv (g, \"%s\", &hdr, &err,\n " shortname;
6733 pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
6736 pr " if (r == -1) {\n";
6737 pr " guestfs___end_busy (g);\n";
6738 pr " return %s;\n" error_code;
6742 pr " if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
6743 (String.uppercase shortname);
6744 pr " guestfs___end_busy (g);\n";
6745 pr " return %s;\n" error_code;
6749 pr " if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
6750 pr " error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
6751 pr " free (err.error_message);\n";
6752 pr " guestfs___end_busy (g);\n";
6753 pr " return %s;\n" error_code;
6757 (* Expecting to receive further files (FileOut)? *)
6761 pr " if (guestfs___recv_file (g, %s) == -1) {\n" n;
6762 pr " guestfs___end_busy (g);\n";
6763 pr " return %s;\n" error_code;
6769 pr " guestfs___end_busy (g);\n";
6771 (match fst style with
6772 | RErr -> pr " return 0;\n"
6773 | RInt n | RInt64 n | RBool n ->
6774 pr " return ret.%s;\n" n
6775 | RConstString _ | RConstOptString _ ->
6776 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6778 pr " return ret.%s; /* caller will free */\n" n
6779 | RStringList n | RHashtable n ->
6780 pr " /* caller will free this, but we need to add a NULL entry */\n";
6781 pr " ret.%s.%s_val =\n" n n;
6782 pr " safe_realloc (g, ret.%s.%s_val,\n" n n;
6783 pr " sizeof (char *) * (ret.%s.%s_len + 1));\n"
6785 pr " ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
6786 pr " return ret.%s.%s_val;\n" n n
6788 pr " /* caller will free this */\n";
6789 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6790 | RStructList (n, _) ->
6791 pr " /* caller will free this */\n";
6792 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6794 pr " /* RBufferOut is tricky: If the buffer is zero-length, then\n";
6795 pr " * _val might be NULL here. To make the API saner for\n";
6796 pr " * callers, we turn this case into a unique pointer (using\n";
6797 pr " * malloc(1)).\n";
6799 pr " if (ret.%s.%s_len > 0) {\n" n n;
6800 pr " *size_r = ret.%s.%s_len;\n" n n;
6801 pr " return ret.%s.%s_val; /* caller will free */\n" n n;
6803 pr " free (ret.%s.%s_val);\n" n n;
6804 pr " char *p = safe_malloc (g, 1);\n";
6805 pr " *size_r = ret.%s.%s_len;\n" n n;
6813 (* Functions to free structures. *)
6814 pr "/* Structure-freeing functions. These rely on the fact that the\n";
6815 pr " * structure format is identical to the XDR format. See note in\n";
6816 pr " * generator.ml.\n";
6823 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
6825 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
6831 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
6833 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
6840 (* Generate daemon/actions.h. *)
6841 and generate_daemon_actions_h () =
6842 generate_header CStyle GPLv2plus;
6844 pr "#include \"../src/guestfs_protocol.h\"\n";
6848 fun (name, style, _, _, _, _, _) ->
6850 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
6854 (* Generate the linker script which controls the visibility of
6855 * symbols in the public ABI and ensures no other symbols get
6856 * exported accidentally.
6858 and generate_linker_script () =
6859 generate_header HashStyle GPLv2plus;
6864 "guestfs_get_error_handler";
6865 "guestfs_get_out_of_memory_handler";
6866 "guestfs_last_error";
6867 "guestfs_set_close_callback";
6868 "guestfs_set_error_handler";
6869 "guestfs_set_launch_done_callback";
6870 "guestfs_set_log_message_callback";
6871 "guestfs_set_out_of_memory_handler";
6872 "guestfs_set_subprocess_quit_callback";
6874 (* Unofficial parts of the API: the bindings code use these
6875 * functions, so it is useful to export them.
6877 "guestfs_safe_calloc";
6878 "guestfs_safe_malloc";
6879 "guestfs_safe_strdup";
6880 "guestfs_safe_memdup";
6883 List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
6887 List.map (fun (typ, _) ->
6888 ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
6891 let globals = List.sort compare (globals @ functions @ structs) in
6895 List.iter (pr " %s;\n") globals;
6902 (* Generate the server-side stubs. *)
6903 and generate_daemon_actions () =
6904 generate_header CStyle GPLv2plus;
6906 pr "#include <config.h>\n";
6908 pr "#include <stdio.h>\n";
6909 pr "#include <stdlib.h>\n";
6910 pr "#include <string.h>\n";
6911 pr "#include <inttypes.h>\n";
6912 pr "#include <rpc/types.h>\n";
6913 pr "#include <rpc/xdr.h>\n";
6915 pr "#include \"daemon.h\"\n";
6916 pr "#include \"c-ctype.h\"\n";
6917 pr "#include \"../src/guestfs_protocol.h\"\n";
6918 pr "#include \"actions.h\"\n";
6922 fun (name, style, _, _, _, _, _) ->
6923 (* Generate server-side stubs. *)
6924 pr "static void %s_stub (XDR *xdr_in)\n" name;
6927 match fst style with
6928 | RErr | RInt _ -> pr " int r;\n"; "-1"
6929 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6930 | RBool _ -> pr " int r;\n"; "-1"
6931 | RConstString _ | RConstOptString _ ->
6932 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6933 | RString _ -> pr " char *r;\n"; "NULL"
6934 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6935 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
6936 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL"
6938 pr " size_t size = 1;\n";
6942 (match snd style with
6945 pr " struct guestfs_%s_args args;\n" name;
6948 | Device n | Dev_or_Path n
6952 | OptString n -> pr " char *%s;\n" n
6953 | StringList n | DeviceList n -> pr " char **%s;\n" n
6954 | Bool n -> pr " int %s;\n" n
6955 | Int n -> pr " int %s;\n" n
6956 | Int64 n -> pr " int64_t %s;\n" n
6957 | FileIn _ | FileOut _ -> ()
6959 pr " const char *%s;\n" n;
6960 pr " size_t %s_size;\n" n
6966 List.exists (function FileIn _ -> true | _ -> false) (snd style) in
6968 (match snd style with
6971 pr " memset (&args, 0, sizeof args);\n";
6973 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
6975 pr " if (cancel_receive () != -2)\n";
6976 pr " reply_with_error (\"daemon failed to decode procedure arguments\");\n";
6980 pr " char *%s = args.%s;\n" n n
6982 let pr_list_handling_code n =
6983 pr " %s = realloc (args.%s.%s_val,\n" n n n;
6984 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
6985 pr " if (%s == NULL) {\n" n;
6987 pr " if (cancel_receive () != -2)\n";
6988 pr " reply_with_perror (\"realloc\");\n";
6991 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
6992 pr " args.%s.%s_val = %s;\n" n n n;
6998 pr " ABS_PATH (%s, %s, goto done);\n"
6999 n (if is_filein then "cancel_receive ()" else "0");
7002 pr " RESOLVE_DEVICE (%s, %s, goto done);\n"
7003 n (if is_filein then "cancel_receive ()" else "0");
7006 pr " REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
7007 n (if is_filein then "cancel_receive ()" else "0");
7008 | String n | Key n -> pr_args n
7009 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
7011 pr_list_handling_code n;
7013 pr_list_handling_code n;
7014 pr " /* Ensure that each is a device,\n";
7015 pr " * and perform device name translation.\n";
7019 pr " for (i = 0; %s[i] != NULL; ++i)\n" n;
7020 pr " RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
7021 (if is_filein then "cancel_receive ()" else "0");
7023 | Bool n -> pr " %s = args.%s;\n" n n
7024 | Int n -> pr " %s = args.%s;\n" n n
7025 | Int64 n -> pr " %s = args.%s;\n" n n
7026 | FileIn _ | FileOut _ -> ()
7028 pr " %s = args.%s.%s_val;\n" n n n;
7029 pr " %s_size = args.%s.%s_len;\n" n n n
7034 (* this is used at least for do_equal *)
7035 if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
7036 (* Emit NEED_ROOT just once, even when there are two or
7037 more Pathname args *)
7038 pr " NEED_ROOT (%s, goto done);\n"
7039 (if is_filein then "cancel_receive ()" else "0");
7042 (* Don't want to call the impl with any FileIn or FileOut
7043 * parameters, since these go "outside" the RPC protocol.
7046 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
7048 pr " r = do_%s " name;
7049 generate_c_call_args (fst style, args');
7052 (match fst style with
7053 | RErr | RInt _ | RInt64 _ | RBool _
7054 | RConstString _ | RConstOptString _
7055 | RString _ | RStringList _ | RHashtable _
7056 | RStruct (_, _) | RStructList (_, _) ->
7057 pr " if (r == %s)\n" error_code;
7058 pr " /* do_%s has already called reply_with_error */\n" name;
7062 pr " /* size == 0 && r == NULL could be a non-error case (just\n";
7063 pr " * an ordinary zero-length buffer), so be careful ...\n";
7065 pr " if (size == 1 && r == %s)\n" error_code;
7066 pr " /* do_%s has already called reply_with_error */\n" name;
7071 (* If there are any FileOut parameters, then the impl must
7072 * send its own reply.
7075 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
7077 pr " /* do_%s has already sent a reply */\n" name
7079 match fst style with
7080 | RErr -> pr " reply (NULL, NULL);\n"
7081 | RInt n | RInt64 n | RBool n ->
7082 pr " struct guestfs_%s_ret ret;\n" name;
7083 pr " ret.%s = r;\n" n;
7084 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7086 | RConstString _ | RConstOptString _ ->
7087 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7089 pr " struct guestfs_%s_ret ret;\n" name;
7090 pr " ret.%s = r;\n" n;
7091 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7094 | RStringList n | RHashtable n ->
7095 pr " struct guestfs_%s_ret ret;\n" name;
7096 pr " ret.%s.%s_len = count_strings (r);\n" n n;
7097 pr " ret.%s.%s_val = r;\n" n n;
7098 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7100 pr " free_strings (r);\n"
7102 pr " struct guestfs_%s_ret ret;\n" name;
7103 pr " ret.%s = *r;\n" n;
7104 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7106 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7108 | RStructList (n, _) ->
7109 pr " struct guestfs_%s_ret ret;\n" name;
7110 pr " ret.%s = *r;\n" n;
7111 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7113 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7116 pr " struct guestfs_%s_ret ret;\n" name;
7117 pr " ret.%s.%s_val = r;\n" n n;
7118 pr " ret.%s.%s_len = size;\n" n n;
7119 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7124 (* Free the args. *)
7126 (match snd style with
7129 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
7136 (* Dispatch function. *)
7137 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
7139 pr " switch (proc_nr) {\n";
7142 fun (name, style, _, _, _, _, _) ->
7143 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
7144 pr " %s_stub (xdr_in);\n" name;
7149 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";
7154 (* LVM columns and tokenization functions. *)
7155 (* XXX This generates crap code. We should rethink how we
7161 pr "static const char *lvm_%s_cols = \"%s\";\n"
7162 typ (String.concat "," (List.map fst cols));
7165 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
7167 pr " char *tok, *p, *next;\n";
7168 pr " size_t i, j;\n";
7171 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
7174 pr " if (!str) {\n";
7175 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
7178 pr " if (!*str || c_isspace (*str)) {\n";
7179 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
7184 fun (name, coltype) ->
7185 pr " if (!tok) {\n";
7186 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
7189 pr " p = strchrnul (tok, ',');\n";
7190 pr " if (*p) next = p+1; else next = NULL;\n";
7191 pr " *p = '\\0';\n";
7194 pr " r->%s = strdup (tok);\n" name;
7195 pr " if (r->%s == NULL) {\n" name;
7196 pr " perror (\"strdup\");\n";
7200 pr " for (i = j = 0; i < 32; ++j) {\n";
7201 pr " if (tok[j] == '\\0') {\n";
7202 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
7204 pr " } else if (tok[j] != '-')\n";
7205 pr " r->%s[i++] = tok[j];\n" name;
7208 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
7209 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7213 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
7214 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7218 pr " if (tok[0] == '\\0')\n";
7219 pr " r->%s = -1;\n" name;
7220 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
7221 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7224 | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
7225 assert false (* can never be an LVM column *)
7227 pr " tok = next;\n";
7230 pr " if (tok != NULL) {\n";
7231 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
7238 pr "guestfs_int_lvm_%s_list *\n" typ;
7239 pr "parse_command_line_%ss (void)\n" typ;
7241 pr " char *out, *err;\n";
7242 pr " char *p, *pend;\n";
7244 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
7245 pr " void *newp;\n";
7247 pr " ret = malloc (sizeof *ret);\n";
7248 pr " if (!ret) {\n";
7249 pr " reply_with_perror (\"malloc\");\n";
7250 pr " return NULL;\n";
7253 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
7254 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
7256 pr " r = command (&out, &err,\n";
7257 pr " \"lvm\", \"%ss\",\n" typ;
7258 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
7259 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
7260 pr " if (r == -1) {\n";
7261 pr " reply_with_error (\"%%s\", err);\n";
7262 pr " free (out);\n";
7263 pr " free (err);\n";
7264 pr " free (ret);\n";
7265 pr " return NULL;\n";
7268 pr " free (err);\n";
7270 pr " /* Tokenize each line of the output. */\n";
7273 pr " while (p) {\n";
7274 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
7275 pr " if (pend) {\n";
7276 pr " *pend = '\\0';\n";
7280 pr " while (*p && c_isspace (*p)) /* Skip any leading whitespace. */\n";
7283 pr " if (!*p) { /* Empty line? Skip it. */\n";
7288 pr " /* Allocate some space to store this next entry. */\n";
7289 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
7290 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
7291 pr " if (newp == NULL) {\n";
7292 pr " reply_with_perror (\"realloc\");\n";
7293 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7294 pr " free (ret);\n";
7295 pr " free (out);\n";
7296 pr " return NULL;\n";
7298 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
7300 pr " /* Tokenize the next entry. */\n";
7301 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
7302 pr " if (r == -1) {\n";
7303 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
7304 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7305 pr " free (ret);\n";
7306 pr " free (out);\n";
7307 pr " return NULL;\n";
7314 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
7316 pr " free (out);\n";
7317 pr " return ret;\n";
7320 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
7322 (* Generate a list of function names, for debugging in the daemon.. *)
7323 and generate_daemon_names () =
7324 generate_header CStyle GPLv2plus;
7326 pr "#include <config.h>\n";
7328 pr "#include \"daemon.h\"\n";
7331 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
7332 pr "const char *function_names[] = {\n";
7334 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
7338 (* Generate the optional groups for the daemon to implement
7339 * guestfs_available.
7341 and generate_daemon_optgroups_c () =
7342 generate_header CStyle GPLv2plus;
7344 pr "#include <config.h>\n";
7346 pr "#include \"daemon.h\"\n";
7347 pr "#include \"optgroups.h\"\n";
7350 pr "struct optgroup optgroups[] = {\n";
7353 pr " { \"%s\", optgroup_%s_available },\n" group group
7355 pr " { NULL, NULL }\n";
7358 and generate_daemon_optgroups_h () =
7359 generate_header CStyle GPLv2plus;
7363 pr "extern int optgroup_%s_available (void);\n" group
7366 (* Generate the tests. *)
7367 and generate_tests () =
7368 generate_header CStyle GPLv2plus;
7375 #include <sys/types.h>
7378 #include \"guestfs.h\"
7379 #include \"guestfs-internal.h\"
7381 static guestfs_h *g;
7382 static int suppress_error = 0;
7384 static void print_error (guestfs_h *g, void *data, const char *msg)
7386 if (!suppress_error)
7387 fprintf (stderr, \"%%s\\n\", msg);
7390 /* FIXME: nearly identical code appears in fish.c */
7391 static void print_strings (char *const *argv)
7395 for (argc = 0; argv[argc] != NULL; ++argc)
7396 printf (\"\\t%%s\\n\", argv[argc]);
7400 static void print_table (char const *const *argv)
7404 for (i = 0; argv[i] != NULL; i += 2)
7405 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
7410 is_available (const char *group)
7412 const char *groups[] = { group, NULL };
7416 r = guestfs_available (g, (char **) groups);
7423 incr (guestfs_h *g, void *iv)
7425 int *i = (int *) iv;
7431 (* Generate a list of commands which are not tested anywhere. *)
7432 pr "static void no_test_warnings (void)\n";
7435 let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
7437 fun (_, _, _, _, tests, _, _) ->
7438 let tests = filter_map (
7440 | (_, (Always|If _|Unless _|IfAvailable _), test) -> Some test
7441 | (_, Disabled, _) -> None
7443 let seq = List.concat (List.map seq_of_test tests) in
7444 let cmds_tested = List.map List.hd seq in
7445 List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
7449 fun (name, _, _, _, _, _, _) ->
7450 if not (Hashtbl.mem hash name) then
7451 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
7457 (* Generate the actual tests. Note that we generate the tests
7458 * in reverse order, deliberately, so that (in general) the
7459 * newest tests run first. This makes it quicker and easier to
7464 fun (name, _, _, flags, tests, _, _) ->
7465 mapi (generate_one_test name flags) tests
7466 ) (List.rev all_functions) in
7467 let test_names = List.concat test_names in
7468 let nr_tests = List.length test_names in
7471 int main (int argc, char *argv[])
7474 unsigned long int n_failed = 0;
7475 const char *filename;
7477 int nr_tests, test_num = 0;
7479 setbuf (stdout, NULL);
7481 no_test_warnings ();
7483 g = guestfs_create ();
7485 printf (\"guestfs_create FAILED\\n\");
7486 exit (EXIT_FAILURE);
7489 guestfs_set_error_handler (g, print_error, NULL);
7491 guestfs_set_path (g, \"../appliance\");
7493 filename = \"test1.img\";
7494 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7497 exit (EXIT_FAILURE);
7499 if (lseek (fd, %d, SEEK_SET) == -1) {
7503 exit (EXIT_FAILURE);
7505 if (write (fd, &c, 1) == -1) {
7509 exit (EXIT_FAILURE);
7511 if (close (fd) == -1) {
7514 exit (EXIT_FAILURE);
7516 if (guestfs_add_drive (g, filename) == -1) {
7517 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7518 exit (EXIT_FAILURE);
7521 filename = \"test2.img\";
7522 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7525 exit (EXIT_FAILURE);
7527 if (lseek (fd, %d, SEEK_SET) == -1) {
7531 exit (EXIT_FAILURE);
7533 if (write (fd, &c, 1) == -1) {
7537 exit (EXIT_FAILURE);
7539 if (close (fd) == -1) {
7542 exit (EXIT_FAILURE);
7544 if (guestfs_add_drive (g, filename) == -1) {
7545 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7546 exit (EXIT_FAILURE);
7549 filename = \"test3.img\";
7550 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7553 exit (EXIT_FAILURE);
7555 if (lseek (fd, %d, SEEK_SET) == -1) {
7559 exit (EXIT_FAILURE);
7561 if (write (fd, &c, 1) == -1) {
7565 exit (EXIT_FAILURE);
7567 if (close (fd) == -1) {
7570 exit (EXIT_FAILURE);
7572 if (guestfs_add_drive (g, filename) == -1) {
7573 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7574 exit (EXIT_FAILURE);
7577 if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
7578 printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
7579 exit (EXIT_FAILURE);
7582 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
7585 if (guestfs_launch (g) == -1) {
7586 printf (\"guestfs_launch FAILED\\n\");
7587 exit (EXIT_FAILURE);
7590 /* Cancel previous alarm. */
7595 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
7599 pr " test_num++;\n";
7600 pr " if (guestfs_get_verbose (g))\n";
7601 pr " printf (\"-------------------------------------------------------------------------------\\n\");\n";
7602 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
7603 pr " if (%s () == -1) {\n" test_name;
7604 pr " printf (\"%s FAILED\\n\");\n" test_name;
7605 pr " n_failed++;\n";
7610 pr " /* Check close callback is called. */
7611 int close_sentinel = 1;
7612 guestfs_set_close_callback (g, incr, &close_sentinel);
7616 if (close_sentinel != 2) {
7617 fprintf (stderr, \"close callback was not called\\n\");
7618 exit (EXIT_FAILURE);
7621 unlink (\"test1.img\");
7622 unlink (\"test2.img\");
7623 unlink (\"test3.img\");
7627 pr " if (n_failed > 0) {\n";
7628 pr " printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
7629 pr " exit (EXIT_FAILURE);\n";
7633 pr " exit (EXIT_SUCCESS);\n";
7636 and generate_one_test name flags i (init, prereq, test) =
7637 let test_name = sprintf "test_%s_%d" name i in
7640 static int %s_skip (void)
7644 str = getenv (\"TEST_ONLY\");
7646 return strstr (str, \"%s\") == NULL;
7647 str = getenv (\"SKIP_%s\");
7648 if (str && STREQ (str, \"1\")) return 1;
7649 str = getenv (\"SKIP_TEST_%s\");
7650 if (str && STREQ (str, \"1\")) return 1;
7654 " test_name name (String.uppercase test_name) (String.uppercase name);
7657 | Disabled | Always | IfAvailable _ -> ()
7658 | If code | Unless code ->
7659 pr "static int %s_prereq (void)\n" test_name;
7667 static int %s (void)
7670 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
7674 " test_name test_name test_name;
7676 (* Optional functions should only be tested if the relevant
7677 * support is available in the daemon.
7682 pr " if (!is_available (\"%s\")) {\n" group;
7683 pr " printf (\" %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", \"%s\");\n" test_name group;
7691 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
7693 pr " if (! %s_prereq ()) {\n" test_name;
7694 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7698 generate_one_test_body name i test_name init test;
7700 pr " if (%s_prereq ()) {\n" test_name;
7701 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7705 generate_one_test_body name i test_name init test;
7706 | IfAvailable group ->
7707 pr " if (!is_available (\"%s\")) {\n" group;
7708 pr " printf (\" %%s skipped (reason: %%s not available)\\n\", \"%s\", \"%s\");\n" test_name group;
7712 generate_one_test_body name i test_name init test;
7714 generate_one_test_body name i test_name init test
7722 and generate_one_test_body name i test_name init test =
7724 | InitNone (* XXX at some point, InitNone and InitEmpty became
7725 * folded together as the same thing. Really we should
7726 * make InitNone do nothing at all, but the tests may
7727 * need to be checked to make sure this is OK.
7730 pr " /* InitNone|InitEmpty for %s */\n" test_name;
7731 List.iter (generate_test_command_call test_name)
7732 [["blockdev_setrw"; "/dev/sda"];
7736 pr " /* InitPartition for %s: create /dev/sda1 */\n" test_name;
7737 List.iter (generate_test_command_call test_name)
7738 [["blockdev_setrw"; "/dev/sda"];
7741 ["part_disk"; "/dev/sda"; "mbr"]]
7743 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
7744 List.iter (generate_test_command_call test_name)
7745 [["blockdev_setrw"; "/dev/sda"];
7748 ["part_disk"; "/dev/sda"; "mbr"];
7749 ["mkfs"; "ext2"; "/dev/sda1"];
7750 ["mount_options"; ""; "/dev/sda1"; "/"]]
7751 | InitBasicFSonLVM ->
7752 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
7754 List.iter (generate_test_command_call test_name)
7755 [["blockdev_setrw"; "/dev/sda"];
7758 ["part_disk"; "/dev/sda"; "mbr"];
7759 ["pvcreate"; "/dev/sda1"];
7760 ["vgcreate"; "VG"; "/dev/sda1"];
7761 ["lvcreate"; "LV"; "VG"; "8"];
7762 ["mkfs"; "ext2"; "/dev/VG/LV"];
7763 ["mount_options"; ""; "/dev/VG/LV"; "/"]]
7765 pr " /* InitISOFS for %s */\n" test_name;
7766 List.iter (generate_test_command_call test_name)
7767 [["blockdev_setrw"; "/dev/sda"];
7770 ["mount_ro"; "/dev/sdd"; "/"]]
7773 let get_seq_last = function
7775 failwithf "%s: you cannot use [] (empty list) when expecting a command"
7778 let seq = List.rev seq in
7779 List.rev (List.tl seq), List.hd seq
7784 pr " /* TestRun for %s (%d) */\n" name i;
7785 List.iter (generate_test_command_call test_name) seq
7786 | TestOutput (seq, expected) ->
7787 pr " /* TestOutput for %s (%d) */\n" name i;
7788 pr " const char *expected = \"%s\";\n" (c_quote expected);
7789 let seq, last = get_seq_last seq in
7791 pr " if (STRNEQ (r, expected)) {\n";
7792 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7796 List.iter (generate_test_command_call test_name) seq;
7797 generate_test_command_call ~test test_name last
7798 | TestOutputList (seq, expected) ->
7799 pr " /* TestOutputList for %s (%d) */\n" name i;
7800 let seq, last = get_seq_last seq in
7804 pr " if (!r[%d]) {\n" i;
7805 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7806 pr " print_strings (r);\n";
7810 pr " const char *expected = \"%s\";\n" (c_quote str);
7811 pr " if (STRNEQ (r[%d], expected)) {\n" i;
7812 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7817 pr " if (r[%d] != NULL) {\n" (List.length expected);
7818 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7820 pr " print_strings (r);\n";
7824 List.iter (generate_test_command_call test_name) seq;
7825 generate_test_command_call ~test test_name last
7826 | TestOutputListOfDevices (seq, expected) ->
7827 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
7828 let seq, last = get_seq_last seq in
7832 pr " if (!r[%d]) {\n" i;
7833 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7834 pr " print_strings (r);\n";
7838 pr " const char *expected = \"%s\";\n" (c_quote str);
7839 pr " r[%d][5] = 's';\n" i;
7840 pr " if (STRNEQ (r[%d], expected)) {\n" i;
7841 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7846 pr " if (r[%d] != NULL) {\n" (List.length expected);
7847 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7849 pr " print_strings (r);\n";
7853 List.iter (generate_test_command_call test_name) seq;
7854 generate_test_command_call ~test test_name last
7855 | TestOutputInt (seq, expected) ->
7856 pr " /* TestOutputInt for %s (%d) */\n" name i;
7857 let seq, last = get_seq_last seq in
7859 pr " if (r != %d) {\n" expected;
7860 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
7866 List.iter (generate_test_command_call test_name) seq;
7867 generate_test_command_call ~test test_name last
7868 | TestOutputIntOp (seq, op, expected) ->
7869 pr " /* TestOutputIntOp for %s (%d) */\n" name i;
7870 let seq, last = get_seq_last seq in
7872 pr " if (! (r %s %d)) {\n" op expected;
7873 pr " fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
7874 test_name op expected;
7879 List.iter (generate_test_command_call test_name) seq;
7880 generate_test_command_call ~test test_name last
7881 | TestOutputTrue seq ->
7882 pr " /* TestOutputTrue for %s (%d) */\n" name i;
7883 let seq, last = get_seq_last seq in
7886 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
7891 List.iter (generate_test_command_call test_name) seq;
7892 generate_test_command_call ~test test_name last
7893 | TestOutputFalse seq ->
7894 pr " /* TestOutputFalse for %s (%d) */\n" name i;
7895 let seq, last = get_seq_last seq in
7898 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
7903 List.iter (generate_test_command_call test_name) seq;
7904 generate_test_command_call ~test test_name last
7905 | TestOutputLength (seq, expected) ->
7906 pr " /* TestOutputLength for %s (%d) */\n" name i;
7907 let seq, last = get_seq_last seq in
7910 pr " for (j = 0; j < %d; ++j)\n" expected;
7911 pr " if (r[j] == NULL) {\n";
7912 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
7914 pr " print_strings (r);\n";
7917 pr " if (r[j] != NULL) {\n";
7918 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
7920 pr " print_strings (r);\n";
7924 List.iter (generate_test_command_call test_name) seq;
7925 generate_test_command_call ~test test_name last
7926 | TestOutputBuffer (seq, expected) ->
7927 pr " /* TestOutputBuffer for %s (%d) */\n" name i;
7928 pr " const char *expected = \"%s\";\n" (c_quote expected);
7929 let seq, last = get_seq_last seq in
7930 let len = String.length expected in
7932 pr " if (size != %d) {\n" len;
7933 pr " fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
7936 pr " if (STRNEQLEN (r, expected, size)) {\n";
7937 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7941 List.iter (generate_test_command_call test_name) seq;
7942 generate_test_command_call ~test test_name last
7943 | TestOutputStruct (seq, checks) ->
7944 pr " /* TestOutputStruct for %s (%d) */\n" name i;
7945 let seq, last = get_seq_last seq in
7949 | CompareWithInt (field, expected) ->
7950 pr " if (r->%s != %d) {\n" field expected;
7951 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
7952 test_name field expected;
7953 pr " (int) r->%s);\n" field;
7956 | CompareWithIntOp (field, op, expected) ->
7957 pr " if (!(r->%s %s %d)) {\n" field op expected;
7958 pr " fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
7959 test_name field op expected;
7960 pr " (int) r->%s);\n" field;
7963 | CompareWithString (field, expected) ->
7964 pr " if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
7965 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
7966 test_name field expected;
7967 pr " r->%s);\n" field;
7970 | CompareFieldsIntEq (field1, field2) ->
7971 pr " if (r->%s != r->%s) {\n" field1 field2;
7972 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
7973 test_name field1 field2;
7974 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
7977 | CompareFieldsStrEq (field1, field2) ->
7978 pr " if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
7979 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
7980 test_name field1 field2;
7981 pr " r->%s, r->%s);\n" field1 field2;
7986 List.iter (generate_test_command_call test_name) seq;
7987 generate_test_command_call ~test test_name last
7988 | TestLastFail seq ->
7989 pr " /* TestLastFail for %s (%d) */\n" name i;
7990 let seq, last = get_seq_last seq in
7991 List.iter (generate_test_command_call test_name) seq;
7992 generate_test_command_call test_name ~expect_error:true last
7994 (* Generate the code to run a command, leaving the result in 'r'.
7995 * If you expect to get an error then you should set expect_error:true.
7997 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
7999 | [] -> assert false
8001 (* Look up the command to find out what args/ret it has. *)
8004 let _, style, _, _, _, _, _ =
8005 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
8008 failwithf "%s: in test, command %s was not found" test_name name in
8010 if List.length (snd style) <> List.length args then
8011 failwithf "%s: in test, wrong number of args given to %s"
8018 | OptString n, "NULL" -> ()
8021 | Dev_or_Path n, arg
8025 pr " const char *%s = \"%s\";\n" n (c_quote arg);
8026 | BufferIn n, arg ->
8027 pr " const char *%s = \"%s\";\n" n (c_quote arg);
8028 pr " size_t %s_size = %d;\n" n (String.length arg)
8032 | FileIn _, _ | FileOut _, _ -> ()
8033 | StringList n, "" | DeviceList n, "" ->
8034 pr " const char *const %s[1] = { NULL };\n" n
8035 | StringList n, arg | DeviceList n, arg ->
8036 let strs = string_split " " arg in
8039 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
8041 pr " const char *const %s[] = {\n" n;
8043 fun i _ -> pr " %s_%d,\n" n i
8047 ) (List.combine (snd style) args);
8050 match fst style with
8051 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
8052 | RInt64 _ -> pr " int64_t r;\n"; "-1"
8053 | RConstString _ | RConstOptString _ ->
8054 pr " const char *r;\n"; "NULL"
8055 | RString _ -> pr " char *r;\n"; "NULL"
8056 | RStringList _ | RHashtable _ ->
8060 | RStruct (_, typ) ->
8061 pr " struct guestfs_%s *r;\n" typ; "NULL"
8062 | RStructList (_, typ) ->
8063 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
8066 pr " size_t size;\n";
8069 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
8070 pr " r = guestfs_%s (g" name;
8072 (* Generate the parameters. *)
8075 | OptString _, "NULL" -> pr ", NULL"
8077 | Device n, _ | Dev_or_Path n, _
8083 pr ", %s, %s_size" n n
8084 | FileIn _, arg | FileOut _, arg ->
8085 pr ", \"%s\"" (c_quote arg)
8086 | StringList n, _ | DeviceList n, _ ->
8087 pr ", (char **) %s" n
8090 try int_of_string arg
8091 with Failure "int_of_string" ->
8092 failwithf "%s: expecting an int, but got '%s'" test_name arg in
8096 try Int64.of_string arg
8097 with Failure "int_of_string" ->
8098 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
8101 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
8102 ) (List.combine (snd style) args);
8104 (match fst style with
8105 | RBufferOut _ -> pr ", &size"
8111 if not expect_error then
8112 pr " if (r == %s)\n" error_code
8114 pr " if (r != %s)\n" error_code;
8117 (* Insert the test code. *)
8123 (match fst style with
8124 | RErr | RInt _ | RInt64 _ | RBool _
8125 | RConstString _ | RConstOptString _ -> ()
8126 | RString _ | RBufferOut _ -> pr " free (r);\n"
8127 | RStringList _ | RHashtable _ ->
8128 pr " for (i = 0; r[i] != NULL; ++i)\n";
8129 pr " free (r[i]);\n";
8131 | RStruct (_, typ) ->
8132 pr " guestfs_free_%s (r);\n" typ
8133 | RStructList (_, typ) ->
8134 pr " guestfs_free_%s_list (r);\n" typ
8140 let str = replace_str str "\r" "\\r" in
8141 let str = replace_str str "\n" "\\n" in
8142 let str = replace_str str "\t" "\\t" in
8143 let str = replace_str str "\000" "\\0" in
8146 (* Generate a lot of different functions for guestfish. *)
8147 and generate_fish_cmds () =
8148 generate_header CStyle GPLv2plus;
8152 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8154 let all_functions_sorted =
8156 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8157 ) all_functions_sorted in
8159 pr "#include <config.h>\n";
8161 pr "#include <stdio.h>\n";
8162 pr "#include <stdlib.h>\n";
8163 pr "#include <string.h>\n";
8164 pr "#include <inttypes.h>\n";
8166 pr "#include <guestfs.h>\n";
8167 pr "#include \"c-ctype.h\"\n";
8168 pr "#include \"full-write.h\"\n";
8169 pr "#include \"xstrtol.h\"\n";
8170 pr "#include \"fish.h\"\n";
8172 pr "/* Valid suffixes allowed for numbers. See Gnulib xstrtol function. */\n";
8173 pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
8176 (* list_commands function, which implements guestfish -h *)
8177 pr "void list_commands (void)\n";
8179 pr " printf (\" %%-16s %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
8180 pr " list_builtin_commands ();\n";
8182 fun (name, _, _, flags, _, shortdesc, _) ->
8183 let name = replace_char name '_' '-' in
8184 pr " printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
8186 ) all_functions_sorted;
8187 pr " printf (\" %%s\\n\",";
8188 pr " _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
8192 (* display_command function, which implements guestfish -h cmd *)
8193 pr "int display_command (const char *cmd)\n";
8196 fun (name, style, _, flags, _, shortdesc, longdesc) ->
8197 let name2 = replace_char name '_' '-' in
8199 try find_map (function FishAlias n -> Some n | _ -> None) flags
8200 with Not_found -> name in
8201 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
8203 match snd style with
8206 let args = List.filter (function Key _ -> false | _ -> true) args in
8208 name2 (String.concat " " (List.map name_of_argt args)) in
8211 if List.exists (function Key _ -> true | _ -> false) (snd style) then
8212 "\n\nThis command has one or more key or passphrase parameters.
8213 Guestfish will prompt for these separately."
8218 if List.mem ProtocolLimitWarning flags then
8219 ("\n\n" ^ protocol_limit_warning)
8222 (* For DangerWillRobinson commands, we should probably have
8223 * guestfish prompt before allowing you to use them (especially
8224 * in interactive mode). XXX
8228 if List.mem DangerWillRobinson flags then
8229 ("\n\n" ^ danger_will_robinson)
8234 match deprecation_notice flags with
8236 | Some txt -> "\n\n" ^ txt in
8238 let describe_alias =
8239 if name <> alias then
8240 sprintf "\n\nYou can use '%s' as an alias for this command." alias
8244 pr "STRCASEEQ (cmd, \"%s\")" name;
8245 if name <> name2 then
8246 pr " || STRCASEEQ (cmd, \"%s\")" name2;
8247 if name <> alias then
8248 pr " || STRCASEEQ (cmd, \"%s\")" alias;
8250 pr " pod2text (\"%s\", _(\"%s\"), %S);\n"
8252 ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
8253 "=head1 DESCRIPTION\n\n" ^
8254 longdesc ^ warnings ^ describe_alias);
8259 pr " return display_builtin_command (cmd);\n";
8263 let emit_print_list_function typ =
8264 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
8267 pr " unsigned int i;\n";
8269 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
8270 pr " printf (\"[%%d] = {\\n\", i);\n";
8271 pr " print_%s_indent (&%ss->val[i], \" \");\n" typ typ;
8272 pr " printf (\"}\\n\");\n";
8278 (* print_* functions *)
8282 List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
8284 pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
8287 pr " unsigned int i;\n";
8293 pr " printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
8295 pr " printf (\"%%s%s: \", indent);\n" name;
8296 pr " for (i = 0; i < 32; ++i)\n";
8297 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
8298 pr " printf (\"\\n\");\n"
8300 pr " printf (\"%%s%s: \", indent);\n" name;
8301 pr " for (i = 0; i < %s->%s_len; ++i)\n" typ name;
8302 pr " if (c_isprint (%s->%s[i]))\n" typ name;
8303 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
8305 pr " printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
8306 pr " printf (\"\\n\");\n"
8307 | name, (FUInt64|FBytes) ->
8308 pr " printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
8311 pr " printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
8314 pr " printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
8317 pr " printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
8320 pr " printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
8322 | name, FOptPercent ->
8323 pr " if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
8324 typ name name typ name;
8325 pr " else printf (\"%%s%s: \\n\", indent);\n" name
8331 (* Emit a print_TYPE_list function definition only if that function is used. *)
8334 | typ, (RStructListOnly | RStructAndList) ->
8335 (* generate the function for typ *)
8336 emit_print_list_function typ
8337 | typ, _ -> () (* empty *)
8338 ) (rstructs_used_by all_functions);
8340 (* Emit a print_TYPE function definition only if that function is used. *)
8343 | typ, (RStructOnly | RStructAndList) ->
8344 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
8346 pr " print_%s_indent (%s, \"\");\n" typ typ;
8349 | typ, _ -> () (* empty *)
8350 ) (rstructs_used_by all_functions);
8352 (* run_<action> actions *)
8354 fun (name, style, _, flags, _, _, _) ->
8355 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
8357 (match fst style with
8360 | RBool _ -> pr " int r;\n"
8361 | RInt64 _ -> pr " int64_t r;\n"
8362 | RConstString _ | RConstOptString _ -> pr " const char *r;\n"
8363 | RString _ -> pr " char *r;\n"
8364 | RStringList _ | RHashtable _ -> pr " char **r;\n"
8365 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
8366 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
8369 pr " size_t size;\n";
8375 | OptString n -> pr " const char *%s;\n" n
8380 | Key n -> pr " char *%s;\n" n
8382 pr " const char *%s;\n" n;
8383 pr " size_t %s_size;\n" n
8384 | StringList n | DeviceList n -> pr " char **%s;\n" n
8385 | Bool n -> pr " int %s;\n" n
8386 | Int n -> pr " int %s;\n" n
8387 | Int64 n -> pr " int64_t %s;\n" n
8390 (* Check and convert parameters. *)
8393 List.filter (function Key _ -> false | _ -> true) (snd style) in
8394 List.length args_no_keys in
8395 pr " if (argc != %d) {\n" argc_expected;
8396 pr " fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
8398 pr " fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
8402 let parse_integer fn fntyp rtyp range name =
8404 pr " strtol_error xerr;\n";
8405 pr " %s r;\n" fntyp;
8407 pr " xerr = %s (argv[i++], NULL, 0, &r, xstrtol_suffixes);\n" fn;
8408 pr " if (xerr != LONGINT_OK) {\n";
8409 pr " fprintf (stderr,\n";
8410 pr " _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
8411 pr " cmd, \"%s\", \"%s\", xerr);\n" name fn;
8416 | Some (min, max, comment) ->
8417 pr " /* %s */\n" comment;
8418 pr " if (r < %s || r > %s) {\n" min max;
8419 pr " fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
8423 pr " /* The check above should ensure this assignment does not overflow. */\n";
8425 pr " %s = r;\n" name;
8429 if snd style <> [] then
8430 pr " size_t i = 0;\n";
8436 pr " %s = argv[i++];\n" name
8438 | Dev_or_Path name ->
8439 pr " %s = resolve_win_path (argv[i++]);\n" name;
8440 pr " if (%s == NULL) return -1;\n" name
8442 pr " %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
8445 pr " %s = argv[i];\n" name;
8446 pr " %s_size = strlen (argv[i]);\n" name;
8449 pr " %s = file_in (argv[i++]);\n" name;
8450 pr " if (%s == NULL) return -1;\n" name
8452 pr " %s = file_out (argv[i++]);\n" name;
8453 pr " if (%s == NULL) return -1;\n" name
8454 | StringList name | DeviceList name ->
8455 pr " %s = parse_string_list (argv[i++]);\n" name;
8456 pr " if (%s == NULL) return -1;\n" name
8458 pr " %s = read_key (\"%s\");\n" name name;
8459 pr " if (%s == NULL) return -1;\n" name
8461 pr " %s = is_true (argv[i++]) ? 1 : 0;\n" name
8464 let min = "(-(2LL<<30))"
8465 and max = "((2LL<<30)-1)"
8467 "The Int type in the generator is a signed 31 bit int." in
8468 Some (min, max, comment) in
8469 parse_integer "xstrtoll" "long long" "int" range name
8471 parse_integer "xstrtoll" "long long" "int64_t" None name
8474 (* Call C API function. *)
8475 pr " r = guestfs_%s " name;
8476 generate_c_call_args ~handle:"g" style;
8481 | Device _ | String _
8482 | OptString _ | Bool _
8485 | Pathname name | Dev_or_Path name | FileOut name
8487 pr " free (%s);\n" name
8489 pr " free_file_in (%s);\n" name
8490 | StringList name | DeviceList name ->
8491 pr " free_strings (%s);\n" name
8494 (* Any output flags? *)
8496 let flags = filter_map (
8497 function FishOutput flag -> Some flag | _ -> None
8503 failwithf "%s: more than one FishOutput flag is not allowed" name in
8505 (* Check return value for errors and display command results. *)
8506 (match fst style with
8507 | RErr -> pr " return r;\n"
8509 pr " if (r == -1) return -1;\n";
8510 (match fish_output with
8512 pr " printf (\"%%d\\n\", r);\n";
8513 | Some FishOutputOctal ->
8514 pr " printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
8515 | Some FishOutputHexadecimal ->
8516 pr " printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8519 pr " if (r == -1) return -1;\n";
8520 (match fish_output with
8522 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
8523 | Some FishOutputOctal ->
8524 pr " printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
8525 | Some FishOutputHexadecimal ->
8526 pr " printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8529 pr " if (r == -1) return -1;\n";
8530 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
8533 pr " if (r == NULL) return -1;\n";
8534 pr " printf (\"%%s\\n\", r);\n";
8536 | RConstOptString _ ->
8537 pr " printf (\"%%s\\n\", r ? : \"(null)\");\n";
8540 pr " if (r == NULL) return -1;\n";
8541 pr " printf (\"%%s\\n\", r);\n";
8545 pr " if (r == NULL) return -1;\n";
8546 pr " print_strings (r);\n";
8547 pr " free_strings (r);\n";
8549 | RStruct (_, typ) ->
8550 pr " if (r == NULL) return -1;\n";
8551 pr " print_%s (r);\n" typ;
8552 pr " guestfs_free_%s (r);\n" typ;
8554 | RStructList (_, typ) ->
8555 pr " if (r == NULL) return -1;\n";
8556 pr " print_%s_list (r);\n" typ;
8557 pr " guestfs_free_%s_list (r);\n" typ;
8560 pr " if (r == NULL) return -1;\n";
8561 pr " print_table (r);\n";
8562 pr " free_strings (r);\n";
8565 pr " if (r == NULL) return -1;\n";
8566 pr " if (full_write (1, r, size) != size) {\n";
8567 pr " perror (\"write\");\n";
8578 (* run_action function *)
8579 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
8582 fun (name, _, _, flags, _, _, _) ->
8583 let name2 = replace_char name '_' '-' in
8585 try find_map (function FishAlias n -> Some n | _ -> None) flags
8586 with Not_found -> name in
8588 pr "STRCASEEQ (cmd, \"%s\")" name;
8589 if name <> name2 then
8590 pr " || STRCASEEQ (cmd, \"%s\")" name2;
8591 if name <> alias then
8592 pr " || STRCASEEQ (cmd, \"%s\")" alias;
8594 pr " return run_%s (cmd, argc, argv);\n" name;
8598 pr " fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
8599 pr " if (command_num == 1)\n";
8600 pr " extended_help_message ();\n";
8607 (* Readline completion for guestfish. *)
8608 and generate_fish_completion () =
8609 generate_header CStyle GPLv2plus;
8613 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8623 #ifdef HAVE_LIBREADLINE
8624 #include <readline/readline.h>
8629 #ifdef HAVE_LIBREADLINE
8631 static const char *const commands[] = {
8632 BUILTIN_COMMANDS_FOR_COMPLETION,
8635 (* Get the commands, including the aliases. They don't need to be
8636 * sorted - the generator() function just does a dumb linear search.
8640 fun (name, _, _, flags, _, _, _) ->
8641 let name2 = replace_char name '_' '-' in
8643 try find_map (function FishAlias n -> Some n | _ -> None) flags
8644 with Not_found -> name in
8646 if name <> alias then [name2; alias] else [name2]
8648 let commands = List.flatten commands in
8650 List.iter (pr " \"%s\",\n") commands;
8656 generator (const char *text, int state)
8658 static size_t index, len;
8663 len = strlen (text);
8666 rl_attempted_completion_over = 1;
8668 while ((name = commands[index]) != NULL) {
8670 if (STRCASEEQLEN (name, text, len))
8671 return strdup (name);
8677 #endif /* HAVE_LIBREADLINE */
8679 #ifdef HAVE_RL_COMPLETION_MATCHES
8680 #define RL_COMPLETION_MATCHES rl_completion_matches
8682 #ifdef HAVE_COMPLETION_MATCHES
8683 #define RL_COMPLETION_MATCHES completion_matches
8685 #endif /* else just fail if we don't have either symbol */
8688 do_completion (const char *text, int start, int end)
8690 char **matches = NULL;
8692 #ifdef HAVE_LIBREADLINE
8693 rl_completion_append_character = ' ';
8696 matches = RL_COMPLETION_MATCHES (text, generator);
8697 else if (complete_dest_paths)
8698 matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
8705 (* Generate the POD documentation for guestfish. *)
8706 and generate_fish_actions_pod () =
8707 let all_functions_sorted =
8709 fun (_, _, _, flags, _, _, _) ->
8710 not (List.mem NotInFish flags || List.mem NotInDocs flags)
8711 ) all_functions_sorted in
8713 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
8716 fun (name, style, _, flags, _, _, longdesc) ->
8718 Str.global_substitute rex (
8721 try Str.matched_group 1 s
8723 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
8724 "C<" ^ replace_char sub '_' '-' ^ ">"
8726 let name = replace_char name '_' '-' in
8728 try find_map (function FishAlias n -> Some n | _ -> None) flags
8729 with Not_found -> name in
8731 pr "=head2 %s" name;
8732 if name <> alias then
8739 | Pathname n | Device n | Dev_or_Path n | String n ->
8741 | OptString n -> pr " %s" n
8742 | StringList n | DeviceList n -> pr " '%s ...'" n
8743 | Bool _ -> pr " true|false"
8744 | Int n -> pr " %s" n
8745 | Int64 n -> pr " %s" n
8746 | FileIn n | FileOut n -> pr " (%s|-)" n
8747 | BufferIn n -> pr " %s" n
8748 | Key _ -> () (* keys are entered at a prompt *)
8752 pr "%s\n\n" longdesc;
8754 if List.exists (function FileIn _ | FileOut _ -> true
8755 | _ -> false) (snd style) then
8756 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
8758 if List.exists (function Key _ -> true | _ -> false) (snd style) then
8759 pr "This command has one or more key or passphrase parameters.
8760 Guestfish will prompt for these separately.\n\n";
8762 if List.mem ProtocolLimitWarning flags then
8763 pr "%s\n\n" protocol_limit_warning;
8765 if List.mem DangerWillRobinson flags then
8766 pr "%s\n\n" danger_will_robinson;
8768 match deprecation_notice flags with
8770 | Some txt -> pr "%s\n\n" txt
8771 ) all_functions_sorted
8773 (* Generate a C function prototype. *)
8774 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
8775 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
8777 ?handle name style =
8778 if extern then pr "extern ";
8779 if static then pr "static ";
8780 (match fst style with
8782 | RInt _ -> pr "int "
8783 | RInt64 _ -> pr "int64_t "
8784 | RBool _ -> pr "int "
8785 | RConstString _ | RConstOptString _ -> pr "const char *"
8786 | RString _ | RBufferOut _ -> pr "char *"
8787 | RStringList _ | RHashtable _ -> pr "char **"
8788 | RStruct (_, typ) ->
8789 if not in_daemon then pr "struct guestfs_%s *" typ
8790 else pr "guestfs_int_%s *" typ
8791 | RStructList (_, typ) ->
8792 if not in_daemon then pr "struct guestfs_%s_list *" typ
8793 else pr "guestfs_int_%s_list *" typ
8795 let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
8796 pr "%s%s (" prefix name;
8797 if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
8800 let comma = ref false in
8803 | Some handle -> pr "guestfs_h *%s" handle; comma := true
8807 if single_line then pr ", " else pr ",\n\t\t"
8814 | Device n | Dev_or_Path n
8819 pr "const char *%s" n
8820 | StringList n | DeviceList n ->
8822 pr "char *const *%s" n
8823 | Bool n -> next (); pr "int %s" n
8824 | Int n -> next (); pr "int %s" n
8825 | Int64 n -> next (); pr "int64_t %s" n
8828 if not in_daemon then (next (); pr "const char *%s" n)
8831 pr "const char *%s" n;
8833 pr "size_t %s_size" n
8835 if is_RBufferOut then (next (); pr "size_t *size_r");
8838 if semicolon then pr ";";
8839 if newline then pr "\n"
8841 (* Generate C call arguments, eg "(handle, foo, bar)" *)
8842 and generate_c_call_args ?handle ?(decl = false) style =
8844 let comma = ref false in
8846 if !comma then pr ", ";
8851 | Some handle -> pr "%s" handle; comma := true
8857 pr "%s, %s_size" n n
8860 pr "%s" (name_of_argt arg)
8862 (* For RBufferOut calls, add implicit &size parameter. *)
8864 match fst style with
8872 (* Generate the OCaml bindings interface. *)
8873 and generate_ocaml_mli () =
8874 generate_header OCamlStyle LGPLv2plus;
8877 (** For API documentation you should refer to the C API
8878 in the guestfs(3) manual page. The OCaml API uses almost
8879 exactly the same calls. *)
8882 (** A [guestfs_h] handle. *)
8884 exception Error of string
8885 (** This exception is raised when there is an error. *)
8887 exception Handle_closed of string
8888 (** This exception is raised if you use a {!Guestfs.t} handle
8889 after calling {!close} on it. The string is the name of
8892 val create : unit -> t
8893 (** Create a {!Guestfs.t} handle. *)
8895 val close : t -> unit
8896 (** Close the {!Guestfs.t} handle and free up all resources used
8899 Handles are closed by the garbage collector when they become
8900 unreferenced, but callers can call this in order to provide
8901 predictable cleanup. *)
8904 generate_ocaml_structure_decls ();
8908 fun (name, style, _, _, _, shortdesc, _) ->
8909 generate_ocaml_prototype name style;
8910 pr "(** %s *)\n" shortdesc;
8912 ) all_functions_sorted
8914 (* Generate the OCaml bindings implementation. *)
8915 and generate_ocaml_ml () =
8916 generate_header OCamlStyle LGPLv2plus;
8921 exception Error of string
8922 exception Handle_closed of string
8924 external create : unit -> t = \"ocaml_guestfs_create\"
8925 external close : t -> unit = \"ocaml_guestfs_close\"
8927 (* Give the exceptions names, so they can be raised from the C code. *)
8929 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
8930 Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
8934 generate_ocaml_structure_decls ();
8938 fun (name, style, _, _, _, shortdesc, _) ->
8939 generate_ocaml_prototype ~is_external:true name style;
8940 ) all_functions_sorted
8942 (* Generate the OCaml bindings C implementation. *)
8943 and generate_ocaml_c () =
8944 generate_header CStyle LGPLv2plus;
8951 #include <caml/config.h>
8952 #include <caml/alloc.h>
8953 #include <caml/callback.h>
8954 #include <caml/fail.h>
8955 #include <caml/memory.h>
8956 #include <caml/mlvalues.h>
8957 #include <caml/signals.h>
8959 #include \"guestfs.h\"
8961 #include \"guestfs_c.h\"
8963 /* Copy a hashtable of string pairs into an assoc-list. We return
8964 * the list in reverse order, but hashtables aren't supposed to be
8967 static CAMLprim value
8968 copy_table (char * const * argv)
8971 CAMLlocal5 (rv, pairv, kv, vv, cons);
8975 for (i = 0; argv[i] != NULL; i += 2) {
8976 kv = caml_copy_string (argv[i]);
8977 vv = caml_copy_string (argv[i+1]);
8978 pairv = caml_alloc (2, 0);
8979 Store_field (pairv, 0, kv);
8980 Store_field (pairv, 1, vv);
8981 cons = caml_alloc (2, 0);
8982 Store_field (cons, 1, rv);
8984 Store_field (cons, 0, pairv);
8992 (* Struct copy functions. *)
8994 let emit_ocaml_copy_list_function typ =
8995 pr "static CAMLprim value\n";
8996 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
8998 pr " CAMLparam0 ();\n";
8999 pr " CAMLlocal2 (rv, v);\n";
9000 pr " unsigned int i;\n";
9002 pr " if (%ss->len == 0)\n" typ;
9003 pr " CAMLreturn (Atom (0));\n";
9005 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
9006 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
9007 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
9008 pr " caml_modify (&Field (rv, i), v);\n";
9010 pr " CAMLreturn (rv);\n";
9018 let has_optpercent_col =
9019 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
9021 pr "static CAMLprim value\n";
9022 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
9024 pr " CAMLparam0 ();\n";
9025 if has_optpercent_col then
9026 pr " CAMLlocal3 (rv, v, v2);\n"
9028 pr " CAMLlocal2 (rv, v);\n";
9030 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
9035 pr " v = caml_copy_string (%s->%s);\n" typ name
9037 pr " v = caml_alloc_string (%s->%s_len);\n" typ name;
9038 pr " memcpy (String_val (v), %s->%s, %s->%s_len);\n"
9041 pr " v = caml_alloc_string (32);\n";
9042 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
9043 | name, (FBytes|FInt64|FUInt64) ->
9044 pr " v = caml_copy_int64 (%s->%s);\n" typ name
9045 | name, (FInt32|FUInt32) ->
9046 pr " v = caml_copy_int32 (%s->%s);\n" typ name
9047 | name, FOptPercent ->
9048 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
9049 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
9050 pr " v = caml_alloc (1, 0);\n";
9051 pr " Store_field (v, 0, v2);\n";
9052 pr " } else /* None */\n";
9053 pr " v = Val_int (0);\n";
9055 pr " v = Val_int (%s->%s);\n" typ name
9057 pr " Store_field (rv, %d, v);\n" i
9059 pr " CAMLreturn (rv);\n";
9064 (* Emit a copy_TYPE_list function definition only if that function is used. *)
9067 | typ, (RStructListOnly | RStructAndList) ->
9068 (* generate the function for typ *)
9069 emit_ocaml_copy_list_function typ
9070 | typ, _ -> () (* empty *)
9071 ) (rstructs_used_by all_functions);
9075 fun (name, style, _, _, _, _, _) ->
9076 pr "/* Automatically generated wrapper for function\n";
9078 generate_ocaml_prototype name style;
9083 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
9085 let needs_extra_vs =
9086 match fst style with RConstOptString _ -> true | _ -> false in
9088 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9089 pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
9090 List.iter (pr ", value %s") (List.tl params); pr ");\n";
9093 pr "CAMLprim value\n";
9094 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
9095 List.iter (pr ", value %s") (List.tl params);
9100 | [p1; p2; p3; p4; p5] ->
9101 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
9102 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
9103 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
9104 pr " CAMLxparam%d (%s);\n"
9105 (List.length rest) (String.concat ", " rest)
9107 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
9109 if not needs_extra_vs then
9110 pr " CAMLlocal1 (rv);\n"
9112 pr " CAMLlocal3 (rv, v, v2);\n";
9115 pr " guestfs_h *g = Guestfs_val (gv);\n";
9116 pr " if (g == NULL)\n";
9117 pr " ocaml_guestfs_raise_closed (\"%s\");\n" name;
9123 | Device n | Dev_or_Path n
9128 (* Copy strings in case the GC moves them: RHBZ#604691 *)
9129 pr " char *%s = guestfs_safe_strdup (g, String_val (%sv));\n" n n
9131 pr " char *%s =\n" n;
9132 pr " %sv != Val_int (0) ?" n;
9133 pr " guestfs_safe_strdup (g, String_val (Field (%sv, 0))) : NULL;\n" n
9135 pr " size_t %s_size = caml_string_length (%sv);\n" n n;
9136 pr " char *%s = guestfs_safe_memdup (g, String_val (%sv), %s_size);\n" n n n
9137 | StringList n | DeviceList n ->
9138 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
9140 pr " int %s = Bool_val (%sv);\n" n n
9142 pr " int %s = Int_val (%sv);\n" n n
9144 pr " int64_t %s = Int64_val (%sv);\n" n n
9147 match fst style with
9148 | RErr -> pr " int r;\n"; "-1"
9149 | RInt _ -> pr " int r;\n"; "-1"
9150 | RInt64 _ -> pr " int64_t r;\n"; "-1"
9151 | RBool _ -> pr " int r;\n"; "-1"
9152 | RConstString _ | RConstOptString _ ->
9153 pr " const char *r;\n"; "NULL"
9154 | RString _ -> pr " char *r;\n"; "NULL"
9159 | RStruct (_, typ) ->
9160 pr " struct guestfs_%s *r;\n" typ; "NULL"
9161 | RStructList (_, typ) ->
9162 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
9169 pr " size_t size;\n";
9173 pr " caml_enter_blocking_section ();\n";
9174 pr " r = guestfs_%s " name;
9175 generate_c_call_args ~handle:"g" style;
9177 pr " caml_leave_blocking_section ();\n";
9179 (* Free strings if we copied them above. *)
9182 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
9183 | FileIn n | FileOut n | BufferIn n | Key n ->
9184 pr " free (%s);\n" n
9185 | StringList n | DeviceList n ->
9186 pr " ocaml_guestfs_free_strings (%s);\n" n;
9187 | Bool _ | Int _ | Int64 _ -> ()
9190 pr " if (r == %s)\n" error_code;
9191 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
9194 (match fst style with
9195 | RErr -> pr " rv = Val_unit;\n"
9196 | RInt _ -> pr " rv = Val_int (r);\n"
9198 pr " rv = caml_copy_int64 (r);\n"
9199 | RBool _ -> pr " rv = Val_bool (r);\n"
9201 pr " rv = caml_copy_string (r);\n"
9202 | RConstOptString _ ->
9203 pr " if (r) { /* Some string */\n";
9204 pr " v = caml_alloc (1, 0);\n";
9205 pr " v2 = caml_copy_string (r);\n";
9206 pr " Store_field (v, 0, v2);\n";
9207 pr " } else /* None */\n";
9208 pr " v = Val_int (0);\n";
9210 pr " rv = caml_copy_string (r);\n";
9213 pr " rv = caml_copy_string_array ((const char **) r);\n";
9214 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9216 | RStruct (_, typ) ->
9217 pr " rv = copy_%s (r);\n" typ;
9218 pr " guestfs_free_%s (r);\n" typ;
9219 | RStructList (_, typ) ->
9220 pr " rv = copy_%s_list (r);\n" typ;
9221 pr " guestfs_free_%s_list (r);\n" typ;
9223 pr " rv = copy_table (r);\n";
9224 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9227 pr " rv = caml_alloc_string (size);\n";
9228 pr " memcpy (String_val (rv), r, size);\n";
9231 pr " CAMLreturn (rv);\n";
9235 if List.length params > 5 then (
9236 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9237 pr "CAMLprim value ";
9238 pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
9239 pr "CAMLprim value\n";
9240 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
9242 pr " return ocaml_guestfs_%s (argv[0]" name;
9243 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
9248 ) all_functions_sorted
9250 and generate_ocaml_structure_decls () =
9253 pr "type %s = {\n" typ;
9256 | name, FString -> pr " %s : string;\n" name
9257 | name, FBuffer -> pr " %s : string;\n" name
9258 | name, FUUID -> pr " %s : string;\n" name
9259 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
9260 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
9261 | name, FChar -> pr " %s : char;\n" name
9262 | name, FOptPercent -> pr " %s : float option;\n" name
9268 and generate_ocaml_prototype ?(is_external = false) name style =
9269 if is_external then pr "external " else pr "val ";
9270 pr "%s : t -> " name;
9273 | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _
9274 | BufferIn _ | Key _ -> pr "string -> "
9275 | OptString _ -> pr "string option -> "
9276 | StringList _ | DeviceList _ -> pr "string array -> "
9277 | Bool _ -> pr "bool -> "
9278 | Int _ -> pr "int -> "
9279 | Int64 _ -> pr "int64 -> "
9281 (match fst style with
9282 | RErr -> pr "unit" (* all errors are turned into exceptions *)
9283 | RInt _ -> pr "int"
9284 | RInt64 _ -> pr "int64"
9285 | RBool _ -> pr "bool"
9286 | RConstString _ -> pr "string"
9287 | RConstOptString _ -> pr "string option"
9288 | RString _ | RBufferOut _ -> pr "string"
9289 | RStringList _ -> pr "string array"
9290 | RStruct (_, typ) -> pr "%s" typ
9291 | RStructList (_, typ) -> pr "%s array" typ
9292 | RHashtable _ -> pr "(string * string) list"
9294 if is_external then (
9296 if List.length (snd style) + 1 > 5 then
9297 pr "\"ocaml_guestfs_%s_byte\" " name;
9298 pr "\"ocaml_guestfs_%s\"" name
9302 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
9303 and generate_perl_xs () =
9304 generate_header CStyle LGPLv2plus;
9307 #include \"EXTERN.h\"
9311 #include <guestfs.h>
9314 #define PRId64 \"lld\"
9318 my_newSVll(long long val) {
9319 #ifdef USE_64_BIT_ALL
9320 return newSViv(val);
9324 len = snprintf(buf, 100, \"%%\" PRId64, val);
9325 return newSVpv(buf, len);
9330 #define PRIu64 \"llu\"
9334 my_newSVull(unsigned long long val) {
9335 #ifdef USE_64_BIT_ALL
9336 return newSVuv(val);
9340 len = snprintf(buf, 100, \"%%\" PRIu64, val);
9341 return newSVpv(buf, len);
9345 /* http://www.perlmonks.org/?node_id=680842 */
9347 XS_unpack_charPtrPtr (SV *arg) {
9352 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
9353 croak (\"array reference expected\");
9355 av = (AV *)SvRV (arg);
9356 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
9358 croak (\"malloc failed\");
9360 for (i = 0; i <= av_len (av); i++) {
9361 SV **elem = av_fetch (av, i, 0);
9363 if (!elem || !*elem)
9364 croak (\"missing element in list\");
9366 ret[i] = SvPV_nolen (*elem);
9374 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
9381 RETVAL = guestfs_create ();
9383 croak (\"could not create guestfs handle\");
9384 guestfs_set_error_handler (RETVAL, NULL, NULL);
9392 /* For the 'g' argument above we do the conversion explicitly and
9393 * don't rely on the typemap, because if the handle has been
9394 * explicitly closed we don't want the typemap conversion to
9397 HV *hv = (HV *) SvRV (sv);
9398 SV **svp = hv_fetch (hv, \"_g\", 2, 0);
9400 guestfs_h *g = (guestfs_h *) SvIV (*svp);
9410 /* Avoid double-free in DESTROY method. */
9411 HV *hv = (HV *) SvRV (ST(0));
9412 (void) hv_delete (hv, \"_g\", 2, G_DISCARD);
9417 fun (name, style, _, _, _, _, _) ->
9418 (match fst style with
9419 | RErr -> pr "void\n"
9420 | RInt _ -> pr "SV *\n"
9421 | RInt64 _ -> pr "SV *\n"
9422 | RBool _ -> pr "SV *\n"
9423 | RConstString _ -> pr "SV *\n"
9424 | RConstOptString _ -> pr "SV *\n"
9425 | RString _ -> pr "SV *\n"
9426 | RBufferOut _ -> pr "SV *\n"
9428 | RStruct _ | RStructList _
9430 pr "void\n" (* all lists returned implictly on the stack *)
9432 (* Call and arguments. *)
9435 fun arg -> pr ", %s" (name_of_argt arg)
9438 pr " guestfs_h *g;\n";
9442 | Pathname n | Device n | Dev_or_Path n | String n
9443 | FileIn n | FileOut n | Key n ->
9446 pr " char *%s;\n" n;
9447 pr " size_t %s_size = SvCUR (ST(%d));\n" n (i+1)
9449 (* http://www.perlmonks.org/?node_id=554277
9450 * Note that the implicit handle argument means we have
9451 * to add 1 to the ST(x) operator.
9453 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
9454 | StringList n | DeviceList n -> pr " char **%s;\n" n
9455 | Bool n -> pr " int %s;\n" n
9456 | Int n -> pr " int %s;\n" n
9457 | Int64 n -> pr " int64_t %s;\n" n
9460 let do_cleanups () =
9463 | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
9464 | Bool _ | Int _ | Int64 _
9465 | FileIn _ | FileOut _
9466 | BufferIn _ | Key _ -> ()
9467 | StringList n | DeviceList n -> pr " free (%s);\n" n
9472 (match fst style with
9477 pr " r = guestfs_%s " name;
9478 generate_c_call_args ~handle:"g" style;
9481 pr " if (r == -1)\n";
9482 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9488 pr " %s = guestfs_%s " n name;
9489 generate_c_call_args ~handle:"g" style;
9492 pr " if (%s == -1)\n" n;
9493 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9494 pr " RETVAL = newSViv (%s);\n" n;
9499 pr " int64_t %s;\n" n;
9501 pr " %s = guestfs_%s " n name;
9502 generate_c_call_args ~handle:"g" style;
9505 pr " if (%s == -1)\n" n;
9506 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9507 pr " RETVAL = my_newSVll (%s);\n" n;
9512 pr " const char *%s;\n" n;
9514 pr " %s = guestfs_%s " n name;
9515 generate_c_call_args ~handle:"g" style;
9518 pr " if (%s == NULL)\n" n;
9519 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9520 pr " RETVAL = newSVpv (%s, 0);\n" n;
9523 | RConstOptString n ->
9525 pr " const char *%s;\n" n;
9527 pr " %s = guestfs_%s " n name;
9528 generate_c_call_args ~handle:"g" style;
9531 pr " if (%s == NULL)\n" n;
9532 pr " RETVAL = &PL_sv_undef;\n";
9534 pr " RETVAL = newSVpv (%s, 0);\n" n;
9539 pr " char *%s;\n" n;
9541 pr " %s = guestfs_%s " n name;
9542 generate_c_call_args ~handle:"g" style;
9545 pr " if (%s == NULL)\n" n;
9546 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9547 pr " RETVAL = newSVpv (%s, 0);\n" n;
9548 pr " free (%s);\n" n;
9551 | RStringList n | RHashtable n ->
9553 pr " char **%s;\n" n;
9554 pr " size_t i, n;\n";
9556 pr " %s = guestfs_%s " n name;
9557 generate_c_call_args ~handle:"g" style;
9560 pr " if (%s == NULL)\n" n;
9561 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9562 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
9563 pr " EXTEND (SP, n);\n";
9564 pr " for (i = 0; i < n; ++i) {\n";
9565 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
9566 pr " free (%s[i]);\n" n;
9568 pr " free (%s);\n" n;
9569 | RStruct (n, typ) ->
9570 let cols = cols_of_struct typ in
9571 generate_perl_struct_code typ cols name style n do_cleanups
9572 | RStructList (n, typ) ->
9573 let cols = cols_of_struct typ in
9574 generate_perl_struct_list_code typ cols name style n do_cleanups
9577 pr " char *%s;\n" n;
9578 pr " size_t size;\n";
9580 pr " %s = guestfs_%s " n name;
9581 generate_c_call_args ~handle:"g" style;
9584 pr " if (%s == NULL)\n" n;
9585 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9586 pr " RETVAL = newSVpvn (%s, size);\n" n;
9587 pr " free (%s);\n" n;
9595 and generate_perl_struct_list_code typ cols name style n do_cleanups =
9597 pr " struct guestfs_%s_list *%s;\n" typ n;
9601 pr " %s = guestfs_%s " n name;
9602 generate_c_call_args ~handle:"g" style;
9605 pr " if (%s == NULL)\n" n;
9606 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9607 pr " EXTEND (SP, %s->len);\n" n;
9608 pr " for (i = 0; i < %s->len; ++i) {\n" n;
9609 pr " hv = newHV ();\n";
9613 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
9614 name (String.length name) n name
9616 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
9617 name (String.length name) n name
9619 pr " (void) hv_store (hv, \"%s\", %d, newSVpvn (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
9620 name (String.length name) n name n name
9621 | name, (FBytes|FUInt64) ->
9622 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
9623 name (String.length name) n name
9625 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
9626 name (String.length name) n name
9627 | name, (FInt32|FUInt32) ->
9628 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9629 name (String.length name) n name
9631 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
9632 name (String.length name) n name
9633 | name, FOptPercent ->
9634 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9635 name (String.length name) n name
9637 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
9639 pr " guestfs_free_%s_list (%s);\n" typ n
9641 and generate_perl_struct_code typ cols name style n do_cleanups =
9643 pr " struct guestfs_%s *%s;\n" typ n;
9645 pr " %s = guestfs_%s " n name;
9646 generate_c_call_args ~handle:"g" style;
9649 pr " if (%s == NULL)\n" n;
9650 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9651 pr " EXTEND (SP, 2 * %d);\n" (List.length cols);
9653 fun ((name, _) as col) ->
9654 pr " PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
9658 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
9661 pr " PUSHs (sv_2mortal (newSVpvn (%s->%s, %s->%s_len)));\n"
9664 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
9666 | name, (FBytes|FUInt64) ->
9667 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
9670 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
9672 | name, (FInt32|FUInt32) ->
9673 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9676 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
9678 | name, FOptPercent ->
9679 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9682 pr " free (%s);\n" n
9684 (* Generate Sys/Guestfs.pm. *)
9685 and generate_perl_pm () =
9686 generate_header HashStyle LGPLv2plus;
9693 Sys::Guestfs - Perl bindings for libguestfs
9699 my $h = Sys::Guestfs->new ();
9700 $h->add_drive ('guest.img');
9702 $h->mount ('/dev/sda1', '/');
9703 $h->touch ('/hello');
9708 The C<Sys::Guestfs> module provides a Perl XS binding to the
9709 libguestfs API for examining and modifying virtual machine
9712 Amongst the things this is good for: making batch configuration
9713 changes to guests, getting disk used/free statistics (see also:
9714 virt-df), migrating between virtualization systems (see also:
9715 virt-p2v), performing partial backups, performing partial guest
9716 clones, cloning guests and changing registry/UUID/hostname info, and
9719 Libguestfs uses Linux kernel and qemu code, and can access any type of
9720 guest filesystem that Linux and qemu can, including but not limited
9721 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
9722 schemes, qcow, qcow2, vmdk.
9724 Libguestfs provides ways to enumerate guest storage (eg. partitions,
9725 LVs, what filesystem is in each LV, etc.). It can also run commands
9726 in the context of the guest. Also you can access filesystems over
9729 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
9730 functions for using libguestfs from Perl, including integration
9735 All errors turn into calls to C<croak> (see L<Carp(3)>).
9743 package Sys::Guestfs;
9748 # This version number changes whenever a new function
9749 # is added to the libguestfs API. It is not directly
9750 # related to the libguestfs version number.
9751 use vars qw($VERSION);
9755 XSLoader::load ('Sys::Guestfs');
9757 =item $h = Sys::Guestfs->new ();
9759 Create a new guestfs handle.
9765 my $class = ref ($proto) || $proto;
9767 my $g = Sys::Guestfs::_create ();
9768 my $self = { _g => $g };
9769 bless $self, $class;
9775 Explicitly close the guestfs handle.
9777 B<Note:> You should not usually call this function. The handle will
9778 be closed implicitly when its reference count goes to zero (eg.
9779 when it goes out of scope or the program ends). This call is
9780 only required in some exceptional cases, such as where the program
9781 may contain cached references to the handle 'somewhere' and you
9782 really have to have the close happen right away. After calling
9783 C<close> the program must not call any method (including C<close>)
9784 on the handle (but the implicit call to C<DESTROY> that happens
9785 when the final reference is cleaned up is OK).
9791 (* Actions. We only need to print documentation for these as
9792 * they are pulled in from the XS code automatically.
9795 fun (name, style, _, flags, _, _, longdesc) ->
9796 if not (List.mem NotInDocs flags) then (
9797 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
9799 generate_perl_prototype name style;
9801 pr "%s\n\n" longdesc;
9802 if List.mem ProtocolLimitWarning flags then
9803 pr "%s\n\n" protocol_limit_warning;
9804 if List.mem DangerWillRobinson flags then
9805 pr "%s\n\n" danger_will_robinson;
9806 match deprecation_notice flags with
9808 | Some txt -> pr "%s\n\n" txt
9810 ) all_functions_sorted;
9822 Copyright (C) %s Red Hat Inc.
9826 Please see the file COPYING.LIB for the full license.
9832 L<http://libguestfs.org>,
9833 L<Sys::Guestfs::Lib(3)>.
9838 and generate_perl_prototype name style =
9839 (match fst style with
9847 | RBufferOut n -> pr "$%s = " n
9849 | RHashtable n -> pr "%%%s = " n
9851 | RStructList (n,_) -> pr "@%s = " n
9854 let comma = ref false in
9857 if !comma then pr ", ";
9860 | Pathname n | Device n | Dev_or_Path n | String n
9861 | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n
9862 | BufferIn n | Key n ->
9864 | StringList n | DeviceList n ->
9869 (* Generate Python C module. *)
9870 and generate_python_c () =
9871 generate_header CStyle LGPLv2plus;
9874 #define PY_SSIZE_T_CLEAN 1
9877 #if PY_VERSION_HEX < 0x02050000
9878 typedef int Py_ssize_t;
9879 #define PY_SSIZE_T_MAX INT_MAX
9880 #define PY_SSIZE_T_MIN INT_MIN
9887 #include \"guestfs.h\"
9889 #ifndef HAVE_PYCAPSULE_NEW
9897 get_handle (PyObject *obj)
9900 assert (obj != Py_None);
9901 #ifndef HAVE_PYCAPSULE_NEW
9902 return ((Pyguestfs_Object *) obj)->g;
9904 return (guestfs_h*) PyCapsule_GetPointer(obj, \"guestfs_h\");
9909 put_handle (guestfs_h *g)
9912 #ifndef HAVE_PYCAPSULE_NEW
9914 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
9916 return PyCapsule_New ((void *) g, \"guestfs_h\", NULL);
9920 /* This list should be freed (but not the strings) after use. */
9922 get_string_list (PyObject *obj)
9929 if (!PyList_Check (obj)) {
9930 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
9934 Py_ssize_t slen = PyList_Size (obj);
9936 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: PyList_Size failure\");
9939 len = (size_t) slen;
9940 r = malloc (sizeof (char *) * (len+1));
9942 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
9946 for (i = 0; i < len; ++i)
9947 r[i] = PyString_AsString (PyList_GetItem (obj, i));
9954 put_string_list (char * const * const argv)
9959 for (argc = 0; argv[argc] != NULL; ++argc)
9962 list = PyList_New (argc);
9963 for (i = 0; i < argc; ++i)
9964 PyList_SetItem (list, i, PyString_FromString (argv[i]));
9970 put_table (char * const * const argv)
9972 PyObject *list, *item;
9975 for (argc = 0; argv[argc] != NULL; ++argc)
9978 list = PyList_New (argc >> 1);
9979 for (i = 0; i < argc; i += 2) {
9980 item = PyTuple_New (2);
9981 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
9982 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
9983 PyList_SetItem (list, i >> 1, item);
9990 free_strings (char **argv)
9994 for (argc = 0; argv[argc] != NULL; ++argc)
10000 py_guestfs_create (PyObject *self, PyObject *args)
10004 g = guestfs_create ();
10006 PyErr_SetString (PyExc_RuntimeError,
10007 \"guestfs.create: failed to allocate handle\");
10010 guestfs_set_error_handler (g, NULL, NULL);
10011 /* This can return NULL, but in that case put_handle will have
10012 * set the Python error string.
10014 return put_handle (g);
10018 py_guestfs_close (PyObject *self, PyObject *args)
10023 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
10025 g = get_handle (py_g);
10029 Py_INCREF (Py_None);
10035 let emit_put_list_function typ =
10036 pr "static PyObject *\n";
10037 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
10039 pr " PyObject *list;\n";
10042 pr " list = PyList_New (%ss->len);\n" typ;
10043 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
10044 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
10045 pr " return list;\n";
10050 (* Structures, turned into Python dictionaries. *)
10053 pr "static PyObject *\n";
10054 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
10056 pr " PyObject *dict;\n";
10058 pr " dict = PyDict_New ();\n";
10062 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10063 pr " PyString_FromString (%s->%s));\n"
10066 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10067 pr " PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
10070 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10071 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
10073 | name, (FBytes|FUInt64) ->
10074 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10075 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
10078 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10079 pr " PyLong_FromLongLong (%s->%s));\n"
10082 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10083 pr " PyLong_FromUnsignedLong (%s->%s));\n"
10086 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10087 pr " PyLong_FromLong (%s->%s));\n"
10089 | name, FOptPercent ->
10090 pr " if (%s->%s >= 0)\n" typ name;
10091 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10092 pr " PyFloat_FromDouble ((double) %s->%s));\n"
10095 pr " Py_INCREF (Py_None);\n";
10096 pr " PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
10099 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10100 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
10102 pr " return dict;\n";
10108 (* Emit a put_TYPE_list function definition only if that function is used. *)
10111 | typ, (RStructListOnly | RStructAndList) ->
10112 (* generate the function for typ *)
10113 emit_put_list_function typ
10114 | typ, _ -> () (* empty *)
10115 ) (rstructs_used_by all_functions);
10117 (* Python wrapper functions. *)
10119 fun (name, style, _, _, _, _, _) ->
10120 pr "static PyObject *\n";
10121 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
10124 pr " PyObject *py_g;\n";
10125 pr " guestfs_h *g;\n";
10126 pr " PyObject *py_r;\n";
10129 match fst style with
10130 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
10131 | RInt64 _ -> pr " int64_t r;\n"; "-1"
10132 | RConstString _ | RConstOptString _ ->
10133 pr " const char *r;\n"; "NULL"
10134 | RString _ -> pr " char *r;\n"; "NULL"
10135 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
10136 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
10137 | RStructList (_, typ) ->
10138 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
10141 pr " size_t size;\n";
10146 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10147 | FileIn n | FileOut n ->
10148 pr " const char *%s;\n" n
10149 | OptString n -> pr " const char *%s;\n" n
10151 pr " const char *%s;\n" n;
10152 pr " Py_ssize_t %s_size;\n" n
10153 | StringList n | DeviceList n ->
10154 pr " PyObject *py_%s;\n" n;
10155 pr " char **%s;\n" n
10156 | Bool n -> pr " int %s;\n" n
10157 | Int n -> pr " int %s;\n" n
10158 | Int64 n -> pr " long long %s;\n" n
10163 (* Convert the parameters. *)
10164 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
10167 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10168 | FileIn _ | FileOut _ -> pr "s"
10169 | OptString _ -> pr "z"
10170 | StringList _ | DeviceList _ -> pr "O"
10171 | Bool _ -> pr "i" (* XXX Python has booleans? *)
10173 | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
10174 * emulate C's int/long/long long in Python?
10176 | BufferIn _ -> pr "s#"
10178 pr ":guestfs_%s\",\n" name;
10182 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10183 | FileIn n | FileOut n -> pr ", &%s" n
10184 | OptString n -> pr ", &%s" n
10185 | StringList n | DeviceList n -> pr ", &py_%s" n
10186 | Bool n -> pr ", &%s" n
10187 | Int n -> pr ", &%s" n
10188 | Int64 n -> pr ", &%s" n
10189 | BufferIn n -> pr ", &%s, &%s_size" n n
10193 pr " return NULL;\n";
10195 pr " g = get_handle (py_g);\n";
10198 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10199 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10201 | StringList n | DeviceList n ->
10202 pr " %s = get_string_list (py_%s);\n" n n;
10203 pr " if (!%s) return NULL;\n" n
10208 pr " r = guestfs_%s " name;
10209 generate_c_call_args ~handle:"g" style;
10214 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10215 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10217 | StringList n | DeviceList n ->
10218 pr " free (%s);\n" n
10221 pr " if (r == %s) {\n" error_code;
10222 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
10223 pr " return NULL;\n";
10227 (match fst style with
10229 pr " Py_INCREF (Py_None);\n";
10230 pr " py_r = Py_None;\n"
10232 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
10233 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
10234 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
10235 | RConstOptString _ ->
10237 pr " py_r = PyString_FromString (r);\n";
10239 pr " Py_INCREF (Py_None);\n";
10240 pr " py_r = Py_None;\n";
10243 pr " py_r = PyString_FromString (r);\n";
10246 pr " py_r = put_string_list (r);\n";
10247 pr " free_strings (r);\n"
10248 | RStruct (_, typ) ->
10249 pr " py_r = put_%s (r);\n" typ;
10250 pr " guestfs_free_%s (r);\n" typ
10251 | RStructList (_, typ) ->
10252 pr " py_r = put_%s_list (r);\n" typ;
10253 pr " guestfs_free_%s_list (r);\n" typ
10255 pr " py_r = put_table (r);\n";
10256 pr " free_strings (r);\n"
10258 pr " py_r = PyString_FromStringAndSize (r, size);\n";
10262 pr " return py_r;\n";
10267 (* Table of functions. *)
10268 pr "static PyMethodDef methods[] = {\n";
10269 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
10270 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
10272 fun (name, _, _, _, _, _, _) ->
10273 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
10276 pr " { NULL, NULL, 0, NULL }\n";
10280 (* Init function. *)
10283 initlibguestfsmod (void)
10285 static int initialized = 0;
10287 if (initialized) return;
10288 Py_InitModule ((char *) \"libguestfsmod\", methods);
10293 (* Generate Python module. *)
10294 and generate_python_py () =
10295 generate_header HashStyle LGPLv2plus;
10298 u\"\"\"Python bindings for libguestfs
10301 g = guestfs.GuestFS ()
10302 g.add_drive (\"guest.img\")
10304 parts = g.list_partitions ()
10306 The guestfs module provides a Python binding to the libguestfs API
10307 for examining and modifying virtual machine disk images.
10309 Amongst the things this is good for: making batch configuration
10310 changes to guests, getting disk used/free statistics (see also:
10311 virt-df), migrating between virtualization systems (see also:
10312 virt-p2v), performing partial backups, performing partial guest
10313 clones, cloning guests and changing registry/UUID/hostname info, and
10316 Libguestfs uses Linux kernel and qemu code, and can access any type of
10317 guest filesystem that Linux and qemu can, including but not limited
10318 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
10319 schemes, qcow, qcow2, vmdk.
10321 Libguestfs provides ways to enumerate guest storage (eg. partitions,
10322 LVs, what filesystem is in each LV, etc.). It can also run commands
10323 in the context of the guest. Also you can access filesystems over
10326 Errors which happen while using the API are turned into Python
10327 RuntimeError exceptions.
10329 To create a guestfs handle you usually have to perform the following
10332 # Create the handle, call add_drive at least once, and possibly
10333 # several times if the guest has multiple block devices:
10334 g = guestfs.GuestFS ()
10335 g.add_drive (\"guest.img\")
10337 # Launch the qemu subprocess and wait for it to become ready:
10340 # Now you can issue commands, for example:
10345 import libguestfsmod
10348 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
10350 def __init__ (self):
10351 \"\"\"Create a new libguestfs handle.\"\"\"
10352 self._o = libguestfsmod.create ()
10354 def __del__ (self):
10355 libguestfsmod.close (self._o)
10360 fun (name, style, _, flags, _, _, longdesc) ->
10361 pr " def %s " name;
10362 generate_py_call_args ~handle:"self" (snd style);
10365 if not (List.mem NotInDocs flags) then (
10366 let doc = replace_str longdesc "C<guestfs_" "C<g." in
10368 match fst style with
10369 | RErr | RInt _ | RInt64 _ | RBool _
10370 | RConstOptString _ | RConstString _
10371 | RString _ | RBufferOut _ -> doc
10373 doc ^ "\n\nThis function returns a list of strings."
10374 | RStruct (_, typ) ->
10375 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
10376 | RStructList (_, typ) ->
10377 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
10379 doc ^ "\n\nThis function returns a dictionary." in
10381 if List.mem ProtocolLimitWarning flags then
10382 doc ^ "\n\n" ^ protocol_limit_warning
10385 if List.mem DangerWillRobinson flags then
10386 doc ^ "\n\n" ^ danger_will_robinson
10389 match deprecation_notice flags with
10391 | Some txt -> doc ^ "\n\n" ^ txt in
10392 let doc = pod2text ~width:60 name doc in
10393 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
10394 let doc = String.concat "\n " doc in
10395 pr " u\"\"\"%s\"\"\"\n" doc;
10397 pr " return libguestfsmod.%s " name;
10398 generate_py_call_args ~handle:"self._o" (snd style);
10403 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
10404 and generate_py_call_args ~handle args =
10406 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10409 (* Useful if you need the longdesc POD text as plain text. Returns a
10412 * Because this is very slow (the slowest part of autogeneration),
10413 * we memoize the results.
10415 and pod2text ~width name longdesc =
10416 let key = width, name, longdesc in
10417 try Hashtbl.find pod2text_memo key
10419 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
10420 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
10422 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
10423 let chan = open_process_in cmd in
10424 let lines = ref [] in
10426 let line = input_line chan in
10427 if i = 1 then (* discard the first line of output *)
10430 let line = triml line in
10431 lines := line :: !lines;
10434 let lines = try loop 1 with End_of_file -> List.rev !lines in
10436 (match close_process_in chan with
10439 failwithf "pod2text: process exited with non-zero status (%d)" i
10440 | WSIGNALED i | WSTOPPED i ->
10441 failwithf "pod2text: process signalled or stopped by signal %d" i
10443 Hashtbl.add pod2text_memo key lines;
10444 pod2text_memo_updated ();
10447 (* Generate ruby bindings. *)
10448 and generate_ruby_c () =
10449 generate_header CStyle LGPLv2plus;
10453 #include <stdlib.h>
10457 #include \"guestfs.h\"
10459 #include \"extconf.h\"
10461 /* For Ruby < 1.9 */
10463 #define RARRAY_LEN(r) (RARRAY((r))->len)
10466 static VALUE m_guestfs; /* guestfs module */
10467 static VALUE c_guestfs; /* guestfs_h handle */
10468 static VALUE e_Error; /* used for all errors */
10470 static void ruby_guestfs_free (void *p)
10473 guestfs_close ((guestfs_h *) p);
10476 static VALUE ruby_guestfs_create (VALUE m)
10480 g = guestfs_create ();
10482 rb_raise (e_Error, \"failed to create guestfs handle\");
10484 /* Don't print error messages to stderr by default. */
10485 guestfs_set_error_handler (g, NULL, NULL);
10487 /* Wrap it, and make sure the close function is called when the
10488 * handle goes away.
10490 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
10493 static VALUE ruby_guestfs_close (VALUE gv)
10496 Data_Get_Struct (gv, guestfs_h, g);
10498 ruby_guestfs_free (g);
10499 DATA_PTR (gv) = NULL;
10507 fun (name, style, _, _, _, _, _) ->
10508 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
10509 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
10512 pr " guestfs_h *g;\n";
10513 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
10515 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
10521 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10522 | FileIn n | FileOut n ->
10523 pr " Check_Type (%sv, T_STRING);\n" n;
10524 pr " const char *%s = StringValueCStr (%sv);\n" n n;
10525 pr " if (!%s)\n" n;
10526 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10527 pr " \"%s\", \"%s\");\n" n name
10529 pr " Check_Type (%sv, T_STRING);\n" n;
10530 pr " const char *%s = RSTRING (%sv)->ptr;\n" n n;
10531 pr " if (!%s)\n" n;
10532 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10533 pr " \"%s\", \"%s\");\n" n name;
10534 pr " size_t %s_size = RSTRING (%sv)->len;\n" n n
10536 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
10537 | StringList n | DeviceList n ->
10538 pr " char **%s;\n" n;
10539 pr " Check_Type (%sv, T_ARRAY);\n" n;
10541 pr " size_t i, len;\n";
10542 pr " len = RARRAY_LEN (%sv);\n" n;
10543 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
10545 pr " for (i = 0; i < len; ++i) {\n";
10546 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
10547 pr " %s[i] = StringValueCStr (v);\n" n;
10549 pr " %s[len] = NULL;\n" n;
10552 pr " int %s = RTEST (%sv);\n" n n
10554 pr " int %s = NUM2INT (%sv);\n" n n
10556 pr " long long %s = NUM2LL (%sv);\n" n n
10561 match fst style with
10562 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
10563 | RInt64 _ -> pr " int64_t r;\n"; "-1"
10564 | RConstString _ | RConstOptString _ ->
10565 pr " const char *r;\n"; "NULL"
10566 | RString _ -> pr " char *r;\n"; "NULL"
10567 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
10568 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
10569 | RStructList (_, typ) ->
10570 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
10573 pr " size_t size;\n";
10577 pr " r = guestfs_%s " name;
10578 generate_c_call_args ~handle:"g" style;
10583 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10584 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10586 | StringList n | DeviceList n ->
10587 pr " free (%s);\n" n
10590 pr " if (r == %s)\n" error_code;
10591 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
10594 (match fst style with
10596 pr " return Qnil;\n"
10597 | RInt _ | RBool _ ->
10598 pr " return INT2NUM (r);\n"
10600 pr " return ULL2NUM (r);\n"
10601 | RConstString _ ->
10602 pr " return rb_str_new2 (r);\n";
10603 | RConstOptString _ ->
10605 pr " return rb_str_new2 (r);\n";
10607 pr " return Qnil;\n";
10609 pr " VALUE rv = rb_str_new2 (r);\n";
10611 pr " return rv;\n";
10613 pr " size_t i, len = 0;\n";
10614 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
10615 pr " VALUE rv = rb_ary_new2 (len);\n";
10616 pr " for (i = 0; r[i] != NULL; ++i) {\n";
10617 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
10618 pr " free (r[i]);\n";
10622 | RStruct (_, typ) ->
10623 let cols = cols_of_struct typ in
10624 generate_ruby_struct_code typ cols
10625 | RStructList (_, typ) ->
10626 let cols = cols_of_struct typ in
10627 generate_ruby_struct_list_code typ cols
10629 pr " VALUE rv = rb_hash_new ();\n";
10631 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
10632 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
10633 pr " free (r[i]);\n";
10634 pr " free (r[i+1]);\n";
10639 pr " VALUE rv = rb_str_new (r, size);\n";
10641 pr " return rv;\n";
10649 /* Initialize the module. */
10650 void Init__guestfs ()
10652 m_guestfs = rb_define_module (\"Guestfs\");
10653 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
10654 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
10656 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
10657 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
10660 (* Define the rest of the methods. *)
10662 fun (name, style, _, _, _, _, _) ->
10663 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
10664 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
10669 (* Ruby code to return a struct. *)
10670 and generate_ruby_struct_code typ cols =
10671 pr " VALUE rv = rb_hash_new ();\n";
10675 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
10677 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
10679 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
10680 | name, (FBytes|FUInt64) ->
10681 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10683 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
10685 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
10687 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
10688 | name, FOptPercent ->
10689 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
10690 | name, FChar -> (* XXX wrong? *)
10691 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10693 pr " guestfs_free_%s (r);\n" typ;
10696 (* Ruby code to return a struct list. *)
10697 and generate_ruby_struct_list_code typ cols =
10698 pr " VALUE rv = rb_ary_new2 (r->len);\n";
10700 pr " for (i = 0; i < r->len; ++i) {\n";
10701 pr " VALUE hv = rb_hash_new ();\n";
10705 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
10707 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
10709 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
10710 | name, (FBytes|FUInt64) ->
10711 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10713 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
10715 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
10717 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
10718 | name, FOptPercent ->
10719 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
10720 | name, FChar -> (* XXX wrong? *)
10721 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10723 pr " rb_ary_push (rv, hv);\n";
10725 pr " guestfs_free_%s_list (r);\n" typ;
10728 (* Generate Java bindings GuestFS.java file. *)
10729 and generate_java_java () =
10730 generate_header CStyle LGPLv2plus;
10733 package com.redhat.et.libguestfs;
10735 import java.util.HashMap;
10736 import com.redhat.et.libguestfs.LibGuestFSException;
10737 import com.redhat.et.libguestfs.PV;
10738 import com.redhat.et.libguestfs.VG;
10739 import com.redhat.et.libguestfs.LV;
10740 import com.redhat.et.libguestfs.Stat;
10741 import com.redhat.et.libguestfs.StatVFS;
10742 import com.redhat.et.libguestfs.IntBool;
10743 import com.redhat.et.libguestfs.Dirent;
10746 * The GuestFS object is a libguestfs handle.
10750 public class GuestFS {
10751 // Load the native code.
10753 System.loadLibrary (\"guestfs_jni\");
10757 * The native guestfs_h pointer.
10762 * Create a libguestfs handle.
10764 * @throws LibGuestFSException
10766 public GuestFS () throws LibGuestFSException
10770 private native long _create () throws LibGuestFSException;
10773 * Close a libguestfs handle.
10775 * You can also leave handles to be collected by the garbage
10776 * collector, but this method ensures that the resources used
10777 * by the handle are freed up immediately. If you call any
10778 * other methods after closing the handle, you will get an
10781 * @throws LibGuestFSException
10783 public void close () throws LibGuestFSException
10789 private native void _close (long g) throws LibGuestFSException;
10791 public void finalize () throws LibGuestFSException
10799 fun (name, style, _, flags, _, shortdesc, longdesc) ->
10800 if not (List.mem NotInDocs flags); then (
10801 let doc = replace_str longdesc "C<guestfs_" "C<g." in
10803 if List.mem ProtocolLimitWarning flags then
10804 doc ^ "\n\n" ^ protocol_limit_warning
10807 if List.mem DangerWillRobinson flags then
10808 doc ^ "\n\n" ^ danger_will_robinson
10811 match deprecation_notice flags with
10813 | Some txt -> doc ^ "\n\n" ^ txt in
10814 let doc = pod2text ~width:60 name doc in
10815 let doc = List.map ( (* RHBZ#501883 *)
10818 | nonempty -> nonempty
10820 let doc = String.concat "\n * " doc in
10823 pr " * %s\n" shortdesc;
10826 pr " * @throws LibGuestFSException\n";
10830 generate_java_prototype ~public:true ~semicolon:false name style;
10833 pr " if (g == 0)\n";
10834 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
10837 if fst style <> RErr then pr "return ";
10839 generate_java_call_args ~handle:"g" (snd style);
10843 generate_java_prototype ~privat:true ~native:true name style;
10850 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
10851 and generate_java_call_args ~handle args =
10853 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10856 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
10857 ?(semicolon=true) name style =
10858 if privat then pr "private ";
10859 if public then pr "public ";
10860 if native then pr "native ";
10863 (match fst style with
10864 | RErr -> pr "void ";
10865 | RInt _ -> pr "int ";
10866 | RInt64 _ -> pr "long ";
10867 | RBool _ -> pr "boolean ";
10868 | RConstString _ | RConstOptString _ | RString _
10869 | RBufferOut _ -> pr "String ";
10870 | RStringList _ -> pr "String[] ";
10871 | RStruct (_, typ) ->
10872 let name = java_name_of_struct typ in
10874 | RStructList (_, typ) ->
10875 let name = java_name_of_struct typ in
10877 | RHashtable _ -> pr "HashMap<String,String> ";
10880 if native then pr "_%s " name else pr "%s " name;
10882 let needs_comma = ref false in
10885 needs_comma := true
10891 if !needs_comma then pr ", ";
10892 needs_comma := true;
10896 | Device n | Dev_or_Path n
10905 | StringList n | DeviceList n ->
10916 pr " throws LibGuestFSException";
10917 if semicolon then pr ";"
10919 and generate_java_struct jtyp cols () =
10920 generate_header CStyle LGPLv2plus;
10923 package com.redhat.et.libguestfs;
10926 * Libguestfs %s structure.
10938 | name, FBuffer -> pr " public String %s;\n" name
10939 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
10940 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
10941 | name, FChar -> pr " public char %s;\n" name
10942 | name, FOptPercent ->
10943 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
10944 pr " public float %s;\n" name
10949 and generate_java_c () =
10950 generate_header CStyle LGPLv2plus;
10954 #include <stdlib.h>
10955 #include <string.h>
10957 #include \"com_redhat_et_libguestfs_GuestFS.h\"
10958 #include \"guestfs.h\"
10960 /* Note that this function returns. The exception is not thrown
10961 * until after the wrapper function returns.
10964 throw_exception (JNIEnv *env, const char *msg)
10967 cl = (*env)->FindClass (env,
10968 \"com/redhat/et/libguestfs/LibGuestFSException\");
10969 (*env)->ThrowNew (env, cl, msg);
10972 JNIEXPORT jlong JNICALL
10973 Java_com_redhat_et_libguestfs_GuestFS__1create
10974 (JNIEnv *env, jobject obj)
10978 g = guestfs_create ();
10980 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
10983 guestfs_set_error_handler (g, NULL, NULL);
10984 return (jlong) (long) g;
10987 JNIEXPORT void JNICALL
10988 Java_com_redhat_et_libguestfs_GuestFS__1close
10989 (JNIEnv *env, jobject obj, jlong jg)
10991 guestfs_h *g = (guestfs_h *) (long) jg;
10998 fun (name, style, _, _, _, _, _) ->
11000 (match fst style with
11001 | RErr -> pr "void ";
11002 | RInt _ -> pr "jint ";
11003 | RInt64 _ -> pr "jlong ";
11004 | RBool _ -> pr "jboolean ";
11005 | RConstString _ | RConstOptString _ | RString _
11006 | RBufferOut _ -> pr "jstring ";
11007 | RStruct _ | RHashtable _ ->
11009 | RStringList _ | RStructList _ ->
11010 pr "jobjectArray ";
11013 pr "Java_com_redhat_et_libguestfs_GuestFS_";
11014 pr "%s" (replace_str ("_" ^ name) "_" "_1");
11016 pr " (JNIEnv *env, jobject obj, jlong jg";
11020 | Device n | Dev_or_Path n
11026 pr ", jstring j%s" n
11028 pr ", jbyteArray j%s" n
11029 | StringList n | DeviceList n ->
11030 pr ", jobjectArray j%s" n
11032 pr ", jboolean j%s" n
11040 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
11041 let error_code, no_ret =
11042 match fst style with
11043 | RErr -> pr " int r;\n"; "-1", ""
11045 | RInt _ -> pr " int r;\n"; "-1", "0"
11046 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
11047 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
11048 | RConstOptString _ -> pr " const char *r;\n"; "NULL", "NULL"
11050 pr " jstring jr;\n";
11051 pr " char *r;\n"; "NULL", "NULL"
11053 pr " jobjectArray jr;\n";
11054 pr " int r_len;\n";
11055 pr " jclass cl;\n";
11056 pr " jstring jstr;\n";
11057 pr " char **r;\n"; "NULL", "NULL"
11058 | RStruct (_, typ) ->
11059 pr " jobject jr;\n";
11060 pr " jclass cl;\n";
11061 pr " jfieldID fl;\n";
11062 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
11063 | RStructList (_, typ) ->
11064 pr " jobjectArray jr;\n";
11065 pr " jclass cl;\n";
11066 pr " jfieldID fl;\n";
11067 pr " jobject jfl;\n";
11068 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
11069 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL"
11071 pr " jstring jr;\n";
11073 pr " size_t size;\n";
11078 | Device n | Dev_or_Path n
11084 pr " const char *%s;\n" n
11086 pr " jbyte *%s;\n" n;
11087 pr " size_t %s_size;\n" n
11088 | StringList n | DeviceList n ->
11089 pr " int %s_len;\n" n;
11090 pr " const char **%s;\n" n
11095 pr " int64_t %s;\n" n
11099 (match fst style with
11100 | RStringList _ | RStructList _ -> true
11101 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
11102 | RConstOptString _
11103 | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
11104 List.exists (function
11105 | StringList _ -> true
11106 | DeviceList _ -> true
11107 | _ -> false) (snd style) in
11113 (* Get the parameters. *)
11117 | Device n | Dev_or_Path n
11122 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
11124 (* This is completely undocumented, but Java null becomes
11125 * a NULL parameter.
11127 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
11129 pr " %s = (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n;
11130 pr " %s_size = (*env)->GetArrayLength (env, j%s);\n" n n
11131 | StringList n | DeviceList n ->
11132 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
11133 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
11134 pr " for (i = 0; i < %s_len; ++i) {\n" n;
11135 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11137 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
11139 pr " %s[%s_len] = NULL;\n" n n;
11143 pr " %s = j%s;\n" n n
11146 (* Make the call. *)
11147 pr " r = guestfs_%s " name;
11148 generate_c_call_args ~handle:"g" style;
11151 (* Release the parameters. *)
11155 | Device n | Dev_or_Path n
11160 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11162 pr " if (j%s)\n" n;
11163 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11165 pr " (*env)->ReleaseByteArrayElements (env, j%s, %s, 0);\n" n n
11166 | StringList n | DeviceList n ->
11167 pr " for (i = 0; i < %s_len; ++i) {\n" n;
11168 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11170 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
11172 pr " free (%s);\n" n
11178 (* Check for errors. *)
11179 pr " if (r == %s) {\n" error_code;
11180 pr " throw_exception (env, guestfs_last_error (g));\n";
11181 pr " return %s;\n" no_ret;
11184 (* Return value. *)
11185 (match fst style with
11187 | RInt _ -> pr " return (jint) r;\n"
11188 | RBool _ -> pr " return (jboolean) r;\n"
11189 | RInt64 _ -> pr " return (jlong) r;\n"
11190 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
11191 | RConstOptString _ ->
11192 pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
11194 pr " jr = (*env)->NewStringUTF (env, r);\n";
11198 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
11199 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
11200 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
11201 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
11202 pr " for (i = 0; i < r_len; ++i) {\n";
11203 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
11204 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
11205 pr " free (r[i]);\n";
11209 | RStruct (_, typ) ->
11210 let jtyp = java_name_of_struct typ in
11211 let cols = cols_of_struct typ in
11212 generate_java_struct_return typ jtyp cols
11213 | RStructList (_, typ) ->
11214 let jtyp = java_name_of_struct typ in
11215 let cols = cols_of_struct typ in
11216 generate_java_struct_list_return typ jtyp cols
11219 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
11220 pr " return NULL;\n"
11222 pr " jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
11231 and generate_java_struct_return typ jtyp cols =
11232 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11233 pr " jr = (*env)->AllocObject (env, cl);\n";
11237 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11238 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
11241 pr " char s[33];\n";
11242 pr " memcpy (s, r->%s, 32);\n" name;
11243 pr " s[32] = 0;\n";
11244 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11245 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11249 pr " int len = r->%s_len;\n" name;
11250 pr " char s[len+1];\n";
11251 pr " memcpy (s, r->%s, len);\n" name;
11252 pr " s[len] = 0;\n";
11253 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11254 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11256 | name, (FBytes|FUInt64|FInt64) ->
11257 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11258 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11259 | name, (FUInt32|FInt32) ->
11260 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11261 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11262 | name, FOptPercent ->
11263 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11264 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
11266 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11267 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11272 and generate_java_struct_list_return typ jtyp cols =
11273 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11274 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
11275 pr " for (i = 0; i < r->len; ++i) {\n";
11276 pr " jfl = (*env)->AllocObject (env, cl);\n";
11280 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11281 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
11284 pr " char s[33];\n";
11285 pr " memcpy (s, r->val[i].%s, 32);\n" name;
11286 pr " s[32] = 0;\n";
11287 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11288 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11292 pr " int len = r->val[i].%s_len;\n" name;
11293 pr " char s[len+1];\n";
11294 pr " memcpy (s, r->val[i].%s, len);\n" name;
11295 pr " s[len] = 0;\n";
11296 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11297 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11299 | name, (FBytes|FUInt64|FInt64) ->
11300 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11301 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11302 | name, (FUInt32|FInt32) ->
11303 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11304 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11305 | name, FOptPercent ->
11306 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11307 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
11309 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11310 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11312 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
11314 pr " guestfs_free_%s_list (r);\n" typ;
11317 and generate_java_makefile_inc () =
11318 generate_header HashStyle GPLv2plus;
11320 pr "java_built_sources = \\\n";
11323 pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
11325 pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
11327 and generate_haskell_hs () =
11328 generate_header HaskellStyle LGPLv2plus;
11330 (* XXX We only know how to generate partial FFI for Haskell
11331 * at the moment. Please help out!
11333 let can_generate style =
11337 | RInt64 _, _ -> true
11339 | RConstString _, _
11340 | RConstOptString _, _
11346 | RBufferOut _, _ -> false in
11349 {-# INCLUDE <guestfs.h> #-}
11350 {-# LANGUAGE ForeignFunctionInterface #-}
11355 (* List out the names of the actions we want to export. *)
11357 fun (name, style, _, _, _, _, _) ->
11358 if can_generate style then pr ",\n %s" name
11364 -- Unfortunately some symbols duplicate ones already present
11365 -- in Prelude. We don't know which, so we hard-code a list
11367 import Prelude hiding (truncate)
11371 import Foreign.C.Types
11373 import Control.Exception
11374 import Data.Typeable
11376 data GuestfsS = GuestfsS -- represents the opaque C struct
11377 type GuestfsP = Ptr GuestfsS -- guestfs_h *
11378 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
11380 -- XXX define properly later XXX
11384 data IntBool = IntBool
11386 data StatVFS = StatVFS
11387 data Hashtable = Hashtable
11389 foreign import ccall unsafe \"guestfs_create\" c_create
11391 foreign import ccall unsafe \"&guestfs_close\" c_close
11392 :: FunPtr (GuestfsP -> IO ())
11393 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
11394 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
11396 create :: IO GuestfsH
11399 c_set_error_handler p nullPtr nullPtr
11400 h <- newForeignPtr c_close p
11403 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
11404 :: GuestfsP -> IO CString
11406 -- last_error :: GuestfsH -> IO (Maybe String)
11407 -- last_error h = do
11408 -- str <- withForeignPtr h (\\p -> c_last_error p)
11409 -- maybePeek peekCString str
11411 last_error :: GuestfsH -> IO (String)
11413 str <- withForeignPtr h (\\p -> c_last_error p)
11414 if (str == nullPtr)
11415 then return \"no error\"
11416 else peekCString str
11420 (* Generate wrappers for each foreign function. *)
11422 fun (name, style, _, _, _, _, _) ->
11423 if can_generate style then (
11424 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
11426 generate_haskell_prototype ~handle:"GuestfsP" style;
11430 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
11432 pr "%s %s = do\n" name
11433 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
11435 (* Convert pointer arguments using with* functions. *)
11440 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
11441 pr "withCString %s $ \\%s -> " n n
11443 pr "withCStringLen %s $ \\(%s, %s_size) -> " n n n
11444 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
11445 | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
11446 | Bool _ | Int _ | Int64 _ -> ()
11448 (* Convert integer arguments. *)
11452 | Bool n -> sprintf "(fromBool %s)" n
11453 | Int n -> sprintf "(fromIntegral %s)" n
11454 | Int64 n -> sprintf "(fromIntegral %s)" n
11455 | FileIn n | FileOut n
11456 | Pathname n | Device n | Dev_or_Path n
11457 | String n | OptString n
11458 | StringList n | DeviceList n
11460 | BufferIn n -> sprintf "%s (fromIntegral %s_size)" n n
11462 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
11463 (String.concat " " ("p" :: args));
11464 (match fst style with
11465 | RErr | RInt _ | RInt64 _ | RBool _ ->
11466 pr " if (r == -1)\n";
11468 pr " err <- last_error h\n";
11470 | RConstString _ | RConstOptString _ | RString _
11471 | RStringList _ | RStruct _
11472 | RStructList _ | RHashtable _ | RBufferOut _ ->
11473 pr " if (r == nullPtr)\n";
11475 pr " err <- last_error h\n";
11478 (match fst style with
11480 pr " else return ()\n"
11482 pr " else return (fromIntegral r)\n"
11484 pr " else return (fromIntegral r)\n"
11486 pr " else return (toBool r)\n"
11488 | RConstOptString _
11495 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
11501 and generate_haskell_prototype ~handle ?(hs = false) style =
11502 pr "%s -> " handle;
11503 let string = if hs then "String" else "CString" in
11504 let int = if hs then "Int" else "CInt" in
11505 let bool = if hs then "Bool" else "CInt" in
11506 let int64 = if hs then "Integer" else "Int64" in
11510 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _ ->
11513 if hs then pr "String"
11514 else pr "CString -> CInt"
11515 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
11516 | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
11517 | Bool _ -> pr "%s" bool
11518 | Int _ -> pr "%s" int
11519 | Int64 _ -> pr "%s" int
11520 | FileIn _ -> pr "%s" string
11521 | FileOut _ -> pr "%s" string
11526 (match fst style with
11527 | RErr -> if not hs then pr "CInt"
11528 | RInt _ -> pr "%s" int
11529 | RInt64 _ -> pr "%s" int64
11530 | RBool _ -> pr "%s" bool
11531 | RConstString _ -> pr "%s" string
11532 | RConstOptString _ -> pr "Maybe %s" string
11533 | RString _ -> pr "%s" string
11534 | RStringList _ -> pr "[%s]" string
11535 | RStruct (_, typ) ->
11536 let name = java_name_of_struct typ in
11538 | RStructList (_, typ) ->
11539 let name = java_name_of_struct typ in
11541 | RHashtable _ -> pr "Hashtable"
11542 | RBufferOut _ -> pr "%s" string
11546 and generate_csharp () =
11547 generate_header CPlusPlusStyle LGPLv2plus;
11549 (* XXX Make this configurable by the C# assembly users. *)
11550 let library = "libguestfs.so.0" in
11553 // These C# bindings are highly experimental at present.
11555 // Firstly they only work on Linux (ie. Mono). In order to get them
11556 // to work on Windows (ie. .Net) you would need to port the library
11557 // itself to Windows first.
11559 // The second issue is that some calls are known to be incorrect and
11560 // can cause Mono to segfault. Particularly: calls which pass or
11561 // return string[], or return any structure value. This is because
11562 // we haven't worked out the correct way to do this from C#.
11564 // The third issue is that when compiling you get a lot of warnings.
11565 // We are not sure whether the warnings are important or not.
11567 // Fourthly we do not routinely build or test these bindings as part
11568 // of the make && make check cycle, which means that regressions might
11571 // Suggestions and patches are welcome.
11575 // gmcs Libguestfs.cs
11576 // mono Libguestfs.exe
11578 // (You'll probably want to add a Test class / static main function
11579 // otherwise this won't do anything useful).
11583 using System.Runtime.InteropServices;
11584 using System.Runtime.Serialization;
11585 using System.Collections;
11589 class Error : System.ApplicationException
11591 public Error (string message) : base (message) {}
11592 protected Error (SerializationInfo info, StreamingContext context) {}
11599 [DllImport (\"%s\")]
11600 static extern IntPtr guestfs_create ();
11604 _handle = guestfs_create ();
11605 if (_handle == IntPtr.Zero)
11606 throw new Error (\"could not create guestfs handle\");
11609 [DllImport (\"%s\")]
11610 static extern void guestfs_close (IntPtr h);
11614 guestfs_close (_handle);
11617 [DllImport (\"%s\")]
11618 static extern string guestfs_last_error (IntPtr h);
11620 " library library library;
11622 (* Generate C# structure bindings. We prefix struct names with
11623 * underscore because C# cannot have conflicting struct names and
11624 * method names (eg. "class stat" and "stat").
11628 pr " [StructLayout (LayoutKind.Sequential)]\n";
11629 pr " public class _%s {\n" typ;
11632 | name, FChar -> pr " char %s;\n" name
11633 | name, FString -> pr " string %s;\n" name
11635 pr " uint %s_len;\n" name;
11636 pr " string %s;\n" name
11638 pr " [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
11639 pr " string %s;\n" name
11640 | name, FUInt32 -> pr " uint %s;\n" name
11641 | name, FInt32 -> pr " int %s;\n" name
11642 | name, (FUInt64|FBytes) -> pr " ulong %s;\n" name
11643 | name, FInt64 -> pr " long %s;\n" name
11644 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
11650 (* Generate C# function bindings. *)
11652 fun (name, style, _, _, _, shortdesc, _) ->
11653 let rec csharp_return_type () =
11654 match fst style with
11656 | RBool n -> "bool"
11658 | RInt64 n -> "long"
11660 | RConstOptString n
11662 | RBufferOut n -> "string"
11663 | RStruct (_,n) -> "_" ^ n
11664 | RHashtable n -> "Hashtable"
11665 | RStringList n -> "string[]"
11666 | RStructList (_,n) -> sprintf "_%s[]" n
11668 and c_return_type () =
11669 match fst style with
11673 | RInt64 _ -> "long"
11675 | RConstOptString _
11677 | RBufferOut _ -> "string"
11678 | RStruct (_,n) -> "_" ^ n
11680 | RStringList _ -> "string[]"
11681 | RStructList (_,n) -> sprintf "_%s[]" n
11683 and c_error_comparison () =
11684 match fst style with
11688 | RInt64 _ -> "== -1"
11690 | RConstOptString _
11696 | RStructList (_,_) -> "== null"
11698 and generate_extern_prototype () =
11699 pr " static extern %s guestfs_%s (IntPtr h"
11700 (c_return_type ()) name;
11703 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11704 | FileIn n | FileOut n
11707 pr ", [In] string %s" n
11708 | StringList n | DeviceList n ->
11709 pr ", [In] string[] %s" n
11719 and generate_public_prototype () =
11720 pr " public %s %s (" (csharp_return_type ()) name;
11721 let comma = ref false in
11723 if !comma then pr ", ";
11728 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11729 | FileIn n | FileOut n
11732 next (); pr "string %s" n
11733 | StringList n | DeviceList n ->
11734 next (); pr "string[] %s" n
11736 next (); pr "bool %s" n
11738 next (); pr "int %s" n
11740 next (); pr "long %s" n
11744 and generate_call () =
11745 pr "guestfs_%s (_handle" name;
11746 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
11750 pr " [DllImport (\"%s\")]\n" library;
11751 generate_extern_prototype ();
11753 pr " /// <summary>\n";
11754 pr " /// %s\n" shortdesc;
11755 pr " /// </summary>\n";
11756 generate_public_prototype ();
11758 pr " %s r;\n" (c_return_type ());
11761 pr " if (r %s)\n" (c_error_comparison ());
11762 pr " throw new Error (guestfs_last_error (_handle));\n";
11763 (match fst style with
11766 pr " return r != 0 ? true : false;\n"
11768 pr " Hashtable rr = new Hashtable ();\n";
11769 pr " for (size_t i = 0; i < r.Length; i += 2)\n";
11770 pr " rr.Add (r[i], r[i+1]);\n";
11772 | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
11773 | RString _ | RBufferOut _ | RStruct _ | RStringList _
11779 ) all_functions_sorted;
11785 and generate_bindtests () =
11786 generate_header CStyle LGPLv2plus;
11790 #include <stdlib.h>
11791 #include <inttypes.h>
11792 #include <string.h>
11794 #include \"guestfs.h\"
11795 #include \"guestfs-internal.h\"
11796 #include \"guestfs-internal-actions.h\"
11797 #include \"guestfs_protocol.h\"
11799 #define error guestfs_error
11800 #define safe_calloc guestfs_safe_calloc
11801 #define safe_malloc guestfs_safe_malloc
11804 print_strings (char *const *argv)
11809 for (argc = 0; argv[argc] != NULL; ++argc) {
11810 if (argc > 0) printf (\", \");
11811 printf (\"\\\"%%s\\\"\", argv[argc]);
11816 /* The test0 function prints its parameters to stdout. */
11820 match test_functions with
11821 | [] -> assert false
11822 | test0 :: tests -> test0, tests in
11825 let (name, style, _, _, _, _, _) = test0 in
11826 generate_prototype ~extern:false ~semicolon:false ~newline:true
11827 ~handle:"g" ~prefix:"guestfs__" name style;
11832 | Device n | Dev_or_Path n
11836 | Key n -> pr " printf (\"%%s\\n\", %s);\n" n
11840 pr " for (i = 0; i < %s_size; ++i)\n" n;
11841 pr " printf (\"<%%02x>\", %s[i]);\n" n;
11842 pr " printf (\"\\n\");\n";
11844 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
11845 | StringList n | DeviceList n -> pr " print_strings (%s);\n" n
11846 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
11847 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
11848 | Int64 n -> pr " printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
11850 pr " /* Java changes stdout line buffering so we need this: */\n";
11851 pr " fflush (stdout);\n";
11857 fun (name, style, _, _, _, _, _) ->
11858 if String.sub name (String.length name - 3) 3 <> "err" then (
11859 pr "/* Test normal return. */\n";
11860 generate_prototype ~extern:false ~semicolon:false ~newline:true
11861 ~handle:"g" ~prefix:"guestfs__" name style;
11863 (match fst style with
11868 pr " sscanf (val, \"%%d\", &r);\n";
11871 pr " int64_t r;\n";
11872 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
11875 pr " return STREQ (val, \"true\");\n"
11877 | RConstOptString _ ->
11878 (* Can't return the input string here. Return a static
11879 * string so we ensure we get a segfault if the caller
11880 * tries to free it.
11882 pr " return \"static string\";\n"
11884 pr " return strdup (val);\n"
11886 pr " char **strs;\n";
11888 pr " sscanf (val, \"%%d\", &n);\n";
11889 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
11890 pr " for (i = 0; i < n; ++i) {\n";
11891 pr " strs[i] = safe_malloc (g, 16);\n";
11892 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
11894 pr " strs[n] = NULL;\n";
11895 pr " return strs;\n"
11896 | RStruct (_, typ) ->
11897 pr " struct guestfs_%s *r;\n" typ;
11898 pr " r = safe_calloc (g, sizeof *r, 1);\n";
11900 | RStructList (_, typ) ->
11901 pr " struct guestfs_%s_list *r;\n" typ;
11902 pr " r = safe_calloc (g, sizeof *r, 1);\n";
11903 pr " sscanf (val, \"%%d\", &r->len);\n";
11904 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
11907 pr " char **strs;\n";
11909 pr " sscanf (val, \"%%d\", &n);\n";
11910 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
11911 pr " for (i = 0; i < n; ++i) {\n";
11912 pr " strs[i*2] = safe_malloc (g, 16);\n";
11913 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
11914 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
11915 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
11917 pr " strs[n*2] = NULL;\n";
11918 pr " return strs;\n"
11920 pr " return strdup (val);\n"
11925 pr "/* Test error return. */\n";
11926 generate_prototype ~extern:false ~semicolon:false ~newline:true
11927 ~handle:"g" ~prefix:"guestfs__" name style;
11929 pr " error (g, \"error\");\n";
11930 (match fst style with
11931 | RErr | RInt _ | RInt64 _ | RBool _ ->
11933 | RConstString _ | RConstOptString _
11934 | RString _ | RStringList _ | RStruct _
11938 pr " return NULL;\n"
11945 and generate_ocaml_bindtests () =
11946 generate_header OCamlStyle GPLv2plus;
11950 let g = Guestfs.create () in
11954 String.concat " " (
11957 | CallString s -> "\"" ^ s ^ "\""
11958 | CallOptString None -> "None"
11959 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
11960 | CallStringList xs ->
11961 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
11962 | CallInt i when i >= 0 -> string_of_int i
11963 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
11964 | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
11965 | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
11966 | CallBool b -> string_of_bool b
11967 | CallBuffer s -> sprintf "%S" s
11972 generate_lang_bindtests (
11973 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
11976 pr "print_endline \"EOF\"\n"
11978 and generate_perl_bindtests () =
11979 pr "#!/usr/bin/perl -w\n";
11980 generate_header HashStyle GPLv2plus;
11987 my $g = Sys::Guestfs->new ();
11991 String.concat ", " (
11994 | CallString s -> "\"" ^ s ^ "\""
11995 | CallOptString None -> "undef"
11996 | CallOptString (Some s) -> sprintf "\"%s\"" s
11997 | CallStringList xs ->
11998 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
11999 | CallInt i -> string_of_int i
12000 | CallInt64 i -> Int64.to_string i
12001 | CallBool b -> if b then "1" else "0"
12002 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12007 generate_lang_bindtests (
12008 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
12011 pr "print \"EOF\\n\"\n"
12013 and generate_python_bindtests () =
12014 generate_header HashStyle GPLv2plus;
12019 g = guestfs.GuestFS ()
12023 String.concat ", " (
12026 | CallString s -> "\"" ^ s ^ "\""
12027 | CallOptString None -> "None"
12028 | CallOptString (Some s) -> sprintf "\"%s\"" s
12029 | CallStringList xs ->
12030 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12031 | CallInt i -> string_of_int i
12032 | CallInt64 i -> Int64.to_string i
12033 | CallBool b -> if b then "1" else "0"
12034 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12039 generate_lang_bindtests (
12040 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
12043 pr "print \"EOF\"\n"
12045 and generate_ruby_bindtests () =
12046 generate_header HashStyle GPLv2plus;
12051 g = Guestfs::create()
12055 String.concat ", " (
12058 | CallString s -> "\"" ^ s ^ "\""
12059 | CallOptString None -> "nil"
12060 | CallOptString (Some s) -> sprintf "\"%s\"" s
12061 | CallStringList xs ->
12062 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12063 | CallInt i -> string_of_int i
12064 | CallInt64 i -> Int64.to_string i
12065 | CallBool b -> string_of_bool b
12066 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12071 generate_lang_bindtests (
12072 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
12075 pr "print \"EOF\\n\"\n"
12077 and generate_java_bindtests () =
12078 generate_header CStyle GPLv2plus;
12081 import com.redhat.et.libguestfs.*;
12083 public class Bindtests {
12084 public static void main (String[] argv)
12087 GuestFS g = new GuestFS ();
12091 String.concat ", " (
12094 | CallString s -> "\"" ^ s ^ "\""
12095 | CallOptString None -> "null"
12096 | CallOptString (Some s) -> sprintf "\"%s\"" s
12097 | CallStringList xs ->
12099 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
12100 | CallInt i -> string_of_int i
12101 | CallInt64 i -> Int64.to_string i
12102 | CallBool b -> string_of_bool b
12104 "new byte[] { " ^ String.concat "," (
12105 map_chars (fun c -> string_of_int (Char.code c)) s
12111 generate_lang_bindtests (
12112 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
12116 System.out.println (\"EOF\");
12118 catch (Exception exn) {
12119 System.err.println (exn);
12126 and generate_haskell_bindtests () =
12127 generate_header HaskellStyle GPLv2plus;
12130 module Bindtests where
12131 import qualified Guestfs
12134 g <- Guestfs.create
12138 String.concat " " (
12141 | CallString s -> "\"" ^ s ^ "\""
12142 | CallOptString None -> "Nothing"
12143 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
12144 | CallStringList xs ->
12145 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12146 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
12147 | CallInt i -> string_of_int i
12148 | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
12149 | CallInt64 i -> Int64.to_string i
12150 | CallBool true -> "True"
12151 | CallBool false -> "False"
12152 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12157 generate_lang_bindtests (
12158 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
12161 pr " putStrLn \"EOF\"\n"
12163 (* Language-independent bindings tests - we do it this way to
12164 * ensure there is parity in testing bindings across all languages.
12166 and generate_lang_bindtests call =
12167 call "test0" [CallString "abc"; CallOptString (Some "def");
12168 CallStringList []; CallBool false;
12169 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12170 CallBuffer "abc\000abc"];
12171 call "test0" [CallString "abc"; CallOptString None;
12172 CallStringList []; CallBool false;
12173 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12174 CallBuffer "abc\000abc"];
12175 call "test0" [CallString ""; CallOptString (Some "def");
12176 CallStringList []; CallBool false;
12177 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12178 CallBuffer "abc\000abc"];
12179 call "test0" [CallString ""; CallOptString (Some "");
12180 CallStringList []; CallBool false;
12181 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12182 CallBuffer "abc\000abc"];
12183 call "test0" [CallString "abc"; CallOptString (Some "def");
12184 CallStringList ["1"]; CallBool false;
12185 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12186 CallBuffer "abc\000abc"];
12187 call "test0" [CallString "abc"; CallOptString (Some "def");
12188 CallStringList ["1"; "2"]; CallBool false;
12189 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12190 CallBuffer "abc\000abc"];
12191 call "test0" [CallString "abc"; CallOptString (Some "def");
12192 CallStringList ["1"]; CallBool true;
12193 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12194 CallBuffer "abc\000abc"];
12195 call "test0" [CallString "abc"; CallOptString (Some "def");
12196 CallStringList ["1"]; CallBool false;
12197 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456";
12198 CallBuffer "abc\000abc"];
12199 call "test0" [CallString "abc"; CallOptString (Some "def");
12200 CallStringList ["1"]; CallBool false;
12201 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456";
12202 CallBuffer "abc\000abc"];
12203 call "test0" [CallString "abc"; CallOptString (Some "def");
12204 CallStringList ["1"]; CallBool false;
12205 CallInt 1; CallInt64 1L; CallString "123"; CallString "456";
12206 CallBuffer "abc\000abc"];
12207 call "test0" [CallString "abc"; CallOptString (Some "def");
12208 CallStringList ["1"]; CallBool false;
12209 CallInt 2; CallInt64 2L; CallString "123"; CallString "456";
12210 CallBuffer "abc\000abc"];
12211 call "test0" [CallString "abc"; CallOptString (Some "def");
12212 CallStringList ["1"]; CallBool false;
12213 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456";
12214 CallBuffer "abc\000abc"];
12215 call "test0" [CallString "abc"; CallOptString (Some "def");
12216 CallStringList ["1"]; CallBool false;
12217 CallInt 0; CallInt64 0L; CallString ""; CallString "";
12218 CallBuffer "abc\000abc"]
12220 (* XXX Add here tests of the return and error functions. *)
12222 and generate_max_proc_nr () =
12223 pr "%d\n" max_proc_nr
12225 let output_to filename k =
12226 let filename_new = filename ^ ".new" in
12227 chan := open_out filename_new;
12230 chan := Pervasives.stdout;
12232 (* Is the new file different from the current file? *)
12233 if Sys.file_exists filename && files_equal filename filename_new then
12234 unlink filename_new (* same, so skip it *)
12236 (* different, overwrite old one *)
12237 (try chmod filename 0o644 with Unix_error _ -> ());
12238 rename filename_new filename;
12239 chmod filename 0o444;
12240 printf "written %s\n%!" filename;
12243 let perror msg = function
12244 | Unix_error (err, _, _) ->
12245 eprintf "%s: %s\n" msg (error_message err)
12247 eprintf "%s: %s\n" msg (Printexc.to_string exn)
12249 (* Main program. *)
12252 try openfile "HACKING" [O_RDWR] 0
12254 | Unix_error (ENOENT, _, _) ->
12256 You are probably running this from the wrong directory.
12257 Run it from the top source directory using the command
12262 perror "open: HACKING" exn;
12265 (* Acquire a lock so parallel builds won't try to run the generator
12266 * twice at the same time. Subsequent builds will wait for the first
12267 * one to finish. Note the lock is released implicitly when the
12270 (try lockf lock_fd F_LOCK 1
12272 perror "lock: HACKING" exn;
12275 check_functions ();
12277 output_to "src/guestfs_protocol.x" generate_xdr;
12278 output_to "src/guestfs-structs.h" generate_structs_h;
12279 output_to "src/guestfs-actions.h" generate_actions_h;
12280 output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
12281 output_to "src/actions.c" generate_client_actions;
12282 output_to "src/bindtests.c" generate_bindtests;
12283 output_to "src/guestfs-structs.pod" generate_structs_pod;
12284 output_to "src/guestfs-actions.pod" generate_actions_pod;
12285 output_to "src/guestfs-availability.pod" generate_availability_pod;
12286 output_to "src/MAX_PROC_NR" generate_max_proc_nr;
12287 output_to "src/libguestfs.syms" generate_linker_script;
12288 output_to "daemon/actions.h" generate_daemon_actions_h;
12289 output_to "daemon/stubs.c" generate_daemon_actions;
12290 output_to "daemon/names.c" generate_daemon_names;
12291 output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
12292 output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
12293 output_to "capitests/tests.c" generate_tests;
12294 output_to "fish/cmds.c" generate_fish_cmds;
12295 output_to "fish/completion.c" generate_fish_completion;
12296 output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
12297 output_to "ocaml/guestfs.mli" generate_ocaml_mli;
12298 output_to "ocaml/guestfs.ml" generate_ocaml_ml;
12299 output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
12300 output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
12301 output_to "perl/Guestfs.xs" generate_perl_xs;
12302 output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
12303 output_to "perl/bindtests.pl" generate_perl_bindtests;
12304 output_to "python/guestfs-py.c" generate_python_c;
12305 output_to "python/guestfs.py" generate_python_py;
12306 output_to "python/bindtests.py" generate_python_bindtests;
12307 output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
12308 output_to "ruby/bindtests.rb" generate_ruby_bindtests;
12309 output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
12313 let cols = cols_of_struct typ in
12314 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
12315 output_to filename (generate_java_struct jtyp cols);
12318 output_to "java/Makefile.inc" generate_java_makefile_inc;
12319 output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
12320 output_to "java/Bindtests.java" generate_java_bindtests;
12321 output_to "haskell/Guestfs.hs" generate_haskell_hs;
12322 output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
12323 output_to "csharp/Libguestfs.cs" generate_csharp;
12325 (* Always generate this file last, and unconditionally. It's used
12326 * by the Makefile to know when we must re-run the generator.
12328 let chan = open_out "src/stamp-generator" in
12329 fprintf chan "1\n";
12332 printf "generated %d lines of code\n" !lines