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 *)
195 | Progress (* function can generate progress messages *)
198 | FishOutputOctal (* for int return, print in octal *)
199 | FishOutputHexadecimal (* for int return, print in hex *)
201 (* You can supply zero or as many tests as you want per API call.
203 * Note that the test environment has 3 block devices, of size 500MB,
204 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
205 * a fourth ISO block device with some known files on it (/dev/sdd).
207 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
208 * Number of cylinders was 63 for IDE emulated disks with precisely
209 * the same size. How exactly this is calculated is a mystery.
211 * The ISO block device (/dev/sdd) comes from images/test.iso.
213 * To be able to run the tests in a reasonable amount of time,
214 * the virtual machine and block devices are reused between tests.
215 * So don't try testing kill_subprocess :-x
217 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
219 * Don't assume anything about the previous contents of the block
220 * devices. Use 'Init*' to create some initial scenarios.
222 * You can add a prerequisite clause to any individual test. This
223 * is a run-time check, which, if it fails, causes the test to be
224 * skipped. Useful if testing a command which might not work on
225 * all variations of libguestfs builds. A test that has prerequisite
226 * of 'Always' is run unconditionally.
228 * In addition, packagers can skip individual tests by setting the
229 * environment variables: eg:
230 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
231 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
233 type tests = (test_init * test_prereq * test) list
235 (* Run the command sequence and just expect nothing to fail. *)
238 (* Run the command sequence and expect the output of the final
239 * command to be the string.
241 | TestOutput of seq * string
243 (* Run the command sequence and expect the output of the final
244 * command to be the list of strings.
246 | TestOutputList of seq * string list
248 (* Run the command sequence and expect the output of the final
249 * command to be the list of block devices (could be either
250 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
251 * character of each string).
253 | TestOutputListOfDevices of seq * string list
255 (* Run the command sequence and expect the output of the final
256 * command to be the integer.
258 | TestOutputInt of seq * int
260 (* Run the command sequence and expect the output of the final
261 * command to be <op> <int>, eg. ">=", "1".
263 | TestOutputIntOp of seq * string * int
265 (* Run the command sequence and expect the output of the final
266 * command to be a true value (!= 0 or != NULL).
268 | TestOutputTrue of seq
270 (* Run the command sequence and expect the output of the final
271 * command to be a false value (== 0 or == NULL, but not an error).
273 | TestOutputFalse of seq
275 (* Run the command sequence and expect the output of the final
276 * command to be a list of the given length (but don't care about
279 | TestOutputLength of seq * int
281 (* Run the command sequence and expect the output of the final
282 * command to be a buffer (RBufferOut), ie. string + size.
284 | TestOutputBuffer of seq * string
286 (* Run the command sequence and expect the output of the final
287 * command to be a structure.
289 | TestOutputStruct of seq * test_field_compare list
291 (* Run the command sequence and expect the final command (only)
294 | TestLastFail of seq
296 and test_field_compare =
297 | CompareWithInt of string * int
298 | CompareWithIntOp of string * string * int
299 | CompareWithString of string * string
300 | CompareFieldsIntEq of string * string
301 | CompareFieldsStrEq of string * string
303 (* Test prerequisites. *)
305 (* Test always runs. *)
308 (* Test is currently disabled - eg. it fails, or it tests some
309 * unimplemented feature.
313 (* 'string' is some C code (a function body) that should return
314 * true or false. The test will run if the code returns true.
318 (* As for 'If' but the test runs _unless_ the code returns true. *)
321 (* Run the test only if 'string' is available in the daemon. *)
322 | IfAvailable of string
324 (* Some initial scenarios for testing. *)
326 (* Do nothing, block devices could contain random stuff including
327 * LVM PVs, and some filesystems might be mounted. This is usually
332 (* Block devices are empty and no filesystems are mounted. *)
335 (* /dev/sda contains a single partition /dev/sda1, with random
336 * content. /dev/sdb and /dev/sdc may have random content.
341 (* /dev/sda contains a single partition /dev/sda1, which is formatted
342 * as ext2, empty [except for lost+found] and mounted on /.
343 * /dev/sdb and /dev/sdc may have random content.
349 * /dev/sda1 (is a PV):
350 * /dev/VG/LV (size 8MB):
351 * formatted as ext2, empty [except for lost+found], mounted on /
352 * /dev/sdb and /dev/sdc may have random content.
356 (* /dev/sdd (the ISO, see images/ directory in source)
361 (* Sequence of commands for testing. *)
363 and cmd = string list
365 (* Note about long descriptions: When referring to another
366 * action, use the format C<guestfs_other> (ie. the full name of
367 * the C function). This will be replaced as appropriate in other
370 * Apart from that, long descriptions are just perldoc paragraphs.
373 (* Generate a random UUID (used in tests). *)
375 let chan = open_process_in "uuidgen" in
376 let uuid = input_line chan in
377 (match close_process_in chan with
380 failwith "uuidgen: process exited with non-zero status"
381 | WSIGNALED _ | WSTOPPED _ ->
382 failwith "uuidgen: process signalled or stopped by signal"
386 (* These test functions are used in the language binding tests. *)
388 let test_all_args = [
391 StringList "strlist";
400 let test_all_rets = [
401 (* except for RErr, which is tested thoroughly elsewhere *)
402 "test0rint", RInt "valout";
403 "test0rint64", RInt64 "valout";
404 "test0rbool", RBool "valout";
405 "test0rconststring", RConstString "valout";
406 "test0rconstoptstring", RConstOptString "valout";
407 "test0rstring", RString "valout";
408 "test0rstringlist", RStringList "valout";
409 "test0rstruct", RStruct ("valout", "lvm_pv");
410 "test0rstructlist", RStructList ("valout", "lvm_pv");
411 "test0rhashtable", RHashtable "valout";
414 let test_functions = [
415 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
417 "internal test function - do not use",
419 This is an internal test function which is used to test whether
420 the automatically generated bindings can handle every possible
421 parameter type correctly.
423 It echos the contents of each parameter to stdout.
425 You probably don't want to call this function.");
429 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
431 "internal test function - do not use",
433 This is an internal test function which is used to test whether
434 the automatically generated bindings can handle every possible
435 return type correctly.
437 It converts string C<val> to the return type.
439 You probably don't want to call this function.");
440 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
442 "internal test function - do not use",
444 This is an internal test function which is used to test whether
445 the automatically generated bindings can handle every possible
446 return type correctly.
448 This function always returns an error.
450 You probably don't want to call this function.")]
454 (* non_daemon_functions are any functions which don't get processed
455 * in the daemon, eg. functions for setting and getting local
456 * configuration values.
459 let non_daemon_functions = test_functions @ [
460 ("launch", (RErr, []), -1, [FishAlias "run"],
462 "launch the qemu subprocess",
464 Internally libguestfs is implemented by running a virtual machine
467 You should call this after configuring the handle
468 (eg. adding drives) but before performing any actions.");
470 ("wait_ready", (RErr, []), -1, [NotInFish],
472 "wait until the qemu subprocess launches (no op)",
474 This function is a no op.
476 In versions of the API E<lt> 1.0.71 you had to call this function
477 just after calling C<guestfs_launch> to wait for the launch
478 to complete. However this is no longer necessary because
479 C<guestfs_launch> now does the waiting.
481 If you see any calls to this function in code then you can just
482 remove them, unless you want to retain compatibility with older
483 versions of the API.");
485 ("kill_subprocess", (RErr, []), -1, [],
487 "kill the qemu subprocess",
489 This kills the qemu subprocess. You should never need to call this.");
491 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
493 "add an image to examine or modify",
495 This function adds a virtual machine disk image C<filename> to the
496 guest. The first time you call this function, the disk appears as IDE
497 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
500 You don't necessarily need to be root when using libguestfs. However
501 you obviously do need sufficient permissions to access the filename
502 for whatever operations you want to perform (ie. read access if you
503 just want to read the image or write access if you want to modify the
506 This is equivalent to the qemu parameter
507 C<-drive file=filename,cache=off,if=...>.
509 C<cache=off> is omitted in cases where it is not supported by
510 the underlying filesystem.
512 C<if=...> is set at compile time by the configuration option
513 C<./configure --with-drive-if=...>. In the rare case where you
514 might need to change this at run time, use C<guestfs_add_drive_with_if>
515 or C<guestfs_add_drive_ro_with_if>.
517 Note that this call checks for the existence of C<filename>. This
518 stops you from specifying other types of drive which are supported
519 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
520 the general C<guestfs_config> call instead.");
522 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
524 "add a CD-ROM disk image to examine",
526 This function adds a virtual CD-ROM disk image to the guest.
528 This is equivalent to the qemu parameter C<-cdrom filename>.
536 This call checks for the existence of C<filename>. This
537 stops you from specifying other types of drive which are supported
538 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
539 the general C<guestfs_config> call instead.
543 If you just want to add an ISO file (often you use this as an
544 efficient way to transfer large files into the guest), then you
545 should probably use C<guestfs_add_drive_ro> instead.
549 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
551 "add a drive in snapshot mode (read-only)",
553 This adds a drive in snapshot mode, making it effectively
556 Note that writes to the device are allowed, and will be seen for
557 the duration of the guestfs handle, but they are written
558 to a temporary file which is discarded as soon as the guestfs
559 handle is closed. We don't currently have any method to enable
560 changes to be committed, although qemu can support this.
562 This is equivalent to the qemu parameter
563 C<-drive file=filename,snapshot=on,if=...>.
565 C<if=...> is set at compile time by the configuration option
566 C<./configure --with-drive-if=...>. In the rare case where you
567 might need to change this at run time, use C<guestfs_add_drive_with_if>
568 or C<guestfs_add_drive_ro_with_if>.
570 Note that this call checks for the existence of C<filename>. This
571 stops you from specifying other types of drive which are supported
572 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
573 the general C<guestfs_config> call instead.");
575 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
577 "add qemu parameters",
579 This can be used to add arbitrary qemu command line parameters
580 of the form C<-param value>. Actually it's not quite arbitrary - we
581 prevent you from setting some parameters which would interfere with
582 parameters that we use.
584 The first character of C<param> string must be a C<-> (dash).
586 C<value> can be NULL.");
588 ("set_qemu", (RErr, [OptString "qemu"]), -1, [FishAlias "qemu"],
590 "set the qemu binary",
592 Set the qemu binary that we will use.
594 The default is chosen when the library was compiled by the
597 You can also override this by setting the C<LIBGUESTFS_QEMU>
598 environment variable.
600 Setting C<qemu> to C<NULL> restores the default qemu binary.
602 Note that you should call this function as early as possible
603 after creating the handle. This is because some pre-launch
604 operations depend on testing qemu features (by running C<qemu -help>).
605 If the qemu binary changes, we don't retest features, and
606 so you might see inconsistent results. Using the environment
607 variable C<LIBGUESTFS_QEMU> is safest of all since that picks
608 the qemu binary at the same time as the handle is created.");
610 ("get_qemu", (RConstString "qemu", []), -1, [],
611 [InitNone, Always, TestRun (
613 "get the qemu binary",
615 Return the current qemu binary.
617 This is always non-NULL. If it wasn't set already, then this will
618 return the default qemu binary name.");
620 ("set_path", (RErr, [OptString "searchpath"]), -1, [FishAlias "path"],
622 "set the search path",
624 Set the path that libguestfs searches for kernel and initrd.img.
626 The default is C<$libdir/guestfs> unless overridden by setting
627 C<LIBGUESTFS_PATH> environment variable.
629 Setting C<path> to C<NULL> restores the default path.");
631 ("get_path", (RConstString "path", []), -1, [],
632 [InitNone, Always, TestRun (
634 "get the search path",
636 Return the current search path.
638 This is always non-NULL. If it wasn't set already, then this will
639 return the default path.");
641 ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
643 "add options to kernel command line",
645 This function is used to add additional options to the
646 guest kernel command line.
648 The default is C<NULL> unless overridden by setting
649 C<LIBGUESTFS_APPEND> environment variable.
651 Setting C<append> to C<NULL> means I<no> additional options
652 are passed (libguestfs always adds a few of its own).");
654 ("get_append", (RConstOptString "append", []), -1, [],
655 (* This cannot be tested with the current framework. The
656 * function can return NULL in normal operations, which the
657 * test framework interprets as an error.
660 "get the additional kernel options",
662 Return the additional kernel options which are added to the
663 guest kernel command line.
665 If C<NULL> then no options are added.");
667 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
671 If C<autosync> is true, this enables autosync. Libguestfs will make a
672 best effort attempt to run C<guestfs_umount_all> followed by
673 C<guestfs_sync> when the handle is closed
674 (also if the program exits without closing handles).
676 This is disabled by default (except in guestfish where it is
677 enabled by default).");
679 ("get_autosync", (RBool "autosync", []), -1, [],
680 [InitNone, Always, TestRun (
681 [["get_autosync"]])],
684 Get the autosync flag.");
686 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
690 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
692 Verbose messages are disabled unless the environment variable
693 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
695 ("get_verbose", (RBool "verbose", []), -1, [],
699 This returns the verbose messages flag.");
701 ("is_ready", (RBool "ready", []), -1, [],
702 [InitNone, Always, TestOutputTrue (
704 "is ready to accept commands",
706 This returns true iff this handle is ready to accept commands
707 (in the C<READY> state).
709 For more information on states, see L<guestfs(3)>.");
711 ("is_config", (RBool "config", []), -1, [],
712 [InitNone, Always, TestOutputFalse (
714 "is in configuration state",
716 This returns true iff this handle is being configured
717 (in the C<CONFIG> state).
719 For more information on states, see L<guestfs(3)>.");
721 ("is_launching", (RBool "launching", []), -1, [],
722 [InitNone, Always, TestOutputFalse (
723 [["is_launching"]])],
724 "is launching subprocess",
726 This returns true iff this handle is launching the subprocess
727 (in the C<LAUNCHING> state).
729 For more information on states, see L<guestfs(3)>.");
731 ("is_busy", (RBool "busy", []), -1, [],
732 [InitNone, Always, TestOutputFalse (
734 "is busy processing a command",
736 This returns true iff this handle is busy processing a command
737 (in the C<BUSY> state).
739 For more information on states, see L<guestfs(3)>.");
741 ("get_state", (RInt "state", []), -1, [],
743 "get the current state",
745 This returns the current state as an opaque integer. This is
746 only useful for printing debug and internal error messages.
748 For more information on states, see L<guestfs(3)>.");
750 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
751 [InitNone, Always, TestOutputInt (
752 [["set_memsize"; "500"];
753 ["get_memsize"]], 500)],
754 "set memory allocated to the qemu subprocess",
756 This sets the memory size in megabytes allocated to the
757 qemu subprocess. This only has any effect if called before
760 You can also change this by setting the environment
761 variable C<LIBGUESTFS_MEMSIZE> before the handle is
764 For more information on the architecture of libguestfs,
765 see L<guestfs(3)>.");
767 ("get_memsize", (RInt "memsize", []), -1, [],
768 [InitNone, Always, TestOutputIntOp (
769 [["get_memsize"]], ">=", 256)],
770 "get memory allocated to the qemu subprocess",
772 This gets the memory size in megabytes allocated to the
775 If C<guestfs_set_memsize> was not called
776 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
777 then this returns the compiled-in default value for memsize.
779 For more information on the architecture of libguestfs,
780 see L<guestfs(3)>.");
782 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
783 [InitNone, Always, TestOutputIntOp (
784 [["get_pid"]], ">=", 1)],
785 "get PID of qemu subprocess",
787 Return the process ID of the qemu subprocess. If there is no
788 qemu subprocess, then this will return an error.
790 This is an internal call used for debugging and testing.");
792 ("version", (RStruct ("version", "version"), []), -1, [],
793 [InitNone, Always, TestOutputStruct (
794 [["version"]], [CompareWithInt ("major", 1)])],
795 "get the library version number",
797 Return the libguestfs version number that the program is linked
800 Note that because of dynamic linking this is not necessarily
801 the version of libguestfs that you compiled against. You can
802 compile the program, and then at runtime dynamically link
803 against a completely different C<libguestfs.so> library.
805 This call was added in version C<1.0.58>. In previous
806 versions of libguestfs there was no way to get the version
807 number. From C code you can use dynamic linker functions
808 to find out if this symbol exists (if it doesn't, then
809 it's an earlier version).
811 The call returns a structure with four elements. The first
812 three (C<major>, C<minor> and C<release>) are numbers and
813 correspond to the usual version triplet. The fourth element
814 (C<extra>) is a string and is normally empty, but may be
815 used for distro-specific information.
817 To construct the original version string:
818 C<$major.$minor.$release$extra>
820 See also: L<guestfs(3)/LIBGUESTFS VERSION NUMBERS>.
822 I<Note:> Don't use this call to test for availability
823 of features. In enterprise distributions we backport
824 features from later versions into earlier versions,
825 making this an unreliable way to test for features.
826 Use C<guestfs_available> instead.");
828 ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
829 [InitNone, Always, TestOutputTrue (
830 [["set_selinux"; "true"];
832 "set SELinux enabled or disabled at appliance boot",
834 This sets the selinux flag that is passed to the appliance
835 at boot time. The default is C<selinux=0> (disabled).
837 Note that if SELinux is enabled, it is always in
838 Permissive mode (C<enforcing=0>).
840 For more information on the architecture of libguestfs,
841 see L<guestfs(3)>.");
843 ("get_selinux", (RBool "selinux", []), -1, [],
845 "get SELinux enabled flag",
847 This returns the current setting of the selinux flag which
848 is passed to the appliance at boot time. See C<guestfs_set_selinux>.
850 For more information on the architecture of libguestfs,
851 see L<guestfs(3)>.");
853 ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
854 [InitNone, Always, TestOutputFalse (
855 [["set_trace"; "false"];
857 "enable or disable command traces",
859 If the command trace flag is set to 1, then commands are
860 printed on stderr before they are executed in a format
861 which is very similar to the one used by guestfish. In
862 other words, you can run a program with this enabled, and
863 you will get out a script which you can feed to guestfish
864 to perform the same set of actions.
866 If you want to trace C API calls into libguestfs (and
867 other libraries) then possibly a better way is to use
868 the external ltrace(1) command.
870 Command traces are disabled unless the environment variable
871 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
873 ("get_trace", (RBool "trace", []), -1, [],
875 "get command trace enabled flag",
877 Return the command trace flag.");
879 ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
880 [InitNone, Always, TestOutputFalse (
881 [["set_direct"; "false"];
883 "enable or disable direct appliance mode",
885 If the direct appliance mode flag is enabled, then stdin and
886 stdout are passed directly through to the appliance once it
889 One consequence of this is that log messages aren't caught
890 by the library and handled by C<guestfs_set_log_message_callback>,
891 but go straight to stdout.
893 You probably don't want to use this unless you know what you
896 The default is disabled.");
898 ("get_direct", (RBool "direct", []), -1, [],
900 "get direct appliance mode flag",
902 Return the direct appliance mode flag.");
904 ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
905 [InitNone, Always, TestOutputTrue (
906 [["set_recovery_proc"; "true"];
907 ["get_recovery_proc"]])],
908 "enable or disable the recovery process",
910 If this is called with the parameter C<false> then
911 C<guestfs_launch> does not create a recovery process. The
912 purpose of the recovery process is to stop runaway qemu
913 processes in the case where the main program aborts abruptly.
915 This only has any effect if called before C<guestfs_launch>,
916 and the default is true.
918 About the only time when you would want to disable this is
919 if the main process will fork itself into the background
920 (\"daemonize\" itself). In this case the recovery process
921 thinks that the main program has disappeared and so kills
922 qemu, which is not very helpful.");
924 ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
926 "get recovery process enabled flag",
928 Return the recovery process enabled flag.");
930 ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
932 "add a drive specifying the QEMU block emulation to use",
934 This is the same as C<guestfs_add_drive> but it allows you
935 to specify the QEMU interface emulation to use at run time.");
937 ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
939 "add a drive read-only specifying the QEMU block emulation to use",
941 This is the same as C<guestfs_add_drive_ro> but it allows you
942 to specify the QEMU interface emulation to use at run time.");
944 ("file_architecture", (RString "arch", [Pathname "filename"]), -1, [],
945 [InitISOFS, Always, TestOutput (
946 [["file_architecture"; "/bin-i586-dynamic"]], "i386");
947 InitISOFS, Always, TestOutput (
948 [["file_architecture"; "/bin-sparc-dynamic"]], "sparc");
949 InitISOFS, Always, TestOutput (
950 [["file_architecture"; "/bin-win32.exe"]], "i386");
951 InitISOFS, Always, TestOutput (
952 [["file_architecture"; "/bin-win64.exe"]], "x86_64");
953 InitISOFS, Always, TestOutput (
954 [["file_architecture"; "/bin-x86_64-dynamic"]], "x86_64");
955 InitISOFS, Always, TestOutput (
956 [["file_architecture"; "/lib-i586.so"]], "i386");
957 InitISOFS, Always, TestOutput (
958 [["file_architecture"; "/lib-sparc.so"]], "sparc");
959 InitISOFS, Always, TestOutput (
960 [["file_architecture"; "/lib-win32.dll"]], "i386");
961 InitISOFS, Always, TestOutput (
962 [["file_architecture"; "/lib-win64.dll"]], "x86_64");
963 InitISOFS, Always, TestOutput (
964 [["file_architecture"; "/lib-x86_64.so"]], "x86_64");
965 InitISOFS, Always, TestOutput (
966 [["file_architecture"; "/initrd-x86_64.img"]], "x86_64");
967 InitISOFS, Always, TestOutput (
968 [["file_architecture"; "/initrd-x86_64.img.gz"]], "x86_64");],
969 "detect the architecture of a binary file",
971 This detects the architecture of the binary C<filename>,
972 and returns it if known.
974 Currently defined architectures are:
980 This string is returned for all 32 bit i386, i486, i586, i686 binaries
981 irrespective of the precise processor requirements of the binary.
993 64 bit SPARC V9 and above.
1009 Libguestfs may return other architecture strings in future.
1011 The function works on at least the following types of files:
1017 many types of Un*x and Linux binary
1021 many types of Un*x and Linux shared library
1025 Windows Win32 and Win64 binaries
1029 Windows Win32 and Win64 DLLs
1031 Win32 binaries and DLLs return C<i386>.
1033 Win64 binaries and DLLs return C<x86_64>.
1037 Linux kernel modules
1041 Linux new-style initrd images
1045 some non-x86 Linux vmlinuz kernels
1049 What it can't do currently:
1055 static libraries (libfoo.a)
1059 Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
1063 x86 Linux vmlinuz kernels
1065 x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and
1066 compressed code, and are horribly hard to unpack. If you want to find
1067 the architecture of a kernel, use the architecture of the associated
1068 initrd or kernel module(s) instead.
1072 ("inspect_os", (RStringList "roots", []), -1, [],
1074 "inspect disk and return list of operating systems found",
1076 This function uses other libguestfs functions and certain
1077 heuristics to inspect the disk(s) (usually disks belonging to
1078 a virtual machine), looking for operating systems.
1080 The list returned is empty if no operating systems were found.
1082 If one operating system was found, then this returns a list with
1083 a single element, which is the name of the root filesystem of
1084 this operating system. It is also possible for this function
1085 to return a list containing more than one element, indicating
1086 a dual-boot or multi-boot virtual machine, with each element being
1087 the root filesystem of one of the operating systems.
1089 You can pass the root string(s) returned to other
1090 C<guestfs_inspect_get_*> functions in order to query further
1091 information about each operating system, such as the name
1094 This function uses other libguestfs features such as
1095 C<guestfs_mount_ro> and C<guestfs_umount_all> in order to mount
1096 and unmount filesystems and look at the contents. This should
1097 be called with no disks currently mounted. The function may also
1098 use Augeas, so any existing Augeas handle will be closed.
1100 This function cannot decrypt encrypted disks. The caller
1101 must do that first (supplying the necessary keys) if the
1104 Please read L<guestfs(3)/INSPECTION> for more details.");
1106 ("inspect_get_type", (RString "name", [Device "root"]), -1, [],
1108 "get type of inspected operating system",
1110 This function should only be called with a root device string
1111 as returned by C<guestfs_inspect_os>.
1113 This returns the type of the inspected operating system.
1114 Currently defined types are:
1120 Any Linux-based operating system.
1124 Any Microsoft Windows operating system.
1128 The operating system type could not be determined.
1132 Future versions of libguestfs may return other strings here.
1133 The caller should be prepared to handle any string.
1135 Please read L<guestfs(3)/INSPECTION> for more details.");
1137 ("inspect_get_arch", (RString "arch", [Device "root"]), -1, [],
1139 "get architecture of inspected operating system",
1141 This function should only be called with a root device string
1142 as returned by C<guestfs_inspect_os>.
1144 This returns the architecture of the inspected operating system.
1145 The possible return values are listed under
1146 C<guestfs_file_architecture>.
1148 If the architecture could not be determined, then the
1149 string C<unknown> is returned.
1151 Please read L<guestfs(3)/INSPECTION> for more details.");
1153 ("inspect_get_distro", (RString "distro", [Device "root"]), -1, [],
1155 "get distro of inspected operating system",
1157 This function should only be called with a root device string
1158 as returned by C<guestfs_inspect_os>.
1160 This returns the distro (distribution) of the inspected operating
1163 Currently defined distros are:
1169 Debian or a Debian-derived distro such as Ubuntu.
1175 =item \"redhat-based\"
1177 Some Red Hat-derived distro.
1181 Red Hat Enterprise Linux and some derivatives.
1185 Windows does not have distributions. This string is
1186 returned if the OS type is Windows.
1190 The distro could not be determined.
1194 Future versions of libguestfs may return other strings here.
1195 The caller should be prepared to handle any string.
1197 Please read L<guestfs(3)/INSPECTION> for more details.");
1199 ("inspect_get_major_version", (RInt "major", [Device "root"]), -1, [],
1201 "get major version of inspected operating system",
1203 This function should only be called with a root device string
1204 as returned by C<guestfs_inspect_os>.
1206 This returns the major version number of the inspected operating
1209 Windows uses a consistent versioning scheme which is I<not>
1210 reflected in the popular public names used by the operating system.
1211 Notably the operating system known as \"Windows 7\" is really
1212 version 6.1 (ie. major = 6, minor = 1). You can find out the
1213 real versions corresponding to releases of Windows by consulting
1216 If the version could not be determined, then C<0> is returned.
1218 Please read L<guestfs(3)/INSPECTION> for more details.");
1220 ("inspect_get_minor_version", (RInt "minor", [Device "root"]), -1, [],
1222 "get minor version of inspected operating system",
1224 This function should only be called with a root device string
1225 as returned by C<guestfs_inspect_os>.
1227 This returns the minor version number of the inspected operating
1230 If the version could not be determined, then C<0> is returned.
1232 Please read L<guestfs(3)/INSPECTION> for more details.
1233 See also C<guestfs_inspect_get_major_version>.");
1235 ("inspect_get_product_name", (RString "product", [Device "root"]), -1, [],
1237 "get product name of inspected operating system",
1239 This function should only be called with a root device string
1240 as returned by C<guestfs_inspect_os>.
1242 This returns the product name of the inspected operating
1243 system. The product name is generally some freeform string
1244 which can be displayed to the user, but should not be
1247 If the product name could not be determined, then the
1248 string C<unknown> is returned.
1250 Please read L<guestfs(3)/INSPECTION> for more details.");
1252 ("inspect_get_mountpoints", (RHashtable "mountpoints", [Device "root"]), -1, [],
1254 "get mountpoints of inspected operating system",
1256 This function should only be called with a root device string
1257 as returned by C<guestfs_inspect_os>.
1259 This returns a hash of where we think the filesystems
1260 associated with this operating system should be mounted.
1261 Callers should note that this is at best an educated guess
1262 made by reading configuration files such as C</etc/fstab>.
1264 Each element in the returned hashtable has a key which
1265 is the path of the mountpoint (eg. C</boot>) and a value
1266 which is the filesystem that would be mounted there
1269 Non-mounted devices such as swap devices are I<not>
1270 returned in this list.
1272 Please read L<guestfs(3)/INSPECTION> for more details.
1273 See also C<guestfs_inspect_get_filesystems>.");
1275 ("inspect_get_filesystems", (RStringList "filesystems", [Device "root"]), -1, [],
1277 "get filesystems associated with inspected operating system",
1279 This function should only be called with a root device string
1280 as returned by C<guestfs_inspect_os>.
1282 This returns a list of all the filesystems that we think
1283 are associated with this operating system. This includes
1284 the root filesystem, other ordinary filesystems, and
1285 non-mounted devices like swap partitions.
1287 In the case of a multi-boot virtual machine, it is possible
1288 for a filesystem to be shared between operating systems.
1290 Please read L<guestfs(3)/INSPECTION> for more details.
1291 See also C<guestfs_inspect_get_mountpoints>.");
1293 ("set_network", (RErr, [Bool "network"]), -1, [FishAlias "network"],
1295 "set enable network flag",
1297 If C<network> is true, then the network is enabled in the
1298 libguestfs appliance. The default is false.
1300 This affects whether commands are able to access the network
1301 (see L<guestfs(3)/RUNNING COMMANDS>).
1303 You must call this before calling C<guestfs_launch>, otherwise
1304 it has no effect.");
1306 ("get_network", (RBool "network", []), -1, [],
1308 "get enable network flag",
1310 This returns the enable network flag.");
1314 (* daemon_functions are any functions which cause some action
1315 * to take place in the daemon.
1318 let daemon_functions = [
1319 ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
1320 [InitEmpty, Always, TestOutput (
1321 [["part_disk"; "/dev/sda"; "mbr"];
1322 ["mkfs"; "ext2"; "/dev/sda1"];
1323 ["mount"; "/dev/sda1"; "/"];
1324 ["write"; "/new"; "new file contents"];
1325 ["cat"; "/new"]], "new file contents")],
1326 "mount a guest disk at a position in the filesystem",
1328 Mount a guest disk at a position in the filesystem. Block devices
1329 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
1330 the guest. If those block devices contain partitions, they will have
1331 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
1334 The rules are the same as for L<mount(2)>: A filesystem must
1335 first be mounted on C</> before others can be mounted. Other
1336 filesystems can only be mounted on directories which already
1339 The mounted filesystem is writable, if we have sufficient permissions
1340 on the underlying device.
1343 When you use this call, the filesystem options C<sync> and C<noatime>
1344 are set implicitly. This was originally done because we thought it
1345 would improve reliability, but it turns out that I<-o sync> has a
1346 very large negative performance impact and negligible effect on
1347 reliability. Therefore we recommend that you avoid using
1348 C<guestfs_mount> in any code that needs performance, and instead
1349 use C<guestfs_mount_options> (use an empty string for the first
1350 parameter if you don't want any options).");
1352 ("sync", (RErr, []), 2, [],
1353 [ InitEmpty, Always, TestRun [["sync"]]],
1354 "sync disks, writes are flushed through to the disk image",
1356 This syncs the disk, so that any writes are flushed through to the
1357 underlying disk image.
1359 You should always call this if you have modified a disk image, before
1360 closing the handle.");
1362 ("touch", (RErr, [Pathname "path"]), 3, [],
1363 [InitBasicFS, Always, TestOutputTrue (
1365 ["exists"; "/new"]])],
1366 "update file timestamps or create a new file",
1368 Touch acts like the L<touch(1)> command. It can be used to
1369 update the timestamps on a file, or, if the file does not exist,
1370 to create a new zero-length file.
1372 This command only works on regular files, and will fail on other
1373 file types such as directories, symbolic links, block special etc.");
1375 ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
1376 [InitISOFS, Always, TestOutput (
1377 [["cat"; "/known-2"]], "abcdef\n")],
1378 "list the contents of a file",
1380 Return the contents of the file named C<path>.
1382 Note that this function cannot correctly handle binary files
1383 (specifically, files containing C<\\0> character which is treated
1384 as end of string). For those you need to use the C<guestfs_read_file>
1385 or C<guestfs_download> functions which have a more complex interface.");
1387 ("ll", (RString "listing", [Pathname "directory"]), 5, [],
1388 [], (* XXX Tricky to test because it depends on the exact format
1389 * of the 'ls -l' command, which changes between F10 and F11.
1391 "list the files in a directory (long format)",
1393 List the files in C<directory> (relative to the root directory,
1394 there is no cwd) in the format of 'ls -la'.
1396 This command is mostly useful for interactive sessions. It
1397 is I<not> intended that you try to parse the output string.");
1399 ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
1400 [InitBasicFS, Always, TestOutputList (
1402 ["touch"; "/newer"];
1403 ["touch"; "/newest"];
1404 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
1405 "list the files in a directory",
1407 List the files in C<directory> (relative to the root directory,
1408 there is no cwd). The '.' and '..' entries are not returned, but
1409 hidden files are shown.
1411 This command is mostly useful for interactive sessions. Programs
1412 should probably use C<guestfs_readdir> instead.");
1414 ("list_devices", (RStringList "devices", []), 7, [],
1415 [InitEmpty, Always, TestOutputListOfDevices (
1416 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1417 "list the block devices",
1419 List all the block devices.
1421 The full block device names are returned, eg. C</dev/sda>");
1423 ("list_partitions", (RStringList "partitions", []), 8, [],
1424 [InitBasicFS, Always, TestOutputListOfDevices (
1425 [["list_partitions"]], ["/dev/sda1"]);
1426 InitEmpty, Always, TestOutputListOfDevices (
1427 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1428 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1429 "list the partitions",
1431 List all the partitions detected on all block devices.
1433 The full partition device names are returned, eg. C</dev/sda1>
1435 This does not return logical volumes. For that you will need to
1436 call C<guestfs_lvs>.");
1438 ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1439 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1440 [["pvs"]], ["/dev/sda1"]);
1441 InitEmpty, Always, TestOutputListOfDevices (
1442 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1443 ["pvcreate"; "/dev/sda1"];
1444 ["pvcreate"; "/dev/sda2"];
1445 ["pvcreate"; "/dev/sda3"];
1446 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1447 "list the LVM physical volumes (PVs)",
1449 List all the physical volumes detected. This is the equivalent
1450 of the L<pvs(8)> command.
1452 This returns a list of just the device names that contain
1453 PVs (eg. C</dev/sda2>).
1455 See also C<guestfs_pvs_full>.");
1457 ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1458 [InitBasicFSonLVM, Always, TestOutputList (
1460 InitEmpty, Always, TestOutputList (
1461 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1462 ["pvcreate"; "/dev/sda1"];
1463 ["pvcreate"; "/dev/sda2"];
1464 ["pvcreate"; "/dev/sda3"];
1465 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1466 ["vgcreate"; "VG2"; "/dev/sda3"];
1467 ["vgs"]], ["VG1"; "VG2"])],
1468 "list the LVM volume groups (VGs)",
1470 List all the volumes groups detected. This is the equivalent
1471 of the L<vgs(8)> command.
1473 This returns a list of just the volume group names that were
1474 detected (eg. C<VolGroup00>).
1476 See also C<guestfs_vgs_full>.");
1478 ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1479 [InitBasicFSonLVM, Always, TestOutputList (
1480 [["lvs"]], ["/dev/VG/LV"]);
1481 InitEmpty, Always, TestOutputList (
1482 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1483 ["pvcreate"; "/dev/sda1"];
1484 ["pvcreate"; "/dev/sda2"];
1485 ["pvcreate"; "/dev/sda3"];
1486 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1487 ["vgcreate"; "VG2"; "/dev/sda3"];
1488 ["lvcreate"; "LV1"; "VG1"; "50"];
1489 ["lvcreate"; "LV2"; "VG1"; "50"];
1490 ["lvcreate"; "LV3"; "VG2"; "50"];
1491 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1492 "list the LVM logical volumes (LVs)",
1494 List all the logical volumes detected. This is the equivalent
1495 of the L<lvs(8)> command.
1497 This returns a list of the logical volume device names
1498 (eg. C</dev/VolGroup00/LogVol00>).
1500 See also C<guestfs_lvs_full>.");
1502 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1503 [], (* XXX how to test? *)
1504 "list the LVM physical volumes (PVs)",
1506 List all the physical volumes detected. This is the equivalent
1507 of the L<pvs(8)> command. The \"full\" version includes all fields.");
1509 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1510 [], (* XXX how to test? *)
1511 "list the LVM volume groups (VGs)",
1513 List all the volumes groups detected. This is the equivalent
1514 of the L<vgs(8)> command. The \"full\" version includes all fields.");
1516 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1517 [], (* XXX how to test? *)
1518 "list the LVM logical volumes (LVs)",
1520 List all the logical volumes detected. This is the equivalent
1521 of the L<lvs(8)> command. The \"full\" version includes all fields.");
1523 ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1524 [InitISOFS, Always, TestOutputList (
1525 [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1526 InitISOFS, Always, TestOutputList (
1527 [["read_lines"; "/empty"]], [])],
1528 "read file as lines",
1530 Return the contents of the file named C<path>.
1532 The file contents are returned as a list of lines. Trailing
1533 C<LF> and C<CRLF> character sequences are I<not> returned.
1535 Note that this function cannot correctly handle binary files
1536 (specifically, files containing C<\\0> character which is treated
1537 as end of line). For those you need to use the C<guestfs_read_file>
1538 function which has a more complex interface.");
1540 ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1541 [], (* XXX Augeas code needs tests. *)
1542 "create a new Augeas handle",
1544 Create a new Augeas handle for editing configuration files.
1545 If there was any previous Augeas handle associated with this
1546 guestfs session, then it is closed.
1548 You must call this before using any other C<guestfs_aug_*>
1551 C<root> is the filesystem root. C<root> must not be NULL,
1554 The flags are the same as the flags defined in
1555 E<lt>augeas.hE<gt>, the logical I<or> of the following
1560 =item C<AUG_SAVE_BACKUP> = 1
1562 Keep the original file with a C<.augsave> extension.
1564 =item C<AUG_SAVE_NEWFILE> = 2
1566 Save changes into a file with extension C<.augnew>, and
1567 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
1569 =item C<AUG_TYPE_CHECK> = 4
1571 Typecheck lenses (can be expensive).
1573 =item C<AUG_NO_STDINC> = 8
1575 Do not use standard load path for modules.
1577 =item C<AUG_SAVE_NOOP> = 16
1579 Make save a no-op, just record what would have been changed.
1581 =item C<AUG_NO_LOAD> = 32
1583 Do not load the tree in C<guestfs_aug_init>.
1587 To close the handle, you can call C<guestfs_aug_close>.
1589 To find out more about Augeas, see L<http://augeas.net/>.");
1591 ("aug_close", (RErr, []), 26, [Optional "augeas"],
1592 [], (* XXX Augeas code needs tests. *)
1593 "close the current Augeas handle",
1595 Close the current Augeas handle and free up any resources
1596 used by it. After calling this, you have to call
1597 C<guestfs_aug_init> again before you can use any other
1598 Augeas functions.");
1600 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1601 [], (* XXX Augeas code needs tests. *)
1602 "define an Augeas variable",
1604 Defines an Augeas variable C<name> whose value is the result
1605 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
1608 On success this returns the number of nodes in C<expr>, or
1609 C<0> if C<expr> evaluates to something which is not a nodeset.");
1611 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1612 [], (* XXX Augeas code needs tests. *)
1613 "define an Augeas node",
1615 Defines a variable C<name> whose value is the result of
1618 If C<expr> evaluates to an empty nodeset, a node is created,
1619 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1620 C<name> will be the nodeset containing that single node.
1622 On success this returns a pair containing the
1623 number of nodes in the nodeset, and a boolean flag
1624 if a node was created.");
1626 ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1627 [], (* XXX Augeas code needs tests. *)
1628 "look up the value of an Augeas path",
1630 Look up the value associated with C<path>. If C<path>
1631 matches exactly one node, the C<value> is returned.");
1633 ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1634 [], (* XXX Augeas code needs tests. *)
1635 "set Augeas path to value",
1637 Set the value associated with C<path> to C<val>.
1639 In the Augeas API, it is possible to clear a node by setting
1640 the value to NULL. Due to an oversight in the libguestfs API
1641 you cannot do that with this call. Instead you must use the
1642 C<guestfs_aug_clear> call.");
1644 ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1645 [], (* XXX Augeas code needs tests. *)
1646 "insert a sibling Augeas node",
1648 Create a new sibling C<label> for C<path>, inserting it into
1649 the tree before or after C<path> (depending on the boolean
1652 C<path> must match exactly one existing node in the tree, and
1653 C<label> must be a label, ie. not contain C</>, C<*> or end
1654 with a bracketed index C<[N]>.");
1656 ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1657 [], (* XXX Augeas code needs tests. *)
1658 "remove an Augeas path",
1660 Remove C<path> and all of its children.
1662 On success this returns the number of entries which were removed.");
1664 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1665 [], (* XXX Augeas code needs tests. *)
1668 Move the node C<src> to C<dest>. C<src> must match exactly
1669 one node. C<dest> is overwritten if it exists.");
1671 ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1672 [], (* XXX Augeas code needs tests. *)
1673 "return Augeas nodes which match augpath",
1675 Returns a list of paths which match the path expression C<path>.
1676 The returned paths are sufficiently qualified so that they match
1677 exactly one node in the current tree.");
1679 ("aug_save", (RErr, []), 25, [Optional "augeas"],
1680 [], (* XXX Augeas code needs tests. *)
1681 "write all pending Augeas changes to disk",
1683 This writes all pending changes to disk.
1685 The flags which were passed to C<guestfs_aug_init> affect exactly
1686 how files are saved.");
1688 ("aug_load", (RErr, []), 27, [Optional "augeas"],
1689 [], (* XXX Augeas code needs tests. *)
1690 "load files into the tree",
1692 Load files into the tree.
1694 See C<aug_load> in the Augeas documentation for the full gory
1697 ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1698 [], (* XXX Augeas code needs tests. *)
1699 "list Augeas nodes under augpath",
1701 This is just a shortcut for listing C<guestfs_aug_match>
1702 C<path/*> and sorting the resulting nodes into alphabetical order.");
1704 ("rm", (RErr, [Pathname "path"]), 29, [],
1705 [InitBasicFS, Always, TestRun
1708 InitBasicFS, Always, TestLastFail
1710 InitBasicFS, Always, TestLastFail
1715 Remove the single file C<path>.");
1717 ("rmdir", (RErr, [Pathname "path"]), 30, [],
1718 [InitBasicFS, Always, TestRun
1721 InitBasicFS, Always, TestLastFail
1722 [["rmdir"; "/new"]];
1723 InitBasicFS, Always, TestLastFail
1725 ["rmdir"; "/new"]]],
1726 "remove a directory",
1728 Remove the single directory C<path>.");
1730 ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1731 [InitBasicFS, Always, TestOutputFalse
1733 ["mkdir"; "/new/foo"];
1734 ["touch"; "/new/foo/bar"];
1736 ["exists"; "/new"]]],
1737 "remove a file or directory recursively",
1739 Remove the file or directory C<path>, recursively removing the
1740 contents if its a directory. This is like the C<rm -rf> shell
1743 ("mkdir", (RErr, [Pathname "path"]), 32, [],
1744 [InitBasicFS, Always, TestOutputTrue
1746 ["is_dir"; "/new"]];
1747 InitBasicFS, Always, TestLastFail
1748 [["mkdir"; "/new/foo/bar"]]],
1749 "create a directory",
1751 Create a directory named C<path>.");
1753 ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1754 [InitBasicFS, Always, TestOutputTrue
1755 [["mkdir_p"; "/new/foo/bar"];
1756 ["is_dir"; "/new/foo/bar"]];
1757 InitBasicFS, Always, TestOutputTrue
1758 [["mkdir_p"; "/new/foo/bar"];
1759 ["is_dir"; "/new/foo"]];
1760 InitBasicFS, Always, TestOutputTrue
1761 [["mkdir_p"; "/new/foo/bar"];
1762 ["is_dir"; "/new"]];
1763 (* Regression tests for RHBZ#503133: *)
1764 InitBasicFS, Always, TestRun
1766 ["mkdir_p"; "/new"]];
1767 InitBasicFS, Always, TestLastFail
1769 ["mkdir_p"; "/new"]]],
1770 "create a directory and parents",
1772 Create a directory named C<path>, creating any parent directories
1773 as necessary. This is like the C<mkdir -p> shell command.");
1775 ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1776 [], (* XXX Need stat command to test *)
1779 Change the mode (permissions) of C<path> to C<mode>. Only
1780 numeric modes are supported.
1782 I<Note>: When using this command from guestfish, C<mode>
1783 by default would be decimal, unless you prefix it with
1784 C<0> to get octal, ie. use C<0700> not C<700>.
1786 The mode actually set is affected by the umask.");
1788 ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1789 [], (* XXX Need stat command to test *)
1790 "change file owner and group",
1792 Change the file owner to C<owner> and group to C<group>.
1794 Only numeric uid and gid are supported. If you want to use
1795 names, you will need to locate and parse the password file
1796 yourself (Augeas support makes this relatively easy).");
1798 ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1799 [InitISOFS, Always, TestOutputTrue (
1800 [["exists"; "/empty"]]);
1801 InitISOFS, Always, TestOutputTrue (
1802 [["exists"; "/directory"]])],
1803 "test if file or directory exists",
1805 This returns C<true> if and only if there is a file, directory
1806 (or anything) with the given C<path> name.
1808 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1810 ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1811 [InitISOFS, Always, TestOutputTrue (
1812 [["is_file"; "/known-1"]]);
1813 InitISOFS, Always, TestOutputFalse (
1814 [["is_file"; "/directory"]])],
1815 "test if file exists",
1817 This returns C<true> if and only if there is a file
1818 with the given C<path> name. Note that it returns false for
1819 other objects like directories.
1821 See also C<guestfs_stat>.");
1823 ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1824 [InitISOFS, Always, TestOutputFalse (
1825 [["is_dir"; "/known-3"]]);
1826 InitISOFS, Always, TestOutputTrue (
1827 [["is_dir"; "/directory"]])],
1828 "test if file exists",
1830 This returns C<true> if and only if there is a directory
1831 with the given C<path> name. Note that it returns false for
1832 other objects like files.
1834 See also C<guestfs_stat>.");
1836 ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1837 [InitEmpty, Always, TestOutputListOfDevices (
1838 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1839 ["pvcreate"; "/dev/sda1"];
1840 ["pvcreate"; "/dev/sda2"];
1841 ["pvcreate"; "/dev/sda3"];
1842 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1843 "create an LVM physical volume",
1845 This creates an LVM physical volume on the named C<device>,
1846 where C<device> should usually be a partition name such
1849 ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1850 [InitEmpty, Always, TestOutputList (
1851 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1852 ["pvcreate"; "/dev/sda1"];
1853 ["pvcreate"; "/dev/sda2"];
1854 ["pvcreate"; "/dev/sda3"];
1855 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1856 ["vgcreate"; "VG2"; "/dev/sda3"];
1857 ["vgs"]], ["VG1"; "VG2"])],
1858 "create an LVM volume group",
1860 This creates an LVM volume group called C<volgroup>
1861 from the non-empty list of physical volumes C<physvols>.");
1863 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1864 [InitEmpty, Always, TestOutputList (
1865 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1866 ["pvcreate"; "/dev/sda1"];
1867 ["pvcreate"; "/dev/sda2"];
1868 ["pvcreate"; "/dev/sda3"];
1869 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1870 ["vgcreate"; "VG2"; "/dev/sda3"];
1871 ["lvcreate"; "LV1"; "VG1"; "50"];
1872 ["lvcreate"; "LV2"; "VG1"; "50"];
1873 ["lvcreate"; "LV3"; "VG2"; "50"];
1874 ["lvcreate"; "LV4"; "VG2"; "50"];
1875 ["lvcreate"; "LV5"; "VG2"; "50"];
1877 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1878 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1879 "create an LVM logical volume",
1881 This creates an LVM logical volume called C<logvol>
1882 on the volume group C<volgroup>, with C<size> megabytes.");
1884 ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1885 [InitEmpty, Always, TestOutput (
1886 [["part_disk"; "/dev/sda"; "mbr"];
1887 ["mkfs"; "ext2"; "/dev/sda1"];
1888 ["mount_options"; ""; "/dev/sda1"; "/"];
1889 ["write"; "/new"; "new file contents"];
1890 ["cat"; "/new"]], "new file contents")],
1891 "make a filesystem",
1893 This creates a filesystem on C<device> (usually a partition
1894 or LVM logical volume). The filesystem type is C<fstype>, for
1897 ("sfdisk", (RErr, [Device "device";
1898 Int "cyls"; Int "heads"; Int "sectors";
1899 StringList "lines"]), 43, [DangerWillRobinson],
1901 "create partitions on a block device",
1903 This is a direct interface to the L<sfdisk(8)> program for creating
1904 partitions on block devices.
1906 C<device> should be a block device, for example C</dev/sda>.
1908 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1909 and sectors on the device, which are passed directly to sfdisk as
1910 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1911 of these, then the corresponding parameter is omitted. Usually for
1912 'large' disks, you can just pass C<0> for these, but for small
1913 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1914 out the right geometry and you will need to tell it.
1916 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1917 information refer to the L<sfdisk(8)> manpage.
1919 To create a single partition occupying the whole disk, you would
1920 pass C<lines> as a single element list, when the single element being
1921 the string C<,> (comma).
1923 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1924 C<guestfs_part_init>");
1926 ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning; DeprecatedBy "write"],
1927 (* Regression test for RHBZ#597135. *)
1928 [InitBasicFS, Always, TestLastFail
1929 [["write_file"; "/new"; "abc"; "10000"]]],
1932 This call creates a file called C<path>. The contents of the
1933 file is the string C<content> (which can contain any 8 bit data),
1934 with length C<size>.
1936 As a special case, if C<size> is C<0>
1937 then the length is calculated using C<strlen> (so in this case
1938 the content cannot contain embedded ASCII NULs).
1940 I<NB.> Owing to a bug, writing content containing ASCII NUL
1941 characters does I<not> work, even if the length is specified.");
1943 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1944 [InitEmpty, Always, TestOutputListOfDevices (
1945 [["part_disk"; "/dev/sda"; "mbr"];
1946 ["mkfs"; "ext2"; "/dev/sda1"];
1947 ["mount_options"; ""; "/dev/sda1"; "/"];
1948 ["mounts"]], ["/dev/sda1"]);
1949 InitEmpty, Always, TestOutputList (
1950 [["part_disk"; "/dev/sda"; "mbr"];
1951 ["mkfs"; "ext2"; "/dev/sda1"];
1952 ["mount_options"; ""; "/dev/sda1"; "/"];
1955 "unmount a filesystem",
1957 This unmounts the given filesystem. The filesystem may be
1958 specified either by its mountpoint (path) or the device which
1959 contains the filesystem.");
1961 ("mounts", (RStringList "devices", []), 46, [],
1962 [InitBasicFS, Always, TestOutputListOfDevices (
1963 [["mounts"]], ["/dev/sda1"])],
1964 "show mounted filesystems",
1966 This returns the list of currently mounted filesystems. It returns
1967 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1969 Some internal mounts are not shown.
1971 See also: C<guestfs_mountpoints>");
1973 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1974 [InitBasicFS, Always, TestOutputList (
1977 (* check that umount_all can unmount nested mounts correctly: *)
1978 InitEmpty, Always, TestOutputList (
1979 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1980 ["mkfs"; "ext2"; "/dev/sda1"];
1981 ["mkfs"; "ext2"; "/dev/sda2"];
1982 ["mkfs"; "ext2"; "/dev/sda3"];
1983 ["mount_options"; ""; "/dev/sda1"; "/"];
1985 ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1986 ["mkdir"; "/mp1/mp2"];
1987 ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1988 ["mkdir"; "/mp1/mp2/mp3"];
1991 "unmount all filesystems",
1993 This unmounts all mounted filesystems.
1995 Some internal mounts are not unmounted by this call.");
1997 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1999 "remove all LVM LVs, VGs and PVs",
2001 This command removes all LVM logical volumes, volume groups
2002 and physical volumes.");
2004 ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
2005 [InitISOFS, Always, TestOutput (
2006 [["file"; "/empty"]], "empty");
2007 InitISOFS, Always, TestOutput (
2008 [["file"; "/known-1"]], "ASCII text");
2009 InitISOFS, Always, TestLastFail (
2010 [["file"; "/notexists"]]);
2011 InitISOFS, Always, TestOutput (
2012 [["file"; "/abssymlink"]], "symbolic link");
2013 InitISOFS, Always, TestOutput (
2014 [["file"; "/directory"]], "directory")],
2015 "determine file type",
2017 This call uses the standard L<file(1)> command to determine
2018 the type or contents of the file.
2020 This call will also transparently look inside various types
2023 The exact command which runs is C<file -zb path>. Note in
2024 particular that the filename is not prepended to the output
2027 This command can also be used on C</dev/> devices
2028 (and partitions, LV names). You can for example use this
2029 to determine if a device contains a filesystem, although
2030 it's usually better to use C<guestfs_vfs_type>.
2032 If the C<path> does not begin with C</dev/> then
2033 this command only works for the content of regular files.
2034 For other file types (directory, symbolic link etc) it
2035 will just return the string C<directory> etc.");
2037 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
2038 [InitBasicFS, Always, TestOutput (
2039 [["upload"; "test-command"; "/test-command"];
2040 ["chmod"; "0o755"; "/test-command"];
2041 ["command"; "/test-command 1"]], "Result1");
2042 InitBasicFS, Always, TestOutput (
2043 [["upload"; "test-command"; "/test-command"];
2044 ["chmod"; "0o755"; "/test-command"];
2045 ["command"; "/test-command 2"]], "Result2\n");
2046 InitBasicFS, Always, TestOutput (
2047 [["upload"; "test-command"; "/test-command"];
2048 ["chmod"; "0o755"; "/test-command"];
2049 ["command"; "/test-command 3"]], "\nResult3");
2050 InitBasicFS, Always, TestOutput (
2051 [["upload"; "test-command"; "/test-command"];
2052 ["chmod"; "0o755"; "/test-command"];
2053 ["command"; "/test-command 4"]], "\nResult4\n");
2054 InitBasicFS, Always, TestOutput (
2055 [["upload"; "test-command"; "/test-command"];
2056 ["chmod"; "0o755"; "/test-command"];
2057 ["command"; "/test-command 5"]], "\nResult5\n\n");
2058 InitBasicFS, Always, TestOutput (
2059 [["upload"; "test-command"; "/test-command"];
2060 ["chmod"; "0o755"; "/test-command"];
2061 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
2062 InitBasicFS, Always, TestOutput (
2063 [["upload"; "test-command"; "/test-command"];
2064 ["chmod"; "0o755"; "/test-command"];
2065 ["command"; "/test-command 7"]], "");
2066 InitBasicFS, Always, TestOutput (
2067 [["upload"; "test-command"; "/test-command"];
2068 ["chmod"; "0o755"; "/test-command"];
2069 ["command"; "/test-command 8"]], "\n");
2070 InitBasicFS, Always, TestOutput (
2071 [["upload"; "test-command"; "/test-command"];
2072 ["chmod"; "0o755"; "/test-command"];
2073 ["command"; "/test-command 9"]], "\n\n");
2074 InitBasicFS, Always, TestOutput (
2075 [["upload"; "test-command"; "/test-command"];
2076 ["chmod"; "0o755"; "/test-command"];
2077 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
2078 InitBasicFS, Always, TestOutput (
2079 [["upload"; "test-command"; "/test-command"];
2080 ["chmod"; "0o755"; "/test-command"];
2081 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
2082 InitBasicFS, Always, TestLastFail (
2083 [["upload"; "test-command"; "/test-command"];
2084 ["chmod"; "0o755"; "/test-command"];
2085 ["command"; "/test-command"]])],
2086 "run a command from the guest filesystem",
2088 This call runs a command from the guest filesystem. The
2089 filesystem must be mounted, and must contain a compatible
2090 operating system (ie. something Linux, with the same
2091 or compatible processor architecture).
2093 The single parameter is an argv-style list of arguments.
2094 The first element is the name of the program to run.
2095 Subsequent elements are parameters. The list must be
2096 non-empty (ie. must contain a program name). Note that
2097 the command runs directly, and is I<not> invoked via
2098 the shell (see C<guestfs_sh>).
2100 The return value is anything printed to I<stdout> by
2103 If the command returns a non-zero exit status, then
2104 this function returns an error message. The error message
2105 string is the content of I<stderr> from the command.
2107 The C<$PATH> environment variable will contain at least
2108 C</usr/bin> and C</bin>. If you require a program from
2109 another location, you should provide the full path in the
2112 Shared libraries and data files required by the program
2113 must be available on filesystems which are mounted in the
2114 correct places. It is the caller's responsibility to ensure
2115 all filesystems that are needed are mounted at the right
2118 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
2119 [InitBasicFS, Always, TestOutputList (
2120 [["upload"; "test-command"; "/test-command"];
2121 ["chmod"; "0o755"; "/test-command"];
2122 ["command_lines"; "/test-command 1"]], ["Result1"]);
2123 InitBasicFS, Always, TestOutputList (
2124 [["upload"; "test-command"; "/test-command"];
2125 ["chmod"; "0o755"; "/test-command"];
2126 ["command_lines"; "/test-command 2"]], ["Result2"]);
2127 InitBasicFS, Always, TestOutputList (
2128 [["upload"; "test-command"; "/test-command"];
2129 ["chmod"; "0o755"; "/test-command"];
2130 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
2131 InitBasicFS, Always, TestOutputList (
2132 [["upload"; "test-command"; "/test-command"];
2133 ["chmod"; "0o755"; "/test-command"];
2134 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
2135 InitBasicFS, Always, TestOutputList (
2136 [["upload"; "test-command"; "/test-command"];
2137 ["chmod"; "0o755"; "/test-command"];
2138 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
2139 InitBasicFS, Always, TestOutputList (
2140 [["upload"; "test-command"; "/test-command"];
2141 ["chmod"; "0o755"; "/test-command"];
2142 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
2143 InitBasicFS, Always, TestOutputList (
2144 [["upload"; "test-command"; "/test-command"];
2145 ["chmod"; "0o755"; "/test-command"];
2146 ["command_lines"; "/test-command 7"]], []);
2147 InitBasicFS, Always, TestOutputList (
2148 [["upload"; "test-command"; "/test-command"];
2149 ["chmod"; "0o755"; "/test-command"];
2150 ["command_lines"; "/test-command 8"]], [""]);
2151 InitBasicFS, Always, TestOutputList (
2152 [["upload"; "test-command"; "/test-command"];
2153 ["chmod"; "0o755"; "/test-command"];
2154 ["command_lines"; "/test-command 9"]], ["";""]);
2155 InitBasicFS, Always, TestOutputList (
2156 [["upload"; "test-command"; "/test-command"];
2157 ["chmod"; "0o755"; "/test-command"];
2158 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
2159 InitBasicFS, Always, TestOutputList (
2160 [["upload"; "test-command"; "/test-command"];
2161 ["chmod"; "0o755"; "/test-command"];
2162 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
2163 "run a command, returning lines",
2165 This is the same as C<guestfs_command>, but splits the
2166 result into a list of lines.
2168 See also: C<guestfs_sh_lines>");
2170 ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
2171 [InitISOFS, Always, TestOutputStruct (
2172 [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
2173 "get file information",
2175 Returns file information for the given C<path>.
2177 This is the same as the C<stat(2)> system call.");
2179 ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
2180 [InitISOFS, Always, TestOutputStruct (
2181 [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
2182 "get file information for a symbolic link",
2184 Returns file information for the given C<path>.
2186 This is the same as C<guestfs_stat> except that if C<path>
2187 is a symbolic link, then the link is stat-ed, not the file it
2190 This is the same as the C<lstat(2)> system call.");
2192 ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
2193 [InitISOFS, Always, TestOutputStruct (
2194 [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
2195 "get file system statistics",
2197 Returns file system statistics for any mounted file system.
2198 C<path> should be a file or directory in the mounted file system
2199 (typically it is the mount point itself, but it doesn't need to be).
2201 This is the same as the C<statvfs(2)> system call.");
2203 ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
2205 "get ext2/ext3/ext4 superblock details",
2207 This returns the contents of the ext2, ext3 or ext4 filesystem
2208 superblock on C<device>.
2210 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
2211 manpage for more details. The list of fields returned isn't
2212 clearly defined, and depends on both the version of C<tune2fs>
2213 that libguestfs was built against, and the filesystem itself.");
2215 ("blockdev_setro", (RErr, [Device "device"]), 56, [],
2216 [InitEmpty, Always, TestOutputTrue (
2217 [["blockdev_setro"; "/dev/sda"];
2218 ["blockdev_getro"; "/dev/sda"]])],
2219 "set block device to read-only",
2221 Sets the block device named C<device> to read-only.
2223 This uses the L<blockdev(8)> command.");
2225 ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
2226 [InitEmpty, Always, TestOutputFalse (
2227 [["blockdev_setrw"; "/dev/sda"];
2228 ["blockdev_getro"; "/dev/sda"]])],
2229 "set block device to read-write",
2231 Sets the block device named C<device> to read-write.
2233 This uses the L<blockdev(8)> command.");
2235 ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
2236 [InitEmpty, Always, TestOutputTrue (
2237 [["blockdev_setro"; "/dev/sda"];
2238 ["blockdev_getro"; "/dev/sda"]])],
2239 "is block device set to read-only",
2241 Returns a boolean indicating if the block device is read-only
2242 (true if read-only, false if not).
2244 This uses the L<blockdev(8)> command.");
2246 ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
2247 [InitEmpty, Always, TestOutputInt (
2248 [["blockdev_getss"; "/dev/sda"]], 512)],
2249 "get sectorsize of block device",
2251 This returns the size of sectors on a block device.
2252 Usually 512, but can be larger for modern devices.
2254 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
2257 This uses the L<blockdev(8)> command.");
2259 ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
2260 [InitEmpty, Always, TestOutputInt (
2261 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
2262 "get blocksize of block device",
2264 This returns the block size of a device.
2266 (Note this is different from both I<size in blocks> and
2267 I<filesystem block size>).
2269 This uses the L<blockdev(8)> command.");
2271 ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
2273 "set blocksize of block device",
2275 This sets the block size of a device.
2277 (Note this is different from both I<size in blocks> and
2278 I<filesystem block size>).
2280 This uses the L<blockdev(8)> command.");
2282 ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
2283 [InitEmpty, Always, TestOutputInt (
2284 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
2285 "get total size of device in 512-byte sectors",
2287 This returns the size of the device in units of 512-byte sectors
2288 (even if the sectorsize isn't 512 bytes ... weird).
2290 See also C<guestfs_blockdev_getss> for the real sector size of
2291 the device, and C<guestfs_blockdev_getsize64> for the more
2292 useful I<size in bytes>.
2294 This uses the L<blockdev(8)> command.");
2296 ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
2297 [InitEmpty, Always, TestOutputInt (
2298 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
2299 "get total size of device in bytes",
2301 This returns the size of the device in bytes.
2303 See also C<guestfs_blockdev_getsz>.
2305 This uses the L<blockdev(8)> command.");
2307 ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
2308 [InitEmpty, Always, TestRun
2309 [["blockdev_flushbufs"; "/dev/sda"]]],
2310 "flush device buffers",
2312 This tells the kernel to flush internal buffers associated
2315 This uses the L<blockdev(8)> command.");
2317 ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
2318 [InitEmpty, Always, TestRun
2319 [["blockdev_rereadpt"; "/dev/sda"]]],
2320 "reread partition table",
2322 Reread the partition table on C<device>.
2324 This uses the L<blockdev(8)> command.");
2326 ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
2327 [InitBasicFS, Always, TestOutput (
2328 (* Pick a file from cwd which isn't likely to change. *)
2329 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2330 ["checksum"; "md5"; "/COPYING.LIB"]],
2331 Digest.to_hex (Digest.file "COPYING.LIB"))],
2332 "upload a file from the local machine",
2334 Upload local file C<filename> to C<remotefilename> on the
2337 C<filename> can also be a named pipe.
2339 See also C<guestfs_download>.");
2341 ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [Progress],
2342 [InitBasicFS, Always, TestOutput (
2343 (* Pick a file from cwd which isn't likely to change. *)
2344 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2345 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
2346 ["upload"; "testdownload.tmp"; "/upload"];
2347 ["checksum"; "md5"; "/upload"]],
2348 Digest.to_hex (Digest.file "COPYING.LIB"))],
2349 "download a file to the local machine",
2351 Download file C<remotefilename> and save it as C<filename>
2352 on the local machine.
2354 C<filename> can also be a named pipe.
2356 See also C<guestfs_upload>, C<guestfs_cat>.");
2358 ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
2359 [InitISOFS, Always, TestOutput (
2360 [["checksum"; "crc"; "/known-3"]], "2891671662");
2361 InitISOFS, Always, TestLastFail (
2362 [["checksum"; "crc"; "/notexists"]]);
2363 InitISOFS, Always, TestOutput (
2364 [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
2365 InitISOFS, Always, TestOutput (
2366 [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
2367 InitISOFS, Always, TestOutput (
2368 [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
2369 InitISOFS, Always, TestOutput (
2370 [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
2371 InitISOFS, Always, TestOutput (
2372 [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
2373 InitISOFS, Always, TestOutput (
2374 [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6");
2375 (* Test for RHBZ#579608, absolute symbolic links. *)
2376 InitISOFS, Always, TestOutput (
2377 [["checksum"; "sha512"; "/abssymlink"]], "5f57d0639bc95081c53afc63a449403883818edc64da48930ad6b1a4fb49be90404686877743fbcd7c99811f3def7df7bc22635c885c6a8cf79c806b43451c1a")],
2378 "compute MD5, SHAx or CRC checksum of file",
2380 This call computes the MD5, SHAx or CRC checksum of the
2383 The type of checksum to compute is given by the C<csumtype>
2384 parameter which must have one of the following values:
2390 Compute the cyclic redundancy check (CRC) specified by POSIX
2391 for the C<cksum> command.
2395 Compute the MD5 hash (using the C<md5sum> program).
2399 Compute the SHA1 hash (using the C<sha1sum> program).
2403 Compute the SHA224 hash (using the C<sha224sum> program).
2407 Compute the SHA256 hash (using the C<sha256sum> program).
2411 Compute the SHA384 hash (using the C<sha384sum> program).
2415 Compute the SHA512 hash (using the C<sha512sum> program).
2419 The checksum is returned as a printable string.
2421 To get the checksum for a device, use C<guestfs_checksum_device>.
2423 To get the checksums for many files, use C<guestfs_checksums_out>.");
2425 ("tar_in", (RErr, [FileIn "tarfile"; Pathname "directory"]), 69, [],
2426 [InitBasicFS, Always, TestOutput (
2427 [["tar_in"; "../images/helloworld.tar"; "/"];
2428 ["cat"; "/hello"]], "hello\n")],
2429 "unpack tarfile to directory",
2431 This command uploads and unpacks local file C<tarfile> (an
2432 I<uncompressed> tar file) into C<directory>.
2434 To upload a compressed tarball, use C<guestfs_tgz_in>
2435 or C<guestfs_txz_in>.");
2437 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2439 "pack directory into tarfile",
2441 This command packs the contents of C<directory> and downloads
2442 it to local file C<tarfile>.
2444 To download a compressed tarball, use C<guestfs_tgz_out>
2445 or C<guestfs_txz_out>.");
2447 ("tgz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 71, [],
2448 [InitBasicFS, Always, TestOutput (
2449 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2450 ["cat"; "/hello"]], "hello\n")],
2451 "unpack compressed tarball to directory",
2453 This command uploads and unpacks local file C<tarball> (a
2454 I<gzip compressed> tar file) into C<directory>.
2456 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2458 ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2460 "pack directory into compressed tarball",
2462 This command packs the contents of C<directory> and downloads
2463 it to local file C<tarball>.
2465 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2467 ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2468 [InitBasicFS, Always, TestLastFail (
2470 ["mount_ro"; "/dev/sda1"; "/"];
2471 ["touch"; "/new"]]);
2472 InitBasicFS, Always, TestOutput (
2473 [["write"; "/new"; "data"];
2475 ["mount_ro"; "/dev/sda1"; "/"];
2476 ["cat"; "/new"]], "data")],
2477 "mount a guest disk, read-only",
2479 This is the same as the C<guestfs_mount> command, but it
2480 mounts the filesystem with the read-only (I<-o ro>) flag.");
2482 ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2484 "mount a guest disk with mount options",
2486 This is the same as the C<guestfs_mount> command, but it
2487 allows you to set the mount options as for the
2488 L<mount(8)> I<-o> flag.
2490 If the C<options> parameter is an empty string, then
2491 no options are passed (all options default to whatever
2492 the filesystem uses).");
2494 ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2496 "mount a guest disk with mount options and vfstype",
2498 This is the same as the C<guestfs_mount> command, but it
2499 allows you to set both the mount options and the vfstype
2500 as for the L<mount(8)> I<-o> and I<-t> flags.");
2502 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2504 "debugging and internals",
2506 The C<guestfs_debug> command exposes some internals of
2507 C<guestfsd> (the guestfs daemon) that runs inside the
2510 There is no comprehensive help for this command. You have
2511 to look at the file C<daemon/debug.c> in the libguestfs source
2512 to find out what you can do.");
2514 ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2515 [InitEmpty, Always, TestOutputList (
2516 [["part_disk"; "/dev/sda"; "mbr"];
2517 ["pvcreate"; "/dev/sda1"];
2518 ["vgcreate"; "VG"; "/dev/sda1"];
2519 ["lvcreate"; "LV1"; "VG"; "50"];
2520 ["lvcreate"; "LV2"; "VG"; "50"];
2521 ["lvremove"; "/dev/VG/LV1"];
2522 ["lvs"]], ["/dev/VG/LV2"]);
2523 InitEmpty, Always, TestOutputList (
2524 [["part_disk"; "/dev/sda"; "mbr"];
2525 ["pvcreate"; "/dev/sda1"];
2526 ["vgcreate"; "VG"; "/dev/sda1"];
2527 ["lvcreate"; "LV1"; "VG"; "50"];
2528 ["lvcreate"; "LV2"; "VG"; "50"];
2529 ["lvremove"; "/dev/VG"];
2531 InitEmpty, Always, TestOutputList (
2532 [["part_disk"; "/dev/sda"; "mbr"];
2533 ["pvcreate"; "/dev/sda1"];
2534 ["vgcreate"; "VG"; "/dev/sda1"];
2535 ["lvcreate"; "LV1"; "VG"; "50"];
2536 ["lvcreate"; "LV2"; "VG"; "50"];
2537 ["lvremove"; "/dev/VG"];
2539 "remove an LVM logical volume",
2541 Remove an LVM logical volume C<device>, where C<device> is
2542 the path to the LV, such as C</dev/VG/LV>.
2544 You can also remove all LVs in a volume group by specifying
2545 the VG name, C</dev/VG>.");
2547 ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2548 [InitEmpty, Always, TestOutputList (
2549 [["part_disk"; "/dev/sda"; "mbr"];
2550 ["pvcreate"; "/dev/sda1"];
2551 ["vgcreate"; "VG"; "/dev/sda1"];
2552 ["lvcreate"; "LV1"; "VG"; "50"];
2553 ["lvcreate"; "LV2"; "VG"; "50"];
2556 InitEmpty, Always, TestOutputList (
2557 [["part_disk"; "/dev/sda"; "mbr"];
2558 ["pvcreate"; "/dev/sda1"];
2559 ["vgcreate"; "VG"; "/dev/sda1"];
2560 ["lvcreate"; "LV1"; "VG"; "50"];
2561 ["lvcreate"; "LV2"; "VG"; "50"];
2564 "remove an LVM volume group",
2566 Remove an LVM volume group C<vgname>, (for example C<VG>).
2568 This also forcibly removes all logical volumes in the volume
2571 ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2572 [InitEmpty, Always, TestOutputListOfDevices (
2573 [["part_disk"; "/dev/sda"; "mbr"];
2574 ["pvcreate"; "/dev/sda1"];
2575 ["vgcreate"; "VG"; "/dev/sda1"];
2576 ["lvcreate"; "LV1"; "VG"; "50"];
2577 ["lvcreate"; "LV2"; "VG"; "50"];
2579 ["pvremove"; "/dev/sda1"];
2581 InitEmpty, Always, TestOutputListOfDevices (
2582 [["part_disk"; "/dev/sda"; "mbr"];
2583 ["pvcreate"; "/dev/sda1"];
2584 ["vgcreate"; "VG"; "/dev/sda1"];
2585 ["lvcreate"; "LV1"; "VG"; "50"];
2586 ["lvcreate"; "LV2"; "VG"; "50"];
2588 ["pvremove"; "/dev/sda1"];
2590 InitEmpty, Always, TestOutputListOfDevices (
2591 [["part_disk"; "/dev/sda"; "mbr"];
2592 ["pvcreate"; "/dev/sda1"];
2593 ["vgcreate"; "VG"; "/dev/sda1"];
2594 ["lvcreate"; "LV1"; "VG"; "50"];
2595 ["lvcreate"; "LV2"; "VG"; "50"];
2597 ["pvremove"; "/dev/sda1"];
2599 "remove an LVM physical volume",
2601 This wipes a physical volume C<device> so that LVM will no longer
2604 The implementation uses the C<pvremove> command which refuses to
2605 wipe physical volumes that contain any volume groups, so you have
2606 to remove those first.");
2608 ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2609 [InitBasicFS, Always, TestOutput (
2610 [["set_e2label"; "/dev/sda1"; "testlabel"];
2611 ["get_e2label"; "/dev/sda1"]], "testlabel")],
2612 "set the ext2/3/4 filesystem label",
2614 This sets the ext2/3/4 filesystem label of the filesystem on
2615 C<device> to C<label>. Filesystem labels are limited to
2618 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2619 to return the existing label on a filesystem.");
2621 ("get_e2label", (RString "label", [Device "device"]), 81, [DeprecatedBy "vfs_label"],
2623 "get the ext2/3/4 filesystem label",
2625 This returns the ext2/3/4 filesystem label of the filesystem on
2628 ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2629 (let uuid = uuidgen () in
2630 [InitBasicFS, Always, TestOutput (
2631 [["set_e2uuid"; "/dev/sda1"; uuid];
2632 ["get_e2uuid"; "/dev/sda1"]], uuid);
2633 InitBasicFS, Always, TestOutput (
2634 [["set_e2uuid"; "/dev/sda1"; "clear"];
2635 ["get_e2uuid"; "/dev/sda1"]], "");
2636 (* We can't predict what UUIDs will be, so just check the commands run. *)
2637 InitBasicFS, Always, TestRun (
2638 [["set_e2uuid"; "/dev/sda1"; "random"]]);
2639 InitBasicFS, Always, TestRun (
2640 [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2641 "set the ext2/3/4 filesystem UUID",
2643 This sets the ext2/3/4 filesystem UUID of the filesystem on
2644 C<device> to C<uuid>. The format of the UUID and alternatives
2645 such as C<clear>, C<random> and C<time> are described in the
2646 L<tune2fs(8)> manpage.
2648 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2649 to return the existing UUID of a filesystem.");
2651 ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [DeprecatedBy "vfs_uuid"],
2652 (* Regression test for RHBZ#597112. *)
2653 (let uuid = uuidgen () in
2654 [InitBasicFS, Always, TestOutput (
2655 [["mke2journal"; "1024"; "/dev/sdb"];
2656 ["set_e2uuid"; "/dev/sdb"; uuid];
2657 ["get_e2uuid"; "/dev/sdb"]], uuid)]),
2658 "get the ext2/3/4 filesystem UUID",
2660 This returns the ext2/3/4 filesystem UUID of the filesystem on
2663 ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [FishOutput FishOutputHexadecimal],
2664 [InitBasicFS, Always, TestOutputInt (
2665 [["umount"; "/dev/sda1"];
2666 ["fsck"; "ext2"; "/dev/sda1"]], 0);
2667 InitBasicFS, Always, TestOutputInt (
2668 [["umount"; "/dev/sda1"];
2669 ["zero"; "/dev/sda1"];
2670 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2671 "run the filesystem checker",
2673 This runs the filesystem checker (fsck) on C<device> which
2674 should have filesystem type C<fstype>.
2676 The returned integer is the status. See L<fsck(8)> for the
2677 list of status codes from C<fsck>.
2685 Multiple status codes can be summed together.
2689 A non-zero return code can mean \"success\", for example if
2690 errors have been corrected on the filesystem.
2694 Checking or repairing NTFS volumes is not supported
2699 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2701 ("zero", (RErr, [Device "device"]), 85, [Progress],
2702 [InitBasicFS, Always, TestOutput (
2703 [["umount"; "/dev/sda1"];
2704 ["zero"; "/dev/sda1"];
2705 ["file"; "/dev/sda1"]], "data")],
2706 "write zeroes to the device",
2708 This command writes zeroes over the first few blocks of C<device>.
2710 How many blocks are zeroed isn't specified (but it's I<not> enough
2711 to securely wipe the device). It should be sufficient to remove
2712 any partition tables, filesystem superblocks and so on.
2714 See also: C<guestfs_zero_device>, C<guestfs_scrub_device>.");
2716 ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2718 * https://bugzilla.redhat.com/show_bug.cgi?id=484986
2719 * https://bugzilla.redhat.com/show_bug.cgi?id=479760
2721 [InitBasicFS, Always, TestOutputTrue (
2722 [["mkdir_p"; "/boot/grub"];
2723 ["write"; "/boot/grub/device.map"; "(hd0) /dev/vda"];
2724 ["grub_install"; "/"; "/dev/vda"];
2725 ["is_dir"; "/boot"]])],
2728 This command installs GRUB (the Grand Unified Bootloader) on
2729 C<device>, with the root directory being C<root>.
2731 Note: If grub-install reports the error
2732 \"No suitable drive was found in the generated device map.\"
2733 it may be that you need to create a C</boot/grub/device.map>
2734 file first that contains the mapping between grub device names
2735 and Linux device names. It is usually sufficient to create
2740 replacing C</dev/vda> with the name of the installation device.");
2742 ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2743 [InitBasicFS, Always, TestOutput (
2744 [["write"; "/old"; "file content"];
2745 ["cp"; "/old"; "/new"];
2746 ["cat"; "/new"]], "file content");
2747 InitBasicFS, Always, TestOutputTrue (
2748 [["write"; "/old"; "file content"];
2749 ["cp"; "/old"; "/new"];
2750 ["is_file"; "/old"]]);
2751 InitBasicFS, Always, TestOutput (
2752 [["write"; "/old"; "file content"];
2754 ["cp"; "/old"; "/dir/new"];
2755 ["cat"; "/dir/new"]], "file content")],
2758 This copies a file from C<src> to C<dest> where C<dest> is
2759 either a destination filename or destination directory.");
2761 ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2762 [InitBasicFS, Always, TestOutput (
2763 [["mkdir"; "/olddir"];
2764 ["mkdir"; "/newdir"];
2765 ["write"; "/olddir/file"; "file content"];
2766 ["cp_a"; "/olddir"; "/newdir"];
2767 ["cat"; "/newdir/olddir/file"]], "file content")],
2768 "copy a file or directory recursively",
2770 This copies a file or directory from C<src> to C<dest>
2771 recursively using the C<cp -a> command.");
2773 ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2774 [InitBasicFS, Always, TestOutput (
2775 [["write"; "/old"; "file content"];
2776 ["mv"; "/old"; "/new"];
2777 ["cat"; "/new"]], "file content");
2778 InitBasicFS, Always, TestOutputFalse (
2779 [["write"; "/old"; "file content"];
2780 ["mv"; "/old"; "/new"];
2781 ["is_file"; "/old"]])],
2784 This moves a file from C<src> to C<dest> where C<dest> is
2785 either a destination filename or destination directory.");
2787 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2788 [InitEmpty, Always, TestRun (
2789 [["drop_caches"; "3"]])],
2790 "drop kernel page cache, dentries and inodes",
2792 This instructs the guest kernel to drop its page cache,
2793 and/or dentries and inode caches. The parameter C<whattodrop>
2794 tells the kernel what precisely to drop, see
2795 L<http://linux-mm.org/Drop_Caches>
2797 Setting C<whattodrop> to 3 should drop everything.
2799 This automatically calls L<sync(2)> before the operation,
2800 so that the maximum guest memory is freed.");
2802 ("dmesg", (RString "kmsgs", []), 91, [],
2803 [InitEmpty, Always, TestRun (
2805 "return kernel messages",
2807 This returns the kernel messages (C<dmesg> output) from
2808 the guest kernel. This is sometimes useful for extended
2809 debugging of problems.
2811 Another way to get the same information is to enable
2812 verbose messages with C<guestfs_set_verbose> or by setting
2813 the environment variable C<LIBGUESTFS_DEBUG=1> before
2814 running the program.");
2816 ("ping_daemon", (RErr, []), 92, [],
2817 [InitEmpty, Always, TestRun (
2818 [["ping_daemon"]])],
2819 "ping the guest daemon",
2821 This is a test probe into the guestfs daemon running inside
2822 the qemu subprocess. Calling this function checks that the
2823 daemon responds to the ping message, without affecting the daemon
2824 or attached block device(s) in any other way.");
2826 ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2827 [InitBasicFS, Always, TestOutputTrue (
2828 [["write"; "/file1"; "contents of a file"];
2829 ["cp"; "/file1"; "/file2"];
2830 ["equal"; "/file1"; "/file2"]]);
2831 InitBasicFS, Always, TestOutputFalse (
2832 [["write"; "/file1"; "contents of a file"];
2833 ["write"; "/file2"; "contents of another file"];
2834 ["equal"; "/file1"; "/file2"]]);
2835 InitBasicFS, Always, TestLastFail (
2836 [["equal"; "/file1"; "/file2"]])],
2837 "test if two files have equal contents",
2839 This compares the two files C<file1> and C<file2> and returns
2840 true if their content is exactly equal, or false otherwise.
2842 The external L<cmp(1)> program is used for the comparison.");
2844 ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2845 [InitISOFS, Always, TestOutputList (
2846 [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2847 InitISOFS, Always, TestOutputList (
2848 [["strings"; "/empty"]], []);
2849 (* Test for RHBZ#579608, absolute symbolic links. *)
2850 InitISOFS, Always, TestRun (
2851 [["strings"; "/abssymlink"]])],
2852 "print the printable strings in a file",
2854 This runs the L<strings(1)> command on a file and returns
2855 the list of printable strings found.");
2857 ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2858 [InitISOFS, Always, TestOutputList (
2859 [["strings_e"; "b"; "/known-5"]], []);
2860 InitBasicFS, Always, TestOutputList (
2861 [["write"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"];
2862 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2863 "print the printable strings in a file",
2865 This is like the C<guestfs_strings> command, but allows you to
2866 specify the encoding of strings that are looked for in
2867 the source file C<path>.
2869 Allowed encodings are:
2875 Single 7-bit-byte characters like ASCII and the ASCII-compatible
2876 parts of ISO-8859-X (this is what C<guestfs_strings> uses).
2880 Single 8-bit-byte characters.
2884 16-bit big endian strings such as those encoded in
2885 UTF-16BE or UCS-2BE.
2887 =item l (lower case letter L)
2889 16-bit little endian such as UTF-16LE and UCS-2LE.
2890 This is useful for examining binaries in Windows guests.
2894 32-bit big endian such as UCS-4BE.
2898 32-bit little endian such as UCS-4LE.
2902 The returned strings are transcoded to UTF-8.");
2904 ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2905 [InitISOFS, Always, TestOutput (
2906 [["hexdump"; "/known-4"]], "00000000 61 62 63 0a 64 65 66 0a 67 68 69 |abc.def.ghi|\n0000000b\n");
2907 (* Test for RHBZ#501888c2 regression which caused large hexdump
2908 * commands to segfault.
2910 InitISOFS, Always, TestRun (
2911 [["hexdump"; "/100krandom"]]);
2912 (* Test for RHBZ#579608, absolute symbolic links. *)
2913 InitISOFS, Always, TestRun (
2914 [["hexdump"; "/abssymlink"]])],
2915 "dump a file in hexadecimal",
2917 This runs C<hexdump -C> on the given C<path>. The result is
2918 the human-readable, canonical hex dump of the file.");
2920 ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2921 [InitNone, Always, TestOutput (
2922 [["part_disk"; "/dev/sda"; "mbr"];
2923 ["mkfs"; "ext3"; "/dev/sda1"];
2924 ["mount_options"; ""; "/dev/sda1"; "/"];
2925 ["write"; "/new"; "test file"];
2926 ["umount"; "/dev/sda1"];
2927 ["zerofree"; "/dev/sda1"];
2928 ["mount_options"; ""; "/dev/sda1"; "/"];
2929 ["cat"; "/new"]], "test file")],
2930 "zero unused inodes and disk blocks on ext2/3 filesystem",
2932 This runs the I<zerofree> program on C<device>. This program
2933 claims to zero unused inodes and disk blocks on an ext2/3
2934 filesystem, thus making it possible to compress the filesystem
2937 You should B<not> run this program if the filesystem is
2940 It is possible that using this program can damage the filesystem
2941 or data on the filesystem.");
2943 ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2945 "resize an LVM physical volume",
2947 This resizes (expands or shrinks) an existing LVM physical
2948 volume to match the new size of the underlying device.");
2950 ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2951 Int "cyls"; Int "heads"; Int "sectors";
2952 String "line"]), 99, [DangerWillRobinson],
2954 "modify a single partition on a block device",
2956 This runs L<sfdisk(8)> option to modify just the single
2957 partition C<n> (note: C<n> counts from 1).
2959 For other parameters, see C<guestfs_sfdisk>. You should usually
2960 pass C<0> for the cyls/heads/sectors parameters.
2962 See also: C<guestfs_part_add>");
2964 ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2966 "display the partition table",
2968 This displays the partition table on C<device>, in the
2969 human-readable output of the L<sfdisk(8)> command. It is
2970 not intended to be parsed.
2972 See also: C<guestfs_part_list>");
2974 ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2976 "display the kernel geometry",
2978 This displays the kernel's idea of the geometry of C<device>.
2980 The result is in human-readable format, and not designed to
2983 ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2985 "display the disk geometry from the partition table",
2987 This displays the disk geometry of C<device> read from the
2988 partition table. Especially in the case where the underlying
2989 block device has been resized, this can be different from the
2990 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2992 The result is in human-readable format, and not designed to
2995 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2997 "activate or deactivate all volume groups",
2999 This command activates or (if C<activate> is false) deactivates
3000 all logical volumes in all volume groups.
3001 If activated, then they are made known to the
3002 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
3003 then those devices disappear.
3005 This command is the same as running C<vgchange -a y|n>");
3007 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
3009 "activate or deactivate some volume groups",
3011 This command activates or (if C<activate> is false) deactivates
3012 all logical volumes in the listed volume groups C<volgroups>.
3013 If activated, then they are made known to the
3014 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
3015 then those devices disappear.
3017 This command is the same as running C<vgchange -a y|n volgroups...>
3019 Note that if C<volgroups> is an empty list then B<all> volume groups
3020 are activated or deactivated.");
3022 ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
3023 [InitNone, Always, TestOutput (
3024 [["part_disk"; "/dev/sda"; "mbr"];
3025 ["pvcreate"; "/dev/sda1"];
3026 ["vgcreate"; "VG"; "/dev/sda1"];
3027 ["lvcreate"; "LV"; "VG"; "10"];
3028 ["mkfs"; "ext2"; "/dev/VG/LV"];
3029 ["mount_options"; ""; "/dev/VG/LV"; "/"];
3030 ["write"; "/new"; "test content"];
3032 ["lvresize"; "/dev/VG/LV"; "20"];
3033 ["e2fsck_f"; "/dev/VG/LV"];
3034 ["resize2fs"; "/dev/VG/LV"];
3035 ["mount_options"; ""; "/dev/VG/LV"; "/"];
3036 ["cat"; "/new"]], "test content");
3037 InitNone, Always, TestRun (
3038 (* Make an LV smaller to test RHBZ#587484. *)
3039 [["part_disk"; "/dev/sda"; "mbr"];
3040 ["pvcreate"; "/dev/sda1"];
3041 ["vgcreate"; "VG"; "/dev/sda1"];
3042 ["lvcreate"; "LV"; "VG"; "20"];
3043 ["lvresize"; "/dev/VG/LV"; "10"]])],
3044 "resize an LVM logical volume",
3046 This resizes (expands or shrinks) an existing LVM logical
3047 volume to C<mbytes>. When reducing, data in the reduced part
3050 ("resize2fs", (RErr, [Device "device"]), 106, [],
3051 [], (* lvresize tests this *)
3052 "resize an ext2, ext3 or ext4 filesystem",
3054 This resizes an ext2, ext3 or ext4 filesystem to match the size of
3055 the underlying device.
3057 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
3058 on the C<device> before calling this command. For unknown reasons
3059 C<resize2fs> sometimes gives an error about this and sometimes not.
3060 In any case, it is always safe to call C<guestfs_e2fsck_f> before
3061 calling this function.");
3063 ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
3064 [InitBasicFS, Always, TestOutputList (
3065 [["find"; "/"]], ["lost+found"]);
3066 InitBasicFS, Always, TestOutputList (
3070 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
3071 InitBasicFS, Always, TestOutputList (
3072 [["mkdir_p"; "/a/b/c"];
3073 ["touch"; "/a/b/c/d"];
3074 ["find"; "/a/b/"]], ["c"; "c/d"])],
3075 "find all files and directories",
3077 This command lists out all files and directories, recursively,
3078 starting at C<directory>. It is essentially equivalent to
3079 running the shell command C<find directory -print> but some
3080 post-processing happens on the output, described below.
3082 This returns a list of strings I<without any prefix>. Thus
3083 if the directory structure was:
3089 then the returned list from C<guestfs_find> C</tmp> would be
3097 If C<directory> is not a directory, then this command returns
3100 The returned list is sorted.
3102 See also C<guestfs_find0>.");
3104 ("e2fsck_f", (RErr, [Device "device"]), 108, [],
3105 [], (* lvresize tests this *)
3106 "check an ext2/ext3 filesystem",
3108 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
3109 filesystem checker on C<device>, noninteractively (C<-p>),
3110 even if the filesystem appears to be clean (C<-f>).
3112 This command is only needed because of C<guestfs_resize2fs>
3113 (q.v.). Normally you should use C<guestfs_fsck>.");
3115 ("sleep", (RErr, [Int "secs"]), 109, [],
3116 [InitNone, Always, TestRun (
3118 "sleep for some seconds",
3120 Sleep for C<secs> seconds.");
3122 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
3123 [InitNone, Always, TestOutputInt (
3124 [["part_disk"; "/dev/sda"; "mbr"];
3125 ["mkfs"; "ntfs"; "/dev/sda1"];
3126 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
3127 InitNone, Always, TestOutputInt (
3128 [["part_disk"; "/dev/sda"; "mbr"];
3129 ["mkfs"; "ext2"; "/dev/sda1"];
3130 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
3131 "probe NTFS volume",
3133 This command runs the L<ntfs-3g.probe(8)> command which probes
3134 an NTFS C<device> for mountability. (Not all NTFS volumes can
3135 be mounted read-write, and some cannot be mounted at all).
3137 C<rw> is a boolean flag. Set it to true if you want to test
3138 if the volume can be mounted read-write. Set it to false if
3139 you want to test if the volume can be mounted read-only.
3141 The return value is an integer which C<0> if the operation
3142 would succeed, or some non-zero value documented in the
3143 L<ntfs-3g.probe(8)> manual page.");
3145 ("sh", (RString "output", [String "command"]), 111, [],
3146 [], (* XXX needs tests *)
3147 "run a command via the shell",
3149 This call runs a command from the guest filesystem via the
3152 This is like C<guestfs_command>, but passes the command to:
3154 /bin/sh -c \"command\"
3156 Depending on the guest's shell, this usually results in
3157 wildcards being expanded, shell expressions being interpolated
3160 All the provisos about C<guestfs_command> apply to this call.");
3162 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
3163 [], (* XXX needs tests *)
3164 "run a command via the shell returning lines",
3166 This is the same as C<guestfs_sh>, but splits the result
3167 into a list of lines.
3169 See also: C<guestfs_command_lines>");
3171 ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
3172 (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
3173 * code in stubs.c, since all valid glob patterns must start with "/".
3174 * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
3176 [InitBasicFS, Always, TestOutputList (
3177 [["mkdir_p"; "/a/b/c"];
3178 ["touch"; "/a/b/c/d"];
3179 ["touch"; "/a/b/c/e"];
3180 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3181 InitBasicFS, Always, TestOutputList (
3182 [["mkdir_p"; "/a/b/c"];
3183 ["touch"; "/a/b/c/d"];
3184 ["touch"; "/a/b/c/e"];
3185 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3186 InitBasicFS, Always, TestOutputList (
3187 [["mkdir_p"; "/a/b/c"];
3188 ["touch"; "/a/b/c/d"];
3189 ["touch"; "/a/b/c/e"];
3190 ["glob_expand"; "/a/*/x/*"]], [])],
3191 "expand a wildcard path",
3193 This command searches for all the pathnames matching
3194 C<pattern> according to the wildcard expansion rules
3197 If no paths match, then this returns an empty list
3198 (note: not an error).
3200 It is just a wrapper around the C L<glob(3)> function
3201 with flags C<GLOB_MARK|GLOB_BRACE>.
3202 See that manual page for more details.");
3204 ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
3205 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
3206 [["scrub_device"; "/dev/sdc"]])],
3207 "scrub (securely wipe) a device",
3209 This command writes patterns over C<device> to make data retrieval
3212 It is an interface to the L<scrub(1)> program. See that
3213 manual page for more details.");
3215 ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
3216 [InitBasicFS, Always, TestRun (
3217 [["write"; "/file"; "content"];
3218 ["scrub_file"; "/file"]])],
3219 "scrub (securely wipe) a file",
3221 This command writes patterns over a file to make data retrieval
3224 The file is I<removed> after scrubbing.
3226 It is an interface to the L<scrub(1)> program. See that
3227 manual page for more details.");
3229 ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
3230 [], (* XXX needs testing *)
3231 "scrub (securely wipe) free space",
3233 This command creates the directory C<dir> and then fills it
3234 with files until the filesystem is full, and scrubs the files
3235 as for C<guestfs_scrub_file>, and deletes them.
3236 The intention is to scrub any free space on the partition
3239 It is an interface to the L<scrub(1)> program. See that
3240 manual page for more details.");
3242 ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
3243 [InitBasicFS, Always, TestRun (
3245 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
3246 "create a temporary directory",
3248 This command creates a temporary directory. The
3249 C<template> parameter should be a full pathname for the
3250 temporary directory name with the final six characters being
3253 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
3254 the second one being suitable for Windows filesystems.
3256 The name of the temporary directory that was created
3259 The temporary directory is created with mode 0700
3260 and is owned by root.
3262 The caller is responsible for deleting the temporary
3263 directory and its contents after use.
3265 See also: L<mkdtemp(3)>");
3267 ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
3268 [InitISOFS, Always, TestOutputInt (
3269 [["wc_l"; "/10klines"]], 10000);
3270 (* Test for RHBZ#579608, absolute symbolic links. *)
3271 InitISOFS, Always, TestOutputInt (
3272 [["wc_l"; "/abssymlink"]], 10000)],
3273 "count lines in a file",
3275 This command counts the lines in a file, using the
3276 C<wc -l> external command.");
3278 ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
3279 [InitISOFS, Always, TestOutputInt (
3280 [["wc_w"; "/10klines"]], 10000)],
3281 "count words in a file",
3283 This command counts the words in a file, using the
3284 C<wc -w> external command.");
3286 ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
3287 [InitISOFS, Always, TestOutputInt (
3288 [["wc_c"; "/100kallspaces"]], 102400)],
3289 "count characters in a file",
3291 This command counts the characters in a file, using the
3292 C<wc -c> external command.");
3294 ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
3295 [InitISOFS, Always, TestOutputList (
3296 [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"]);
3297 (* Test for RHBZ#579608, absolute symbolic links. *)
3298 InitISOFS, Always, TestOutputList (
3299 [["head"; "/abssymlink"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
3300 "return first 10 lines of a file",
3302 This command returns up to the first 10 lines of a file as
3303 a list of strings.");
3305 ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
3306 [InitISOFS, Always, TestOutputList (
3307 [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3308 InitISOFS, Always, TestOutputList (
3309 [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3310 InitISOFS, Always, TestOutputList (
3311 [["head_n"; "0"; "/10klines"]], [])],
3312 "return first N lines of a file",
3314 If the parameter C<nrlines> is a positive number, this returns the first
3315 C<nrlines> lines of the file C<path>.
3317 If the parameter C<nrlines> is a negative number, this returns lines
3318 from the file C<path>, excluding the last C<nrlines> lines.
3320 If the parameter C<nrlines> is zero, this returns an empty list.");
3322 ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
3323 [InitISOFS, Always, TestOutputList (
3324 [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
3325 "return last 10 lines of a file",
3327 This command returns up to the last 10 lines of a file as
3328 a list of strings.");
3330 ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
3331 [InitISOFS, Always, TestOutputList (
3332 [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3333 InitISOFS, Always, TestOutputList (
3334 [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3335 InitISOFS, Always, TestOutputList (
3336 [["tail_n"; "0"; "/10klines"]], [])],
3337 "return last N lines of a file",
3339 If the parameter C<nrlines> is a positive number, this returns the last
3340 C<nrlines> lines of the file C<path>.
3342 If the parameter C<nrlines> is a negative number, this returns lines
3343 from the file C<path>, starting with the C<-nrlines>th line.
3345 If the parameter C<nrlines> is zero, this returns an empty list.");
3347 ("df", (RString "output", []), 125, [],
3348 [], (* XXX Tricky to test because it depends on the exact format
3349 * of the 'df' command and other imponderables.
3351 "report file system disk space usage",
3353 This command runs the C<df> command to report disk space used.
3355 This command is mostly useful for interactive sessions. It
3356 is I<not> intended that you try to parse the output string.
3357 Use C<statvfs> from programs.");
3359 ("df_h", (RString "output", []), 126, [],
3360 [], (* XXX Tricky to test because it depends on the exact format
3361 * of the 'df' command and other imponderables.
3363 "report file system disk space usage (human readable)",
3365 This command runs the C<df -h> command to report disk space used
3366 in human-readable format.
3368 This command is mostly useful for interactive sessions. It
3369 is I<not> intended that you try to parse the output string.
3370 Use C<statvfs> from programs.");
3372 ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
3373 [InitISOFS, Always, TestOutputInt (
3374 [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
3375 "estimate file space usage",
3377 This command runs the C<du -s> command to estimate file space
3380 C<path> can be a file or a directory. If C<path> is a directory
3381 then the estimate includes the contents of the directory and all
3382 subdirectories (recursively).
3384 The result is the estimated size in I<kilobytes>
3385 (ie. units of 1024 bytes).");
3387 ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
3388 [InitISOFS, Always, TestOutputList (
3389 [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
3390 "list files in an initrd",
3392 This command lists out files contained in an initrd.
3394 The files are listed without any initial C</> character. The
3395 files are listed in the order they appear (not necessarily
3396 alphabetical). Directory names are listed as separate items.
3398 Old Linux kernels (2.4 and earlier) used a compressed ext2
3399 filesystem as initrd. We I<only> support the newer initramfs
3400 format (compressed cpio files).");
3402 ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
3404 "mount a file using the loop device",
3406 This command lets you mount C<file> (a filesystem image
3407 in a file) on a mount point. It is entirely equivalent to
3408 the command C<mount -o loop file mountpoint>.");
3410 ("mkswap", (RErr, [Device "device"]), 130, [],
3411 [InitEmpty, Always, TestRun (
3412 [["part_disk"; "/dev/sda"; "mbr"];
3413 ["mkswap"; "/dev/sda1"]])],
3414 "create a swap partition",
3416 Create a swap partition on C<device>.");
3418 ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
3419 [InitEmpty, Always, TestRun (
3420 [["part_disk"; "/dev/sda"; "mbr"];
3421 ["mkswap_L"; "hello"; "/dev/sda1"]])],
3422 "create a swap partition with a label",
3424 Create a swap partition on C<device> with label C<label>.
3426 Note that you cannot attach a swap label to a block device
3427 (eg. C</dev/sda>), just to a partition. This appears to be
3428 a limitation of the kernel or swap tools.");
3430 ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
3431 (let uuid = uuidgen () in
3432 [InitEmpty, Always, TestRun (
3433 [["part_disk"; "/dev/sda"; "mbr"];
3434 ["mkswap_U"; uuid; "/dev/sda1"]])]),
3435 "create a swap partition with an explicit UUID",
3437 Create a swap partition on C<device> with UUID C<uuid>.");
3439 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
3440 [InitBasicFS, Always, TestOutputStruct (
3441 [["mknod"; "0o10777"; "0"; "0"; "/node"];
3442 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
3443 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
3444 InitBasicFS, Always, TestOutputStruct (
3445 [["mknod"; "0o60777"; "66"; "99"; "/node"];
3446 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3447 "make block, character or FIFO devices",
3449 This call creates block or character special devices, or
3450 named pipes (FIFOs).
3452 The C<mode> parameter should be the mode, using the standard
3453 constants. C<devmajor> and C<devminor> are the
3454 device major and minor numbers, only used when creating block
3455 and character special devices.
3457 Note that, just like L<mknod(2)>, the mode must be bitwise
3458 OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
3459 just creates a regular file). These constants are
3460 available in the standard Linux header files, or you can use
3461 C<guestfs_mknod_b>, C<guestfs_mknod_c> or C<guestfs_mkfifo>
3462 which are wrappers around this command which bitwise OR
3463 in the appropriate constant for you.
3465 The mode actually set is affected by the umask.");
3467 ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
3468 [InitBasicFS, Always, TestOutputStruct (
3469 [["mkfifo"; "0o777"; "/node"];
3470 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
3471 "make FIFO (named pipe)",
3473 This call creates a FIFO (named pipe) called C<path> with
3474 mode C<mode>. It is just a convenient wrapper around
3477 The mode actually set is affected by the umask.");
3479 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
3480 [InitBasicFS, Always, TestOutputStruct (
3481 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
3482 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3483 "make block device node",
3485 This call creates a block device node called C<path> with
3486 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3487 It is just a convenient wrapper around C<guestfs_mknod>.
3489 The mode actually set is affected by the umask.");
3491 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
3492 [InitBasicFS, Always, TestOutputStruct (
3493 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
3494 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
3495 "make char device node",
3497 This call creates a char device node called C<path> with
3498 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3499 It is just a convenient wrapper around C<guestfs_mknod>.
3501 The mode actually set is affected by the umask.");
3503 ("umask", (RInt "oldmask", [Int "mask"]), 137, [FishOutput FishOutputOctal],
3504 [InitEmpty, Always, TestOutputInt (
3505 [["umask"; "0o22"]], 0o22)],
3506 "set file mode creation mask (umask)",
3508 This function sets the mask used for creating new files and
3509 device nodes to C<mask & 0777>.
3511 Typical umask values would be C<022> which creates new files
3512 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3513 C<002> which creates new files with permissions like
3514 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3516 The default umask is C<022>. This is important because it
3517 means that directories and device nodes will be created with
3518 C<0644> or C<0755> mode even if you specify C<0777>.
3520 See also C<guestfs_get_umask>,
3521 L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3523 This call returns the previous umask.");
3525 ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3527 "read directories entries",
3529 This returns the list of directory entries in directory C<dir>.
3531 All entries in the directory are returned, including C<.> and
3532 C<..>. The entries are I<not> sorted, but returned in the same
3533 order as the underlying filesystem.
3535 Also this call returns basic file type information about each
3536 file. The C<ftyp> field will contain one of the following characters:
3574 The L<readdir(3)> call returned a C<d_type> field with an
3579 This function is primarily intended for use by programs. To
3580 get a simple list of names, use C<guestfs_ls>. To get a printable
3581 directory for human consumption, use C<guestfs_ll>.");
3583 ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3585 "create partitions on a block device",
3587 This is a simplified interface to the C<guestfs_sfdisk>
3588 command, where partition sizes are specified in megabytes
3589 only (rounded to the nearest cylinder) and you don't need
3590 to specify the cyls, heads and sectors parameters which
3591 were rarely if ever used anyway.
3593 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3594 and C<guestfs_part_disk>");
3596 ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3598 "determine file type inside a compressed file",
3600 This command runs C<file> after first decompressing C<path>
3603 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3605 Since 1.0.63, use C<guestfs_file> instead which can now
3606 process compressed files.");
3608 ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3610 "list extended attributes of a file or directory",
3612 This call lists the extended attributes of the file or directory
3615 At the system call level, this is a combination of the
3616 L<listxattr(2)> and L<getxattr(2)> calls.
3618 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3620 ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3622 "list extended attributes of a file or directory",
3624 This is the same as C<guestfs_getxattrs>, but if C<path>
3625 is a symbolic link, then it returns the extended attributes
3626 of the link itself.");
3628 ("setxattr", (RErr, [String "xattr";
3629 String "val"; Int "vallen"; (* will be BufferIn *)
3630 Pathname "path"]), 143, [Optional "linuxxattrs"],
3632 "set extended attribute of a file or directory",
3634 This call sets the extended attribute named C<xattr>
3635 of the file C<path> to the value C<val> (of length C<vallen>).
3636 The value is arbitrary 8 bit data.
3638 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3640 ("lsetxattr", (RErr, [String "xattr";
3641 String "val"; Int "vallen"; (* will be BufferIn *)
3642 Pathname "path"]), 144, [Optional "linuxxattrs"],
3644 "set extended attribute of a file or directory",
3646 This is the same as C<guestfs_setxattr>, but if C<path>
3647 is a symbolic link, then it sets an extended attribute
3648 of the link itself.");
3650 ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3652 "remove extended attribute of a file or directory",
3654 This call removes the extended attribute named C<xattr>
3655 of the file C<path>.
3657 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3659 ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3661 "remove extended attribute of a file or directory",
3663 This is the same as C<guestfs_removexattr>, but if C<path>
3664 is a symbolic link, then it removes an extended attribute
3665 of the link itself.");
3667 ("mountpoints", (RHashtable "mps", []), 147, [],
3671 This call is similar to C<guestfs_mounts>. That call returns
3672 a list of devices. This one returns a hash table (map) of
3673 device name to directory where the device is mounted.");
3675 ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3676 (* This is a special case: while you would expect a parameter
3677 * of type "Pathname", that doesn't work, because it implies
3678 * NEED_ROOT in the generated calling code in stubs.c, and
3679 * this function cannot use NEED_ROOT.
3682 "create a mountpoint",
3684 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3685 specialized calls that can be used to create extra mountpoints
3686 before mounting the first filesystem.
3688 These calls are I<only> necessary in some very limited circumstances,
3689 mainly the case where you want to mount a mix of unrelated and/or
3690 read-only filesystems together.
3692 For example, live CDs often contain a \"Russian doll\" nest of
3693 filesystems, an ISO outer layer, with a squashfs image inside, with
3694 an ext2/3 image inside that. You can unpack this as follows
3697 add-ro Fedora-11-i686-Live.iso
3700 mkmountpoint /squash
3703 mount-loop /cd/LiveOS/squashfs.img /squash
3704 mount-loop /squash/LiveOS/ext3fs.img /ext3
3706 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3708 ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3710 "remove a mountpoint",
3712 This calls removes a mountpoint that was previously created
3713 with C<guestfs_mkmountpoint>. See C<guestfs_mkmountpoint>
3714 for full details.");
3716 ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3717 [InitISOFS, Always, TestOutputBuffer (
3718 [["read_file"; "/known-4"]], "abc\ndef\nghi");
3719 (* Test various near large, large and too large files (RHBZ#589039). *)
3720 InitBasicFS, Always, TestLastFail (
3722 ["truncate_size"; "/a"; "4194303"]; (* GUESTFS_MESSAGE_MAX - 1 *)
3723 ["read_file"; "/a"]]);
3724 InitBasicFS, Always, TestLastFail (
3726 ["truncate_size"; "/a"; "4194304"]; (* GUESTFS_MESSAGE_MAX *)
3727 ["read_file"; "/a"]]);
3728 InitBasicFS, Always, TestLastFail (
3730 ["truncate_size"; "/a"; "41943040"]; (* GUESTFS_MESSAGE_MAX * 10 *)
3731 ["read_file"; "/a"]])],
3734 This calls returns the contents of the file C<path> as a
3737 Unlike C<guestfs_cat>, this function can correctly
3738 handle files that contain embedded ASCII NUL characters.
3739 However unlike C<guestfs_download>, this function is limited
3740 in the total size of file that can be handled.");
3742 ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3743 [InitISOFS, Always, TestOutputList (
3744 [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3745 InitISOFS, Always, TestOutputList (
3746 [["grep"; "nomatch"; "/test-grep.txt"]], []);
3747 (* Test for RHBZ#579608, absolute symbolic links. *)
3748 InitISOFS, Always, TestOutputList (
3749 [["grep"; "nomatch"; "/abssymlink"]], [])],
3750 "return lines matching a pattern",
3752 This calls the external C<grep> program and returns the
3755 ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3756 [InitISOFS, Always, TestOutputList (
3757 [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3758 "return lines matching a pattern",
3760 This calls the external C<egrep> program and returns the
3763 ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3764 [InitISOFS, Always, TestOutputList (
3765 [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3766 "return lines matching a pattern",
3768 This calls the external C<fgrep> program and returns the
3771 ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3772 [InitISOFS, Always, TestOutputList (
3773 [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3774 "return lines matching a pattern",
3776 This calls the external C<grep -i> program and returns the
3779 ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3780 [InitISOFS, Always, TestOutputList (
3781 [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3782 "return lines matching a pattern",
3784 This calls the external C<egrep -i> program and returns the
3787 ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3788 [InitISOFS, Always, TestOutputList (
3789 [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3790 "return lines matching a pattern",
3792 This calls the external C<fgrep -i> program and returns the
3795 ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3796 [InitISOFS, Always, TestOutputList (
3797 [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3798 "return lines matching a pattern",
3800 This calls the external C<zgrep> program and returns the
3803 ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3804 [InitISOFS, Always, TestOutputList (
3805 [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3806 "return lines matching a pattern",
3808 This calls the external C<zegrep> program and returns the
3811 ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3812 [InitISOFS, Always, TestOutputList (
3813 [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3814 "return lines matching a pattern",
3816 This calls the external C<zfgrep> program and returns the
3819 ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3820 [InitISOFS, Always, TestOutputList (
3821 [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3822 "return lines matching a pattern",
3824 This calls the external C<zgrep -i> program and returns the
3827 ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3828 [InitISOFS, Always, TestOutputList (
3829 [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3830 "return lines matching a pattern",
3832 This calls the external C<zegrep -i> program and returns the
3835 ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3836 [InitISOFS, Always, TestOutputList (
3837 [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3838 "return lines matching a pattern",
3840 This calls the external C<zfgrep -i> program and returns the
3843 ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3844 [InitISOFS, Always, TestOutput (
3845 [["realpath"; "/../directory"]], "/directory")],
3846 "canonicalized absolute pathname",
3848 Return the canonicalized absolute pathname of C<path>. The
3849 returned path has no C<.>, C<..> or symbolic link path elements.");
3851 ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3852 [InitBasicFS, Always, TestOutputStruct (
3855 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3856 "create a hard link",
3858 This command creates a hard link using the C<ln> command.");
3860 ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3861 [InitBasicFS, Always, TestOutputStruct (
3864 ["ln_f"; "/a"; "/b"];
3865 ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3866 "create a hard link",
3868 This command creates a hard link using the C<ln -f> command.
3869 The C<-f> option removes the link (C<linkname>) if it exists already.");
3871 ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3872 [InitBasicFS, Always, TestOutputStruct (
3874 ["ln_s"; "a"; "/b"];
3875 ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3876 "create a symbolic link",
3878 This command creates a symbolic link using the C<ln -s> command.");
3880 ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3881 [InitBasicFS, Always, TestOutput (
3882 [["mkdir_p"; "/a/b"];
3883 ["touch"; "/a/b/c"];
3884 ["ln_sf"; "../d"; "/a/b/c"];
3885 ["readlink"; "/a/b/c"]], "../d")],
3886 "create a symbolic link",
3888 This command creates a symbolic link using the C<ln -sf> command,
3889 The C<-f> option removes the link (C<linkname>) if it exists already.");
3891 ("readlink", (RString "link", [Pathname "path"]), 168, [],
3892 [] (* XXX tested above *),
3893 "read the target of a symbolic link",
3895 This command reads the target of a symbolic link.");
3897 ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [DeprecatedBy "fallocate64"],
3898 [InitBasicFS, Always, TestOutputStruct (
3899 [["fallocate"; "/a"; "1000000"];
3900 ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3901 "preallocate a file in the guest filesystem",
3903 This command preallocates a file (containing zero bytes) named
3904 C<path> of size C<len> bytes. If the file exists already, it
3907 Do not confuse this with the guestfish-specific
3908 C<alloc> command which allocates a file in the host and
3909 attaches it as a device.");
3911 ("swapon_device", (RErr, [Device "device"]), 170, [],
3912 [InitPartition, Always, TestRun (
3913 [["mkswap"; "/dev/sda1"];
3914 ["swapon_device"; "/dev/sda1"];
3915 ["swapoff_device"; "/dev/sda1"]])],
3916 "enable swap on device",
3918 This command enables the libguestfs appliance to use the
3919 swap device or partition named C<device>. The increased
3920 memory is made available for all commands, for example
3921 those run using C<guestfs_command> or C<guestfs_sh>.
3923 Note that you should not swap to existing guest swap
3924 partitions unless you know what you are doing. They may
3925 contain hibernation information, or other information that
3926 the guest doesn't want you to trash. You also risk leaking
3927 information about the host to the guest this way. Instead,
3928 attach a new host device to the guest and swap on that.");
3930 ("swapoff_device", (RErr, [Device "device"]), 171, [],
3931 [], (* XXX tested by swapon_device *)
3932 "disable swap on device",
3934 This command disables the libguestfs appliance swap
3935 device or partition named C<device>.
3936 See C<guestfs_swapon_device>.");
3938 ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3939 [InitBasicFS, Always, TestRun (
3940 [["fallocate"; "/swap"; "8388608"];
3941 ["mkswap_file"; "/swap"];
3942 ["swapon_file"; "/swap"];
3943 ["swapoff_file"; "/swap"]])],
3944 "enable swap on file",
3946 This command enables swap to a file.
3947 See C<guestfs_swapon_device> for other notes.");
3949 ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3950 [], (* XXX tested by swapon_file *)
3951 "disable swap on file",
3953 This command disables the libguestfs appliance swap on file.");
3955 ("swapon_label", (RErr, [String "label"]), 174, [],
3956 [InitEmpty, Always, TestRun (
3957 [["part_disk"; "/dev/sdb"; "mbr"];
3958 ["mkswap_L"; "swapit"; "/dev/sdb1"];
3959 ["swapon_label"; "swapit"];
3960 ["swapoff_label"; "swapit"];
3961 ["zero"; "/dev/sdb"];
3962 ["blockdev_rereadpt"; "/dev/sdb"]])],
3963 "enable swap on labeled swap partition",
3965 This command enables swap to a labeled swap partition.
3966 See C<guestfs_swapon_device> for other notes.");
3968 ("swapoff_label", (RErr, [String "label"]), 175, [],
3969 [], (* XXX tested by swapon_label *)
3970 "disable swap on labeled swap partition",
3972 This command disables the libguestfs appliance swap on
3973 labeled swap partition.");
3975 ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3976 (let uuid = uuidgen () in
3977 [InitEmpty, Always, TestRun (
3978 [["mkswap_U"; uuid; "/dev/sdb"];
3979 ["swapon_uuid"; uuid];
3980 ["swapoff_uuid"; uuid]])]),
3981 "enable swap on swap partition by UUID",
3983 This command enables swap to a swap partition with the given UUID.
3984 See C<guestfs_swapon_device> for other notes.");
3986 ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3987 [], (* XXX tested by swapon_uuid *)
3988 "disable swap on swap partition by UUID",
3990 This command disables the libguestfs appliance swap partition
3991 with the given UUID.");
3993 ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3994 [InitBasicFS, Always, TestRun (
3995 [["fallocate"; "/swap"; "8388608"];
3996 ["mkswap_file"; "/swap"]])],
3997 "create a swap file",
4001 This command just writes a swap file signature to an existing
4002 file. To create the file itself, use something like C<guestfs_fallocate>.");
4004 ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
4005 [InitISOFS, Always, TestRun (
4006 [["inotify_init"; "0"]])],
4007 "create an inotify handle",
4009 This command creates a new inotify handle.
4010 The inotify subsystem can be used to notify events which happen to
4011 objects in the guest filesystem.
4013 C<maxevents> is the maximum number of events which will be
4014 queued up between calls to C<guestfs_inotify_read> or
4015 C<guestfs_inotify_files>.
4016 If this is passed as C<0>, then the kernel (or previously set)
4017 default is used. For Linux 2.6.29 the default was 16384 events.
4018 Beyond this limit, the kernel throws away events, but records
4019 the fact that it threw them away by setting a flag
4020 C<IN_Q_OVERFLOW> in the returned structure list (see
4021 C<guestfs_inotify_read>).
4023 Before any events are generated, you have to add some
4024 watches to the internal watch list. See:
4025 C<guestfs_inotify_add_watch>,
4026 C<guestfs_inotify_rm_watch> and
4027 C<guestfs_inotify_watch_all>.
4029 Queued up events should be read periodically by calling
4030 C<guestfs_inotify_read>
4031 (or C<guestfs_inotify_files> which is just a helpful
4032 wrapper around C<guestfs_inotify_read>). If you don't
4033 read the events out often enough then you risk the internal
4036 The handle should be closed after use by calling
4037 C<guestfs_inotify_close>. This also removes any
4038 watches automatically.
4040 See also L<inotify(7)> for an overview of the inotify interface
4041 as exposed by the Linux kernel, which is roughly what we expose
4042 via libguestfs. Note that there is one global inotify handle
4043 per libguestfs instance.");
4045 ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
4046 [InitBasicFS, Always, TestOutputList (
4047 [["inotify_init"; "0"];
4048 ["inotify_add_watch"; "/"; "1073741823"];
4051 ["inotify_files"]], ["a"; "b"])],
4052 "add an inotify watch",
4054 Watch C<path> for the events listed in C<mask>.
4056 Note that if C<path> is a directory then events within that
4057 directory are watched, but this does I<not> happen recursively
4058 (in subdirectories).
4060 Note for non-C or non-Linux callers: the inotify events are
4061 defined by the Linux kernel ABI and are listed in
4062 C</usr/include/sys/inotify.h>.");
4064 ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
4066 "remove an inotify watch",
4068 Remove a previously defined inotify watch.
4069 See C<guestfs_inotify_add_watch>.");
4071 ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
4073 "return list of inotify events",
4075 Return the complete queue of events that have happened
4076 since the previous read call.
4078 If no events have happened, this returns an empty list.
4080 I<Note>: In order to make sure that all events have been
4081 read, you must call this function repeatedly until it
4082 returns an empty list. The reason is that the call will
4083 read events up to the maximum appliance-to-host message
4084 size and leave remaining events in the queue.");
4086 ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
4088 "return list of watched files that had events",
4090 This function is a helpful wrapper around C<guestfs_inotify_read>
4091 which just returns a list of pathnames of objects that were
4092 touched. The returned pathnames are sorted and deduplicated.");
4094 ("inotify_close", (RErr, []), 184, [Optional "inotify"],
4096 "close the inotify handle",
4098 This closes the inotify handle which was previously
4099 opened by inotify_init. It removes all watches, throws
4100 away any pending events, and deallocates all resources.");
4102 ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
4104 "set SELinux security context",
4106 This sets the SELinux security context of the daemon
4107 to the string C<context>.
4109 See the documentation about SELINUX in L<guestfs(3)>.");
4111 ("getcon", (RString "context", []), 186, [Optional "selinux"],
4113 "get SELinux security context",
4115 This gets the SELinux security context of the daemon.
4117 See the documentation about SELINUX in L<guestfs(3)>,
4118 and C<guestfs_setcon>");
4120 ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
4121 [InitEmpty, Always, TestOutput (
4122 [["part_disk"; "/dev/sda"; "mbr"];
4123 ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
4124 ["mount_options"; ""; "/dev/sda1"; "/"];
4125 ["write"; "/new"; "new file contents"];
4126 ["cat"; "/new"]], "new file contents");
4127 InitEmpty, Always, TestRun (
4128 [["part_disk"; "/dev/sda"; "mbr"];
4129 ["mkfs_b"; "vfat"; "32768"; "/dev/sda1"]]);
4130 InitEmpty, Always, TestLastFail (
4131 [["part_disk"; "/dev/sda"; "mbr"];
4132 ["mkfs_b"; "vfat"; "32769"; "/dev/sda1"]]);
4133 InitEmpty, Always, TestLastFail (
4134 [["part_disk"; "/dev/sda"; "mbr"];
4135 ["mkfs_b"; "vfat"; "33280"; "/dev/sda1"]]);
4136 InitEmpty, IfAvailable "ntfsprogs", TestRun (
4137 [["part_disk"; "/dev/sda"; "mbr"];
4138 ["mkfs_b"; "ntfs"; "32768"; "/dev/sda1"]])],
4139 "make a filesystem with block size",
4141 This call is similar to C<guestfs_mkfs>, but it allows you to
4142 control the block size of the resulting filesystem. Supported
4143 block sizes depend on the filesystem type, but typically they
4144 are C<1024>, C<2048> or C<4096> only.
4146 For VFAT and NTFS the C<blocksize> parameter is treated as
4147 the requested cluster size.");
4149 ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
4150 [InitEmpty, Always, TestOutput (
4151 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4152 ["mke2journal"; "4096"; "/dev/sda1"];
4153 ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
4154 ["mount_options"; ""; "/dev/sda2"; "/"];
4155 ["write"; "/new"; "new file contents"];
4156 ["cat"; "/new"]], "new file contents")],
4157 "make ext2/3/4 external journal",
4159 This creates an ext2 external journal on C<device>. It is equivalent
4162 mke2fs -O journal_dev -b blocksize device");
4164 ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
4165 [InitEmpty, Always, TestOutput (
4166 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4167 ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
4168 ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
4169 ["mount_options"; ""; "/dev/sda2"; "/"];
4170 ["write"; "/new"; "new file contents"];
4171 ["cat"; "/new"]], "new file contents")],
4172 "make ext2/3/4 external journal with label",
4174 This creates an ext2 external journal on C<device> with label C<label>.");
4176 ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
4177 (let uuid = uuidgen () in
4178 [InitEmpty, Always, TestOutput (
4179 [["sfdiskM"; "/dev/sda"; ",100 ,"];
4180 ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
4181 ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
4182 ["mount_options"; ""; "/dev/sda2"; "/"];
4183 ["write"; "/new"; "new file contents"];
4184 ["cat"; "/new"]], "new file contents")]),
4185 "make ext2/3/4 external journal with UUID",
4187 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
4189 ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
4191 "make ext2/3/4 filesystem with external journal",
4193 This creates an ext2/3/4 filesystem on C<device> with
4194 an external journal on C<journal>. It is equivalent
4197 mke2fs -t fstype -b blocksize -J device=<journal> <device>
4199 See also C<guestfs_mke2journal>.");
4201 ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
4203 "make ext2/3/4 filesystem with external journal",
4205 This creates an ext2/3/4 filesystem on C<device> with
4206 an external journal on the journal labeled C<label>.
4208 See also C<guestfs_mke2journal_L>.");
4210 ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
4212 "make ext2/3/4 filesystem with external journal",
4214 This creates an ext2/3/4 filesystem on C<device> with
4215 an external journal on the journal with UUID C<uuid>.
4217 See also C<guestfs_mke2journal_U>.");
4219 ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
4220 [InitNone, Always, TestRun [["modprobe"; "fat"]]],
4221 "load a kernel module",
4223 This loads a kernel module in the appliance.
4225 The kernel module must have been whitelisted when libguestfs
4226 was built (see C<appliance/kmod.whitelist.in> in the source).");
4228 ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
4229 [InitNone, Always, TestOutput (
4230 [["echo_daemon"; "This is a test"]], "This is a test"
4232 "echo arguments back to the client",
4234 This command concatenates the list of C<words> passed with single spaces
4235 between them and returns the resulting string.
4237 You can use this command to test the connection through to the daemon.
4239 See also C<guestfs_ping_daemon>.");
4241 ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
4242 [], (* There is a regression test for this. *)
4243 "find all files and directories, returning NUL-separated list",
4245 This command lists out all files and directories, recursively,
4246 starting at C<directory>, placing the resulting list in the
4247 external file called C<files>.
4249 This command works the same way as C<guestfs_find> with the
4250 following exceptions:
4256 The resulting list is written to an external file.
4260 Items (filenames) in the result are separated
4261 by C<\\0> characters. See L<find(1)> option I<-print0>.
4265 This command is not limited in the number of names that it
4270 The result list is not sorted.
4274 ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
4275 [InitISOFS, Always, TestOutput (
4276 [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
4277 InitISOFS, Always, TestOutput (
4278 [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
4279 InitISOFS, Always, TestOutput (
4280 [["case_sensitive_path"; "/Known-1"]], "/known-1");
4281 InitISOFS, Always, TestLastFail (
4282 [["case_sensitive_path"; "/Known-1/"]]);
4283 InitBasicFS, Always, TestOutput (
4285 ["mkdir"; "/a/bbb"];
4286 ["touch"; "/a/bbb/c"];
4287 ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
4288 InitBasicFS, Always, TestOutput (
4290 ["mkdir"; "/a/bbb"];
4291 ["touch"; "/a/bbb/c"];
4292 ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
4293 InitBasicFS, Always, TestLastFail (
4295 ["mkdir"; "/a/bbb"];
4296 ["touch"; "/a/bbb/c"];
4297 ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
4298 "return true path on case-insensitive filesystem",
4300 This can be used to resolve case insensitive paths on
4301 a filesystem which is case sensitive. The use case is
4302 to resolve paths which you have read from Windows configuration
4303 files or the Windows Registry, to the true path.
4305 The command handles a peculiarity of the Linux ntfs-3g
4306 filesystem driver (and probably others), which is that although
4307 the underlying filesystem is case-insensitive, the driver
4308 exports the filesystem to Linux as case-sensitive.
4310 One consequence of this is that special directories such
4311 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
4312 (or other things) depending on the precise details of how
4313 they were created. In Windows itself this would not be
4316 Bug or feature? You decide:
4317 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
4319 This function resolves the true case of each element in the
4320 path and returns the case-sensitive path.
4322 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
4323 might return C<\"/WINDOWS/system32\"> (the exact return value
4324 would depend on details of how the directories were originally
4325 created under Windows).
4328 This function does not handle drive names, backslashes etc.
4330 See also C<guestfs_realpath>.");
4332 ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
4333 [InitBasicFS, Always, TestOutput (
4334 [["vfs_type"; "/dev/sda1"]], "ext2")],
4335 "get the Linux VFS type corresponding to a mounted device",
4337 This command gets the filesystem type corresponding to
4338 the filesystem on C<device>.
4340 For most filesystems, the result is the name of the Linux
4341 VFS module which would be used to mount this filesystem
4342 if you mounted it without specifying the filesystem type.
4343 For example a string such as C<ext3> or C<ntfs>.");
4345 ("truncate", (RErr, [Pathname "path"]), 199, [],
4346 [InitBasicFS, Always, TestOutputStruct (
4347 [["write"; "/test"; "some stuff so size is not zero"];
4348 ["truncate"; "/test"];
4349 ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
4350 "truncate a file to zero size",
4352 This command truncates C<path> to a zero-length file. The
4353 file must exist already.");
4355 ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
4356 [InitBasicFS, Always, TestOutputStruct (
4357 [["touch"; "/test"];
4358 ["truncate_size"; "/test"; "1000"];
4359 ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
4360 "truncate a file to a particular size",
4362 This command truncates C<path> to size C<size> bytes. The file
4365 If the current file size is less than C<size> then
4366 the file is extended to the required size with zero bytes.
4367 This creates a sparse file (ie. disk blocks are not allocated
4368 for the file until you write to it). To create a non-sparse
4369 file of zeroes, use C<guestfs_fallocate64> instead.");
4371 ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
4372 [InitBasicFS, Always, TestOutputStruct (
4373 [["touch"; "/test"];
4374 ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
4375 ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
4376 "set timestamp of a file with nanosecond precision",
4378 This command sets the timestamps of a file with nanosecond
4381 C<atsecs, atnsecs> are the last access time (atime) in secs and
4382 nanoseconds from the epoch.
4384 C<mtsecs, mtnsecs> are the last modification time (mtime) in
4385 secs and nanoseconds from the epoch.
4387 If the C<*nsecs> field contains the special value C<-1> then
4388 the corresponding timestamp is set to the current time. (The
4389 C<*secs> field is ignored in this case).
4391 If the C<*nsecs> field contains the special value C<-2> then
4392 the corresponding timestamp is left unchanged. (The
4393 C<*secs> field is ignored in this case).");
4395 ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
4396 [InitBasicFS, Always, TestOutputStruct (
4397 [["mkdir_mode"; "/test"; "0o111"];
4398 ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
4399 "create a directory with a particular mode",
4401 This command creates a directory, setting the initial permissions
4402 of the directory to C<mode>.
4404 For common Linux filesystems, the actual mode which is set will
4405 be C<mode & ~umask & 01777>. Non-native-Linux filesystems may
4406 interpret the mode in other ways.
4408 See also C<guestfs_mkdir>, C<guestfs_umask>");
4410 ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
4412 "change file owner and group",
4414 Change the file owner to C<owner> and group to C<group>.
4415 This is like C<guestfs_chown> but if C<path> is a symlink then
4416 the link itself is changed, not the target.
4418 Only numeric uid and gid are supported. If you want to use
4419 names, you will need to locate and parse the password file
4420 yourself (Augeas support makes this relatively easy).");
4422 ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
4424 "lstat on multiple files",
4426 This call allows you to perform the C<guestfs_lstat> operation
4427 on multiple files, where all files are in the directory C<path>.
4428 C<names> is the list of files from this directory.
4430 On return you get a list of stat structs, with a one-to-one
4431 correspondence to the C<names> list. If any name did not exist
4432 or could not be lstat'd, then the C<ino> field of that structure
4435 This call is intended for programs that want to efficiently
4436 list a directory contents without making many round-trips.
4437 See also C<guestfs_lxattrlist> for a similarly efficient call
4438 for getting extended attributes. Very long directory listings
4439 might cause the protocol message size to be exceeded, causing
4440 this call to fail. The caller must split up such requests
4441 into smaller groups of names.");
4443 ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
4445 "lgetxattr on multiple files",
4447 This call allows you to get the extended attributes
4448 of multiple files, where all files are in the directory C<path>.
4449 C<names> is the list of files from this directory.
4451 On return you get a flat list of xattr structs which must be
4452 interpreted sequentially. The first xattr struct always has a zero-length
4453 C<attrname>. C<attrval> in this struct is zero-length
4454 to indicate there was an error doing C<lgetxattr> for this
4455 file, I<or> is a C string which is a decimal number
4456 (the number of following attributes for this file, which could
4457 be C<\"0\">). Then after the first xattr struct are the
4458 zero or more attributes for the first named file.
4459 This repeats for the second and subsequent files.
4461 This call is intended for programs that want to efficiently
4462 list a directory contents without making many round-trips.
4463 See also C<guestfs_lstatlist> for a similarly efficient call
4464 for getting standard stats. Very long directory listings
4465 might cause the protocol message size to be exceeded, causing
4466 this call to fail. The caller must split up such requests
4467 into smaller groups of names.");
4469 ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
4471 "readlink on multiple files",
4473 This call allows you to do a C<readlink> operation
4474 on multiple files, where all files are in the directory C<path>.
4475 C<names> is the list of files from this directory.
4477 On return you get a list of strings, with a one-to-one
4478 correspondence to the C<names> list. Each string is the
4479 value of the symbolic link.
4481 If the C<readlink(2)> operation fails on any name, then
4482 the corresponding result string is the empty string C<\"\">.
4483 However the whole operation is completed even if there
4484 were C<readlink(2)> errors, and so you can call this
4485 function with names where you don't know if they are
4486 symbolic links already (albeit slightly less efficient).
4488 This call is intended for programs that want to efficiently
4489 list a directory contents without making many round-trips.
4490 Very long directory listings might cause the protocol
4491 message size to be exceeded, causing
4492 this call to fail. The caller must split up such requests
4493 into smaller groups of names.");
4495 ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
4496 [InitISOFS, Always, TestOutputBuffer (
4497 [["pread"; "/known-4"; "1"; "3"]], "\n");
4498 InitISOFS, Always, TestOutputBuffer (
4499 [["pread"; "/empty"; "0"; "100"]], "")],
4500 "read part of a file",
4502 This command lets you read part of a file. It reads C<count>
4503 bytes of the file, starting at C<offset>, from file C<path>.
4505 This may read fewer bytes than requested. For further details
4506 see the L<pread(2)> system call.
4508 See also C<guestfs_pwrite>.");
4510 ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
4511 [InitEmpty, Always, TestRun (
4512 [["part_init"; "/dev/sda"; "gpt"]])],
4513 "create an empty partition table",
4515 This creates an empty partition table on C<device> of one of the
4516 partition types listed below. Usually C<parttype> should be
4517 either C<msdos> or C<gpt> (for large disks).
4519 Initially there are no partitions. Following this, you should
4520 call C<guestfs_part_add> for each partition required.
4522 Possible values for C<parttype> are:
4526 =item B<efi> | B<gpt>
4528 Intel EFI / GPT partition table.
4530 This is recommended for >= 2 TB partitions that will be accessed
4531 from Linux and Intel-based Mac OS X. It also has limited backwards
4532 compatibility with the C<mbr> format.
4534 =item B<mbr> | B<msdos>
4536 The standard PC \"Master Boot Record\" (MBR) format used
4537 by MS-DOS and Windows. This partition type will B<only> work
4538 for device sizes up to 2 TB. For large disks we recommend
4543 Other partition table types that may work but are not
4552 =item B<amiga> | B<rdb>
4554 Amiga \"Rigid Disk Block\" format.
4562 DASD, used on IBM mainframes.
4570 Old Mac partition format. Modern Macs use C<gpt>.
4574 NEC PC-98 format, common in Japan apparently.
4582 ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4583 [InitEmpty, Always, TestRun (
4584 [["part_init"; "/dev/sda"; "mbr"];
4585 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4586 InitEmpty, Always, TestRun (
4587 [["part_init"; "/dev/sda"; "gpt"];
4588 ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4589 ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4590 InitEmpty, Always, TestRun (
4591 [["part_init"; "/dev/sda"; "mbr"];
4592 ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4593 ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4594 ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4595 ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4596 "add a partition to the device",
4598 This command adds a partition to C<device>. If there is no partition
4599 table on the device, call C<guestfs_part_init> first.
4601 The C<prlogex> parameter is the type of partition. Normally you
4602 should pass C<p> or C<primary> here, but MBR partition tables also
4603 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4606 C<startsect> and C<endsect> are the start and end of the partition
4607 in I<sectors>. C<endsect> may be negative, which means it counts
4608 backwards from the end of the disk (C<-1> is the last sector).
4610 Creating a partition which covers the whole disk is not so easy.
4611 Use C<guestfs_part_disk> to do that.");
4613 ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4614 [InitEmpty, Always, TestRun (
4615 [["part_disk"; "/dev/sda"; "mbr"]]);
4616 InitEmpty, Always, TestRun (
4617 [["part_disk"; "/dev/sda"; "gpt"]])],
4618 "partition whole disk with a single primary partition",
4620 This command is simply a combination of C<guestfs_part_init>
4621 followed by C<guestfs_part_add> to create a single primary partition
4622 covering the whole disk.
4624 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4625 but other possible values are described in C<guestfs_part_init>.");
4627 ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4628 [InitEmpty, Always, TestRun (
4629 [["part_disk"; "/dev/sda"; "mbr"];
4630 ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4631 "make a partition bootable",
4633 This sets the bootable flag on partition numbered C<partnum> on
4634 device C<device>. Note that partitions are numbered from 1.
4636 The bootable flag is used by some operating systems (notably
4637 Windows) to determine which partition to boot from. It is by
4638 no means universally recognized.");
4640 ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4641 [InitEmpty, Always, TestRun (
4642 [["part_disk"; "/dev/sda"; "gpt"];
4643 ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4644 "set partition name",
4646 This sets the partition name on partition numbered C<partnum> on
4647 device C<device>. Note that partitions are numbered from 1.
4649 The partition name can only be set on certain types of partition
4650 table. This works on C<gpt> but not on C<mbr> partitions.");
4652 ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4653 [], (* XXX Add a regression test for this. *)
4654 "list partitions on a device",
4656 This command parses the partition table on C<device> and
4657 returns the list of partitions found.
4659 The fields in the returned structure are:
4665 Partition number, counting from 1.
4669 Start of the partition I<in bytes>. To get sectors you have to
4670 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4674 End of the partition in bytes.
4678 Size of the partition in bytes.
4682 ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4683 [InitEmpty, Always, TestOutput (
4684 [["part_disk"; "/dev/sda"; "gpt"];
4685 ["part_get_parttype"; "/dev/sda"]], "gpt")],
4686 "get the partition table type",
4688 This command examines the partition table on C<device> and
4689 returns the partition table type (format) being used.
4691 Common return values include: C<msdos> (a DOS/Windows style MBR
4692 partition table), C<gpt> (a GPT/EFI-style partition table). Other
4693 values are possible, although unusual. See C<guestfs_part_init>
4696 ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [Progress],
4697 [InitBasicFS, Always, TestOutputBuffer (
4698 [["fill"; "0x63"; "10"; "/test"];
4699 ["read_file"; "/test"]], "cccccccccc")],
4700 "fill a file with octets",
4702 This command creates a new file called C<path>. The initial
4703 content of the file is C<len> octets of C<c>, where C<c>
4704 must be a number in the range C<[0..255]>.
4706 To fill a file with zero bytes (sparsely), it is
4707 much more efficient to use C<guestfs_truncate_size>.
4708 To create a file with a pattern of repeating bytes
4709 use C<guestfs_fill_pattern>.");
4711 ("available", (RErr, [StringList "groups"]), 216, [],
4712 [InitNone, Always, TestRun [["available"; ""]]],
4713 "test availability of some parts of the API",
4715 This command is used to check the availability of some
4716 groups of functionality in the appliance, which not all builds of
4717 the libguestfs appliance will be able to provide.
4719 The libguestfs groups, and the functions that those
4720 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4721 You can also fetch this list at runtime by calling
4722 C<guestfs_available_all_groups>.
4724 The argument C<groups> is a list of group names, eg:
4725 C<[\"inotify\", \"augeas\"]> would check for the availability of
4726 the Linux inotify functions and Augeas (configuration file
4729 The command returns no error if I<all> requested groups are available.
4731 It fails with an error if one or more of the requested
4732 groups is unavailable in the appliance.
4734 If an unknown group name is included in the
4735 list of groups then an error is always returned.
4743 You must call C<guestfs_launch> before calling this function.
4745 The reason is because we don't know what groups are
4746 supported by the appliance/daemon until it is running and can
4751 If a group of functions is available, this does not necessarily
4752 mean that they will work. You still have to check for errors
4753 when calling individual API functions even if they are
4758 It is usually the job of distro packagers to build
4759 complete functionality into the libguestfs appliance.
4760 Upstream libguestfs, if built from source with all
4761 requirements satisfied, will support everything.
4765 This call was added in version C<1.0.80>. In previous
4766 versions of libguestfs all you could do would be to speculatively
4767 execute a command to find out if the daemon implemented it.
4768 See also C<guestfs_version>.
4772 ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4773 [InitBasicFS, Always, TestOutputBuffer (
4774 [["write"; "/src"; "hello, world"];
4775 ["dd"; "/src"; "/dest"];
4776 ["read_file"; "/dest"]], "hello, world")],
4777 "copy from source to destination using dd",
4779 This command copies from one source device or file C<src>
4780 to another destination device or file C<dest>. Normally you
4781 would use this to copy to or from a device or partition, for
4782 example to duplicate a filesystem.
4784 If the destination is a device, it must be as large or larger
4785 than the source file or device, otherwise the copy will fail.
4786 This command cannot do partial copies (see C<guestfs_copy_size>).");
4788 ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4789 [InitBasicFS, Always, TestOutputInt (
4790 [["write"; "/file"; "hello, world"];
4791 ["filesize"; "/file"]], 12)],
4792 "return the size of the file in bytes",
4794 This command returns the size of C<file> in bytes.
4796 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4797 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4798 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4800 ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4801 [InitBasicFSonLVM, Always, TestOutputList (
4802 [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4803 ["lvs"]], ["/dev/VG/LV2"])],
4804 "rename an LVM logical volume",
4806 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4808 ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4809 [InitBasicFSonLVM, Always, TestOutputList (
4811 ["vg_activate"; "false"; "VG"];
4812 ["vgrename"; "VG"; "VG2"];
4813 ["vg_activate"; "true"; "VG2"];
4814 ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4815 ["vgs"]], ["VG2"])],
4816 "rename an LVM volume group",
4818 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4820 ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4821 [InitISOFS, Always, TestOutputBuffer (
4822 [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4823 "list the contents of a single file in an initrd",
4825 This command unpacks the file C<filename> from the initrd file
4826 called C<initrdpath>. The filename must be given I<without> the
4827 initial C</> character.
4829 For example, in guestfish you could use the following command
4830 to examine the boot script (usually called C</init>)
4831 contained in a Linux initrd or initramfs image:
4833 initrd-cat /boot/initrd-<version>.img init
4835 See also C<guestfs_initrd_list>.");
4837 ("pvuuid", (RString "uuid", [Device "device"]), 222, [],
4839 "get the UUID of a physical volume",
4841 This command returns the UUID of the LVM PV C<device>.");
4843 ("vguuid", (RString "uuid", [String "vgname"]), 223, [],
4845 "get the UUID of a volume group",
4847 This command returns the UUID of the LVM VG named C<vgname>.");
4849 ("lvuuid", (RString "uuid", [Device "device"]), 224, [],
4851 "get the UUID of a logical volume",
4853 This command returns the UUID of the LVM LV C<device>.");
4855 ("vgpvuuids", (RStringList "uuids", [String "vgname"]), 225, [],
4857 "get the PV UUIDs containing the volume group",
4859 Given a VG called C<vgname>, this returns the UUIDs of all
4860 the physical volumes that this volume group resides on.
4862 You can use this along with C<guestfs_pvs> and C<guestfs_pvuuid>
4863 calls to associate physical volumes and volume groups.
4865 See also C<guestfs_vglvuuids>.");
4867 ("vglvuuids", (RStringList "uuids", [String "vgname"]), 226, [],
4869 "get the LV UUIDs of all LVs in the volume group",
4871 Given a VG called C<vgname>, this returns the UUIDs of all
4872 the logical volumes created in this volume group.
4874 You can use this along with C<guestfs_lvs> and C<guestfs_lvuuid>
4875 calls to associate logical volumes and volume groups.
4877 See also C<guestfs_vgpvuuids>.");
4879 ("copy_size", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"; Int64 "size"]), 227, [Progress],
4880 [InitBasicFS, Always, TestOutputBuffer (
4881 [["write"; "/src"; "hello, world"];
4882 ["copy_size"; "/src"; "/dest"; "5"];
4883 ["read_file"; "/dest"]], "hello")],
4884 "copy size bytes from source to destination using dd",
4886 This command copies exactly C<size> bytes from one source device
4887 or file C<src> to another destination device or file C<dest>.
4889 Note this will fail if the source is too short or if the destination
4890 is not large enough.");
4892 ("zero_device", (RErr, [Device "device"]), 228, [DangerWillRobinson; Progress],
4893 [InitBasicFSonLVM, Always, TestRun (
4894 [["zero_device"; "/dev/VG/LV"]])],
4895 "write zeroes to an entire device",
4897 This command writes zeroes over the entire C<device>. Compare
4898 with C<guestfs_zero> which just zeroes the first few blocks of
4901 ("txz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 229, [Optional "xz"],
4902 [InitBasicFS, Always, TestOutput (
4903 [["txz_in"; "../images/helloworld.tar.xz"; "/"];
4904 ["cat"; "/hello"]], "hello\n")],
4905 "unpack compressed tarball to directory",
4907 This command uploads and unpacks local file C<tarball> (an
4908 I<xz compressed> tar file) into C<directory>.");
4910 ("txz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 230, [Optional "xz"],
4912 "pack directory into compressed tarball",
4914 This command packs the contents of C<directory> and downloads
4915 it to local file C<tarball> (as an xz compressed tar archive).");
4917 ("ntfsresize", (RErr, [Device "device"]), 231, [Optional "ntfsprogs"],
4919 "resize an NTFS filesystem",
4921 This command resizes an NTFS filesystem, expanding or
4922 shrinking it to the size of the underlying device.
4923 See also L<ntfsresize(8)>.");
4925 ("vgscan", (RErr, []), 232, [],
4926 [InitEmpty, Always, TestRun (
4928 "rescan for LVM physical volumes, volume groups and logical volumes",
4930 This rescans all block devices and rebuilds the list of LVM
4931 physical volumes, volume groups and logical volumes.");
4933 ("part_del", (RErr, [Device "device"; Int "partnum"]), 233, [],
4934 [InitEmpty, Always, TestRun (
4935 [["part_init"; "/dev/sda"; "mbr"];
4936 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4937 ["part_del"; "/dev/sda"; "1"]])],
4938 "delete a partition",
4940 This command deletes the partition numbered C<partnum> on C<device>.
4942 Note that in the case of MBR partitioning, deleting an
4943 extended partition also deletes any logical partitions
4946 ("part_get_bootable", (RBool "bootable", [Device "device"; Int "partnum"]), 234, [],
4947 [InitEmpty, Always, TestOutputTrue (
4948 [["part_init"; "/dev/sda"; "mbr"];
4949 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4950 ["part_set_bootable"; "/dev/sda"; "1"; "true"];
4951 ["part_get_bootable"; "/dev/sda"; "1"]])],
4952 "return true if a partition is bootable",
4954 This command returns true if the partition C<partnum> on
4955 C<device> has the bootable flag set.
4957 See also C<guestfs_part_set_bootable>.");
4959 ("part_get_mbr_id", (RInt "idbyte", [Device "device"; Int "partnum"]), 235, [FishOutput FishOutputHexadecimal],
4960 [InitEmpty, Always, TestOutputInt (
4961 [["part_init"; "/dev/sda"; "mbr"];
4962 ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4963 ["part_set_mbr_id"; "/dev/sda"; "1"; "0x7f"];
4964 ["part_get_mbr_id"; "/dev/sda"; "1"]], 0x7f)],
4965 "get the MBR type byte (ID byte) from a partition",
4967 Returns the MBR type byte (also known as the ID byte) from
4968 the numbered partition C<partnum>.
4970 Note that only MBR (old DOS-style) partitions have type bytes.
4971 You will get undefined results for other partition table
4972 types (see C<guestfs_part_get_parttype>).");
4974 ("part_set_mbr_id", (RErr, [Device "device"; Int "partnum"; Int "idbyte"]), 236, [],
4975 [], (* tested by part_get_mbr_id *)
4976 "set the MBR type byte (ID byte) of a partition",
4978 Sets the MBR type byte (also known as the ID byte) of
4979 the numbered partition C<partnum> to C<idbyte>. Note
4980 that the type bytes quoted in most documentation are
4981 in fact hexadecimal numbers, but usually documented
4982 without any leading \"0x\" which might be confusing.
4984 Note that only MBR (old DOS-style) partitions have type bytes.
4985 You will get undefined results for other partition table
4986 types (see C<guestfs_part_get_parttype>).");
4988 ("checksum_device", (RString "checksum", [String "csumtype"; Device "device"]), 237, [],
4989 [InitISOFS, Always, TestOutput (
4990 [["checksum_device"; "md5"; "/dev/sdd"]],
4991 (Digest.to_hex (Digest.file "images/test.iso")))],
4992 "compute MD5, SHAx or CRC checksum of the contents of a device",
4994 This call computes the MD5, SHAx or CRC checksum of the
4995 contents of the device named C<device>. For the types of
4996 checksums supported see the C<guestfs_checksum> command.");
4998 ("lvresize_free", (RErr, [Device "lv"; Int "percent"]), 238, [Optional "lvm2"],
4999 [InitNone, Always, TestRun (
5000 [["part_disk"; "/dev/sda"; "mbr"];
5001 ["pvcreate"; "/dev/sda1"];
5002 ["vgcreate"; "VG"; "/dev/sda1"];
5003 ["lvcreate"; "LV"; "VG"; "10"];
5004 ["lvresize_free"; "/dev/VG/LV"; "100"]])],
5005 "expand an LV to fill free space",
5007 This expands an existing logical volume C<lv> so that it fills
5008 C<pc>% of the remaining free space in the volume group. Commonly
5009 you would call this with pc = 100 which expands the logical volume
5010 as much as possible, using all remaining free space in the volume
5013 ("aug_clear", (RErr, [String "augpath"]), 239, [Optional "augeas"],
5014 [], (* XXX Augeas code needs tests. *)
5015 "clear Augeas path",
5017 Set the value associated with C<path> to C<NULL>. This
5018 is the same as the L<augtool(1)> C<clear> command.");
5020 ("get_umask", (RInt "mask", []), 240, [FishOutput FishOutputOctal],
5021 [InitEmpty, Always, TestOutputInt (
5022 [["get_umask"]], 0o22)],
5023 "get the current umask",
5025 Return the current umask. By default the umask is C<022>
5026 unless it has been set by calling C<guestfs_umask>.");
5028 ("debug_upload", (RErr, [FileIn "filename"; String "tmpname"; Int "mode"]), 241, [],
5030 "upload a file to the appliance (internal use only)",
5032 The C<guestfs_debug_upload> command uploads a file to
5033 the libguestfs appliance.
5035 There is no comprehensive help for this command. You have
5036 to look at the file C<daemon/debug.c> in the libguestfs source
5037 to find out what it is for.");
5039 ("base64_in", (RErr, [FileIn "base64file"; Pathname "filename"]), 242, [],
5040 [InitBasicFS, Always, TestOutput (
5041 [["base64_in"; "../images/hello.b64"; "/hello"];
5042 ["cat"; "/hello"]], "hello\n")],
5043 "upload base64-encoded data to file",
5045 This command uploads base64-encoded data from C<base64file>
5048 ("base64_out", (RErr, [Pathname "filename"; FileOut "base64file"]), 243, [],
5050 "download file and encode as base64",
5052 This command downloads the contents of C<filename>, writing
5053 it out to local file C<base64file> encoded as base64.");
5055 ("checksums_out", (RErr, [String "csumtype"; Pathname "directory"; FileOut "sumsfile"]), 244, [],
5057 "compute MD5, SHAx or CRC checksum of files in a directory",
5059 This command computes the checksums of all regular files in
5060 C<directory> and then emits a list of those checksums to
5061 the local output file C<sumsfile>.
5063 This can be used for verifying the integrity of a virtual
5064 machine. However to be properly secure you should pay
5065 attention to the output of the checksum command (it uses
5066 the ones from GNU coreutils). In particular when the
5067 filename is not printable, coreutils uses a special
5068 backslash syntax. For more information, see the GNU
5069 coreutils info file.");
5071 ("fill_pattern", (RErr, [String "pattern"; Int "len"; Pathname "path"]), 245, [Progress],
5072 [InitBasicFS, Always, TestOutputBuffer (
5073 [["fill_pattern"; "abcdefghijklmnopqrstuvwxyz"; "28"; "/test"];
5074 ["read_file"; "/test"]], "abcdefghijklmnopqrstuvwxyzab")],
5075 "fill a file with a repeating pattern of bytes",
5077 This function is like C<guestfs_fill> except that it creates
5078 a new file of length C<len> containing the repeating pattern
5079 of bytes in C<pattern>. The pattern is truncated if necessary
5080 to ensure the length of the file is exactly C<len> bytes.");
5082 ("write", (RErr, [Pathname "path"; BufferIn "content"]), 246, [ProtocolLimitWarning],
5083 [InitBasicFS, Always, TestOutput (
5084 [["write"; "/new"; "new file contents"];
5085 ["cat"; "/new"]], "new file contents");
5086 InitBasicFS, Always, TestOutput (
5087 [["write"; "/new"; "\nnew file contents\n"];
5088 ["cat"; "/new"]], "\nnew file contents\n");
5089 InitBasicFS, Always, TestOutput (
5090 [["write"; "/new"; "\n\n"];
5091 ["cat"; "/new"]], "\n\n");
5092 InitBasicFS, Always, TestOutput (
5093 [["write"; "/new"; ""];
5094 ["cat"; "/new"]], "");
5095 InitBasicFS, Always, TestOutput (
5096 [["write"; "/new"; "\n\n\n"];
5097 ["cat"; "/new"]], "\n\n\n");
5098 InitBasicFS, Always, TestOutput (
5099 [["write"; "/new"; "\n"];
5100 ["cat"; "/new"]], "\n")],
5101 "create a new file",
5103 This call creates a file called C<path>. The content of the
5104 file is the string C<content> (which can contain any 8 bit data).");
5106 ("pwrite", (RInt "nbytes", [Pathname "path"; BufferIn "content"; Int64 "offset"]), 247, [ProtocolLimitWarning],
5107 [InitBasicFS, Always, TestOutput (
5108 [["write"; "/new"; "new file contents"];
5109 ["pwrite"; "/new"; "data"; "4"];
5110 ["cat"; "/new"]], "new data contents");
5111 InitBasicFS, Always, TestOutput (
5112 [["write"; "/new"; "new file contents"];
5113 ["pwrite"; "/new"; "is extended"; "9"];
5114 ["cat"; "/new"]], "new file is extended");
5115 InitBasicFS, Always, TestOutput (
5116 [["write"; "/new"; "new file contents"];
5117 ["pwrite"; "/new"; ""; "4"];
5118 ["cat"; "/new"]], "new file contents")],
5119 "write to part of a file",
5121 This command writes to part of a file. It writes the data
5122 buffer C<content> to the file C<path> starting at offset C<offset>.
5124 This command implements the L<pwrite(2)> system call, and like
5125 that system call it may not write the full data requested. The
5126 return value is the number of bytes that were actually written
5127 to the file. This could even be 0, although short writes are
5128 unlikely for regular files in ordinary circumstances.
5130 See also C<guestfs_pread>.");
5132 ("resize2fs_size", (RErr, [Device "device"; Int64 "size"]), 248, [],
5134 "resize an ext2, ext3 or ext4 filesystem (with size)",
5136 This command is the same as C<guestfs_resize2fs> except that it
5137 allows you to specify the new size (in bytes) explicitly.");
5139 ("pvresize_size", (RErr, [Device "device"; Int64 "size"]), 249, [Optional "lvm2"],
5141 "resize an LVM physical volume (with size)",
5143 This command is the same as C<guestfs_pvresize> except that it
5144 allows you to specify the new size (in bytes) explicitly.");
5146 ("ntfsresize_size", (RErr, [Device "device"; Int64 "size"]), 250, [Optional "ntfsprogs"],
5148 "resize an NTFS filesystem (with size)",
5150 This command is the same as C<guestfs_ntfsresize> except that it
5151 allows you to specify the new size (in bytes) explicitly.");
5153 ("available_all_groups", (RStringList "groups", []), 251, [],
5154 [InitNone, Always, TestRun [["available_all_groups"]]],
5155 "return a list of all optional groups",
5157 This command returns a list of all optional groups that this
5158 daemon knows about. Note this returns both supported and unsupported
5159 groups. To find out which ones the daemon can actually support
5160 you have to call C<guestfs_available> on each member of the
5163 See also C<guestfs_available> and L<guestfs(3)/AVAILABILITY>.");
5165 ("fallocate64", (RErr, [Pathname "path"; Int64 "len"]), 252, [],
5166 [InitBasicFS, Always, TestOutputStruct (
5167 [["fallocate64"; "/a"; "1000000"];
5168 ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
5169 "preallocate a file in the guest filesystem",
5171 This command preallocates a file (containing zero bytes) named
5172 C<path> of size C<len> bytes. If the file exists already, it
5175 Note that this call allocates disk blocks for the file.
5176 To create a sparse file use C<guestfs_truncate_size> instead.
5178 The deprecated call C<guestfs_fallocate> does the same,
5179 but owing to an oversight it only allowed 30 bit lengths
5180 to be specified, effectively limiting the maximum size
5181 of files created through that call to 1GB.
5183 Do not confuse this with the guestfish-specific
5184 C<alloc> and C<sparse> commands which create
5185 a file in the host and attach it as a device.");
5187 ("vfs_label", (RString "label", [Device "device"]), 253, [],
5188 [InitBasicFS, Always, TestOutput (
5189 [["set_e2label"; "/dev/sda1"; "LTEST"];
5190 ["vfs_label"; "/dev/sda1"]], "LTEST")],
5191 "get the filesystem label",
5193 This returns the filesystem label of the filesystem on
5196 If the filesystem is unlabeled, this returns the empty string.
5198 To find a filesystem from the label, use C<guestfs_findfs_label>.");
5200 ("vfs_uuid", (RString "uuid", [Device "device"]), 254, [],
5201 (let uuid = uuidgen () in
5202 [InitBasicFS, Always, TestOutput (
5203 [["set_e2uuid"; "/dev/sda1"; uuid];
5204 ["vfs_uuid"; "/dev/sda1"]], uuid)]),
5205 "get the filesystem UUID",
5207 This returns the filesystem UUID of the filesystem on
5210 If the filesystem does not have a UUID, this returns the empty string.
5212 To find a filesystem from the UUID, use C<guestfs_findfs_uuid>.");
5214 ("lvm_set_filter", (RErr, [DeviceList "devices"]), 255, [Optional "lvm2"],
5215 (* Can't be tested with the current framework because
5216 * the VG is being used by the mounted filesystem, so
5217 * the vgchange -an command we do first will fail.
5220 "set LVM device filter",
5222 This sets the LVM device filter so that LVM will only be
5223 able to \"see\" the block devices in the list C<devices>,
5224 and will ignore all other attached block devices.
5226 Where disk image(s) contain duplicate PVs or VGs, this
5227 command is useful to get LVM to ignore the duplicates, otherwise
5228 LVM can get confused. Note also there are two types
5229 of duplication possible: either cloned PVs/VGs which have
5230 identical UUIDs; or VGs that are not cloned but just happen
5231 to have the same name. In normal operation you cannot
5232 create this situation, but you can do it outside LVM, eg.
5233 by cloning disk images or by bit twiddling inside the LVM
5236 This command also clears the LVM cache and performs a volume
5239 You can filter whole block devices or individual partitions.
5241 You cannot use this if any VG is currently in use (eg.
5242 contains a mounted filesystem), even if you are not
5243 filtering out that VG.");
5245 ("lvm_clear_filter", (RErr, []), 256, [],
5246 [], (* see note on lvm_set_filter *)
5247 "clear LVM device filter",
5249 This undoes the effect of C<guestfs_lvm_set_filter>. LVM
5250 will be able to see every block device.
5252 This command also clears the LVM cache and performs a volume
5255 ("luks_open", (RErr, [Device "device"; Key "key"; String "mapname"]), 257, [Optional "luks"],
5257 "open a LUKS-encrypted block device",
5259 This command opens a block device which has been encrypted
5260 according to the Linux Unified Key Setup (LUKS) standard.
5262 C<device> is the encrypted block device or partition.
5264 The caller must supply one of the keys associated with the
5265 LUKS block device, in the C<key> parameter.
5267 This creates a new block device called C</dev/mapper/mapname>.
5268 Reads and writes to this block device are decrypted from and
5269 encrypted to the underlying C<device> respectively.
5271 If this block device contains LVM volume groups, then
5272 calling C<guestfs_vgscan> followed by C<guestfs_vg_activate_all>
5273 will make them visible.");
5275 ("luks_open_ro", (RErr, [Device "device"; Key "key"; String "mapname"]), 258, [Optional "luks"],
5277 "open a LUKS-encrypted block device read-only",
5279 This is the same as C<guestfs_luks_open> except that a read-only
5280 mapping is created.");
5282 ("luks_close", (RErr, [Device "device"]), 259, [Optional "luks"],
5284 "close a LUKS device",
5286 This closes a LUKS device that was created earlier by
5287 C<guestfs_luks_open> or C<guestfs_luks_open_ro>. The
5288 C<device> parameter must be the name of the LUKS mapping
5289 device (ie. C</dev/mapper/mapname>) and I<not> the name
5290 of the underlying block device.");
5292 ("luks_format", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 260, [Optional "luks"; DangerWillRobinson],
5294 "format a block device as a LUKS encrypted device",
5296 This command erases existing data on C<device> and formats
5297 the device as a LUKS encrypted device. C<key> is the
5298 initial key, which is added to key slot C<slot>. (LUKS
5299 supports 8 key slots, numbered 0-7).");
5301 ("luks_format_cipher", (RErr, [Device "device"; Key "key"; Int "keyslot"; String "cipher"]), 261, [Optional "luks"; DangerWillRobinson],
5303 "format a block device as a LUKS encrypted device",
5305 This command is the same as C<guestfs_luks_format> but
5306 it also allows you to set the C<cipher> used.");
5308 ("luks_add_key", (RErr, [Device "device"; Key "key"; Key "newkey"; Int "keyslot"]), 262, [Optional "luks"],
5310 "add a key on a LUKS encrypted device",
5312 This command adds a new key on LUKS device C<device>.
5313 C<key> is any existing key, and is used to access the device.
5314 C<newkey> is the new key to add. C<keyslot> is the key slot
5315 that will be replaced.
5317 Note that if C<keyslot> already contains a key, then this
5318 command will fail. You have to use C<guestfs_luks_kill_slot>
5319 first to remove that key.");
5321 ("luks_kill_slot", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 263, [Optional "luks"],
5323 "remove a key from a LUKS encrypted device",
5325 This command deletes the key in key slot C<keyslot> from the
5326 encrypted LUKS device C<device>. C<key> must be one of the
5329 ("is_lv", (RBool "lvflag", [Device "device"]), 264, [Optional "lvm2"],
5330 [InitBasicFSonLVM, IfAvailable "lvm2", TestOutputTrue (
5331 [["is_lv"; "/dev/VG/LV"]]);
5332 InitBasicFSonLVM, IfAvailable "lvm2", TestOutputFalse (
5333 [["is_lv"; "/dev/sda1"]])],
5334 "test if device is a logical volume",
5336 This command tests whether C<device> is a logical volume, and
5337 returns true iff this is the case.");
5339 ("findfs_uuid", (RString "device", [String "uuid"]), 265, [],
5341 "find a filesystem by UUID",
5343 This command searches the filesystems and returns the one
5344 which has the given UUID. An error is returned if no such
5345 filesystem can be found.
5347 To find the UUID of a filesystem, use C<guestfs_vfs_uuid>.");
5349 ("findfs_label", (RString "device", [String "label"]), 266, [],
5351 "find a filesystem by label",
5353 This command searches the filesystems and returns the one
5354 which has the given label. An error is returned if no such
5355 filesystem can be found.
5357 To find the label of a filesystem, use C<guestfs_vfs_label>.");
5361 let all_functions = non_daemon_functions @ daemon_functions
5363 (* In some places we want the functions to be displayed sorted
5364 * alphabetically, so this is useful:
5366 let all_functions_sorted =
5367 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
5368 compare n1 n2) all_functions
5370 (* This is used to generate the src/MAX_PROC_NR file which
5371 * contains the maximum procedure number, a surrogate for the
5372 * ABI version number. See src/Makefile.am for the details.
5375 let proc_nrs = List.map (
5376 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
5377 ) daemon_functions in
5378 List.fold_left max 0 proc_nrs
5380 (* Field types for structures. *)
5382 | FChar (* C 'char' (really, a 7 bit byte). *)
5383 | FString (* nul-terminated ASCII string, NOT NULL. *)
5384 | FBuffer (* opaque buffer of bytes, (char *, int) pair *)
5389 | FBytes (* Any int measure that counts bytes. *)
5390 | FUUID (* 32 bytes long, NOT nul-terminated. *)
5391 | FOptPercent (* [0..100], or -1 meaning "not present". *)
5393 (* Because we generate extra parsing code for LVM command line tools,
5394 * we have to pull out the LVM columns separately here.
5404 "pv_attr", FString (* XXX *);
5405 "pv_pe_count", FInt64;
5406 "pv_pe_alloc_count", FInt64;
5409 "pv_mda_count", FInt64;
5410 "pv_mda_free", FBytes;
5411 (* Not in Fedora 10:
5412 "pv_mda_size", FBytes;
5419 "vg_attr", FString (* XXX *);
5422 "vg_sysid", FString;
5423 "vg_extent_size", FBytes;
5424 "vg_extent_count", FInt64;
5425 "vg_free_count", FInt64;
5430 "snap_count", FInt64;
5433 "vg_mda_count", FInt64;
5434 "vg_mda_free", FBytes;
5435 (* Not in Fedora 10:
5436 "vg_mda_size", FBytes;
5442 "lv_attr", FString (* XXX *);
5445 "lv_kernel_major", FInt64;
5446 "lv_kernel_minor", FInt64;
5448 "seg_count", FInt64;
5450 "snap_percent", FOptPercent;
5451 "copy_percent", FOptPercent;
5454 "mirror_log", FString;
5458 (* Names and fields in all structures (in RStruct and RStructList)
5462 (* The old RIntBool return type, only ever used for aug_defnode. Do
5463 * not use this struct in any new code.
5466 "i", FInt32; (* for historical compatibility *)
5467 "b", FInt32; (* for historical compatibility *)
5470 (* LVM PVs, VGs, LVs. *)
5471 "lvm_pv", lvm_pv_cols;
5472 "lvm_vg", lvm_vg_cols;
5473 "lvm_lv", lvm_lv_cols;
5475 (* Column names and types from stat structures.
5476 * NB. Can't use things like 'st_atime' because glibc header files
5477 * define some of these as macros. Ugh.
5508 (* Column names in dirent structure. *)
5511 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
5516 (* Version numbers. *)
5524 (* Extended attribute. *)
5526 "attrname", FString;
5530 (* Inotify events. *)
5534 "in_cookie", FUInt32;
5538 (* Partition table entry. *)
5541 "part_start", FBytes;
5543 "part_size", FBytes;
5545 ] (* end of structs *)
5547 (* Ugh, Java has to be different ..
5548 * These names are also used by the Haskell bindings.
5550 let java_structs = [
5551 "int_bool", "IntBool";
5556 "statvfs", "StatVFS";
5558 "version", "Version";
5560 "inotify_event", "INotifyEvent";
5561 "partition", "Partition";
5564 (* What structs are actually returned. *)
5565 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
5567 (* Returns a list of RStruct/RStructList structs that are returned
5568 * by any function. Each element of returned list is a pair:
5570 * (structname, RStructOnly)
5571 * == there exists function which returns RStruct (_, structname)
5572 * (structname, RStructListOnly)
5573 * == there exists function which returns RStructList (_, structname)
5574 * (structname, RStructAndList)
5575 * == there are functions returning both RStruct (_, structname)
5576 * and RStructList (_, structname)
5578 let rstructs_used_by functions =
5579 (* ||| is a "logical OR" for rstructs_used_t *)
5583 | _, RStructAndList -> RStructAndList
5584 | RStructOnly, RStructListOnly
5585 | RStructListOnly, RStructOnly -> RStructAndList
5586 | RStructOnly, RStructOnly -> RStructOnly
5587 | RStructListOnly, RStructListOnly -> RStructListOnly
5590 let h = Hashtbl.create 13 in
5592 (* if elem->oldv exists, update entry using ||| operator,
5593 * else just add elem->newv to the hash
5595 let update elem newv =
5596 try let oldv = Hashtbl.find h elem in
5597 Hashtbl.replace h elem (newv ||| oldv)
5598 with Not_found -> Hashtbl.add h elem newv
5602 fun (_, style, _, _, _, _, _) ->
5603 match fst style with
5604 | RStruct (_, structname) -> update structname RStructOnly
5605 | RStructList (_, structname) -> update structname RStructListOnly
5609 (* return key->values as a list of (key,value) *)
5610 Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
5612 (* Used for testing language bindings. *)
5614 | CallString of string
5615 | CallOptString of string option
5616 | CallStringList of string list
5618 | CallInt64 of int64
5620 | CallBuffer of string
5622 (* Used to memoize the result of pod2text. *)
5623 let pod2text_memo_filename = "src/.pod2text.data"
5624 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
5626 let chan = open_in pod2text_memo_filename in
5627 let v = input_value chan in
5631 _ -> Hashtbl.create 13
5632 let pod2text_memo_updated () =
5633 let chan = open_out pod2text_memo_filename in
5634 output_value chan pod2text_memo;
5637 (* Useful functions.
5638 * Note we don't want to use any external OCaml libraries which
5639 * makes this a bit harder than it should be.
5641 module StringMap = Map.Make (String)
5643 let failwithf fs = ksprintf failwith fs
5645 let unique = let i = ref 0 in fun () -> incr i; !i
5647 let replace_char s c1 c2 =
5648 let s2 = String.copy s in
5649 let r = ref false in
5650 for i = 0 to String.length s2 - 1 do
5651 if String.unsafe_get s2 i = c1 then (
5652 String.unsafe_set s2 i c2;
5656 if not !r then s else s2
5660 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
5662 let triml ?(test = isspace) str =
5664 let n = ref (String.length str) in
5665 while !n > 0 && test str.[!i]; do
5670 else String.sub str !i !n
5672 let trimr ?(test = isspace) str =
5673 let n = ref (String.length str) in
5674 while !n > 0 && test str.[!n-1]; do
5677 if !n = String.length str then str
5678 else String.sub str 0 !n
5680 let trim ?(test = isspace) str =
5681 trimr ~test (triml ~test str)
5683 let rec find s sub =
5684 let len = String.length s in
5685 let sublen = String.length sub in
5687 if i <= len-sublen then (
5689 if j < sublen then (
5690 if s.[i+j] = sub.[j] then loop2 (j+1)
5696 if r = -1 then loop (i+1) else r
5702 let rec replace_str s s1 s2 =
5703 let len = String.length s in
5704 let sublen = String.length s1 in
5705 let i = find s s1 in
5708 let s' = String.sub s 0 i in
5709 let s'' = String.sub s (i+sublen) (len-i-sublen) in
5710 s' ^ s2 ^ replace_str s'' s1 s2
5713 let rec string_split sep str =
5714 let len = String.length str in
5715 let seplen = String.length sep in
5716 let i = find str sep in
5717 if i = -1 then [str]
5719 let s' = String.sub str 0 i in
5720 let s'' = String.sub str (i+seplen) (len-i-seplen) in
5721 s' :: string_split sep s''
5724 let files_equal n1 n2 =
5725 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
5726 match Sys.command cmd with
5729 | i -> failwithf "%s: failed with error code %d" cmd i
5731 let rec filter_map f = function
5735 | Some y -> y :: filter_map f xs
5736 | None -> filter_map f xs
5738 let rec find_map f = function
5739 | [] -> raise Not_found
5743 | None -> find_map f xs
5746 let rec loop i = function
5748 | x :: xs -> f i x; loop (i+1) xs
5753 let rec loop i = function
5755 | x :: xs -> let r = f i x in r :: loop (i+1) xs
5759 let count_chars c str =
5760 let count = ref 0 in
5761 for i = 0 to String.length str - 1 do
5762 if c = String.unsafe_get str i then incr count
5768 for i = 0 to String.length str - 1 do
5769 let c = String.unsafe_get str i in
5774 let map_chars f str =
5775 List.map f (explode str)
5777 let name_of_argt = function
5778 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
5779 | StringList n | DeviceList n | Bool n | Int n | Int64 n
5780 | FileIn n | FileOut n | BufferIn n | Key n -> n
5782 let java_name_of_struct typ =
5783 try List.assoc typ java_structs
5786 "java_name_of_struct: no java_structs entry corresponding to %s" typ
5788 let cols_of_struct typ =
5789 try List.assoc typ structs
5791 failwithf "cols_of_struct: unknown struct %s" typ
5793 let seq_of_test = function
5794 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
5795 | TestOutputListOfDevices (s, _)
5796 | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
5797 | TestOutputTrue s | TestOutputFalse s
5798 | TestOutputLength (s, _) | TestOutputBuffer (s, _)
5799 | TestOutputStruct (s, _)
5800 | TestLastFail s -> s
5802 (* Handling for function flags. *)
5803 let progress_message =
5804 "This long-running command can generate progress notification messages
5805 so that the caller can display a progress bar or indicator.
5806 To receive these messages, the caller must register a progress
5807 callback. See L<guestfs(3)/guestfs_set_progress_callback>."
5809 let protocol_limit_warning =
5810 "Because of the message protocol, there is a transfer limit
5811 of somewhere between 2MB and 4MB. See L<guestfs(3)/PROTOCOL LIMITS>."
5813 let danger_will_robinson =
5814 "B<This command is dangerous. Without careful use you
5815 can easily destroy all your data>."
5817 let deprecation_notice flags =
5820 find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
5822 sprintf "This function is deprecated.
5823 In new code, use the C<%s> call instead.
5825 Deprecated functions will not be removed from the API, but the
5826 fact that they are deprecated indicates that there are problems
5827 with correct use of these functions." alt in
5832 (* Create list of optional groups. *)
5834 let h = Hashtbl.create 13 in
5836 fun (name, _, _, flags, _, _, _) ->
5840 let names = try Hashtbl.find h group with Not_found -> [] in
5841 Hashtbl.replace h group (name :: names)
5845 let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
5848 fun group -> group, List.sort compare (Hashtbl.find h group)
5850 List.sort (fun x y -> compare (fst x) (fst y)) groups
5852 (* Check function names etc. for consistency. *)
5853 let check_functions () =
5854 let contains_uppercase str =
5855 let len = String.length str in
5857 if i >= len then false
5860 if c >= 'A' && c <= 'Z' then true
5867 (* Check function names. *)
5869 fun (name, _, _, _, _, _, _) ->
5870 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
5871 failwithf "function name %s does not need 'guestfs' prefix" name;
5873 failwithf "function name is empty";
5874 if name.[0] < 'a' || name.[0] > 'z' then
5875 failwithf "function name %s must start with lowercase a-z" name;
5876 if String.contains name '-' then
5877 failwithf "function name %s should not contain '-', use '_' instead."
5881 (* Check function parameter/return names. *)
5883 fun (name, style, _, _, _, _, _) ->
5884 let check_arg_ret_name n =
5885 if contains_uppercase n then
5886 failwithf "%s param/ret %s should not contain uppercase chars"
5888 if String.contains n '-' || String.contains n '_' then
5889 failwithf "%s param/ret %s should not contain '-' or '_'"
5892 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;
5893 if n = "int" || n = "char" || n = "short" || n = "long" then
5894 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
5895 if n = "i" || n = "n" then
5896 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
5897 if n = "argv" || n = "args" then
5898 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
5900 (* List Haskell, OCaml and C keywords here.
5901 * http://www.haskell.org/haskellwiki/Keywords
5902 * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
5903 * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
5904 * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
5905 * |perl -pe 's/(.+)/"$1";/'|fmt -70
5906 * Omitting _-containing words, since they're handled above.
5907 * Omitting the OCaml reserved word, "val", is ok,
5908 * and saves us from renaming several parameters.
5911 "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
5912 "char"; "class"; "const"; "constraint"; "continue"; "data";
5913 "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
5914 "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
5915 "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
5916 "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
5917 "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
5919 "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
5920 "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
5921 "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
5922 "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
5923 "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
5924 "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
5925 "volatile"; "when"; "where"; "while";
5927 if List.mem n reserved then
5928 failwithf "%s has param/ret using reserved word %s" name n;
5931 (match fst style with
5933 | RInt n | RInt64 n | RBool n
5934 | RConstString n | RConstOptString n | RString n
5935 | RStringList n | RStruct (n, _) | RStructList (n, _)
5936 | RHashtable n | RBufferOut n ->
5937 check_arg_ret_name n
5939 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
5942 (* Check short descriptions. *)
5944 fun (name, _, _, _, _, shortdesc, _) ->
5945 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
5946 failwithf "short description of %s should begin with lowercase." name;
5947 let c = shortdesc.[String.length shortdesc-1] in
5948 if c = '\n' || c = '.' then
5949 failwithf "short description of %s should not end with . or \\n." name
5952 (* Check long descriptions. *)
5954 fun (name, _, _, _, _, _, longdesc) ->
5955 if longdesc.[String.length longdesc-1] = '\n' then
5956 failwithf "long description of %s should not end with \\n." name
5959 (* Check proc_nrs. *)
5961 fun (name, _, proc_nr, _, _, _, _) ->
5962 if proc_nr <= 0 then
5963 failwithf "daemon function %s should have proc_nr > 0" name
5967 fun (name, _, proc_nr, _, _, _, _) ->
5968 if proc_nr <> -1 then
5969 failwithf "non-daemon function %s should have proc_nr -1" name
5970 ) non_daemon_functions;
5973 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
5976 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
5977 let rec loop = function
5980 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
5982 | (name1,nr1) :: (name2,nr2) :: _ ->
5983 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
5991 (* Ignore functions that have no tests. We generate a
5992 * warning when the user does 'make check' instead.
5994 | name, _, _, _, [], _, _ -> ()
5995 | name, _, _, _, tests, _, _ ->
5999 match seq_of_test test with
6001 failwithf "%s has a test containing an empty sequence" name
6002 | cmds -> List.map List.hd cmds
6004 let funcs = List.flatten funcs in
6006 let tested = List.mem name funcs in
6009 failwithf "function %s has tests but does not test itself" name
6012 (* 'pr' prints to the current output file. *)
6013 let chan = ref Pervasives.stdout
6018 let i = count_chars '\n' str in
6019 lines := !lines + i;
6020 output_string !chan str
6023 let copyright_years =
6024 let this_year = 1900 + (localtime (time ())).tm_year in
6025 if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
6027 (* Generate a header block in a number of standard styles. *)
6028 type comment_style =
6029 CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
6030 type license = GPLv2plus | LGPLv2plus
6032 let generate_header ?(extra_inputs = []) comment license =
6033 let inputs = "src/generator.ml" :: extra_inputs in
6034 let c = match comment with
6035 | CStyle -> pr "/* "; " *"
6036 | CPlusPlusStyle -> pr "// "; "//"
6037 | HashStyle -> pr "# "; "#"
6038 | OCamlStyle -> pr "(* "; " *"
6039 | HaskellStyle -> pr "{- "; " " in
6040 pr "libguestfs generated file\n";
6041 pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
6042 List.iter (pr "%s %s\n" c) inputs;
6043 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
6045 pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
6049 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
6050 pr "%s it under the terms of the GNU General Public License as published by\n" c;
6051 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
6052 pr "%s (at your option) any later version.\n" c;
6054 pr "%s This program is distributed in the hope that it will be useful,\n" c;
6055 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6056 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
6057 pr "%s GNU General Public License for more details.\n" c;
6059 pr "%s You should have received a copy of the GNU General Public License along\n" c;
6060 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
6061 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
6064 pr "%s This library is free software; you can redistribute it and/or\n" c;
6065 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
6066 pr "%s License as published by the Free Software Foundation; either\n" c;
6067 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
6069 pr "%s This library is distributed in the hope that it will be useful,\n" c;
6070 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6071 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
6072 pr "%s Lesser General Public License for more details.\n" c;
6074 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
6075 pr "%s License along with this library; if not, write to the Free Software\n" c;
6076 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
6079 | CStyle -> pr " */\n"
6082 | OCamlStyle -> pr " *)\n"
6083 | HaskellStyle -> pr "-}\n"
6087 (* Start of main code generation functions below this line. *)
6089 (* Generate the pod documentation for the C API. *)
6090 let rec generate_actions_pod () =
6092 fun (shortname, style, _, flags, _, _, longdesc) ->
6093 if not (List.mem NotInDocs flags) then (
6094 let name = "guestfs_" ^ shortname in
6095 pr "=head2 %s\n\n" name;
6097 generate_prototype ~extern:false ~handle:"g" name style;
6099 pr "%s\n\n" longdesc;
6100 (match fst style with
6102 pr "This function returns 0 on success or -1 on error.\n\n"
6104 pr "On error this function returns -1.\n\n"
6106 pr "On error this function returns -1.\n\n"
6108 pr "This function returns a C truth value on success or -1 on error.\n\n"
6110 pr "This function returns a string, or NULL on error.
6111 The string is owned by the guest handle and must I<not> be freed.\n\n"
6112 | RConstOptString _ ->
6113 pr "This function returns a string which may be NULL.
6114 There is no way to return an error from this function.
6115 The string is owned by the guest handle and must I<not> be freed.\n\n"
6117 pr "This function returns a string, or NULL on error.
6118 I<The caller must free the returned string after use>.\n\n"
6120 pr "This function returns a NULL-terminated array of strings
6121 (like L<environ(3)>), or NULL if there was an error.
6122 I<The caller must free the strings and the array after use>.\n\n"
6123 | RStruct (_, typ) ->
6124 pr "This function returns a C<struct guestfs_%s *>,
6125 or NULL if there was an error.
6126 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
6127 | RStructList (_, typ) ->
6128 pr "This function returns a C<struct guestfs_%s_list *>
6129 (see E<lt>guestfs-structs.hE<gt>),
6130 or NULL if there was an error.
6131 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
6133 pr "This function returns a NULL-terminated array of
6134 strings, or NULL if there was an error.
6135 The array of strings will always have length C<2n+1>, where
6136 C<n> keys and values alternate, followed by the trailing NULL entry.
6137 I<The caller must free the strings and the array after use>.\n\n"
6139 pr "This function returns a buffer, or NULL on error.
6140 The size of the returned buffer is written to C<*size_r>.
6141 I<The caller must free the returned buffer after use>.\n\n"
6143 if List.mem Progress flags then
6144 pr "%s\n\n" progress_message;
6145 if List.mem ProtocolLimitWarning flags then
6146 pr "%s\n\n" protocol_limit_warning;
6147 if List.mem DangerWillRobinson flags then
6148 pr "%s\n\n" danger_will_robinson;
6149 if List.exists (function Key _ -> true | _ -> false) (snd style) then
6150 pr "This function takes a key or passphrase parameter which
6151 could contain sensitive material. Read the section
6152 L</KEYS AND PASSPHRASES> for more information.\n\n";
6153 match deprecation_notice flags with
6155 | Some txt -> pr "%s\n\n" txt
6157 ) all_functions_sorted
6159 and generate_structs_pod () =
6160 (* Structs documentation. *)
6163 pr "=head2 guestfs_%s\n" typ;
6165 pr " struct guestfs_%s {\n" typ;
6168 | name, FChar -> pr " char %s;\n" name
6169 | name, FUInt32 -> pr " uint32_t %s;\n" name
6170 | name, FInt32 -> pr " int32_t %s;\n" name
6171 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
6172 | name, FInt64 -> pr " int64_t %s;\n" name
6173 | name, FString -> pr " char *%s;\n" name
6175 pr " /* The next two fields describe a byte array. */\n";
6176 pr " uint32_t %s_len;\n" name;
6177 pr " char *%s;\n" name
6179 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
6180 pr " char %s[32];\n" name
6181 | name, FOptPercent ->
6182 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
6183 pr " float %s;\n" name
6187 pr " struct guestfs_%s_list {\n" typ;
6188 pr " uint32_t len; /* Number of elements in list. */\n";
6189 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
6192 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
6193 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
6198 and generate_availability_pod () =
6199 (* Availability documentation. *)
6203 fun (group, functions) ->
6204 pr "=item B<%s>\n" group;
6206 pr "The following functions:\n";
6207 List.iter (pr "L</guestfs_%s>\n") functions;
6213 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
6214 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
6216 * We have to use an underscore instead of a dash because otherwise
6217 * rpcgen generates incorrect code.
6219 * This header is NOT exported to clients, but see also generate_structs_h.
6221 and generate_xdr () =
6222 generate_header CStyle LGPLv2plus;
6224 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
6225 pr "typedef string guestfs_str<>;\n";
6228 (* Internal structures. *)
6232 pr "struct guestfs_int_%s {\n" typ;
6234 | name, FChar -> pr " char %s;\n" name
6235 | name, FString -> pr " string %s<>;\n" name
6236 | name, FBuffer -> pr " opaque %s<>;\n" name
6237 | name, FUUID -> pr " opaque %s[32];\n" name
6238 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
6239 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
6240 | name, FOptPercent -> pr " float %s;\n" name
6244 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
6249 fun (shortname, style, _, _, _, _, _) ->
6250 let name = "guestfs_" ^ shortname in
6252 (match snd style with
6255 pr "struct %s_args {\n" name;
6258 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6259 pr " string %s<>;\n" n
6260 | OptString n -> pr " guestfs_str *%s;\n" n
6261 | StringList n | DeviceList n -> pr " guestfs_str %s<>;\n" n
6262 | Bool n -> pr " bool %s;\n" n
6263 | Int n -> pr " int %s;\n" n
6264 | Int64 n -> pr " hyper %s;\n" n
6266 pr " opaque %s<>;\n" n
6267 | FileIn _ | FileOut _ -> ()
6271 (match fst style with
6274 pr "struct %s_ret {\n" name;
6278 pr "struct %s_ret {\n" name;
6279 pr " hyper %s;\n" n;
6282 pr "struct %s_ret {\n" name;
6285 | RConstString _ | RConstOptString _ ->
6286 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6288 pr "struct %s_ret {\n" name;
6289 pr " string %s<>;\n" n;
6292 pr "struct %s_ret {\n" name;
6293 pr " guestfs_str %s<>;\n" n;
6295 | RStruct (n, typ) ->
6296 pr "struct %s_ret {\n" name;
6297 pr " guestfs_int_%s %s;\n" typ n;
6299 | RStructList (n, typ) ->
6300 pr "struct %s_ret {\n" name;
6301 pr " guestfs_int_%s_list %s;\n" typ n;
6304 pr "struct %s_ret {\n" name;
6305 pr " guestfs_str %s<>;\n" n;
6308 pr "struct %s_ret {\n" name;
6309 pr " opaque %s<>;\n" n;
6314 (* Table of procedure numbers. *)
6315 pr "enum guestfs_procedure {\n";
6317 fun (shortname, _, proc_nr, _, _, _, _) ->
6318 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
6320 pr " GUESTFS_PROC_NR_PROCS\n";
6324 (* Having to choose a maximum message size is annoying for several
6325 * reasons (it limits what we can do in the API), but it (a) makes
6326 * the protocol a lot simpler, and (b) provides a bound on the size
6327 * of the daemon which operates in limited memory space.
6329 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
6332 (* Message header, etc. *)
6334 /* The communication protocol is now documented in the guestfs(3)
6338 const GUESTFS_PROGRAM = 0x2000F5F5;
6339 const GUESTFS_PROTOCOL_VERSION = 2;
6341 /* These constants must be larger than any possible message length. */
6342 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
6343 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
6344 const GUESTFS_PROGRESS_FLAG = 0xffff5555;
6346 enum guestfs_message_direction {
6347 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
6348 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
6351 enum guestfs_message_status {
6352 GUESTFS_STATUS_OK = 0,
6353 GUESTFS_STATUS_ERROR = 1
6358 pr "const GUESTFS_ERROR_LEN = %d;\n" (64 * 1024);
6362 struct guestfs_message_error {
6363 int linux_errno; /* Linux errno if available. */
6364 string error_message<GUESTFS_ERROR_LEN>;
6367 struct guestfs_message_header {
6368 unsigned prog; /* GUESTFS_PROGRAM */
6369 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
6370 guestfs_procedure proc; /* GUESTFS_PROC_x */
6371 guestfs_message_direction direction;
6372 unsigned serial; /* message serial number */
6373 guestfs_message_status status;
6376 const GUESTFS_MAX_CHUNK_SIZE = 8192;
6378 struct guestfs_chunk {
6379 int cancel; /* if non-zero, transfer is cancelled */
6380 /* data size is 0 bytes if the transfer has finished successfully */
6381 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
6384 /* Progress notifications. Daemon self-limits these messages to
6385 * at most one per second. The daemon can send these messages
6386 * at any time, and the caller should discard unexpected messages.
6387 * 'position' and 'total' have undefined units; however they may
6388 * have meaning for some calls.
6390 * NB. guestfs___recv_from_daemon assumes the XDR-encoded
6391 * structure is 24 bytes long.
6393 struct guestfs_progress {
6394 guestfs_procedure proc; /* @0: GUESTFS_PROC_x */
6395 unsigned serial; /* @4: message serial number */
6396 unsigned hyper position; /* @8: 0 <= position <= total */
6397 unsigned hyper total; /* @16: total size of operation */
6398 /* @24: size of structure */
6402 (* Generate the guestfs-structs.h file. *)
6403 and generate_structs_h () =
6404 generate_header CStyle LGPLv2plus;
6406 (* This is a public exported header file containing various
6407 * structures. The structures are carefully written to have
6408 * exactly the same in-memory format as the XDR structures that
6409 * we use on the wire to the daemon. The reason for creating
6410 * copies of these structures here is just so we don't have to
6411 * export the whole of guestfs_protocol.h (which includes much
6412 * unrelated and XDR-dependent stuff that we don't want to be
6413 * public, or required by clients).
6415 * To reiterate, we will pass these structures to and from the
6416 * client with a simple assignment or memcpy, so the format
6417 * must be identical to what rpcgen / the RFC defines.
6420 (* Public structures. *)
6423 pr "struct guestfs_%s {\n" typ;
6426 | name, FChar -> pr " char %s;\n" name
6427 | name, FString -> pr " char *%s;\n" name
6429 pr " uint32_t %s_len;\n" name;
6430 pr " char *%s;\n" name
6431 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
6432 | name, FUInt32 -> pr " uint32_t %s;\n" name
6433 | name, FInt32 -> pr " int32_t %s;\n" name
6434 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
6435 | name, FInt64 -> pr " int64_t %s;\n" name
6436 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
6440 pr "struct guestfs_%s_list {\n" typ;
6441 pr " uint32_t len;\n";
6442 pr " struct guestfs_%s *val;\n" typ;
6445 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
6446 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
6450 (* Generate the guestfs-actions.h file. *)
6451 and generate_actions_h () =
6452 generate_header CStyle LGPLv2plus;
6454 fun (shortname, style, _, _, _, _, _) ->
6455 let name = "guestfs_" ^ shortname in
6456 generate_prototype ~single_line:true ~newline:true ~handle:"g"
6460 (* Generate the guestfs-internal-actions.h file. *)
6461 and generate_internal_actions_h () =
6462 generate_header CStyle LGPLv2plus;
6464 fun (shortname, style, _, _, _, _, _) ->
6465 let name = "guestfs__" ^ shortname in
6466 generate_prototype ~single_line:true ~newline:true ~handle:"g"
6468 ) non_daemon_functions
6470 (* Generate the client-side dispatch stubs. *)
6471 and generate_client_actions () =
6472 generate_header CStyle LGPLv2plus;
6479 #include <inttypes.h>
6481 #include \"guestfs.h\"
6482 #include \"guestfs-internal.h\"
6483 #include \"guestfs-internal-actions.h\"
6484 #include \"guestfs_protocol.h\"
6486 /* Check the return message from a call for validity. */
6488 check_reply_header (guestfs_h *g,
6489 const struct guestfs_message_header *hdr,
6490 unsigned int proc_nr, unsigned int serial)
6492 if (hdr->prog != GUESTFS_PROGRAM) {
6493 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
6496 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
6497 error (g, \"wrong protocol version (%%d/%%d)\",
6498 hdr->vers, GUESTFS_PROTOCOL_VERSION);
6501 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
6502 error (g, \"unexpected message direction (%%d/%%d)\",
6503 hdr->direction, GUESTFS_DIRECTION_REPLY);
6506 if (hdr->proc != proc_nr) {
6507 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
6510 if (hdr->serial != serial) {
6511 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
6518 /* Check we are in the right state to run a high-level action. */
6520 check_state (guestfs_h *g, const char *caller)
6522 if (!guestfs__is_ready (g)) {
6523 if (guestfs__is_config (g) || guestfs__is_launching (g))
6524 error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
6527 error (g, \"%%s called from the wrong state, %%d != READY\",
6528 caller, guestfs__get_state (g));
6536 let error_code_of = function
6537 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
6538 | RConstString _ | RConstOptString _
6539 | RString _ | RStringList _
6540 | RStruct _ | RStructList _
6541 | RHashtable _ | RBufferOut _ -> "NULL"
6544 (* Generate code to check String-like parameters are not passed in
6545 * as NULL (returning an error if they are).
6547 let check_null_strings shortname style =
6548 let pr_newline = ref false in
6551 (* parameters which should not be NULL *)
6562 pr " if (%s == NULL) {\n" n;
6563 pr " error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
6564 pr " \"%s\", \"%s\");\n" shortname n;
6565 pr " return %s;\n" (error_code_of (fst style));
6572 (* not applicable *)
6578 if !pr_newline then pr "\n";
6581 (* Generate code to generate guestfish call traces. *)
6582 let trace_call shortname style =
6583 pr " if (guestfs__get_trace (g)) {\n";
6586 List.exists (function
6587 | StringList _ | DeviceList _ -> true
6588 | _ -> false) (snd style) in
6594 pr " fprintf (stderr, \"%s\");\n" shortname;
6597 | String n (* strings *)
6605 (* guestfish doesn't support string escaping, so neither do we *)
6606 pr " fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
6607 | OptString n -> (* string option *)
6608 pr " if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
6609 pr " else fprintf (stderr, \" null\");\n"
6611 | DeviceList n -> (* string list *)
6612 pr " fputc (' ', stderr);\n";
6613 pr " fputc ('\"', stderr);\n";
6614 pr " for (i = 0; %s[i]; ++i) {\n" n;
6615 pr " if (i > 0) fputc (' ', stderr);\n";
6616 pr " fputs (%s[i], stderr);\n" n;
6618 pr " fputc ('\"', stderr);\n";
6619 | Bool n -> (* boolean *)
6620 pr " fputs (%s ? \" true\" : \" false\", stderr);\n" n
6621 | Int n -> (* int *)
6622 pr " fprintf (stderr, \" %%d\", %s);\n" n
6624 pr " fprintf (stderr, \" %%\" PRIi64, %s);\n" n
6626 pr " fputc ('\\n', stderr);\n";
6631 (* For non-daemon functions, generate a wrapper around each function. *)
6633 fun (shortname, style, _, _, _, _, _) ->
6634 let name = "guestfs_" ^ shortname in
6636 generate_prototype ~extern:false ~semicolon:false ~newline:true
6637 ~handle:"g" name style;
6639 check_null_strings shortname style;
6640 trace_call shortname style;
6641 pr " return guestfs__%s " shortname;
6642 generate_c_call_args ~handle:"g" style;
6646 ) non_daemon_functions;
6648 (* Client-side stubs for each function. *)
6650 fun (shortname, style, _, _, _, _, _) ->
6651 let name = "guestfs_" ^ shortname in
6652 let error_code = error_code_of (fst style) in
6654 (* Generate the action stub. *)
6655 generate_prototype ~extern:false ~semicolon:false ~newline:true
6656 ~handle:"g" name style;
6660 (match snd style with
6662 | _ -> pr " struct %s_args args;\n" name
6665 pr " guestfs_message_header hdr;\n";
6666 pr " guestfs_message_error err;\n";
6668 match fst style with
6670 | RConstString _ | RConstOptString _ ->
6671 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6673 | RBool _ | RString _ | RStringList _
6674 | RStruct _ | RStructList _
6675 | RHashtable _ | RBufferOut _ ->
6676 pr " struct %s_ret ret;\n" name;
6679 pr " int serial;\n";
6682 check_null_strings shortname style;
6683 trace_call shortname style;
6684 pr " if (check_state (g, \"%s\") == -1) return %s;\n"
6685 shortname error_code;
6686 pr " guestfs___set_busy (g);\n";
6689 (* Send the main header and arguments. *)
6690 (match snd style with
6692 pr " serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
6693 (String.uppercase shortname)
6697 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6698 pr " args.%s = (char *) %s;\n" n n
6700 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
6701 | StringList n | DeviceList n ->
6702 pr " args.%s.%s_val = (char **) %s;\n" n n n;
6703 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
6705 pr " args.%s = %s;\n" n n
6707 pr " args.%s = %s;\n" n n
6709 pr " args.%s = %s;\n" n n
6710 | FileIn _ | FileOut _ -> ()
6712 pr " /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
6713 pr " if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
6714 pr " error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
6716 pr " guestfs___end_busy (g);\n";
6717 pr " return %s;\n" error_code;
6719 pr " args.%s.%s_val = (char *) %s;\n" n n n;
6720 pr " args.%s.%s_len = %s_size;\n" n n n
6722 pr " serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
6723 (String.uppercase shortname);
6724 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
6727 pr " if (serial == -1) {\n";
6728 pr " guestfs___end_busy (g);\n";
6729 pr " return %s;\n" error_code;
6733 (* Send any additional files (FileIn) requested. *)
6734 let need_read_reply_label = ref false in
6738 pr " r = guestfs___send_file (g, %s);\n" n;
6739 pr " if (r == -1) {\n";
6740 pr " guestfs___end_busy (g);\n";
6741 pr " return %s;\n" error_code;
6743 pr " if (r == -2) /* daemon cancelled */\n";
6744 pr " goto read_reply;\n";
6745 need_read_reply_label := true;
6750 (* Wait for the reply from the remote end. *)
6751 if !need_read_reply_label then pr " read_reply:\n";
6752 pr " memset (&hdr, 0, sizeof hdr);\n";
6753 pr " memset (&err, 0, sizeof err);\n";
6754 if has_ret then pr " memset (&ret, 0, sizeof ret);\n";
6756 pr " r = guestfs___recv (g, \"%s\", &hdr, &err,\n " shortname;
6760 pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
6763 pr " if (r == -1) {\n";
6764 pr " guestfs___end_busy (g);\n";
6765 pr " return %s;\n" error_code;
6769 pr " if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
6770 (String.uppercase shortname);
6771 pr " guestfs___end_busy (g);\n";
6772 pr " return %s;\n" error_code;
6776 pr " if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
6777 pr " error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
6778 pr " free (err.error_message);\n";
6779 pr " guestfs___end_busy (g);\n";
6780 pr " return %s;\n" error_code;
6784 (* Expecting to receive further files (FileOut)? *)
6788 pr " if (guestfs___recv_file (g, %s) == -1) {\n" n;
6789 pr " guestfs___end_busy (g);\n";
6790 pr " return %s;\n" error_code;
6796 pr " guestfs___end_busy (g);\n";
6798 (match fst style with
6799 | RErr -> pr " return 0;\n"
6800 | RInt n | RInt64 n | RBool n ->
6801 pr " return ret.%s;\n" n
6802 | RConstString _ | RConstOptString _ ->
6803 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6805 pr " return ret.%s; /* caller will free */\n" n
6806 | RStringList n | RHashtable n ->
6807 pr " /* caller will free this, but we need to add a NULL entry */\n";
6808 pr " ret.%s.%s_val =\n" n n;
6809 pr " safe_realloc (g, ret.%s.%s_val,\n" n n;
6810 pr " sizeof (char *) * (ret.%s.%s_len + 1));\n"
6812 pr " ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
6813 pr " return ret.%s.%s_val;\n" n n
6815 pr " /* caller will free this */\n";
6816 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6817 | RStructList (n, _) ->
6818 pr " /* caller will free this */\n";
6819 pr " return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6821 pr " /* RBufferOut is tricky: If the buffer is zero-length, then\n";
6822 pr " * _val might be NULL here. To make the API saner for\n";
6823 pr " * callers, we turn this case into a unique pointer (using\n";
6824 pr " * malloc(1)).\n";
6826 pr " if (ret.%s.%s_len > 0) {\n" n n;
6827 pr " *size_r = ret.%s.%s_len;\n" n n;
6828 pr " return ret.%s.%s_val; /* caller will free */\n" n n;
6830 pr " free (ret.%s.%s_val);\n" n n;
6831 pr " char *p = safe_malloc (g, 1);\n";
6832 pr " *size_r = ret.%s.%s_len;\n" n n;
6840 (* Functions to free structures. *)
6841 pr "/* Structure-freeing functions. These rely on the fact that the\n";
6842 pr " * structure format is identical to the XDR format. See note in\n";
6843 pr " * generator.ml.\n";
6850 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
6852 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
6858 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
6860 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
6867 (* Generate daemon/actions.h. *)
6868 and generate_daemon_actions_h () =
6869 generate_header CStyle GPLv2plus;
6871 pr "#include \"../src/guestfs_protocol.h\"\n";
6875 fun (name, style, _, _, _, _, _) ->
6877 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
6881 (* Generate the linker script which controls the visibility of
6882 * symbols in the public ABI and ensures no other symbols get
6883 * exported accidentally.
6885 and generate_linker_script () =
6886 generate_header HashStyle GPLv2plus;
6891 "guestfs_get_error_handler";
6892 "guestfs_get_out_of_memory_handler";
6893 "guestfs_get_private";
6894 "guestfs_last_error";
6895 "guestfs_set_close_callback";
6896 "guestfs_set_error_handler";
6897 "guestfs_set_launch_done_callback";
6898 "guestfs_set_log_message_callback";
6899 "guestfs_set_out_of_memory_handler";
6900 "guestfs_set_private";
6901 "guestfs_set_progress_callback";
6902 "guestfs_set_subprocess_quit_callback";
6904 (* Unofficial parts of the API: the bindings code use these
6905 * functions, so it is useful to export them.
6907 "guestfs_safe_calloc";
6908 "guestfs_safe_malloc";
6909 "guestfs_safe_strdup";
6910 "guestfs_safe_memdup";
6913 List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
6917 List.map (fun (typ, _) ->
6918 ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
6921 let globals = List.sort compare (globals @ functions @ structs) in
6925 List.iter (pr " %s;\n") globals;
6932 (* Generate the server-side stubs. *)
6933 and generate_daemon_actions () =
6934 generate_header CStyle GPLv2plus;
6936 pr "#include <config.h>\n";
6938 pr "#include <stdio.h>\n";
6939 pr "#include <stdlib.h>\n";
6940 pr "#include <string.h>\n";
6941 pr "#include <inttypes.h>\n";
6942 pr "#include <rpc/types.h>\n";
6943 pr "#include <rpc/xdr.h>\n";
6945 pr "#include \"daemon.h\"\n";
6946 pr "#include \"c-ctype.h\"\n";
6947 pr "#include \"../src/guestfs_protocol.h\"\n";
6948 pr "#include \"actions.h\"\n";
6952 fun (name, style, _, _, _, _, _) ->
6953 (* Generate server-side stubs. *)
6954 pr "static void %s_stub (XDR *xdr_in)\n" name;
6957 match fst style with
6958 | RErr | RInt _ -> pr " int r;\n"; "-1"
6959 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6960 | RBool _ -> pr " int r;\n"; "-1"
6961 | RConstString _ | RConstOptString _ ->
6962 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6963 | RString _ -> pr " char *r;\n"; "NULL"
6964 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6965 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
6966 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL"
6968 pr " size_t size = 1;\n";
6972 (match snd style with
6975 pr " struct guestfs_%s_args args;\n" name;
6978 | Device n | Dev_or_Path n
6982 | OptString n -> pr " char *%s;\n" n
6983 | StringList n | DeviceList n -> pr " char **%s;\n" n
6984 | Bool n -> pr " int %s;\n" n
6985 | Int n -> pr " int %s;\n" n
6986 | Int64 n -> pr " int64_t %s;\n" n
6987 | FileIn _ | FileOut _ -> ()
6989 pr " const char *%s;\n" n;
6990 pr " size_t %s_size;\n" n
6996 List.exists (function FileIn _ -> true | _ -> false) (snd style) in
6998 (match snd style with
7001 pr " memset (&args, 0, sizeof args);\n";
7003 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
7005 pr " if (cancel_receive () != -2)\n";
7006 pr " reply_with_error (\"daemon failed to decode procedure arguments\");\n";
7010 pr " char *%s = args.%s;\n" n n
7012 let pr_list_handling_code n =
7013 pr " %s = realloc (args.%s.%s_val,\n" n n n;
7014 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
7015 pr " if (%s == NULL) {\n" n;
7017 pr " if (cancel_receive () != -2)\n";
7018 pr " reply_with_perror (\"realloc\");\n";
7021 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
7022 pr " args.%s.%s_val = %s;\n" n n n;
7028 pr " ABS_PATH (%s, %s, goto done);\n"
7029 n (if is_filein then "cancel_receive ()" else "0");
7032 pr " RESOLVE_DEVICE (%s, %s, goto done);\n"
7033 n (if is_filein then "cancel_receive ()" else "0");
7036 pr " REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
7037 n (if is_filein then "cancel_receive ()" else "0");
7038 | String n | Key n -> pr_args n
7039 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
7041 pr_list_handling_code n;
7043 pr_list_handling_code n;
7044 pr " /* Ensure that each is a device,\n";
7045 pr " * and perform device name translation.\n";
7049 pr " for (i = 0; %s[i] != NULL; ++i)\n" n;
7050 pr " RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
7051 (if is_filein then "cancel_receive ()" else "0");
7053 | Bool n -> pr " %s = args.%s;\n" n n
7054 | Int n -> pr " %s = args.%s;\n" n n
7055 | Int64 n -> pr " %s = args.%s;\n" n n
7056 | FileIn _ | FileOut _ -> ()
7058 pr " %s = args.%s.%s_val;\n" n n n;
7059 pr " %s_size = args.%s.%s_len;\n" n n n
7064 (* this is used at least for do_equal *)
7065 if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
7066 (* Emit NEED_ROOT just once, even when there are two or
7067 more Pathname args *)
7068 pr " NEED_ROOT (%s, goto done);\n"
7069 (if is_filein then "cancel_receive ()" else "0");
7072 (* Don't want to call the impl with any FileIn or FileOut
7073 * parameters, since these go "outside" the RPC protocol.
7076 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
7078 pr " r = do_%s " name;
7079 generate_c_call_args (fst style, args');
7082 (match fst style with
7083 | RErr | RInt _ | RInt64 _ | RBool _
7084 | RConstString _ | RConstOptString _
7085 | RString _ | RStringList _ | RHashtable _
7086 | RStruct (_, _) | RStructList (_, _) ->
7087 pr " if (r == %s)\n" error_code;
7088 pr " /* do_%s has already called reply_with_error */\n" name;
7092 pr " /* size == 0 && r == NULL could be a non-error case (just\n";
7093 pr " * an ordinary zero-length buffer), so be careful ...\n";
7095 pr " if (size == 1 && r == %s)\n" error_code;
7096 pr " /* do_%s has already called reply_with_error */\n" name;
7101 (* If there are any FileOut parameters, then the impl must
7102 * send its own reply.
7105 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
7107 pr " /* do_%s has already sent a reply */\n" name
7109 match fst style with
7110 | RErr -> pr " reply (NULL, NULL);\n"
7111 | RInt n | RInt64 n | RBool n ->
7112 pr " struct guestfs_%s_ret ret;\n" name;
7113 pr " ret.%s = r;\n" n;
7114 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7116 | RConstString _ | RConstOptString _ ->
7117 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7119 pr " struct guestfs_%s_ret ret;\n" name;
7120 pr " ret.%s = r;\n" n;
7121 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7124 | RStringList n | RHashtable n ->
7125 pr " struct guestfs_%s_ret ret;\n" name;
7126 pr " ret.%s.%s_len = count_strings (r);\n" n n;
7127 pr " ret.%s.%s_val = r;\n" n n;
7128 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7130 pr " free_strings (r);\n"
7132 pr " struct guestfs_%s_ret ret;\n" name;
7133 pr " ret.%s = *r;\n" n;
7134 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7136 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7138 | RStructList (n, _) ->
7139 pr " struct guestfs_%s_ret ret;\n" name;
7140 pr " ret.%s = *r;\n" n;
7141 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7143 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7146 pr " struct guestfs_%s_ret ret;\n" name;
7147 pr " ret.%s.%s_val = r;\n" n n;
7148 pr " ret.%s.%s_len = size;\n" n n;
7149 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7154 (* Free the args. *)
7156 (match snd style with
7159 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
7166 (* Dispatch function. *)
7167 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
7169 pr " switch (proc_nr) {\n";
7172 fun (name, style, _, _, _, _, _) ->
7173 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
7174 pr " %s_stub (xdr_in);\n" name;
7179 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";
7184 (* LVM columns and tokenization functions. *)
7185 (* XXX This generates crap code. We should rethink how we
7191 pr "static const char *lvm_%s_cols = \"%s\";\n"
7192 typ (String.concat "," (List.map fst cols));
7195 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
7197 pr " char *tok, *p, *next;\n";
7198 pr " size_t i, j;\n";
7201 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
7204 pr " if (!str) {\n";
7205 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
7208 pr " if (!*str || c_isspace (*str)) {\n";
7209 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
7214 fun (name, coltype) ->
7215 pr " if (!tok) {\n";
7216 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
7219 pr " p = strchrnul (tok, ',');\n";
7220 pr " if (*p) next = p+1; else next = NULL;\n";
7221 pr " *p = '\\0';\n";
7224 pr " r->%s = strdup (tok);\n" name;
7225 pr " if (r->%s == NULL) {\n" name;
7226 pr " perror (\"strdup\");\n";
7230 pr " for (i = j = 0; i < 32; ++j) {\n";
7231 pr " if (tok[j] == '\\0') {\n";
7232 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
7234 pr " } else if (tok[j] != '-')\n";
7235 pr " r->%s[i++] = tok[j];\n" name;
7238 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
7239 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7243 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
7244 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7248 pr " if (tok[0] == '\\0')\n";
7249 pr " r->%s = -1;\n" name;
7250 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
7251 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7254 | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
7255 assert false (* can never be an LVM column *)
7257 pr " tok = next;\n";
7260 pr " if (tok != NULL) {\n";
7261 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
7268 pr "guestfs_int_lvm_%s_list *\n" typ;
7269 pr "parse_command_line_%ss (void)\n" typ;
7271 pr " char *out, *err;\n";
7272 pr " char *p, *pend;\n";
7274 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
7275 pr " void *newp;\n";
7277 pr " ret = malloc (sizeof *ret);\n";
7278 pr " if (!ret) {\n";
7279 pr " reply_with_perror (\"malloc\");\n";
7280 pr " return NULL;\n";
7283 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
7284 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
7286 pr " r = command (&out, &err,\n";
7287 pr " \"lvm\", \"%ss\",\n" typ;
7288 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
7289 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
7290 pr " if (r == -1) {\n";
7291 pr " reply_with_error (\"%%s\", err);\n";
7292 pr " free (out);\n";
7293 pr " free (err);\n";
7294 pr " free (ret);\n";
7295 pr " return NULL;\n";
7298 pr " free (err);\n";
7300 pr " /* Tokenize each line of the output. */\n";
7303 pr " while (p) {\n";
7304 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
7305 pr " if (pend) {\n";
7306 pr " *pend = '\\0';\n";
7310 pr " while (*p && c_isspace (*p)) /* Skip any leading whitespace. */\n";
7313 pr " if (!*p) { /* Empty line? Skip it. */\n";
7318 pr " /* Allocate some space to store this next entry. */\n";
7319 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
7320 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
7321 pr " if (newp == NULL) {\n";
7322 pr " reply_with_perror (\"realloc\");\n";
7323 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7324 pr " free (ret);\n";
7325 pr " free (out);\n";
7326 pr " return NULL;\n";
7328 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
7330 pr " /* Tokenize the next entry. */\n";
7331 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
7332 pr " if (r == -1) {\n";
7333 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
7334 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7335 pr " free (ret);\n";
7336 pr " free (out);\n";
7337 pr " return NULL;\n";
7344 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
7346 pr " free (out);\n";
7347 pr " return ret;\n";
7350 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
7352 (* Generate a list of function names, for debugging in the daemon.. *)
7353 and generate_daemon_names () =
7354 generate_header CStyle GPLv2plus;
7356 pr "#include <config.h>\n";
7358 pr "#include \"daemon.h\"\n";
7361 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
7362 pr "const char *function_names[] = {\n";
7364 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
7368 (* Generate the optional groups for the daemon to implement
7369 * guestfs_available.
7371 and generate_daemon_optgroups_c () =
7372 generate_header CStyle GPLv2plus;
7374 pr "#include <config.h>\n";
7376 pr "#include \"daemon.h\"\n";
7377 pr "#include \"optgroups.h\"\n";
7380 pr "struct optgroup optgroups[] = {\n";
7383 pr " { \"%s\", optgroup_%s_available },\n" group group
7385 pr " { NULL, NULL }\n";
7388 and generate_daemon_optgroups_h () =
7389 generate_header CStyle GPLv2plus;
7393 pr "extern int optgroup_%s_available (void);\n" group
7396 (* Generate the tests. *)
7397 and generate_tests () =
7398 generate_header CStyle GPLv2plus;
7405 #include <sys/types.h>
7408 #include \"guestfs.h\"
7409 #include \"guestfs-internal.h\"
7411 static guestfs_h *g;
7412 static int suppress_error = 0;
7414 static void print_error (guestfs_h *g, void *data, const char *msg)
7416 if (!suppress_error)
7417 fprintf (stderr, \"%%s\\n\", msg);
7420 /* FIXME: nearly identical code appears in fish.c */
7421 static void print_strings (char *const *argv)
7425 for (argc = 0; argv[argc] != NULL; ++argc)
7426 printf (\"\\t%%s\\n\", argv[argc]);
7430 static void print_table (char const *const *argv)
7434 for (i = 0; argv[i] != NULL; i += 2)
7435 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
7440 is_available (const char *group)
7442 const char *groups[] = { group, NULL };
7446 r = guestfs_available (g, (char **) groups);
7453 incr (guestfs_h *g, void *iv)
7455 int *i = (int *) iv;
7461 (* Generate a list of commands which are not tested anywhere. *)
7462 pr "static void no_test_warnings (void)\n";
7465 let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
7467 fun (_, _, _, _, tests, _, _) ->
7468 let tests = filter_map (
7470 | (_, (Always|If _|Unless _|IfAvailable _), test) -> Some test
7471 | (_, Disabled, _) -> None
7473 let seq = List.concat (List.map seq_of_test tests) in
7474 let cmds_tested = List.map List.hd seq in
7475 List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
7479 fun (name, _, _, _, _, _, _) ->
7480 if not (Hashtbl.mem hash name) then
7481 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
7487 (* Generate the actual tests. Note that we generate the tests
7488 * in reverse order, deliberately, so that (in general) the
7489 * newest tests run first. This makes it quicker and easier to
7494 fun (name, _, _, flags, tests, _, _) ->
7495 mapi (generate_one_test name flags) tests
7496 ) (List.rev all_functions) in
7497 let test_names = List.concat test_names in
7498 let nr_tests = List.length test_names in
7501 int main (int argc, char *argv[])
7504 unsigned long int n_failed = 0;
7505 const char *filename;
7507 int nr_tests, test_num = 0;
7509 setbuf (stdout, NULL);
7511 no_test_warnings ();
7513 g = guestfs_create ();
7515 printf (\"guestfs_create FAILED\\n\");
7516 exit (EXIT_FAILURE);
7519 guestfs_set_error_handler (g, print_error, NULL);
7521 guestfs_set_path (g, \"../appliance\");
7523 filename = \"test1.img\";
7524 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7527 exit (EXIT_FAILURE);
7529 if (lseek (fd, %d, SEEK_SET) == -1) {
7533 exit (EXIT_FAILURE);
7535 if (write (fd, &c, 1) == -1) {
7539 exit (EXIT_FAILURE);
7541 if (close (fd) == -1) {
7544 exit (EXIT_FAILURE);
7546 if (guestfs_add_drive (g, filename) == -1) {
7547 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7548 exit (EXIT_FAILURE);
7551 filename = \"test2.img\";
7552 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7555 exit (EXIT_FAILURE);
7557 if (lseek (fd, %d, SEEK_SET) == -1) {
7561 exit (EXIT_FAILURE);
7563 if (write (fd, &c, 1) == -1) {
7567 exit (EXIT_FAILURE);
7569 if (close (fd) == -1) {
7572 exit (EXIT_FAILURE);
7574 if (guestfs_add_drive (g, filename) == -1) {
7575 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7576 exit (EXIT_FAILURE);
7579 filename = \"test3.img\";
7580 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7583 exit (EXIT_FAILURE);
7585 if (lseek (fd, %d, SEEK_SET) == -1) {
7589 exit (EXIT_FAILURE);
7591 if (write (fd, &c, 1) == -1) {
7595 exit (EXIT_FAILURE);
7597 if (close (fd) == -1) {
7600 exit (EXIT_FAILURE);
7602 if (guestfs_add_drive (g, filename) == -1) {
7603 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7604 exit (EXIT_FAILURE);
7607 if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
7608 printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
7609 exit (EXIT_FAILURE);
7612 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
7615 if (guestfs_launch (g) == -1) {
7616 printf (\"guestfs_launch FAILED\\n\");
7617 exit (EXIT_FAILURE);
7620 /* Cancel previous alarm. */
7625 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
7629 pr " test_num++;\n";
7630 pr " if (guestfs_get_verbose (g))\n";
7631 pr " printf (\"-------------------------------------------------------------------------------\\n\");\n";
7632 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
7633 pr " if (%s () == -1) {\n" test_name;
7634 pr " printf (\"%s FAILED\\n\");\n" test_name;
7635 pr " n_failed++;\n";
7640 pr " /* Check close callback is called. */
7641 int close_sentinel = 1;
7642 guestfs_set_close_callback (g, incr, &close_sentinel);
7646 if (close_sentinel != 2) {
7647 fprintf (stderr, \"close callback was not called\\n\");
7648 exit (EXIT_FAILURE);
7651 unlink (\"test1.img\");
7652 unlink (\"test2.img\");
7653 unlink (\"test3.img\");
7657 pr " if (n_failed > 0) {\n";
7658 pr " printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
7659 pr " exit (EXIT_FAILURE);\n";
7663 pr " exit (EXIT_SUCCESS);\n";
7666 and generate_one_test name flags i (init, prereq, test) =
7667 let test_name = sprintf "test_%s_%d" name i in
7670 static int %s_skip (void)
7674 str = getenv (\"TEST_ONLY\");
7676 return strstr (str, \"%s\") == NULL;
7677 str = getenv (\"SKIP_%s\");
7678 if (str && STREQ (str, \"1\")) return 1;
7679 str = getenv (\"SKIP_TEST_%s\");
7680 if (str && STREQ (str, \"1\")) return 1;
7684 " test_name name (String.uppercase test_name) (String.uppercase name);
7687 | Disabled | Always | IfAvailable _ -> ()
7688 | If code | Unless code ->
7689 pr "static int %s_prereq (void)\n" test_name;
7697 static int %s (void)
7700 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
7704 " test_name test_name test_name;
7706 (* Optional functions should only be tested if the relevant
7707 * support is available in the daemon.
7712 pr " if (!is_available (\"%s\")) {\n" group;
7713 pr " printf (\" %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", \"%s\");\n" test_name group;
7721 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
7723 pr " if (! %s_prereq ()) {\n" test_name;
7724 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7728 generate_one_test_body name i test_name init test;
7730 pr " if (%s_prereq ()) {\n" test_name;
7731 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7735 generate_one_test_body name i test_name init test;
7736 | IfAvailable group ->
7737 pr " if (!is_available (\"%s\")) {\n" group;
7738 pr " printf (\" %%s skipped (reason: %%s not available)\\n\", \"%s\", \"%s\");\n" test_name group;
7742 generate_one_test_body name i test_name init test;
7744 generate_one_test_body name i test_name init test
7752 and generate_one_test_body name i test_name init test =
7754 | InitNone (* XXX at some point, InitNone and InitEmpty became
7755 * folded together as the same thing. Really we should
7756 * make InitNone do nothing at all, but the tests may
7757 * need to be checked to make sure this is OK.
7760 pr " /* InitNone|InitEmpty for %s */\n" test_name;
7761 List.iter (generate_test_command_call test_name)
7762 [["blockdev_setrw"; "/dev/sda"];
7766 pr " /* InitPartition for %s: create /dev/sda1 */\n" test_name;
7767 List.iter (generate_test_command_call test_name)
7768 [["blockdev_setrw"; "/dev/sda"];
7771 ["part_disk"; "/dev/sda"; "mbr"]]
7773 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
7774 List.iter (generate_test_command_call test_name)
7775 [["blockdev_setrw"; "/dev/sda"];
7778 ["part_disk"; "/dev/sda"; "mbr"];
7779 ["mkfs"; "ext2"; "/dev/sda1"];
7780 ["mount_options"; ""; "/dev/sda1"; "/"]]
7781 | InitBasicFSonLVM ->
7782 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
7784 List.iter (generate_test_command_call test_name)
7785 [["blockdev_setrw"; "/dev/sda"];
7788 ["part_disk"; "/dev/sda"; "mbr"];
7789 ["pvcreate"; "/dev/sda1"];
7790 ["vgcreate"; "VG"; "/dev/sda1"];
7791 ["lvcreate"; "LV"; "VG"; "8"];
7792 ["mkfs"; "ext2"; "/dev/VG/LV"];
7793 ["mount_options"; ""; "/dev/VG/LV"; "/"]]
7795 pr " /* InitISOFS for %s */\n" test_name;
7796 List.iter (generate_test_command_call test_name)
7797 [["blockdev_setrw"; "/dev/sda"];
7800 ["mount_ro"; "/dev/sdd"; "/"]]
7803 let get_seq_last = function
7805 failwithf "%s: you cannot use [] (empty list) when expecting a command"
7808 let seq = List.rev seq in
7809 List.rev (List.tl seq), List.hd seq
7814 pr " /* TestRun for %s (%d) */\n" name i;
7815 List.iter (generate_test_command_call test_name) seq
7816 | TestOutput (seq, expected) ->
7817 pr " /* TestOutput for %s (%d) */\n" name i;
7818 pr " const char *expected = \"%s\";\n" (c_quote expected);
7819 let seq, last = get_seq_last seq in
7821 pr " if (STRNEQ (r, expected)) {\n";
7822 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7826 List.iter (generate_test_command_call test_name) seq;
7827 generate_test_command_call ~test test_name last
7828 | TestOutputList (seq, expected) ->
7829 pr " /* TestOutputList for %s (%d) */\n" name i;
7830 let seq, last = get_seq_last seq in
7834 pr " if (!r[%d]) {\n" i;
7835 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7836 pr " print_strings (r);\n";
7840 pr " const char *expected = \"%s\";\n" (c_quote str);
7841 pr " if (STRNEQ (r[%d], expected)) {\n" i;
7842 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7847 pr " if (r[%d] != NULL) {\n" (List.length expected);
7848 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7850 pr " print_strings (r);\n";
7854 List.iter (generate_test_command_call test_name) seq;
7855 generate_test_command_call ~test test_name last
7856 | TestOutputListOfDevices (seq, expected) ->
7857 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
7858 let seq, last = get_seq_last seq in
7862 pr " if (!r[%d]) {\n" i;
7863 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7864 pr " print_strings (r);\n";
7868 pr " const char *expected = \"%s\";\n" (c_quote str);
7869 pr " r[%d][5] = 's';\n" i;
7870 pr " if (STRNEQ (r[%d], expected)) {\n" i;
7871 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7876 pr " if (r[%d] != NULL) {\n" (List.length expected);
7877 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7879 pr " print_strings (r);\n";
7883 List.iter (generate_test_command_call test_name) seq;
7884 generate_test_command_call ~test test_name last
7885 | TestOutputInt (seq, expected) ->
7886 pr " /* TestOutputInt for %s (%d) */\n" name i;
7887 let seq, last = get_seq_last seq in
7889 pr " if (r != %d) {\n" expected;
7890 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
7896 List.iter (generate_test_command_call test_name) seq;
7897 generate_test_command_call ~test test_name last
7898 | TestOutputIntOp (seq, op, expected) ->
7899 pr " /* TestOutputIntOp for %s (%d) */\n" name i;
7900 let seq, last = get_seq_last seq in
7902 pr " if (! (r %s %d)) {\n" op expected;
7903 pr " fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
7904 test_name op expected;
7909 List.iter (generate_test_command_call test_name) seq;
7910 generate_test_command_call ~test test_name last
7911 | TestOutputTrue seq ->
7912 pr " /* TestOutputTrue for %s (%d) */\n" name i;
7913 let seq, last = get_seq_last seq in
7916 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
7921 List.iter (generate_test_command_call test_name) seq;
7922 generate_test_command_call ~test test_name last
7923 | TestOutputFalse seq ->
7924 pr " /* TestOutputFalse for %s (%d) */\n" name i;
7925 let seq, last = get_seq_last seq in
7928 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
7933 List.iter (generate_test_command_call test_name) seq;
7934 generate_test_command_call ~test test_name last
7935 | TestOutputLength (seq, expected) ->
7936 pr " /* TestOutputLength for %s (%d) */\n" name i;
7937 let seq, last = get_seq_last seq in
7940 pr " for (j = 0; j < %d; ++j)\n" expected;
7941 pr " if (r[j] == NULL) {\n";
7942 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
7944 pr " print_strings (r);\n";
7947 pr " if (r[j] != NULL) {\n";
7948 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
7950 pr " print_strings (r);\n";
7954 List.iter (generate_test_command_call test_name) seq;
7955 generate_test_command_call ~test test_name last
7956 | TestOutputBuffer (seq, expected) ->
7957 pr " /* TestOutputBuffer for %s (%d) */\n" name i;
7958 pr " const char *expected = \"%s\";\n" (c_quote expected);
7959 let seq, last = get_seq_last seq in
7960 let len = String.length expected in
7962 pr " if (size != %d) {\n" len;
7963 pr " fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
7966 pr " if (STRNEQLEN (r, expected, size)) {\n";
7967 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7971 List.iter (generate_test_command_call test_name) seq;
7972 generate_test_command_call ~test test_name last
7973 | TestOutputStruct (seq, checks) ->
7974 pr " /* TestOutputStruct for %s (%d) */\n" name i;
7975 let seq, last = get_seq_last seq in
7979 | CompareWithInt (field, expected) ->
7980 pr " if (r->%s != %d) {\n" field expected;
7981 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
7982 test_name field expected;
7983 pr " (int) r->%s);\n" field;
7986 | CompareWithIntOp (field, op, expected) ->
7987 pr " if (!(r->%s %s %d)) {\n" field op expected;
7988 pr " fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
7989 test_name field op expected;
7990 pr " (int) r->%s);\n" field;
7993 | CompareWithString (field, expected) ->
7994 pr " if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
7995 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
7996 test_name field expected;
7997 pr " r->%s);\n" field;
8000 | CompareFieldsIntEq (field1, field2) ->
8001 pr " if (r->%s != r->%s) {\n" field1 field2;
8002 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
8003 test_name field1 field2;
8004 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
8007 | CompareFieldsStrEq (field1, field2) ->
8008 pr " if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
8009 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
8010 test_name field1 field2;
8011 pr " r->%s, r->%s);\n" field1 field2;
8016 List.iter (generate_test_command_call test_name) seq;
8017 generate_test_command_call ~test test_name last
8018 | TestLastFail seq ->
8019 pr " /* TestLastFail for %s (%d) */\n" name i;
8020 let seq, last = get_seq_last seq in
8021 List.iter (generate_test_command_call test_name) seq;
8022 generate_test_command_call test_name ~expect_error:true last
8024 (* Generate the code to run a command, leaving the result in 'r'.
8025 * If you expect to get an error then you should set expect_error:true.
8027 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
8029 | [] -> assert false
8031 (* Look up the command to find out what args/ret it has. *)
8034 let _, style, _, _, _, _, _ =
8035 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
8038 failwithf "%s: in test, command %s was not found" test_name name in
8040 if List.length (snd style) <> List.length args then
8041 failwithf "%s: in test, wrong number of args given to %s"
8048 | OptString n, "NULL" -> ()
8051 | Dev_or_Path n, arg
8055 pr " const char *%s = \"%s\";\n" n (c_quote arg);
8056 | BufferIn n, arg ->
8057 pr " const char *%s = \"%s\";\n" n (c_quote arg);
8058 pr " size_t %s_size = %d;\n" n (String.length arg)
8062 | FileIn _, _ | FileOut _, _ -> ()
8063 | StringList n, "" | DeviceList n, "" ->
8064 pr " const char *const %s[1] = { NULL };\n" n
8065 | StringList n, arg | DeviceList n, arg ->
8066 let strs = string_split " " arg in
8069 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
8071 pr " const char *const %s[] = {\n" n;
8073 fun i _ -> pr " %s_%d,\n" n i
8077 ) (List.combine (snd style) args);
8080 match fst style with
8081 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
8082 | RInt64 _ -> pr " int64_t r;\n"; "-1"
8083 | RConstString _ | RConstOptString _ ->
8084 pr " const char *r;\n"; "NULL"
8085 | RString _ -> pr " char *r;\n"; "NULL"
8086 | RStringList _ | RHashtable _ ->
8090 | RStruct (_, typ) ->
8091 pr " struct guestfs_%s *r;\n" typ; "NULL"
8092 | RStructList (_, typ) ->
8093 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
8096 pr " size_t size;\n";
8099 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
8100 pr " r = guestfs_%s (g" name;
8102 (* Generate the parameters. *)
8105 | OptString _, "NULL" -> pr ", NULL"
8107 | Device n, _ | Dev_or_Path n, _
8113 pr ", %s, %s_size" n n
8114 | FileIn _, arg | FileOut _, arg ->
8115 pr ", \"%s\"" (c_quote arg)
8116 | StringList n, _ | DeviceList n, _ ->
8117 pr ", (char **) %s" n
8120 try int_of_string arg
8121 with Failure "int_of_string" ->
8122 failwithf "%s: expecting an int, but got '%s'" test_name arg in
8126 try Int64.of_string arg
8127 with Failure "int_of_string" ->
8128 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
8131 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
8132 ) (List.combine (snd style) args);
8134 (match fst style with
8135 | RBufferOut _ -> pr ", &size"
8141 if not expect_error then
8142 pr " if (r == %s)\n" error_code
8144 pr " if (r != %s)\n" error_code;
8147 (* Insert the test code. *)
8153 (match fst style with
8154 | RErr | RInt _ | RInt64 _ | RBool _
8155 | RConstString _ | RConstOptString _ -> ()
8156 | RString _ | RBufferOut _ -> pr " free (r);\n"
8157 | RStringList _ | RHashtable _ ->
8158 pr " for (i = 0; r[i] != NULL; ++i)\n";
8159 pr " free (r[i]);\n";
8161 | RStruct (_, typ) ->
8162 pr " guestfs_free_%s (r);\n" typ
8163 | RStructList (_, typ) ->
8164 pr " guestfs_free_%s_list (r);\n" typ
8170 let str = replace_str str "\r" "\\r" in
8171 let str = replace_str str "\n" "\\n" in
8172 let str = replace_str str "\t" "\\t" in
8173 let str = replace_str str "\000" "\\0" in
8176 (* Generate a lot of different functions for guestfish. *)
8177 and generate_fish_cmds () =
8178 generate_header CStyle GPLv2plus;
8182 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8184 let all_functions_sorted =
8186 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8187 ) all_functions_sorted in
8189 pr "#include <config.h>\n";
8191 pr "#include <stdio.h>\n";
8192 pr "#include <stdlib.h>\n";
8193 pr "#include <string.h>\n";
8194 pr "#include <inttypes.h>\n";
8196 pr "#include <guestfs.h>\n";
8197 pr "#include \"c-ctype.h\"\n";
8198 pr "#include \"full-write.h\"\n";
8199 pr "#include \"xstrtol.h\"\n";
8200 pr "#include \"fish.h\"\n";
8202 pr "/* Valid suffixes allowed for numbers. See Gnulib xstrtol function. */\n";
8203 pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
8206 (* list_commands function, which implements guestfish -h *)
8207 pr "void list_commands (void)\n";
8209 pr " printf (\" %%-16s %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
8210 pr " list_builtin_commands ();\n";
8212 fun (name, _, _, flags, _, shortdesc, _) ->
8213 let name = replace_char name '_' '-' in
8214 pr " printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
8216 ) all_functions_sorted;
8217 pr " printf (\" %%s\\n\",";
8218 pr " _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
8222 (* display_command function, which implements guestfish -h cmd *)
8223 pr "int display_command (const char *cmd)\n";
8226 fun (name, style, _, flags, _, shortdesc, longdesc) ->
8227 let name2 = replace_char name '_' '-' in
8229 try find_map (function FishAlias n -> Some n | _ -> None) flags
8230 with Not_found -> name in
8231 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
8233 match snd style with
8236 let args = List.filter (function Key _ -> false | _ -> true) args in
8238 name2 (String.concat " " (List.map name_of_argt args)) in
8241 if List.exists (function Key _ -> true | _ -> false) (snd style) then
8242 "\n\nThis command has one or more key or passphrase parameters.
8243 Guestfish will prompt for these separately."
8248 if List.mem ProtocolLimitWarning flags then
8249 ("\n\n" ^ protocol_limit_warning)
8252 (* For DangerWillRobinson commands, we should probably have
8253 * guestfish prompt before allowing you to use them (especially
8254 * in interactive mode). XXX
8258 if List.mem DangerWillRobinson flags then
8259 ("\n\n" ^ danger_will_robinson)
8264 match deprecation_notice flags with
8266 | Some txt -> "\n\n" ^ txt in
8268 let describe_alias =
8269 if name <> alias then
8270 sprintf "\n\nYou can use '%s' as an alias for this command." alias
8274 pr "STRCASEEQ (cmd, \"%s\")" name;
8275 if name <> name2 then
8276 pr " || STRCASEEQ (cmd, \"%s\")" name2;
8277 if name <> alias then
8278 pr " || STRCASEEQ (cmd, \"%s\")" alias;
8280 pr " pod2text (\"%s\", _(\"%s\"), %S);\n"
8282 ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
8283 "=head1 DESCRIPTION\n\n" ^
8284 longdesc ^ warnings ^ describe_alias);
8289 pr " return display_builtin_command (cmd);\n";
8293 let emit_print_list_function typ =
8294 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
8297 pr " unsigned int i;\n";
8299 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
8300 pr " printf (\"[%%d] = {\\n\", i);\n";
8301 pr " print_%s_indent (&%ss->val[i], \" \");\n" typ typ;
8302 pr " printf (\"}\\n\");\n";
8308 (* print_* functions *)
8312 List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
8314 pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
8317 pr " unsigned int i;\n";
8323 pr " printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
8325 pr " printf (\"%%s%s: \", indent);\n" name;
8326 pr " for (i = 0; i < 32; ++i)\n";
8327 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
8328 pr " printf (\"\\n\");\n"
8330 pr " printf (\"%%s%s: \", indent);\n" name;
8331 pr " for (i = 0; i < %s->%s_len; ++i)\n" typ name;
8332 pr " if (c_isprint (%s->%s[i]))\n" typ name;
8333 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
8335 pr " printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
8336 pr " printf (\"\\n\");\n"
8337 | name, (FUInt64|FBytes) ->
8338 pr " printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
8341 pr " printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
8344 pr " printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
8347 pr " printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
8350 pr " printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
8352 | name, FOptPercent ->
8353 pr " if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
8354 typ name name typ name;
8355 pr " else printf (\"%%s%s: \\n\", indent);\n" name
8361 (* Emit a print_TYPE_list function definition only if that function is used. *)
8364 | typ, (RStructListOnly | RStructAndList) ->
8365 (* generate the function for typ *)
8366 emit_print_list_function typ
8367 | typ, _ -> () (* empty *)
8368 ) (rstructs_used_by all_functions);
8370 (* Emit a print_TYPE function definition only if that function is used. *)
8373 | typ, (RStructOnly | RStructAndList) ->
8374 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
8376 pr " print_%s_indent (%s, \"\");\n" typ typ;
8379 | typ, _ -> () (* empty *)
8380 ) (rstructs_used_by all_functions);
8382 (* run_<action> actions *)
8384 fun (name, style, _, flags, _, _, _) ->
8385 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
8387 (match fst style with
8390 | RBool _ -> pr " int r;\n"
8391 | RInt64 _ -> pr " int64_t r;\n"
8392 | RConstString _ | RConstOptString _ -> pr " const char *r;\n"
8393 | RString _ -> pr " char *r;\n"
8394 | RStringList _ | RHashtable _ -> pr " char **r;\n"
8395 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
8396 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
8399 pr " size_t size;\n";
8405 | OptString n -> pr " const char *%s;\n" n
8410 | Key n -> pr " char *%s;\n" n
8412 pr " const char *%s;\n" n;
8413 pr " size_t %s_size;\n" n
8414 | StringList n | DeviceList n -> pr " char **%s;\n" n
8415 | Bool n -> pr " int %s;\n" n
8416 | Int n -> pr " int %s;\n" n
8417 | Int64 n -> pr " int64_t %s;\n" n
8420 (* Check and convert parameters. *)
8423 List.filter (function Key _ -> false | _ -> true) (snd style) in
8424 List.length args_no_keys in
8425 pr " if (argc != %d) {\n" argc_expected;
8426 pr " fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
8428 pr " fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
8432 let parse_integer fn fntyp rtyp range name =
8434 pr " strtol_error xerr;\n";
8435 pr " %s r;\n" fntyp;
8437 pr " xerr = %s (argv[i++], NULL, 0, &r, xstrtol_suffixes);\n" fn;
8438 pr " if (xerr != LONGINT_OK) {\n";
8439 pr " fprintf (stderr,\n";
8440 pr " _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
8441 pr " cmd, \"%s\", \"%s\", xerr);\n" name fn;
8446 | Some (min, max, comment) ->
8447 pr " /* %s */\n" comment;
8448 pr " if (r < %s || r > %s) {\n" min max;
8449 pr " fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
8453 pr " /* The check above should ensure this assignment does not overflow. */\n";
8455 pr " %s = r;\n" name;
8459 if snd style <> [] then
8460 pr " size_t i = 0;\n";
8466 pr " %s = argv[i++];\n" name
8468 | Dev_or_Path name ->
8469 pr " %s = resolve_win_path (argv[i++]);\n" name;
8470 pr " if (%s == NULL) return -1;\n" name
8472 pr " %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
8475 pr " %s = argv[i];\n" name;
8476 pr " %s_size = strlen (argv[i]);\n" name;
8479 pr " %s = file_in (argv[i++]);\n" name;
8480 pr " if (%s == NULL) return -1;\n" name
8482 pr " %s = file_out (argv[i++]);\n" name;
8483 pr " if (%s == NULL) return -1;\n" name
8484 | StringList name | DeviceList name ->
8485 pr " %s = parse_string_list (argv[i++]);\n" name;
8486 pr " if (%s == NULL) return -1;\n" name
8488 pr " %s = read_key (\"%s\");\n" name name;
8489 pr " if (%s == NULL) return -1;\n" name
8491 pr " %s = is_true (argv[i++]) ? 1 : 0;\n" name
8494 let min = "(-(2LL<<30))"
8495 and max = "((2LL<<30)-1)"
8497 "The Int type in the generator is a signed 31 bit int." in
8498 Some (min, max, comment) in
8499 parse_integer "xstrtoll" "long long" "int" range name
8501 parse_integer "xstrtoll" "long long" "int64_t" None name
8504 (* Call C API function. *)
8505 pr " r = guestfs_%s " name;
8506 generate_c_call_args ~handle:"g" style;
8511 | Device _ | String _
8512 | OptString _ | Bool _
8515 | Pathname name | Dev_or_Path name | FileOut name
8517 pr " free (%s);\n" name
8519 pr " free_file_in (%s);\n" name
8520 | StringList name | DeviceList name ->
8521 pr " free_strings (%s);\n" name
8524 (* Any output flags? *)
8526 let flags = filter_map (
8527 function FishOutput flag -> Some flag | _ -> None
8533 failwithf "%s: more than one FishOutput flag is not allowed" name in
8535 (* Check return value for errors and display command results. *)
8536 (match fst style with
8537 | RErr -> pr " return r;\n"
8539 pr " if (r == -1) return -1;\n";
8540 (match fish_output with
8542 pr " printf (\"%%d\\n\", r);\n";
8543 | Some FishOutputOctal ->
8544 pr " printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
8545 | Some FishOutputHexadecimal ->
8546 pr " printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8549 pr " if (r == -1) return -1;\n";
8550 (match fish_output with
8552 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
8553 | Some FishOutputOctal ->
8554 pr " printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
8555 | Some FishOutputHexadecimal ->
8556 pr " printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8559 pr " if (r == -1) return -1;\n";
8560 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
8563 pr " if (r == NULL) return -1;\n";
8564 pr " printf (\"%%s\\n\", r);\n";
8566 | RConstOptString _ ->
8567 pr " printf (\"%%s\\n\", r ? : \"(null)\");\n";
8570 pr " if (r == NULL) return -1;\n";
8571 pr " printf (\"%%s\\n\", r);\n";
8575 pr " if (r == NULL) return -1;\n";
8576 pr " print_strings (r);\n";
8577 pr " free_strings (r);\n";
8579 | RStruct (_, typ) ->
8580 pr " if (r == NULL) return -1;\n";
8581 pr " print_%s (r);\n" typ;
8582 pr " guestfs_free_%s (r);\n" typ;
8584 | RStructList (_, typ) ->
8585 pr " if (r == NULL) return -1;\n";
8586 pr " print_%s_list (r);\n" typ;
8587 pr " guestfs_free_%s_list (r);\n" typ;
8590 pr " if (r == NULL) return -1;\n";
8591 pr " print_table (r);\n";
8592 pr " free_strings (r);\n";
8595 pr " if (r == NULL) return -1;\n";
8596 pr " if (full_write (1, r, size) != size) {\n";
8597 pr " perror (\"write\");\n";
8608 (* run_action function *)
8609 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
8612 fun (name, _, _, flags, _, _, _) ->
8613 let name2 = replace_char name '_' '-' in
8615 try find_map (function FishAlias n -> Some n | _ -> None) flags
8616 with Not_found -> name in
8618 pr "STRCASEEQ (cmd, \"%s\")" name;
8619 if name <> name2 then
8620 pr " || STRCASEEQ (cmd, \"%s\")" name2;
8621 if name <> alias then
8622 pr " || STRCASEEQ (cmd, \"%s\")" alias;
8624 pr " return run_%s (cmd, argc, argv);\n" name;
8628 pr " fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
8629 pr " if (command_num == 1)\n";
8630 pr " extended_help_message ();\n";
8637 (* Readline completion for guestfish. *)
8638 and generate_fish_completion () =
8639 generate_header CStyle GPLv2plus;
8643 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8653 #ifdef HAVE_LIBREADLINE
8654 #include <readline/readline.h>
8659 #ifdef HAVE_LIBREADLINE
8661 static const char *const commands[] = {
8662 BUILTIN_COMMANDS_FOR_COMPLETION,
8665 (* Get the commands, including the aliases. They don't need to be
8666 * sorted - the generator() function just does a dumb linear search.
8670 fun (name, _, _, flags, _, _, _) ->
8671 let name2 = replace_char name '_' '-' in
8673 try find_map (function FishAlias n -> Some n | _ -> None) flags
8674 with Not_found -> name in
8676 if name <> alias then [name2; alias] else [name2]
8678 let commands = List.flatten commands in
8680 List.iter (pr " \"%s\",\n") commands;
8686 generator (const char *text, int state)
8688 static size_t index, len;
8693 len = strlen (text);
8696 rl_attempted_completion_over = 1;
8698 while ((name = commands[index]) != NULL) {
8700 if (STRCASEEQLEN (name, text, len))
8701 return strdup (name);
8707 #endif /* HAVE_LIBREADLINE */
8709 #ifdef HAVE_RL_COMPLETION_MATCHES
8710 #define RL_COMPLETION_MATCHES rl_completion_matches
8712 #ifdef HAVE_COMPLETION_MATCHES
8713 #define RL_COMPLETION_MATCHES completion_matches
8715 #endif /* else just fail if we don't have either symbol */
8718 do_completion (const char *text, int start, int end)
8720 char **matches = NULL;
8722 #ifdef HAVE_LIBREADLINE
8723 rl_completion_append_character = ' ';
8726 matches = RL_COMPLETION_MATCHES (text, generator);
8727 else if (complete_dest_paths)
8728 matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
8735 (* Generate the POD documentation for guestfish. *)
8736 and generate_fish_actions_pod () =
8737 let all_functions_sorted =
8739 fun (_, _, _, flags, _, _, _) ->
8740 not (List.mem NotInFish flags || List.mem NotInDocs flags)
8741 ) all_functions_sorted in
8743 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
8746 fun (name, style, _, flags, _, _, longdesc) ->
8748 Str.global_substitute rex (
8751 try Str.matched_group 1 s
8753 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
8754 "C<" ^ replace_char sub '_' '-' ^ ">"
8756 let name = replace_char name '_' '-' in
8758 try find_map (function FishAlias n -> Some n | _ -> None) flags
8759 with Not_found -> name in
8761 pr "=head2 %s" name;
8762 if name <> alias then
8769 | Pathname n | Device n | Dev_or_Path n | String n ->
8771 | OptString n -> pr " %s" n
8772 | StringList n | DeviceList n -> pr " '%s ...'" n
8773 | Bool _ -> pr " true|false"
8774 | Int n -> pr " %s" n
8775 | Int64 n -> pr " %s" n
8776 | FileIn n | FileOut n -> pr " (%s|-)" n
8777 | BufferIn n -> pr " %s" n
8778 | Key _ -> () (* keys are entered at a prompt *)
8782 pr "%s\n\n" longdesc;
8784 if List.exists (function FileIn _ | FileOut _ -> true
8785 | _ -> false) (snd style) then
8786 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
8788 if List.exists (function Key _ -> true | _ -> false) (snd style) then
8789 pr "This command has one or more key or passphrase parameters.
8790 Guestfish will prompt for these separately.\n\n";
8792 if List.mem ProtocolLimitWarning flags then
8793 pr "%s\n\n" protocol_limit_warning;
8795 if List.mem DangerWillRobinson flags then
8796 pr "%s\n\n" danger_will_robinson;
8798 match deprecation_notice flags with
8800 | Some txt -> pr "%s\n\n" txt
8801 ) all_functions_sorted
8803 (* Generate a C function prototype. *)
8804 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
8805 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
8807 ?handle name style =
8808 if extern then pr "extern ";
8809 if static then pr "static ";
8810 (match fst style with
8812 | RInt _ -> pr "int "
8813 | RInt64 _ -> pr "int64_t "
8814 | RBool _ -> pr "int "
8815 | RConstString _ | RConstOptString _ -> pr "const char *"
8816 | RString _ | RBufferOut _ -> pr "char *"
8817 | RStringList _ | RHashtable _ -> pr "char **"
8818 | RStruct (_, typ) ->
8819 if not in_daemon then pr "struct guestfs_%s *" typ
8820 else pr "guestfs_int_%s *" typ
8821 | RStructList (_, typ) ->
8822 if not in_daemon then pr "struct guestfs_%s_list *" typ
8823 else pr "guestfs_int_%s_list *" typ
8825 let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
8826 pr "%s%s (" prefix name;
8827 if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
8830 let comma = ref false in
8833 | Some handle -> pr "guestfs_h *%s" handle; comma := true
8837 if single_line then pr ", " else pr ",\n\t\t"
8844 | Device n | Dev_or_Path n
8849 pr "const char *%s" n
8850 | StringList n | DeviceList n ->
8852 pr "char *const *%s" n
8853 | Bool n -> next (); pr "int %s" n
8854 | Int n -> next (); pr "int %s" n
8855 | Int64 n -> next (); pr "int64_t %s" n
8858 if not in_daemon then (next (); pr "const char *%s" n)
8861 pr "const char *%s" n;
8863 pr "size_t %s_size" n
8865 if is_RBufferOut then (next (); pr "size_t *size_r");
8868 if semicolon then pr ";";
8869 if newline then pr "\n"
8871 (* Generate C call arguments, eg "(handle, foo, bar)" *)
8872 and generate_c_call_args ?handle ?(decl = false) style =
8874 let comma = ref false in
8876 if !comma then pr ", ";
8881 | Some handle -> pr "%s" handle; comma := true
8887 pr "%s, %s_size" n n
8890 pr "%s" (name_of_argt arg)
8892 (* For RBufferOut calls, add implicit &size parameter. *)
8894 match fst style with
8902 (* Generate the OCaml bindings interface. *)
8903 and generate_ocaml_mli () =
8904 generate_header OCamlStyle LGPLv2plus;
8907 (** For API documentation you should refer to the C API
8908 in the guestfs(3) manual page. The OCaml API uses almost
8909 exactly the same calls. *)
8912 (** A [guestfs_h] handle. *)
8914 exception Error of string
8915 (** This exception is raised when there is an error. *)
8917 exception Handle_closed of string
8918 (** This exception is raised if you use a {!Guestfs.t} handle
8919 after calling {!close} on it. The string is the name of
8922 val create : unit -> t
8923 (** Create a {!Guestfs.t} handle. *)
8925 val close : t -> unit
8926 (** Close the {!Guestfs.t} handle and free up all resources used
8929 Handles are closed by the garbage collector when they become
8930 unreferenced, but callers can call this in order to provide
8931 predictable cleanup. *)
8933 type progress_cb = int -> int -> int64 -> int64 -> unit
8935 val set_progress_callback : t -> progress_cb -> unit
8936 (** [set_progress_callback g f] sets [f] as the progress callback function.
8937 For some long-running functions, [f] will be called repeatedly
8938 during the function with progress updates.
8940 The callback is [f proc_nr serial position total]. See
8941 the description of [guestfs_set_progress_callback] in guestfs(3)
8942 for the meaning of these four numbers.
8944 Note that if the closure captures a reference to the handle,
8945 this reference will prevent the handle from being
8946 automatically closed by the garbage collector. There are
8947 three ways to avoid this: be careful not to capture the handle
8948 in the closure, or use a weak reference, or call
8949 {!Guestfs.clear_progress_callback} to remove the reference. *)
8951 val clear_progress_callback : t -> unit
8952 (** [clear_progress_callback g] removes any progress callback function
8953 associated with the handle. See {!Guestfs.set_progress_callback}. *)
8956 generate_ocaml_structure_decls ();
8960 fun (name, style, _, _, _, shortdesc, _) ->
8961 generate_ocaml_prototype name style;
8962 pr "(** %s *)\n" shortdesc;
8964 ) all_functions_sorted
8966 (* Generate the OCaml bindings implementation. *)
8967 and generate_ocaml_ml () =
8968 generate_header OCamlStyle LGPLv2plus;
8973 exception Error of string
8974 exception Handle_closed of string
8976 external create : unit -> t = \"ocaml_guestfs_create\"
8977 external close : t -> unit = \"ocaml_guestfs_close\"
8979 type progress_cb = int -> int -> int64 -> int64 -> unit
8981 external set_progress_callback : t -> progress_cb -> unit
8982 = \"ocaml_guestfs_set_progress_callback\"
8983 external clear_progress_callback : t -> unit
8984 = \"ocaml_guestfs_clear_progress_callback\"
8986 (* Give the exceptions names, so they can be raised from the C code. *)
8988 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
8989 Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
8993 generate_ocaml_structure_decls ();
8997 fun (name, style, _, _, _, shortdesc, _) ->
8998 generate_ocaml_prototype ~is_external:true name style;
8999 ) all_functions_sorted
9001 (* Generate the OCaml bindings C implementation. *)
9002 and generate_ocaml_c () =
9003 generate_header CStyle LGPLv2plus;
9010 #include <caml/config.h>
9011 #include <caml/alloc.h>
9012 #include <caml/callback.h>
9013 #include <caml/fail.h>
9014 #include <caml/memory.h>
9015 #include <caml/mlvalues.h>
9016 #include <caml/signals.h>
9018 #include \"guestfs.h\"
9020 #include \"guestfs_c.h\"
9022 /* Copy a hashtable of string pairs into an assoc-list. We return
9023 * the list in reverse order, but hashtables aren't supposed to be
9026 static CAMLprim value
9027 copy_table (char * const * argv)
9030 CAMLlocal5 (rv, pairv, kv, vv, cons);
9034 for (i = 0; argv[i] != NULL; i += 2) {
9035 kv = caml_copy_string (argv[i]);
9036 vv = caml_copy_string (argv[i+1]);
9037 pairv = caml_alloc (2, 0);
9038 Store_field (pairv, 0, kv);
9039 Store_field (pairv, 1, vv);
9040 cons = caml_alloc (2, 0);
9041 Store_field (cons, 1, rv);
9043 Store_field (cons, 0, pairv);
9051 (* Struct copy functions. *)
9053 let emit_ocaml_copy_list_function typ =
9054 pr "static CAMLprim value\n";
9055 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
9057 pr " CAMLparam0 ();\n";
9058 pr " CAMLlocal2 (rv, v);\n";
9059 pr " unsigned int i;\n";
9061 pr " if (%ss->len == 0)\n" typ;
9062 pr " CAMLreturn (Atom (0));\n";
9064 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
9065 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
9066 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
9067 pr " caml_modify (&Field (rv, i), v);\n";
9069 pr " CAMLreturn (rv);\n";
9077 let has_optpercent_col =
9078 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
9080 pr "static CAMLprim value\n";
9081 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
9083 pr " CAMLparam0 ();\n";
9084 if has_optpercent_col then
9085 pr " CAMLlocal3 (rv, v, v2);\n"
9087 pr " CAMLlocal2 (rv, v);\n";
9089 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
9094 pr " v = caml_copy_string (%s->%s);\n" typ name
9096 pr " v = caml_alloc_string (%s->%s_len);\n" typ name;
9097 pr " memcpy (String_val (v), %s->%s, %s->%s_len);\n"
9100 pr " v = caml_alloc_string (32);\n";
9101 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
9102 | name, (FBytes|FInt64|FUInt64) ->
9103 pr " v = caml_copy_int64 (%s->%s);\n" typ name
9104 | name, (FInt32|FUInt32) ->
9105 pr " v = caml_copy_int32 (%s->%s);\n" typ name
9106 | name, FOptPercent ->
9107 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
9108 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
9109 pr " v = caml_alloc (1, 0);\n";
9110 pr " Store_field (v, 0, v2);\n";
9111 pr " } else /* None */\n";
9112 pr " v = Val_int (0);\n";
9114 pr " v = Val_int (%s->%s);\n" typ name
9116 pr " Store_field (rv, %d, v);\n" i
9118 pr " CAMLreturn (rv);\n";
9123 (* Emit a copy_TYPE_list function definition only if that function is used. *)
9126 | typ, (RStructListOnly | RStructAndList) ->
9127 (* generate the function for typ *)
9128 emit_ocaml_copy_list_function typ
9129 | typ, _ -> () (* empty *)
9130 ) (rstructs_used_by all_functions);
9134 fun (name, style, _, _, _, _, _) ->
9135 pr "/* Automatically generated wrapper for function\n";
9137 generate_ocaml_prototype name style;
9142 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
9144 let needs_extra_vs =
9145 match fst style with RConstOptString _ -> true | _ -> false in
9147 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9148 pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
9149 List.iter (pr ", value %s") (List.tl params); pr ");\n";
9152 pr "CAMLprim value\n";
9153 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
9154 List.iter (pr ", value %s") (List.tl params);
9159 | [p1; p2; p3; p4; p5] ->
9160 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
9161 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
9162 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
9163 pr " CAMLxparam%d (%s);\n"
9164 (List.length rest) (String.concat ", " rest)
9166 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
9168 if not needs_extra_vs then
9169 pr " CAMLlocal1 (rv);\n"
9171 pr " CAMLlocal3 (rv, v, v2);\n";
9174 pr " guestfs_h *g = Guestfs_val (gv);\n";
9175 pr " if (g == NULL)\n";
9176 pr " ocaml_guestfs_raise_closed (\"%s\");\n" name;
9182 | Device n | Dev_or_Path n
9187 (* Copy strings in case the GC moves them: RHBZ#604691 *)
9188 pr " char *%s = guestfs_safe_strdup (g, String_val (%sv));\n" n n
9190 pr " char *%s =\n" n;
9191 pr " %sv != Val_int (0) ?" n;
9192 pr " guestfs_safe_strdup (g, String_val (Field (%sv, 0))) : NULL;\n" n
9194 pr " size_t %s_size = caml_string_length (%sv);\n" n n;
9195 pr " char *%s = guestfs_safe_memdup (g, String_val (%sv), %s_size);\n" n n n
9196 | StringList n | DeviceList n ->
9197 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
9199 pr " int %s = Bool_val (%sv);\n" n n
9201 pr " int %s = Int_val (%sv);\n" n n
9203 pr " int64_t %s = Int64_val (%sv);\n" n n
9206 match fst style with
9207 | RErr -> pr " int r;\n"; "-1"
9208 | RInt _ -> pr " int r;\n"; "-1"
9209 | RInt64 _ -> pr " int64_t r;\n"; "-1"
9210 | RBool _ -> pr " int r;\n"; "-1"
9211 | RConstString _ | RConstOptString _ ->
9212 pr " const char *r;\n"; "NULL"
9213 | RString _ -> pr " char *r;\n"; "NULL"
9218 | RStruct (_, typ) ->
9219 pr " struct guestfs_%s *r;\n" typ; "NULL"
9220 | RStructList (_, typ) ->
9221 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
9228 pr " size_t size;\n";
9232 pr " caml_enter_blocking_section ();\n";
9233 pr " r = guestfs_%s " name;
9234 generate_c_call_args ~handle:"g" style;
9236 pr " caml_leave_blocking_section ();\n";
9238 (* Free strings if we copied them above. *)
9241 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
9242 | FileIn n | FileOut n | BufferIn n | Key n ->
9243 pr " free (%s);\n" n
9244 | StringList n | DeviceList n ->
9245 pr " ocaml_guestfs_free_strings (%s);\n" n;
9246 | Bool _ | Int _ | Int64 _ -> ()
9249 pr " if (r == %s)\n" error_code;
9250 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
9253 (match fst style with
9254 | RErr -> pr " rv = Val_unit;\n"
9255 | RInt _ -> pr " rv = Val_int (r);\n"
9257 pr " rv = caml_copy_int64 (r);\n"
9258 | RBool _ -> pr " rv = Val_bool (r);\n"
9260 pr " rv = caml_copy_string (r);\n"
9261 | RConstOptString _ ->
9262 pr " if (r) { /* Some string */\n";
9263 pr " v = caml_alloc (1, 0);\n";
9264 pr " v2 = caml_copy_string (r);\n";
9265 pr " Store_field (v, 0, v2);\n";
9266 pr " } else /* None */\n";
9267 pr " v = Val_int (0);\n";
9269 pr " rv = caml_copy_string (r);\n";
9272 pr " rv = caml_copy_string_array ((const char **) r);\n";
9273 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9275 | RStruct (_, typ) ->
9276 pr " rv = copy_%s (r);\n" typ;
9277 pr " guestfs_free_%s (r);\n" typ;
9278 | RStructList (_, typ) ->
9279 pr " rv = copy_%s_list (r);\n" typ;
9280 pr " guestfs_free_%s_list (r);\n" typ;
9282 pr " rv = copy_table (r);\n";
9283 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9286 pr " rv = caml_alloc_string (size);\n";
9287 pr " memcpy (String_val (rv), r, size);\n";
9290 pr " CAMLreturn (rv);\n";
9294 if List.length params > 5 then (
9295 pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9296 pr "CAMLprim value ";
9297 pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
9298 pr "CAMLprim value\n";
9299 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
9301 pr " return ocaml_guestfs_%s (argv[0]" name;
9302 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
9307 ) all_functions_sorted
9309 and generate_ocaml_structure_decls () =
9312 pr "type %s = {\n" typ;
9315 | name, FString -> pr " %s : string;\n" name
9316 | name, FBuffer -> pr " %s : string;\n" name
9317 | name, FUUID -> pr " %s : string;\n" name
9318 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
9319 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
9320 | name, FChar -> pr " %s : char;\n" name
9321 | name, FOptPercent -> pr " %s : float option;\n" name
9327 and generate_ocaml_prototype ?(is_external = false) name style =
9328 if is_external then pr "external " else pr "val ";
9329 pr "%s : t -> " name;
9332 | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _
9333 | BufferIn _ | Key _ -> pr "string -> "
9334 | OptString _ -> pr "string option -> "
9335 | StringList _ | DeviceList _ -> pr "string array -> "
9336 | Bool _ -> pr "bool -> "
9337 | Int _ -> pr "int -> "
9338 | Int64 _ -> pr "int64 -> "
9340 (match fst style with
9341 | RErr -> pr "unit" (* all errors are turned into exceptions *)
9342 | RInt _ -> pr "int"
9343 | RInt64 _ -> pr "int64"
9344 | RBool _ -> pr "bool"
9345 | RConstString _ -> pr "string"
9346 | RConstOptString _ -> pr "string option"
9347 | RString _ | RBufferOut _ -> pr "string"
9348 | RStringList _ -> pr "string array"
9349 | RStruct (_, typ) -> pr "%s" typ
9350 | RStructList (_, typ) -> pr "%s array" typ
9351 | RHashtable _ -> pr "(string * string) list"
9353 if is_external then (
9355 if List.length (snd style) + 1 > 5 then
9356 pr "\"ocaml_guestfs_%s_byte\" " name;
9357 pr "\"ocaml_guestfs_%s\"" name
9361 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
9362 and generate_perl_xs () =
9363 generate_header CStyle LGPLv2plus;
9366 #include \"EXTERN.h\"
9370 #include <guestfs.h>
9373 #define PRId64 \"lld\"
9377 my_newSVll(long long val) {
9378 #ifdef USE_64_BIT_ALL
9379 return newSViv(val);
9383 len = snprintf(buf, 100, \"%%\" PRId64, val);
9384 return newSVpv(buf, len);
9389 #define PRIu64 \"llu\"
9393 my_newSVull(unsigned long long val) {
9394 #ifdef USE_64_BIT_ALL
9395 return newSVuv(val);
9399 len = snprintf(buf, 100, \"%%\" PRIu64, val);
9400 return newSVpv(buf, len);
9404 /* http://www.perlmonks.org/?node_id=680842 */
9406 XS_unpack_charPtrPtr (SV *arg) {
9411 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
9412 croak (\"array reference expected\");
9414 av = (AV *)SvRV (arg);
9415 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
9417 croak (\"malloc failed\");
9419 for (i = 0; i <= av_len (av); i++) {
9420 SV **elem = av_fetch (av, i, 0);
9422 if (!elem || !*elem)
9423 croak (\"missing element in list\");
9425 ret[i] = SvPV_nolen (*elem);
9433 #define PROGRESS_KEY \"_perl_progress_cb\"
9436 _clear_progress_callback (guestfs_h *g)
9438 guestfs_set_progress_callback (g, NULL, NULL);
9439 SV *cb = guestfs_get_private (g, PROGRESS_KEY);
9441 guestfs_set_private (g, PROGRESS_KEY, NULL);
9446 /* http://www.perlmonks.org/?node=338857 */
9448 _progress_callback (guestfs_h *g, void *cb,
9449 int proc_nr, int serial, uint64_t position, uint64_t total)
9455 XPUSHs (sv_2mortal (newSViv (proc_nr)));
9456 XPUSHs (sv_2mortal (newSViv (serial)));
9457 XPUSHs (sv_2mortal (my_newSVull (position)));
9458 XPUSHs (sv_2mortal (my_newSVull (total)));
9460 call_sv ((SV *) cb, G_VOID | G_DISCARD | G_EVAL);
9466 _close_handle (guestfs_h *g)
9469 _clear_progress_callback (g);
9473 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
9480 RETVAL = guestfs_create ();
9482 croak (\"could not create guestfs handle\");
9483 guestfs_set_error_handler (RETVAL, NULL, NULL);
9491 /* For the 'g' argument above we do the conversion explicitly and
9492 * don't rely on the typemap, because if the handle has been
9493 * explicitly closed we don't want the typemap conversion to
9496 HV *hv = (HV *) SvRV (sv);
9497 SV **svp = hv_fetch (hv, \"_g\", 2, 0);
9499 guestfs_h *g = (guestfs_h *) SvIV (*svp);
9508 /* Avoid double-free in DESTROY method. */
9509 HV *hv = (HV *) SvRV (ST(0));
9510 (void) hv_delete (hv, \"_g\", 2, G_DISCARD);
9513 set_progress_callback (g, cb)
9517 _clear_progress_callback (g);
9519 guestfs_set_private (g, PROGRESS_KEY, cb);
9520 guestfs_set_progress_callback (g, _progress_callback, cb);
9523 clear_progress_callback (g)
9526 _clear_progress_callback (g);
9531 fun (name, style, _, _, _, _, _) ->
9532 (match fst style with
9533 | RErr -> pr "void\n"
9534 | RInt _ -> pr "SV *\n"
9535 | RInt64 _ -> pr "SV *\n"
9536 | RBool _ -> pr "SV *\n"
9537 | RConstString _ -> pr "SV *\n"
9538 | RConstOptString _ -> pr "SV *\n"
9539 | RString _ -> pr "SV *\n"
9540 | RBufferOut _ -> pr "SV *\n"
9542 | RStruct _ | RStructList _
9544 pr "void\n" (* all lists returned implictly on the stack *)
9546 (* Call and arguments. *)
9549 fun arg -> pr ", %s" (name_of_argt arg)
9552 pr " guestfs_h *g;\n";
9556 | Pathname n | Device n | Dev_or_Path n | String n
9557 | FileIn n | FileOut n | Key n ->
9560 pr " char *%s;\n" n;
9561 pr " size_t %s_size = SvCUR (ST(%d));\n" n (i+1)
9563 (* http://www.perlmonks.org/?node_id=554277
9564 * Note that the implicit handle argument means we have
9565 * to add 1 to the ST(x) operator.
9567 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
9568 | StringList n | DeviceList n -> pr " char **%s;\n" n
9569 | Bool n -> pr " int %s;\n" n
9570 | Int n -> pr " int %s;\n" n
9571 | Int64 n -> pr " int64_t %s;\n" n
9574 let do_cleanups () =
9577 | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
9578 | Bool _ | Int _ | Int64 _
9579 | FileIn _ | FileOut _
9580 | BufferIn _ | Key _ -> ()
9581 | StringList n | DeviceList n -> pr " free (%s);\n" n
9586 (match fst style with
9591 pr " r = guestfs_%s " name;
9592 generate_c_call_args ~handle:"g" style;
9595 pr " if (r == -1)\n";
9596 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9602 pr " %s = guestfs_%s " n name;
9603 generate_c_call_args ~handle:"g" style;
9606 pr " if (%s == -1)\n" n;
9607 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9608 pr " RETVAL = newSViv (%s);\n" n;
9613 pr " int64_t %s;\n" n;
9615 pr " %s = guestfs_%s " n name;
9616 generate_c_call_args ~handle:"g" style;
9619 pr " if (%s == -1)\n" n;
9620 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9621 pr " RETVAL = my_newSVll (%s);\n" n;
9626 pr " const char *%s;\n" n;
9628 pr " %s = guestfs_%s " n name;
9629 generate_c_call_args ~handle:"g" style;
9632 pr " if (%s == NULL)\n" n;
9633 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9634 pr " RETVAL = newSVpv (%s, 0);\n" n;
9637 | RConstOptString n ->
9639 pr " const char *%s;\n" n;
9641 pr " %s = guestfs_%s " n name;
9642 generate_c_call_args ~handle:"g" style;
9645 pr " if (%s == NULL)\n" n;
9646 pr " RETVAL = &PL_sv_undef;\n";
9648 pr " RETVAL = newSVpv (%s, 0);\n" n;
9653 pr " char *%s;\n" n;
9655 pr " %s = guestfs_%s " n name;
9656 generate_c_call_args ~handle:"g" style;
9659 pr " if (%s == NULL)\n" n;
9660 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9661 pr " RETVAL = newSVpv (%s, 0);\n" n;
9662 pr " free (%s);\n" n;
9665 | RStringList n | RHashtable n ->
9667 pr " char **%s;\n" n;
9668 pr " size_t i, n;\n";
9670 pr " %s = guestfs_%s " n name;
9671 generate_c_call_args ~handle:"g" style;
9674 pr " if (%s == NULL)\n" n;
9675 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9676 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
9677 pr " EXTEND (SP, n);\n";
9678 pr " for (i = 0; i < n; ++i) {\n";
9679 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
9680 pr " free (%s[i]);\n" n;
9682 pr " free (%s);\n" n;
9683 | RStruct (n, typ) ->
9684 let cols = cols_of_struct typ in
9685 generate_perl_struct_code typ cols name style n do_cleanups
9686 | RStructList (n, typ) ->
9687 let cols = cols_of_struct typ in
9688 generate_perl_struct_list_code typ cols name style n do_cleanups
9691 pr " char *%s;\n" n;
9692 pr " size_t size;\n";
9694 pr " %s = guestfs_%s " n name;
9695 generate_c_call_args ~handle:"g" style;
9698 pr " if (%s == NULL)\n" n;
9699 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9700 pr " RETVAL = newSVpvn (%s, size);\n" n;
9701 pr " free (%s);\n" n;
9709 and generate_perl_struct_list_code typ cols name style n do_cleanups =
9711 pr " struct guestfs_%s_list *%s;\n" typ n;
9715 pr " %s = guestfs_%s " n name;
9716 generate_c_call_args ~handle:"g" style;
9719 pr " if (%s == NULL)\n" n;
9720 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9721 pr " EXTEND (SP, %s->len);\n" n;
9722 pr " for (i = 0; i < %s->len; ++i) {\n" n;
9723 pr " hv = newHV ();\n";
9727 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
9728 name (String.length name) n name
9730 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
9731 name (String.length name) n name
9733 pr " (void) hv_store (hv, \"%s\", %d, newSVpvn (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
9734 name (String.length name) n name n name
9735 | name, (FBytes|FUInt64) ->
9736 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
9737 name (String.length name) n name
9739 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
9740 name (String.length name) n name
9741 | name, (FInt32|FUInt32) ->
9742 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9743 name (String.length name) n name
9745 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
9746 name (String.length name) n name
9747 | name, FOptPercent ->
9748 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9749 name (String.length name) n name
9751 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
9753 pr " guestfs_free_%s_list (%s);\n" typ n
9755 and generate_perl_struct_code typ cols name style n do_cleanups =
9757 pr " struct guestfs_%s *%s;\n" typ n;
9759 pr " %s = guestfs_%s " n name;
9760 generate_c_call_args ~handle:"g" style;
9763 pr " if (%s == NULL)\n" n;
9764 pr " croak (\"%%s\", guestfs_last_error (g));\n";
9765 pr " EXTEND (SP, 2 * %d);\n" (List.length cols);
9767 fun ((name, _) as col) ->
9768 pr " PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
9772 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
9775 pr " PUSHs (sv_2mortal (newSVpvn (%s->%s, %s->%s_len)));\n"
9778 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
9780 | name, (FBytes|FUInt64) ->
9781 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
9784 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
9786 | name, (FInt32|FUInt32) ->
9787 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9790 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
9792 | name, FOptPercent ->
9793 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9796 pr " free (%s);\n" n
9798 (* Generate Sys/Guestfs.pm. *)
9799 and generate_perl_pm () =
9800 generate_header HashStyle LGPLv2plus;
9807 Sys::Guestfs - Perl bindings for libguestfs
9813 my $h = Sys::Guestfs->new ();
9814 $h->add_drive ('guest.img');
9816 $h->mount ('/dev/sda1', '/');
9817 $h->touch ('/hello');
9822 The C<Sys::Guestfs> module provides a Perl XS binding to the
9823 libguestfs API for examining and modifying virtual machine
9826 Amongst the things this is good for: making batch configuration
9827 changes to guests, getting disk used/free statistics (see also:
9828 virt-df), migrating between virtualization systems (see also:
9829 virt-p2v), performing partial backups, performing partial guest
9830 clones, cloning guests and changing registry/UUID/hostname info, and
9833 Libguestfs uses Linux kernel and qemu code, and can access any type of
9834 guest filesystem that Linux and qemu can, including but not limited
9835 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
9836 schemes, qcow, qcow2, vmdk.
9838 Libguestfs provides ways to enumerate guest storage (eg. partitions,
9839 LVs, what filesystem is in each LV, etc.). It can also run commands
9840 in the context of the guest. Also you can access filesystems over
9843 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
9844 functions for using libguestfs from Perl, including integration
9849 All errors turn into calls to C<croak> (see L<Carp(3)>).
9857 package Sys::Guestfs;
9862 # This version number changes whenever a new function
9863 # is added to the libguestfs API. It is not directly
9864 # related to the libguestfs version number.
9865 use vars qw($VERSION);
9869 XSLoader::load ('Sys::Guestfs');
9871 =item $h = Sys::Guestfs->new ();
9873 Create a new guestfs handle.
9879 my $class = ref ($proto) || $proto;
9881 my $g = Sys::Guestfs::_create ();
9882 my $self = { _g => $g };
9883 bless $self, $class;
9889 Explicitly close the guestfs handle.
9891 B<Note:> You should not usually call this function. The handle will
9892 be closed implicitly when its reference count goes to zero (eg.
9893 when it goes out of scope or the program ends). This call is
9894 only required in some exceptional cases, such as where the program
9895 may contain cached references to the handle 'somewhere' and you
9896 really have to have the close happen right away. After calling
9897 C<close> the program must not call any method (including C<close>)
9898 on the handle (but the implicit call to C<DESTROY> that happens
9899 when the final reference is cleaned up is OK).
9901 =item $h->set_progress_callback (\\&cb);
9903 Set the progress notification callback for this handle
9904 to the Perl closure C<cb>.
9906 C<cb> will be called whenever a long-running operation
9907 generates a progress notification message. The 4 parameters
9908 to the function are: C<proc_nr>, C<serial>, C<position>
9911 You should carefully read the documentation for
9912 L<guestfs(3)/guestfs_set_progress_callback> before using
9915 =item $h->clear_progress_callback ();
9917 This removes any progress callback function associated with
9924 (* Actions. We only need to print documentation for these as
9925 * they are pulled in from the XS code automatically.
9928 fun (name, style, _, flags, _, _, longdesc) ->
9929 if not (List.mem NotInDocs flags) then (
9930 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
9932 generate_perl_prototype name style;
9934 pr "%s\n\n" longdesc;
9935 if List.mem ProtocolLimitWarning flags then
9936 pr "%s\n\n" protocol_limit_warning;
9937 if List.mem DangerWillRobinson flags then
9938 pr "%s\n\n" danger_will_robinson;
9939 match deprecation_notice flags with
9941 | Some txt -> pr "%s\n\n" txt
9943 ) all_functions_sorted;
9955 Copyright (C) %s Red Hat Inc.
9959 Please see the file COPYING.LIB for the full license.
9965 L<http://libguestfs.org>,
9966 L<Sys::Guestfs::Lib(3)>.
9971 and generate_perl_prototype name style =
9972 (match fst style with
9980 | RBufferOut n -> pr "$%s = " n
9982 | RHashtable n -> pr "%%%s = " n
9984 | RStructList (n,_) -> pr "@%s = " n
9987 let comma = ref false in
9990 if !comma then pr ", ";
9993 | Pathname n | Device n | Dev_or_Path n | String n
9994 | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n
9995 | BufferIn n | Key n ->
9997 | StringList n | DeviceList n ->
10002 (* Generate Python C module. *)
10003 and generate_python_c () =
10004 generate_header CStyle LGPLv2plus;
10007 #define PY_SSIZE_T_CLEAN 1
10008 #include <Python.h>
10010 #if PY_VERSION_HEX < 0x02050000
10011 typedef int Py_ssize_t;
10012 #define PY_SSIZE_T_MAX INT_MAX
10013 #define PY_SSIZE_T_MIN INT_MIN
10017 #include <stdlib.h>
10018 #include <assert.h>
10020 #include \"guestfs.h\"
10022 #ifndef HAVE_PYCAPSULE_NEW
10026 } Pyguestfs_Object;
10030 get_handle (PyObject *obj)
10033 assert (obj != Py_None);
10034 #ifndef HAVE_PYCAPSULE_NEW
10035 return ((Pyguestfs_Object *) obj)->g;
10037 return (guestfs_h*) PyCapsule_GetPointer(obj, \"guestfs_h\");
10042 put_handle (guestfs_h *g)
10045 #ifndef HAVE_PYCAPSULE_NEW
10047 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
10049 return PyCapsule_New ((void *) g, \"guestfs_h\", NULL);
10053 /* This list should be freed (but not the strings) after use. */
10055 get_string_list (PyObject *obj)
10062 if (!PyList_Check (obj)) {
10063 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
10067 Py_ssize_t slen = PyList_Size (obj);
10069 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: PyList_Size failure\");
10072 len = (size_t) slen;
10073 r = malloc (sizeof (char *) * (len+1));
10075 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
10079 for (i = 0; i < len; ++i)
10080 r[i] = PyString_AsString (PyList_GetItem (obj, i));
10087 put_string_list (char * const * const argv)
10092 for (argc = 0; argv[argc] != NULL; ++argc)
10095 list = PyList_New (argc);
10096 for (i = 0; i < argc; ++i)
10097 PyList_SetItem (list, i, PyString_FromString (argv[i]));
10103 put_table (char * const * const argv)
10105 PyObject *list, *item;
10108 for (argc = 0; argv[argc] != NULL; ++argc)
10111 list = PyList_New (argc >> 1);
10112 for (i = 0; i < argc; i += 2) {
10113 item = PyTuple_New (2);
10114 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
10115 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
10116 PyList_SetItem (list, i >> 1, item);
10123 free_strings (char **argv)
10127 for (argc = 0; argv[argc] != NULL; ++argc)
10133 py_guestfs_create (PyObject *self, PyObject *args)
10137 g = guestfs_create ();
10139 PyErr_SetString (PyExc_RuntimeError,
10140 \"guestfs.create: failed to allocate handle\");
10143 guestfs_set_error_handler (g, NULL, NULL);
10144 /* This can return NULL, but in that case put_handle will have
10145 * set the Python error string.
10147 return put_handle (g);
10151 py_guestfs_close (PyObject *self, PyObject *args)
10156 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
10158 g = get_handle (py_g);
10162 Py_INCREF (Py_None);
10168 let emit_put_list_function typ =
10169 pr "static PyObject *\n";
10170 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
10172 pr " PyObject *list;\n";
10175 pr " list = PyList_New (%ss->len);\n" typ;
10176 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
10177 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
10178 pr " return list;\n";
10183 (* Structures, turned into Python dictionaries. *)
10186 pr "static PyObject *\n";
10187 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
10189 pr " PyObject *dict;\n";
10191 pr " dict = PyDict_New ();\n";
10195 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10196 pr " PyString_FromString (%s->%s));\n"
10199 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10200 pr " PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
10203 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10204 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
10206 | name, (FBytes|FUInt64) ->
10207 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10208 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
10211 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10212 pr " PyLong_FromLongLong (%s->%s));\n"
10215 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10216 pr " PyLong_FromUnsignedLong (%s->%s));\n"
10219 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10220 pr " PyLong_FromLong (%s->%s));\n"
10222 | name, FOptPercent ->
10223 pr " if (%s->%s >= 0)\n" typ name;
10224 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10225 pr " PyFloat_FromDouble ((double) %s->%s));\n"
10228 pr " Py_INCREF (Py_None);\n";
10229 pr " PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
10232 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
10233 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
10235 pr " return dict;\n";
10241 (* Emit a put_TYPE_list function definition only if that function is used. *)
10244 | typ, (RStructListOnly | RStructAndList) ->
10245 (* generate the function for typ *)
10246 emit_put_list_function typ
10247 | typ, _ -> () (* empty *)
10248 ) (rstructs_used_by all_functions);
10250 (* Python wrapper functions. *)
10252 fun (name, style, _, _, _, _, _) ->
10253 pr "static PyObject *\n";
10254 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
10257 pr " PyObject *py_g;\n";
10258 pr " guestfs_h *g;\n";
10259 pr " PyObject *py_r;\n";
10262 match fst style with
10263 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
10264 | RInt64 _ -> pr " int64_t r;\n"; "-1"
10265 | RConstString _ | RConstOptString _ ->
10266 pr " const char *r;\n"; "NULL"
10267 | RString _ -> pr " char *r;\n"; "NULL"
10268 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
10269 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
10270 | RStructList (_, typ) ->
10271 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
10274 pr " size_t size;\n";
10279 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10280 | FileIn n | FileOut n ->
10281 pr " const char *%s;\n" n
10282 | OptString n -> pr " const char *%s;\n" n
10284 pr " const char *%s;\n" n;
10285 pr " Py_ssize_t %s_size;\n" n
10286 | StringList n | DeviceList n ->
10287 pr " PyObject *py_%s;\n" n;
10288 pr " char **%s;\n" n
10289 | Bool n -> pr " int %s;\n" n
10290 | Int n -> pr " int %s;\n" n
10291 | Int64 n -> pr " long long %s;\n" n
10296 (* Convert the parameters. *)
10297 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
10300 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10301 | FileIn _ | FileOut _ -> pr "s"
10302 | OptString _ -> pr "z"
10303 | StringList _ | DeviceList _ -> pr "O"
10304 | Bool _ -> pr "i" (* XXX Python has booleans? *)
10306 | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
10307 * emulate C's int/long/long long in Python?
10309 | BufferIn _ -> pr "s#"
10311 pr ":guestfs_%s\",\n" name;
10315 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10316 | FileIn n | FileOut n -> pr ", &%s" n
10317 | OptString n -> pr ", &%s" n
10318 | StringList n | DeviceList n -> pr ", &py_%s" n
10319 | Bool n -> pr ", &%s" n
10320 | Int n -> pr ", &%s" n
10321 | Int64 n -> pr ", &%s" n
10322 | BufferIn n -> pr ", &%s, &%s_size" n n
10326 pr " return NULL;\n";
10328 pr " g = get_handle (py_g);\n";
10331 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10332 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10334 | StringList n | DeviceList n ->
10335 pr " %s = get_string_list (py_%s);\n" n n;
10336 pr " if (!%s) return NULL;\n" n
10341 pr " r = guestfs_%s " name;
10342 generate_c_call_args ~handle:"g" style;
10347 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10348 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10350 | StringList n | DeviceList n ->
10351 pr " free (%s);\n" n
10354 pr " if (r == %s) {\n" error_code;
10355 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
10356 pr " return NULL;\n";
10360 (match fst style with
10362 pr " Py_INCREF (Py_None);\n";
10363 pr " py_r = Py_None;\n"
10365 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
10366 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
10367 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
10368 | RConstOptString _ ->
10370 pr " py_r = PyString_FromString (r);\n";
10372 pr " Py_INCREF (Py_None);\n";
10373 pr " py_r = Py_None;\n";
10376 pr " py_r = PyString_FromString (r);\n";
10379 pr " py_r = put_string_list (r);\n";
10380 pr " free_strings (r);\n"
10381 | RStruct (_, typ) ->
10382 pr " py_r = put_%s (r);\n" typ;
10383 pr " guestfs_free_%s (r);\n" typ
10384 | RStructList (_, typ) ->
10385 pr " py_r = put_%s_list (r);\n" typ;
10386 pr " guestfs_free_%s_list (r);\n" typ
10388 pr " py_r = put_table (r);\n";
10389 pr " free_strings (r);\n"
10391 pr " py_r = PyString_FromStringAndSize (r, size);\n";
10395 pr " return py_r;\n";
10400 (* Table of functions. *)
10401 pr "static PyMethodDef methods[] = {\n";
10402 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
10403 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
10405 fun (name, _, _, _, _, _, _) ->
10406 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
10409 pr " { NULL, NULL, 0, NULL }\n";
10413 (* Init function. *)
10416 initlibguestfsmod (void)
10418 static int initialized = 0;
10420 if (initialized) return;
10421 Py_InitModule ((char *) \"libguestfsmod\", methods);
10426 (* Generate Python module. *)
10427 and generate_python_py () =
10428 generate_header HashStyle LGPLv2plus;
10431 u\"\"\"Python bindings for libguestfs
10434 g = guestfs.GuestFS ()
10435 g.add_drive (\"guest.img\")
10437 parts = g.list_partitions ()
10439 The guestfs module provides a Python binding to the libguestfs API
10440 for examining and modifying virtual machine disk images.
10442 Amongst the things this is good for: making batch configuration
10443 changes to guests, getting disk used/free statistics (see also:
10444 virt-df), migrating between virtualization systems (see also:
10445 virt-p2v), performing partial backups, performing partial guest
10446 clones, cloning guests and changing registry/UUID/hostname info, and
10449 Libguestfs uses Linux kernel and qemu code, and can access any type of
10450 guest filesystem that Linux and qemu can, including but not limited
10451 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
10452 schemes, qcow, qcow2, vmdk.
10454 Libguestfs provides ways to enumerate guest storage (eg. partitions,
10455 LVs, what filesystem is in each LV, etc.). It can also run commands
10456 in the context of the guest. Also you can access filesystems over
10459 Errors which happen while using the API are turned into Python
10460 RuntimeError exceptions.
10462 To create a guestfs handle you usually have to perform the following
10465 # Create the handle, call add_drive at least once, and possibly
10466 # several times if the guest has multiple block devices:
10467 g = guestfs.GuestFS ()
10468 g.add_drive (\"guest.img\")
10470 # Launch the qemu subprocess and wait for it to become ready:
10473 # Now you can issue commands, for example:
10478 import libguestfsmod
10481 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
10483 def __init__ (self):
10484 \"\"\"Create a new libguestfs handle.\"\"\"
10485 self._o = libguestfsmod.create ()
10487 def __del__ (self):
10488 libguestfsmod.close (self._o)
10493 fun (name, style, _, flags, _, _, longdesc) ->
10494 pr " def %s " name;
10495 generate_py_call_args ~handle:"self" (snd style);
10498 if not (List.mem NotInDocs flags) then (
10499 let doc = replace_str longdesc "C<guestfs_" "C<g." in
10501 match fst style with
10502 | RErr | RInt _ | RInt64 _ | RBool _
10503 | RConstOptString _ | RConstString _
10504 | RString _ | RBufferOut _ -> doc
10506 doc ^ "\n\nThis function returns a list of strings."
10507 | RStruct (_, typ) ->
10508 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
10509 | RStructList (_, typ) ->
10510 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
10512 doc ^ "\n\nThis function returns a dictionary." in
10514 if List.mem ProtocolLimitWarning flags then
10515 doc ^ "\n\n" ^ protocol_limit_warning
10518 if List.mem DangerWillRobinson flags then
10519 doc ^ "\n\n" ^ danger_will_robinson
10522 match deprecation_notice flags with
10524 | Some txt -> doc ^ "\n\n" ^ txt in
10525 let doc = pod2text ~width:60 name doc in
10526 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
10527 let doc = String.concat "\n " doc in
10528 pr " u\"\"\"%s\"\"\"\n" doc;
10530 pr " return libguestfsmod.%s " name;
10531 generate_py_call_args ~handle:"self._o" (snd style);
10536 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
10537 and generate_py_call_args ~handle args =
10539 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10542 (* Useful if you need the longdesc POD text as plain text. Returns a
10545 * Because this is very slow (the slowest part of autogeneration),
10546 * we memoize the results.
10548 and pod2text ~width name longdesc =
10549 let key = width, name, longdesc in
10550 try Hashtbl.find pod2text_memo key
10552 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
10553 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
10555 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
10556 let chan = open_process_in cmd in
10557 let lines = ref [] in
10559 let line = input_line chan in
10560 if i = 1 then (* discard the first line of output *)
10563 let line = triml line in
10564 lines := line :: !lines;
10567 let lines = try loop 1 with End_of_file -> List.rev !lines in
10569 (match close_process_in chan with
10572 failwithf "pod2text: process exited with non-zero status (%d)" i
10573 | WSIGNALED i | WSTOPPED i ->
10574 failwithf "pod2text: process signalled or stopped by signal %d" i
10576 Hashtbl.add pod2text_memo key lines;
10577 pod2text_memo_updated ();
10580 (* Generate ruby bindings. *)
10581 and generate_ruby_c () =
10582 generate_header CStyle LGPLv2plus;
10586 #include <stdlib.h>
10590 #include \"guestfs.h\"
10592 #include \"extconf.h\"
10594 /* For Ruby < 1.9 */
10596 #define RARRAY_LEN(r) (RARRAY((r))->len)
10599 static VALUE m_guestfs; /* guestfs module */
10600 static VALUE c_guestfs; /* guestfs_h handle */
10601 static VALUE e_Error; /* used for all errors */
10603 static void ruby_guestfs_free (void *p)
10606 guestfs_close ((guestfs_h *) p);
10609 static VALUE ruby_guestfs_create (VALUE m)
10613 g = guestfs_create ();
10615 rb_raise (e_Error, \"failed to create guestfs handle\");
10617 /* Don't print error messages to stderr by default. */
10618 guestfs_set_error_handler (g, NULL, NULL);
10620 /* Wrap it, and make sure the close function is called when the
10621 * handle goes away.
10623 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
10626 static VALUE ruby_guestfs_close (VALUE gv)
10629 Data_Get_Struct (gv, guestfs_h, g);
10631 ruby_guestfs_free (g);
10632 DATA_PTR (gv) = NULL;
10640 fun (name, style, _, _, _, _, _) ->
10641 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
10642 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
10645 pr " guestfs_h *g;\n";
10646 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
10648 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
10654 | Pathname n | Device n | Dev_or_Path n | String n | Key n
10655 | FileIn n | FileOut n ->
10656 pr " Check_Type (%sv, T_STRING);\n" n;
10657 pr " const char *%s = StringValueCStr (%sv);\n" n n;
10658 pr " if (!%s)\n" n;
10659 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10660 pr " \"%s\", \"%s\");\n" n name
10662 pr " Check_Type (%sv, T_STRING);\n" n;
10663 pr " const char *%s = RSTRING (%sv)->ptr;\n" n n;
10664 pr " if (!%s)\n" n;
10665 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10666 pr " \"%s\", \"%s\");\n" n name;
10667 pr " size_t %s_size = RSTRING (%sv)->len;\n" n n
10669 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
10670 | StringList n | DeviceList n ->
10671 pr " char **%s;\n" n;
10672 pr " Check_Type (%sv, T_ARRAY);\n" n;
10674 pr " size_t i, len;\n";
10675 pr " len = RARRAY_LEN (%sv);\n" n;
10676 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
10678 pr " for (i = 0; i < len; ++i) {\n";
10679 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
10680 pr " %s[i] = StringValueCStr (v);\n" n;
10682 pr " %s[len] = NULL;\n" n;
10685 pr " int %s = RTEST (%sv);\n" n n
10687 pr " int %s = NUM2INT (%sv);\n" n n
10689 pr " long long %s = NUM2LL (%sv);\n" n n
10694 match fst style with
10695 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
10696 | RInt64 _ -> pr " int64_t r;\n"; "-1"
10697 | RConstString _ | RConstOptString _ ->
10698 pr " const char *r;\n"; "NULL"
10699 | RString _ -> pr " char *r;\n"; "NULL"
10700 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
10701 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
10702 | RStructList (_, typ) ->
10703 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
10706 pr " size_t size;\n";
10710 pr " r = guestfs_%s " name;
10711 generate_c_call_args ~handle:"g" style;
10716 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10717 | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10719 | StringList n | DeviceList n ->
10720 pr " free (%s);\n" n
10723 pr " if (r == %s)\n" error_code;
10724 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
10727 (match fst style with
10729 pr " return Qnil;\n"
10730 | RInt _ | RBool _ ->
10731 pr " return INT2NUM (r);\n"
10733 pr " return ULL2NUM (r);\n"
10734 | RConstString _ ->
10735 pr " return rb_str_new2 (r);\n";
10736 | RConstOptString _ ->
10738 pr " return rb_str_new2 (r);\n";
10740 pr " return Qnil;\n";
10742 pr " VALUE rv = rb_str_new2 (r);\n";
10744 pr " return rv;\n";
10746 pr " size_t i, len = 0;\n";
10747 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
10748 pr " VALUE rv = rb_ary_new2 (len);\n";
10749 pr " for (i = 0; r[i] != NULL; ++i) {\n";
10750 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
10751 pr " free (r[i]);\n";
10755 | RStruct (_, typ) ->
10756 let cols = cols_of_struct typ in
10757 generate_ruby_struct_code typ cols
10758 | RStructList (_, typ) ->
10759 let cols = cols_of_struct typ in
10760 generate_ruby_struct_list_code typ cols
10762 pr " VALUE rv = rb_hash_new ();\n";
10764 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
10765 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
10766 pr " free (r[i]);\n";
10767 pr " free (r[i+1]);\n";
10772 pr " VALUE rv = rb_str_new (r, size);\n";
10774 pr " return rv;\n";
10782 /* Initialize the module. */
10783 void Init__guestfs ()
10785 m_guestfs = rb_define_module (\"Guestfs\");
10786 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
10787 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
10789 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
10790 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
10793 (* Define the rest of the methods. *)
10795 fun (name, style, _, _, _, _, _) ->
10796 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
10797 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
10802 (* Ruby code to return a struct. *)
10803 and generate_ruby_struct_code typ cols =
10804 pr " VALUE rv = rb_hash_new ();\n";
10808 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
10810 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
10812 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
10813 | name, (FBytes|FUInt64) ->
10814 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10816 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
10818 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
10820 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
10821 | name, FOptPercent ->
10822 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
10823 | name, FChar -> (* XXX wrong? *)
10824 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10826 pr " guestfs_free_%s (r);\n" typ;
10829 (* Ruby code to return a struct list. *)
10830 and generate_ruby_struct_list_code typ cols =
10831 pr " VALUE rv = rb_ary_new2 (r->len);\n";
10833 pr " for (i = 0; i < r->len; ++i) {\n";
10834 pr " VALUE hv = rb_hash_new ();\n";
10838 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
10840 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
10842 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
10843 | name, (FBytes|FUInt64) ->
10844 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10846 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
10848 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
10850 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
10851 | name, FOptPercent ->
10852 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
10853 | name, FChar -> (* XXX wrong? *)
10854 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10856 pr " rb_ary_push (rv, hv);\n";
10858 pr " guestfs_free_%s_list (r);\n" typ;
10861 (* Generate Java bindings GuestFS.java file. *)
10862 and generate_java_java () =
10863 generate_header CStyle LGPLv2plus;
10866 package com.redhat.et.libguestfs;
10868 import java.util.HashMap;
10869 import com.redhat.et.libguestfs.LibGuestFSException;
10870 import com.redhat.et.libguestfs.PV;
10871 import com.redhat.et.libguestfs.VG;
10872 import com.redhat.et.libguestfs.LV;
10873 import com.redhat.et.libguestfs.Stat;
10874 import com.redhat.et.libguestfs.StatVFS;
10875 import com.redhat.et.libguestfs.IntBool;
10876 import com.redhat.et.libguestfs.Dirent;
10879 * The GuestFS object is a libguestfs handle.
10883 public class GuestFS {
10884 // Load the native code.
10886 System.loadLibrary (\"guestfs_jni\");
10890 * The native guestfs_h pointer.
10895 * Create a libguestfs handle.
10897 * @throws LibGuestFSException
10899 public GuestFS () throws LibGuestFSException
10903 private native long _create () throws LibGuestFSException;
10906 * Close a libguestfs handle.
10908 * You can also leave handles to be collected by the garbage
10909 * collector, but this method ensures that the resources used
10910 * by the handle are freed up immediately. If you call any
10911 * other methods after closing the handle, you will get an
10914 * @throws LibGuestFSException
10916 public void close () throws LibGuestFSException
10922 private native void _close (long g) throws LibGuestFSException;
10924 public void finalize () throws LibGuestFSException
10932 fun (name, style, _, flags, _, shortdesc, longdesc) ->
10933 if not (List.mem NotInDocs flags); then (
10934 let doc = replace_str longdesc "C<guestfs_" "C<g." in
10936 if List.mem ProtocolLimitWarning flags then
10937 doc ^ "\n\n" ^ protocol_limit_warning
10940 if List.mem DangerWillRobinson flags then
10941 doc ^ "\n\n" ^ danger_will_robinson
10944 match deprecation_notice flags with
10946 | Some txt -> doc ^ "\n\n" ^ txt in
10947 let doc = pod2text ~width:60 name doc in
10948 let doc = List.map ( (* RHBZ#501883 *)
10951 | nonempty -> nonempty
10953 let doc = String.concat "\n * " doc in
10956 pr " * %s\n" shortdesc;
10959 pr " * @throws LibGuestFSException\n";
10963 generate_java_prototype ~public:true ~semicolon:false name style;
10966 pr " if (g == 0)\n";
10967 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
10970 if fst style <> RErr then pr "return ";
10972 generate_java_call_args ~handle:"g" (snd style);
10976 generate_java_prototype ~privat:true ~native:true name style;
10983 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
10984 and generate_java_call_args ~handle args =
10986 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10989 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
10990 ?(semicolon=true) name style =
10991 if privat then pr "private ";
10992 if public then pr "public ";
10993 if native then pr "native ";
10996 (match fst style with
10997 | RErr -> pr "void ";
10998 | RInt _ -> pr "int ";
10999 | RInt64 _ -> pr "long ";
11000 | RBool _ -> pr "boolean ";
11001 | RConstString _ | RConstOptString _ | RString _
11002 | RBufferOut _ -> pr "String ";
11003 | RStringList _ -> pr "String[] ";
11004 | RStruct (_, typ) ->
11005 let name = java_name_of_struct typ in
11007 | RStructList (_, typ) ->
11008 let name = java_name_of_struct typ in
11010 | RHashtable _ -> pr "HashMap<String,String> ";
11013 if native then pr "_%s " name else pr "%s " name;
11015 let needs_comma = ref false in
11018 needs_comma := true
11024 if !needs_comma then pr ", ";
11025 needs_comma := true;
11029 | Device n | Dev_or_Path n
11038 | StringList n | DeviceList n ->
11049 pr " throws LibGuestFSException";
11050 if semicolon then pr ";"
11052 and generate_java_struct jtyp cols () =
11053 generate_header CStyle LGPLv2plus;
11056 package com.redhat.et.libguestfs;
11059 * Libguestfs %s structure.
11071 | name, FBuffer -> pr " public String %s;\n" name
11072 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
11073 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
11074 | name, FChar -> pr " public char %s;\n" name
11075 | name, FOptPercent ->
11076 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
11077 pr " public float %s;\n" name
11082 and generate_java_c () =
11083 generate_header CStyle LGPLv2plus;
11087 #include <stdlib.h>
11088 #include <string.h>
11090 #include \"com_redhat_et_libguestfs_GuestFS.h\"
11091 #include \"guestfs.h\"
11093 /* Note that this function returns. The exception is not thrown
11094 * until after the wrapper function returns.
11097 throw_exception (JNIEnv *env, const char *msg)
11100 cl = (*env)->FindClass (env,
11101 \"com/redhat/et/libguestfs/LibGuestFSException\");
11102 (*env)->ThrowNew (env, cl, msg);
11105 JNIEXPORT jlong JNICALL
11106 Java_com_redhat_et_libguestfs_GuestFS__1create
11107 (JNIEnv *env, jobject obj)
11111 g = guestfs_create ();
11113 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
11116 guestfs_set_error_handler (g, NULL, NULL);
11117 return (jlong) (long) g;
11120 JNIEXPORT void JNICALL
11121 Java_com_redhat_et_libguestfs_GuestFS__1close
11122 (JNIEnv *env, jobject obj, jlong jg)
11124 guestfs_h *g = (guestfs_h *) (long) jg;
11131 fun (name, style, _, _, _, _, _) ->
11133 (match fst style with
11134 | RErr -> pr "void ";
11135 | RInt _ -> pr "jint ";
11136 | RInt64 _ -> pr "jlong ";
11137 | RBool _ -> pr "jboolean ";
11138 | RConstString _ | RConstOptString _ | RString _
11139 | RBufferOut _ -> pr "jstring ";
11140 | RStruct _ | RHashtable _ ->
11142 | RStringList _ | RStructList _ ->
11143 pr "jobjectArray ";
11146 pr "Java_com_redhat_et_libguestfs_GuestFS_";
11147 pr "%s" (replace_str ("_" ^ name) "_" "_1");
11149 pr " (JNIEnv *env, jobject obj, jlong jg";
11153 | Device n | Dev_or_Path n
11159 pr ", jstring j%s" n
11161 pr ", jbyteArray j%s" n
11162 | StringList n | DeviceList n ->
11163 pr ", jobjectArray j%s" n
11165 pr ", jboolean j%s" n
11173 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
11174 let error_code, no_ret =
11175 match fst style with
11176 | RErr -> pr " int r;\n"; "-1", ""
11178 | RInt _ -> pr " int r;\n"; "-1", "0"
11179 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
11180 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
11181 | RConstOptString _ -> pr " const char *r;\n"; "NULL", "NULL"
11183 pr " jstring jr;\n";
11184 pr " char *r;\n"; "NULL", "NULL"
11186 pr " jobjectArray jr;\n";
11187 pr " int r_len;\n";
11188 pr " jclass cl;\n";
11189 pr " jstring jstr;\n";
11190 pr " char **r;\n"; "NULL", "NULL"
11191 | RStruct (_, typ) ->
11192 pr " jobject jr;\n";
11193 pr " jclass cl;\n";
11194 pr " jfieldID fl;\n";
11195 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
11196 | RStructList (_, typ) ->
11197 pr " jobjectArray jr;\n";
11198 pr " jclass cl;\n";
11199 pr " jfieldID fl;\n";
11200 pr " jobject jfl;\n";
11201 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
11202 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL"
11204 pr " jstring jr;\n";
11206 pr " size_t size;\n";
11211 | Device n | Dev_or_Path n
11217 pr " const char *%s;\n" n
11219 pr " jbyte *%s;\n" n;
11220 pr " size_t %s_size;\n" n
11221 | StringList n | DeviceList n ->
11222 pr " int %s_len;\n" n;
11223 pr " const char **%s;\n" n
11228 pr " int64_t %s;\n" n
11232 (match fst style with
11233 | RStringList _ | RStructList _ -> true
11234 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
11235 | RConstOptString _
11236 | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
11237 List.exists (function
11238 | StringList _ -> true
11239 | DeviceList _ -> true
11240 | _ -> false) (snd style) in
11246 (* Get the parameters. *)
11250 | Device n | Dev_or_Path n
11255 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
11257 (* This is completely undocumented, but Java null becomes
11258 * a NULL parameter.
11260 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
11262 pr " %s = (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n;
11263 pr " %s_size = (*env)->GetArrayLength (env, j%s);\n" n n
11264 | StringList n | DeviceList n ->
11265 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
11266 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
11267 pr " for (i = 0; i < %s_len; ++i) {\n" n;
11268 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11270 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
11272 pr " %s[%s_len] = NULL;\n" n n;
11276 pr " %s = j%s;\n" n n
11279 (* Make the call. *)
11280 pr " r = guestfs_%s " name;
11281 generate_c_call_args ~handle:"g" style;
11284 (* Release the parameters. *)
11288 | Device n | Dev_or_Path n
11293 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11295 pr " if (j%s)\n" n;
11296 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11298 pr " (*env)->ReleaseByteArrayElements (env, j%s, %s, 0);\n" n n
11299 | StringList n | DeviceList n ->
11300 pr " for (i = 0; i < %s_len; ++i) {\n" n;
11301 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11303 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
11305 pr " free (%s);\n" n
11311 (* Check for errors. *)
11312 pr " if (r == %s) {\n" error_code;
11313 pr " throw_exception (env, guestfs_last_error (g));\n";
11314 pr " return %s;\n" no_ret;
11317 (* Return value. *)
11318 (match fst style with
11320 | RInt _ -> pr " return (jint) r;\n"
11321 | RBool _ -> pr " return (jboolean) r;\n"
11322 | RInt64 _ -> pr " return (jlong) r;\n"
11323 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
11324 | RConstOptString _ ->
11325 pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
11327 pr " jr = (*env)->NewStringUTF (env, r);\n";
11331 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
11332 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
11333 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
11334 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
11335 pr " for (i = 0; i < r_len; ++i) {\n";
11336 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
11337 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
11338 pr " free (r[i]);\n";
11342 | RStruct (_, typ) ->
11343 let jtyp = java_name_of_struct typ in
11344 let cols = cols_of_struct typ in
11345 generate_java_struct_return typ jtyp cols
11346 | RStructList (_, typ) ->
11347 let jtyp = java_name_of_struct typ in
11348 let cols = cols_of_struct typ in
11349 generate_java_struct_list_return typ jtyp cols
11352 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
11353 pr " return NULL;\n"
11355 pr " jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
11364 and generate_java_struct_return typ jtyp cols =
11365 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11366 pr " jr = (*env)->AllocObject (env, cl);\n";
11370 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11371 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
11374 pr " char s[33];\n";
11375 pr " memcpy (s, r->%s, 32);\n" name;
11376 pr " s[32] = 0;\n";
11377 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11378 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11382 pr " int len = r->%s_len;\n" name;
11383 pr " char s[len+1];\n";
11384 pr " memcpy (s, r->%s, len);\n" name;
11385 pr " s[len] = 0;\n";
11386 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11387 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11389 | name, (FBytes|FUInt64|FInt64) ->
11390 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11391 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11392 | name, (FUInt32|FInt32) ->
11393 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11394 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11395 | name, FOptPercent ->
11396 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11397 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
11399 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11400 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11405 and generate_java_struct_list_return typ jtyp cols =
11406 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11407 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
11408 pr " for (i = 0; i < r->len; ++i) {\n";
11409 pr " jfl = (*env)->AllocObject (env, cl);\n";
11413 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11414 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
11417 pr " char s[33];\n";
11418 pr " memcpy (s, r->val[i].%s, 32);\n" name;
11419 pr " s[32] = 0;\n";
11420 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11421 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11425 pr " int len = r->val[i].%s_len;\n" name;
11426 pr " char s[len+1];\n";
11427 pr " memcpy (s, r->val[i].%s, len);\n" name;
11428 pr " s[len] = 0;\n";
11429 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11430 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11432 | name, (FBytes|FUInt64|FInt64) ->
11433 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11434 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11435 | name, (FUInt32|FInt32) ->
11436 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11437 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11438 | name, FOptPercent ->
11439 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11440 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
11442 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11443 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11445 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
11447 pr " guestfs_free_%s_list (r);\n" typ;
11450 and generate_java_makefile_inc () =
11451 generate_header HashStyle GPLv2plus;
11453 pr "java_built_sources = \\\n";
11456 pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
11458 pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
11460 and generate_haskell_hs () =
11461 generate_header HaskellStyle LGPLv2plus;
11463 (* XXX We only know how to generate partial FFI for Haskell
11464 * at the moment. Please help out!
11466 let can_generate style =
11470 | RInt64 _, _ -> true
11472 | RConstString _, _
11473 | RConstOptString _, _
11479 | RBufferOut _, _ -> false in
11482 {-# INCLUDE <guestfs.h> #-}
11483 {-# LANGUAGE ForeignFunctionInterface #-}
11488 (* List out the names of the actions we want to export. *)
11490 fun (name, style, _, _, _, _, _) ->
11491 if can_generate style then pr ",\n %s" name
11497 -- Unfortunately some symbols duplicate ones already present
11498 -- in Prelude. We don't know which, so we hard-code a list
11500 import Prelude hiding (truncate)
11504 import Foreign.C.Types
11506 import Control.Exception
11507 import Data.Typeable
11509 data GuestfsS = GuestfsS -- represents the opaque C struct
11510 type GuestfsP = Ptr GuestfsS -- guestfs_h *
11511 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
11513 -- XXX define properly later XXX
11517 data IntBool = IntBool
11519 data StatVFS = StatVFS
11520 data Hashtable = Hashtable
11522 foreign import ccall unsafe \"guestfs_create\" c_create
11524 foreign import ccall unsafe \"&guestfs_close\" c_close
11525 :: FunPtr (GuestfsP -> IO ())
11526 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
11527 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
11529 create :: IO GuestfsH
11532 c_set_error_handler p nullPtr nullPtr
11533 h <- newForeignPtr c_close p
11536 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
11537 :: GuestfsP -> IO CString
11539 -- last_error :: GuestfsH -> IO (Maybe String)
11540 -- last_error h = do
11541 -- str <- withForeignPtr h (\\p -> c_last_error p)
11542 -- maybePeek peekCString str
11544 last_error :: GuestfsH -> IO (String)
11546 str <- withForeignPtr h (\\p -> c_last_error p)
11547 if (str == nullPtr)
11548 then return \"no error\"
11549 else peekCString str
11553 (* Generate wrappers for each foreign function. *)
11555 fun (name, style, _, _, _, _, _) ->
11556 if can_generate style then (
11557 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
11559 generate_haskell_prototype ~handle:"GuestfsP" style;
11563 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
11565 pr "%s %s = do\n" name
11566 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
11568 (* Convert pointer arguments using with* functions. *)
11573 | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
11574 pr "withCString %s $ \\%s -> " n n
11576 pr "withCStringLen %s $ \\(%s, %s_size) -> " n n n
11577 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
11578 | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
11579 | Bool _ | Int _ | Int64 _ -> ()
11581 (* Convert integer arguments. *)
11585 | Bool n -> sprintf "(fromBool %s)" n
11586 | Int n -> sprintf "(fromIntegral %s)" n
11587 | Int64 n -> sprintf "(fromIntegral %s)" n
11588 | FileIn n | FileOut n
11589 | Pathname n | Device n | Dev_or_Path n
11590 | String n | OptString n
11591 | StringList n | DeviceList n
11593 | BufferIn n -> sprintf "%s (fromIntegral %s_size)" n n
11595 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
11596 (String.concat " " ("p" :: args));
11597 (match fst style with
11598 | RErr | RInt _ | RInt64 _ | RBool _ ->
11599 pr " if (r == -1)\n";
11601 pr " err <- last_error h\n";
11603 | RConstString _ | RConstOptString _ | RString _
11604 | RStringList _ | RStruct _
11605 | RStructList _ | RHashtable _ | RBufferOut _ ->
11606 pr " if (r == nullPtr)\n";
11608 pr " err <- last_error h\n";
11611 (match fst style with
11613 pr " else return ()\n"
11615 pr " else return (fromIntegral r)\n"
11617 pr " else return (fromIntegral r)\n"
11619 pr " else return (toBool r)\n"
11621 | RConstOptString _
11628 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
11634 and generate_haskell_prototype ~handle ?(hs = false) style =
11635 pr "%s -> " handle;
11636 let string = if hs then "String" else "CString" in
11637 let int = if hs then "Int" else "CInt" in
11638 let bool = if hs then "Bool" else "CInt" in
11639 let int64 = if hs then "Integer" else "Int64" in
11643 | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _ ->
11646 if hs then pr "String"
11647 else pr "CString -> CInt"
11648 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
11649 | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
11650 | Bool _ -> pr "%s" bool
11651 | Int _ -> pr "%s" int
11652 | Int64 _ -> pr "%s" int
11653 | FileIn _ -> pr "%s" string
11654 | FileOut _ -> pr "%s" string
11659 (match fst style with
11660 | RErr -> if not hs then pr "CInt"
11661 | RInt _ -> pr "%s" int
11662 | RInt64 _ -> pr "%s" int64
11663 | RBool _ -> pr "%s" bool
11664 | RConstString _ -> pr "%s" string
11665 | RConstOptString _ -> pr "Maybe %s" string
11666 | RString _ -> pr "%s" string
11667 | RStringList _ -> pr "[%s]" string
11668 | RStruct (_, typ) ->
11669 let name = java_name_of_struct typ in
11671 | RStructList (_, typ) ->
11672 let name = java_name_of_struct typ in
11674 | RHashtable _ -> pr "Hashtable"
11675 | RBufferOut _ -> pr "%s" string
11679 and generate_csharp () =
11680 generate_header CPlusPlusStyle LGPLv2plus;
11682 (* XXX Make this configurable by the C# assembly users. *)
11683 let library = "libguestfs.so.0" in
11686 // These C# bindings are highly experimental at present.
11688 // Firstly they only work on Linux (ie. Mono). In order to get them
11689 // to work on Windows (ie. .Net) you would need to port the library
11690 // itself to Windows first.
11692 // The second issue is that some calls are known to be incorrect and
11693 // can cause Mono to segfault. Particularly: calls which pass or
11694 // return string[], or return any structure value. This is because
11695 // we haven't worked out the correct way to do this from C#.
11697 // The third issue is that when compiling you get a lot of warnings.
11698 // We are not sure whether the warnings are important or not.
11700 // Fourthly we do not routinely build or test these bindings as part
11701 // of the make && make check cycle, which means that regressions might
11704 // Suggestions and patches are welcome.
11708 // gmcs Libguestfs.cs
11709 // mono Libguestfs.exe
11711 // (You'll probably want to add a Test class / static main function
11712 // otherwise this won't do anything useful).
11716 using System.Runtime.InteropServices;
11717 using System.Runtime.Serialization;
11718 using System.Collections;
11722 class Error : System.ApplicationException
11724 public Error (string message) : base (message) {}
11725 protected Error (SerializationInfo info, StreamingContext context) {}
11732 [DllImport (\"%s\")]
11733 static extern IntPtr guestfs_create ();
11737 _handle = guestfs_create ();
11738 if (_handle == IntPtr.Zero)
11739 throw new Error (\"could not create guestfs handle\");
11742 [DllImport (\"%s\")]
11743 static extern void guestfs_close (IntPtr h);
11747 guestfs_close (_handle);
11750 [DllImport (\"%s\")]
11751 static extern string guestfs_last_error (IntPtr h);
11753 " library library library;
11755 (* Generate C# structure bindings. We prefix struct names with
11756 * underscore because C# cannot have conflicting struct names and
11757 * method names (eg. "class stat" and "stat").
11761 pr " [StructLayout (LayoutKind.Sequential)]\n";
11762 pr " public class _%s {\n" typ;
11765 | name, FChar -> pr " char %s;\n" name
11766 | name, FString -> pr " string %s;\n" name
11768 pr " uint %s_len;\n" name;
11769 pr " string %s;\n" name
11771 pr " [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
11772 pr " string %s;\n" name
11773 | name, FUInt32 -> pr " uint %s;\n" name
11774 | name, FInt32 -> pr " int %s;\n" name
11775 | name, (FUInt64|FBytes) -> pr " ulong %s;\n" name
11776 | name, FInt64 -> pr " long %s;\n" name
11777 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
11783 (* Generate C# function bindings. *)
11785 fun (name, style, _, _, _, shortdesc, _) ->
11786 let rec csharp_return_type () =
11787 match fst style with
11789 | RBool n -> "bool"
11791 | RInt64 n -> "long"
11793 | RConstOptString n
11795 | RBufferOut n -> "string"
11796 | RStruct (_,n) -> "_" ^ n
11797 | RHashtable n -> "Hashtable"
11798 | RStringList n -> "string[]"
11799 | RStructList (_,n) -> sprintf "_%s[]" n
11801 and c_return_type () =
11802 match fst style with
11806 | RInt64 _ -> "long"
11808 | RConstOptString _
11810 | RBufferOut _ -> "string"
11811 | RStruct (_,n) -> "_" ^ n
11813 | RStringList _ -> "string[]"
11814 | RStructList (_,n) -> sprintf "_%s[]" n
11816 and c_error_comparison () =
11817 match fst style with
11821 | RInt64 _ -> "== -1"
11823 | RConstOptString _
11829 | RStructList (_,_) -> "== null"
11831 and generate_extern_prototype () =
11832 pr " static extern %s guestfs_%s (IntPtr h"
11833 (c_return_type ()) name;
11836 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11837 | FileIn n | FileOut n
11840 pr ", [In] string %s" n
11841 | StringList n | DeviceList n ->
11842 pr ", [In] string[] %s" n
11852 and generate_public_prototype () =
11853 pr " public %s %s (" (csharp_return_type ()) name;
11854 let comma = ref false in
11856 if !comma then pr ", ";
11861 | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11862 | FileIn n | FileOut n
11865 next (); pr "string %s" n
11866 | StringList n | DeviceList n ->
11867 next (); pr "string[] %s" n
11869 next (); pr "bool %s" n
11871 next (); pr "int %s" n
11873 next (); pr "long %s" n
11877 and generate_call () =
11878 pr "guestfs_%s (_handle" name;
11879 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
11883 pr " [DllImport (\"%s\")]\n" library;
11884 generate_extern_prototype ();
11886 pr " /// <summary>\n";
11887 pr " /// %s\n" shortdesc;
11888 pr " /// </summary>\n";
11889 generate_public_prototype ();
11891 pr " %s r;\n" (c_return_type ());
11894 pr " if (r %s)\n" (c_error_comparison ());
11895 pr " throw new Error (guestfs_last_error (_handle));\n";
11896 (match fst style with
11899 pr " return r != 0 ? true : false;\n"
11901 pr " Hashtable rr = new Hashtable ();\n";
11902 pr " for (size_t i = 0; i < r.Length; i += 2)\n";
11903 pr " rr.Add (r[i], r[i+1]);\n";
11905 | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
11906 | RString _ | RBufferOut _ | RStruct _ | RStringList _
11912 ) all_functions_sorted;
11918 and generate_bindtests () =
11919 generate_header CStyle LGPLv2plus;
11923 #include <stdlib.h>
11924 #include <inttypes.h>
11925 #include <string.h>
11927 #include \"guestfs.h\"
11928 #include \"guestfs-internal.h\"
11929 #include \"guestfs-internal-actions.h\"
11930 #include \"guestfs_protocol.h\"
11932 #define error guestfs_error
11933 #define safe_calloc guestfs_safe_calloc
11934 #define safe_malloc guestfs_safe_malloc
11937 print_strings (char *const *argv)
11942 for (argc = 0; argv[argc] != NULL; ++argc) {
11943 if (argc > 0) printf (\", \");
11944 printf (\"\\\"%%s\\\"\", argv[argc]);
11949 /* The test0 function prints its parameters to stdout. */
11953 match test_functions with
11954 | [] -> assert false
11955 | test0 :: tests -> test0, tests in
11958 let (name, style, _, _, _, _, _) = test0 in
11959 generate_prototype ~extern:false ~semicolon:false ~newline:true
11960 ~handle:"g" ~prefix:"guestfs__" name style;
11965 | Device n | Dev_or_Path n
11969 | Key n -> pr " printf (\"%%s\\n\", %s);\n" n
11973 pr " for (i = 0; i < %s_size; ++i)\n" n;
11974 pr " printf (\"<%%02x>\", %s[i]);\n" n;
11975 pr " printf (\"\\n\");\n";
11977 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
11978 | StringList n | DeviceList n -> pr " print_strings (%s);\n" n
11979 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
11980 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
11981 | Int64 n -> pr " printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
11983 pr " /* Java changes stdout line buffering so we need this: */\n";
11984 pr " fflush (stdout);\n";
11990 fun (name, style, _, _, _, _, _) ->
11991 if String.sub name (String.length name - 3) 3 <> "err" then (
11992 pr "/* Test normal return. */\n";
11993 generate_prototype ~extern:false ~semicolon:false ~newline:true
11994 ~handle:"g" ~prefix:"guestfs__" name style;
11996 (match fst style with
12001 pr " sscanf (val, \"%%d\", &r);\n";
12004 pr " int64_t r;\n";
12005 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
12008 pr " return STREQ (val, \"true\");\n"
12010 | RConstOptString _ ->
12011 (* Can't return the input string here. Return a static
12012 * string so we ensure we get a segfault if the caller
12013 * tries to free it.
12015 pr " return \"static string\";\n"
12017 pr " return strdup (val);\n"
12019 pr " char **strs;\n";
12021 pr " sscanf (val, \"%%d\", &n);\n";
12022 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
12023 pr " for (i = 0; i < n; ++i) {\n";
12024 pr " strs[i] = safe_malloc (g, 16);\n";
12025 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
12027 pr " strs[n] = NULL;\n";
12028 pr " return strs;\n"
12029 | RStruct (_, typ) ->
12030 pr " struct guestfs_%s *r;\n" typ;
12031 pr " r = safe_calloc (g, sizeof *r, 1);\n";
12033 | RStructList (_, typ) ->
12034 pr " struct guestfs_%s_list *r;\n" typ;
12035 pr " r = safe_calloc (g, sizeof *r, 1);\n";
12036 pr " sscanf (val, \"%%d\", &r->len);\n";
12037 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
12040 pr " char **strs;\n";
12042 pr " sscanf (val, \"%%d\", &n);\n";
12043 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
12044 pr " for (i = 0; i < n; ++i) {\n";
12045 pr " strs[i*2] = safe_malloc (g, 16);\n";
12046 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
12047 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
12048 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
12050 pr " strs[n*2] = NULL;\n";
12051 pr " return strs;\n"
12053 pr " return strdup (val);\n"
12058 pr "/* Test error return. */\n";
12059 generate_prototype ~extern:false ~semicolon:false ~newline:true
12060 ~handle:"g" ~prefix:"guestfs__" name style;
12062 pr " error (g, \"error\");\n";
12063 (match fst style with
12064 | RErr | RInt _ | RInt64 _ | RBool _ ->
12066 | RConstString _ | RConstOptString _
12067 | RString _ | RStringList _ | RStruct _
12071 pr " return NULL;\n"
12078 and generate_ocaml_bindtests () =
12079 generate_header OCamlStyle GPLv2plus;
12083 let g = Guestfs.create () in
12087 String.concat " " (
12090 | CallString s -> "\"" ^ s ^ "\""
12091 | CallOptString None -> "None"
12092 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
12093 | CallStringList xs ->
12094 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
12095 | CallInt i when i >= 0 -> string_of_int i
12096 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
12097 | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
12098 | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
12099 | CallBool b -> string_of_bool b
12100 | CallBuffer s -> sprintf "%S" s
12105 generate_lang_bindtests (
12106 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
12109 pr "print_endline \"EOF\"\n"
12111 and generate_perl_bindtests () =
12112 pr "#!/usr/bin/perl -w\n";
12113 generate_header HashStyle GPLv2plus;
12120 my $g = Sys::Guestfs->new ();
12124 String.concat ", " (
12127 | CallString s -> "\"" ^ s ^ "\""
12128 | CallOptString None -> "undef"
12129 | CallOptString (Some s) -> sprintf "\"%s\"" s
12130 | CallStringList xs ->
12131 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12132 | CallInt i -> string_of_int i
12133 | CallInt64 i -> Int64.to_string i
12134 | CallBool b -> if b then "1" else "0"
12135 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12140 generate_lang_bindtests (
12141 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
12144 pr "print \"EOF\\n\"\n"
12146 and generate_python_bindtests () =
12147 generate_header HashStyle GPLv2plus;
12152 g = guestfs.GuestFS ()
12156 String.concat ", " (
12159 | CallString s -> "\"" ^ s ^ "\""
12160 | CallOptString None -> "None"
12161 | CallOptString (Some s) -> sprintf "\"%s\"" s
12162 | CallStringList xs ->
12163 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12164 | CallInt i -> string_of_int i
12165 | CallInt64 i -> Int64.to_string i
12166 | CallBool b -> if b then "1" else "0"
12167 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12172 generate_lang_bindtests (
12173 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
12176 pr "print \"EOF\"\n"
12178 and generate_ruby_bindtests () =
12179 generate_header HashStyle GPLv2plus;
12184 g = Guestfs::create()
12188 String.concat ", " (
12191 | CallString s -> "\"" ^ s ^ "\""
12192 | CallOptString None -> "nil"
12193 | CallOptString (Some s) -> sprintf "\"%s\"" s
12194 | CallStringList xs ->
12195 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12196 | CallInt i -> string_of_int i
12197 | CallInt64 i -> Int64.to_string i
12198 | CallBool b -> string_of_bool b
12199 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12204 generate_lang_bindtests (
12205 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
12208 pr "print \"EOF\\n\"\n"
12210 and generate_java_bindtests () =
12211 generate_header CStyle GPLv2plus;
12214 import com.redhat.et.libguestfs.*;
12216 public class Bindtests {
12217 public static void main (String[] argv)
12220 GuestFS g = new GuestFS ();
12224 String.concat ", " (
12227 | CallString s -> "\"" ^ s ^ "\""
12228 | CallOptString None -> "null"
12229 | CallOptString (Some s) -> sprintf "\"%s\"" s
12230 | CallStringList xs ->
12232 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
12233 | CallInt i -> string_of_int i
12234 | CallInt64 i -> Int64.to_string i
12235 | CallBool b -> string_of_bool b
12237 "new byte[] { " ^ String.concat "," (
12238 map_chars (fun c -> string_of_int (Char.code c)) s
12244 generate_lang_bindtests (
12245 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
12249 System.out.println (\"EOF\");
12251 catch (Exception exn) {
12252 System.err.println (exn);
12259 and generate_haskell_bindtests () =
12260 generate_header HaskellStyle GPLv2plus;
12263 module Bindtests where
12264 import qualified Guestfs
12267 g <- Guestfs.create
12271 String.concat " " (
12274 | CallString s -> "\"" ^ s ^ "\""
12275 | CallOptString None -> "Nothing"
12276 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
12277 | CallStringList xs ->
12278 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12279 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
12280 | CallInt i -> string_of_int i
12281 | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
12282 | CallInt64 i -> Int64.to_string i
12283 | CallBool true -> "True"
12284 | CallBool false -> "False"
12285 | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12290 generate_lang_bindtests (
12291 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
12294 pr " putStrLn \"EOF\"\n"
12296 (* Language-independent bindings tests - we do it this way to
12297 * ensure there is parity in testing bindings across all languages.
12299 and generate_lang_bindtests call =
12300 call "test0" [CallString "abc"; CallOptString (Some "def");
12301 CallStringList []; CallBool false;
12302 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12303 CallBuffer "abc\000abc"];
12304 call "test0" [CallString "abc"; CallOptString None;
12305 CallStringList []; CallBool false;
12306 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12307 CallBuffer "abc\000abc"];
12308 call "test0" [CallString ""; CallOptString (Some "def");
12309 CallStringList []; CallBool false;
12310 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12311 CallBuffer "abc\000abc"];
12312 call "test0" [CallString ""; CallOptString (Some "");
12313 CallStringList []; CallBool false;
12314 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12315 CallBuffer "abc\000abc"];
12316 call "test0" [CallString "abc"; CallOptString (Some "def");
12317 CallStringList ["1"]; CallBool false;
12318 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12319 CallBuffer "abc\000abc"];
12320 call "test0" [CallString "abc"; CallOptString (Some "def");
12321 CallStringList ["1"; "2"]; CallBool false;
12322 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12323 CallBuffer "abc\000abc"];
12324 call "test0" [CallString "abc"; CallOptString (Some "def");
12325 CallStringList ["1"]; CallBool true;
12326 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12327 CallBuffer "abc\000abc"];
12328 call "test0" [CallString "abc"; CallOptString (Some "def");
12329 CallStringList ["1"]; CallBool false;
12330 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456";
12331 CallBuffer "abc\000abc"];
12332 call "test0" [CallString "abc"; CallOptString (Some "def");
12333 CallStringList ["1"]; CallBool false;
12334 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456";
12335 CallBuffer "abc\000abc"];
12336 call "test0" [CallString "abc"; CallOptString (Some "def");
12337 CallStringList ["1"]; CallBool false;
12338 CallInt 1; CallInt64 1L; CallString "123"; CallString "456";
12339 CallBuffer "abc\000abc"];
12340 call "test0" [CallString "abc"; CallOptString (Some "def");
12341 CallStringList ["1"]; CallBool false;
12342 CallInt 2; CallInt64 2L; CallString "123"; CallString "456";
12343 CallBuffer "abc\000abc"];
12344 call "test0" [CallString "abc"; CallOptString (Some "def");
12345 CallStringList ["1"]; CallBool false;
12346 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456";
12347 CallBuffer "abc\000abc"];
12348 call "test0" [CallString "abc"; CallOptString (Some "def");
12349 CallStringList ["1"]; CallBool false;
12350 CallInt 0; CallInt64 0L; CallString ""; CallString "";
12351 CallBuffer "abc\000abc"]
12353 (* XXX Add here tests of the return and error functions. *)
12355 and generate_max_proc_nr () =
12356 pr "%d\n" max_proc_nr
12358 let output_to filename k =
12359 let filename_new = filename ^ ".new" in
12360 chan := open_out filename_new;
12363 chan := Pervasives.stdout;
12365 (* Is the new file different from the current file? *)
12366 if Sys.file_exists filename && files_equal filename filename_new then
12367 unlink filename_new (* same, so skip it *)
12369 (* different, overwrite old one *)
12370 (try chmod filename 0o644 with Unix_error _ -> ());
12371 rename filename_new filename;
12372 chmod filename 0o444;
12373 printf "written %s\n%!" filename;
12376 let perror msg = function
12377 | Unix_error (err, _, _) ->
12378 eprintf "%s: %s\n" msg (error_message err)
12380 eprintf "%s: %s\n" msg (Printexc.to_string exn)
12382 (* Main program. *)
12385 try openfile "HACKING" [O_RDWR] 0
12387 | Unix_error (ENOENT, _, _) ->
12389 You are probably running this from the wrong directory.
12390 Run it from the top source directory using the command
12395 perror "open: HACKING" exn;
12398 (* Acquire a lock so parallel builds won't try to run the generator
12399 * twice at the same time. Subsequent builds will wait for the first
12400 * one to finish. Note the lock is released implicitly when the
12403 (try lockf lock_fd F_LOCK 1
12405 perror "lock: HACKING" exn;
12408 check_functions ();
12410 output_to "src/guestfs_protocol.x" generate_xdr;
12411 output_to "src/guestfs-structs.h" generate_structs_h;
12412 output_to "src/guestfs-actions.h" generate_actions_h;
12413 output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
12414 output_to "src/actions.c" generate_client_actions;
12415 output_to "src/bindtests.c" generate_bindtests;
12416 output_to "src/guestfs-structs.pod" generate_structs_pod;
12417 output_to "src/guestfs-actions.pod" generate_actions_pod;
12418 output_to "src/guestfs-availability.pod" generate_availability_pod;
12419 output_to "src/MAX_PROC_NR" generate_max_proc_nr;
12420 output_to "src/libguestfs.syms" generate_linker_script;
12421 output_to "daemon/actions.h" generate_daemon_actions_h;
12422 output_to "daemon/stubs.c" generate_daemon_actions;
12423 output_to "daemon/names.c" generate_daemon_names;
12424 output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
12425 output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
12426 output_to "capitests/tests.c" generate_tests;
12427 output_to "fish/cmds.c" generate_fish_cmds;
12428 output_to "fish/completion.c" generate_fish_completion;
12429 output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
12430 output_to "ocaml/guestfs.mli" generate_ocaml_mli;
12431 output_to "ocaml/guestfs.ml" generate_ocaml_ml;
12432 output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
12433 output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
12434 output_to "perl/Guestfs.xs" generate_perl_xs;
12435 output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
12436 output_to "perl/bindtests.pl" generate_perl_bindtests;
12437 output_to "python/guestfs-py.c" generate_python_c;
12438 output_to "python/guestfs.py" generate_python_py;
12439 output_to "python/bindtests.py" generate_python_bindtests;
12440 output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
12441 output_to "ruby/bindtests.rb" generate_ruby_bindtests;
12442 output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
12446 let cols = cols_of_struct typ in
12447 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
12448 output_to filename (generate_java_struct jtyp cols);
12451 output_to "java/Makefile.inc" generate_java_makefile_inc;
12452 output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
12453 output_to "java/Bindtests.java" generate_java_bindtests;
12454 output_to "haskell/Guestfs.hs" generate_haskell_hs;
12455 output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
12456 output_to "csharp/Libguestfs.cs" generate_csharp;
12458 (* Always generate this file last, and unconditionally. It's used
12459 * by the Makefile to know when we must re-run the generator.
12461 let chan = open_out "src/stamp-generator" in
12462 fprintf chan "1\n";
12465 printf "generated %d lines of code\n" !lines