3 * Copyright (C) 2009 Red Hat Inc.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 (* This script generates a large amount of code and documentation for
21 * all the daemon actions.
23 * To add a new action there are only two files you need to change,
24 * this one to describe the interface (see the big table below), and
25 * daemon/<somefile>.c to write the implementation.
27 * After editing this file, run it (./src/generator.ml) to regenerate all the
28 * output files. Note that if you are using a separate build directory you
29 * must run generator.ml from the _source_ directory.
31 * IMPORTANT: This script should NOT print any warnings. If it prints
32 * warnings, you should treat them as errors.
33 * [Need to add -warn-error to ocaml command line]
41 type style = ret * args
43 (* "RErr" as a return value means an int used as a simple error
44 * indication, ie. 0 or -1.
48 (* "RInt" as a return value means an int which is -1 for error
49 * or any value >= 0 on success. Only use this for smallish
50 * positive ints (0 <= i < 2^30).
54 (* "RInt64" is the same as RInt, but is guaranteed to be able
55 * to return a full 64 bit value, _except_ that -1 means error
56 * (so -1 cannot be a valid, non-error return value).
60 (* "RBool" is a bool return value which can be true/false or
65 (* "RConstString" is a string that refers to a constant value.
66 * The return value must NOT be NULL (since NULL indicates
69 * Try to avoid using this. In particular you cannot use this
70 * for values returned from the daemon, because there is no
71 * thread-safe way to return them in the C API.
73 | RConstString of string
75 (* "RConstOptString" is an even more broken version of
76 * "RConstString". The returned string may be NULL and there
77 * is no way to return an error indication. Avoid using this!
79 | RConstOptString of string
81 (* "RString" is a returned string. It must NOT be NULL, since
82 * a NULL return indicates an error. The caller frees this.
86 (* "RStringList" is a list of strings. No string in the list
87 * can be NULL. The caller frees the strings and the array.
89 | RStringList of string
91 (* "RStruct" is a function which returns a single named structure
92 * or an error indication (in C, a struct, and in other languages
93 * with varying representations, but usually very efficient). See
94 * after the function list below for the structures.
96 | RStruct of string * string (* name of retval, name of struct *)
98 (* "RStructList" is a function which returns either a list/array
99 * of structures (could be zero-length), or an error indication.
101 | RStructList of string * string (* name of retval, name of struct *)
103 (* Key-value pairs of untyped strings. Turns into a hashtable or
104 * dictionary in languages which support it. DON'T use this as a
105 * general "bucket" for results. Prefer a stronger typed return
106 * value if one is available, or write a custom struct. Don't use
107 * this if the list could potentially be very long, since it is
108 * inefficient. Keys should be unique. NULLs are not permitted.
110 | RHashtable of string
112 (* "RBufferOut" is handled almost exactly like RString, but
113 * it allows the string to contain arbitrary 8 bit data including
114 * ASCII NUL. In the C API this causes an implicit extra parameter
115 * to be added of type <size_t *size_r>. The extra parameter
116 * returns the actual size of the return buffer in bytes.
118 * Other programming languages support strings with arbitrary 8 bit
121 * At the RPC layer we have to use the opaque<> type instead of
122 * string<>. Returned data is still limited to the max message
125 | RBufferOut of string
127 and args = argt list (* Function parameters, guestfs handle is implicit. *)
129 (* Note in future we should allow a "variable args" parameter as
130 * the final parameter, to allow commands like
131 * chmod mode file [file(s)...]
132 * This is not implemented yet, but many commands (such as chmod)
133 * are currently defined with the argument order keeping this future
134 * possibility in mind.
137 | String of string (* const char *name, cannot be NULL *)
138 | OptString of string (* const char *name, may be NULL *)
139 | StringList of string(* list of strings (each string cannot be NULL) *)
140 | Bool of string (* boolean *)
141 | Int of string (* int (smallish ints, signed, <= 31 bits) *)
142 (* These are treated as filenames (simple string parameters) in
143 * the C API and bindings. But in the RPC protocol, we transfer
144 * the actual file content up to or down from the daemon.
145 * FileIn: local machine -> daemon (in request)
146 * FileOut: daemon -> local machine (in reply)
147 * In guestfish (only), the special name "-" means read from
148 * stdin or write to stdout.
153 (* Opaque buffer which can contain arbitrary 8 bit data.
154 * In the C API, this is expressed as <char *, int> pair.
155 * Most other languages have a string type which can contain
156 * ASCII NUL. We use whatever type is appropriate for each
158 * Buffers are limited by the total message size. To transfer
159 * large blocks of data, use FileIn/FileOut parameters instead.
160 * To return an arbitrary buffer, use RBufferOut.
166 | ProtocolLimitWarning (* display warning about protocol size limits *)
167 | DangerWillRobinson (* flags particularly dangerous commands *)
168 | FishAlias of string (* provide an alias for this cmd in guestfish *)
169 | FishAction of string (* call this function in guestfish *)
170 | NotInFish (* do not export via guestfish *)
171 | NotInDocs (* do not add this function to documentation *)
172 | DeprecatedBy of string (* function is deprecated, use .. instead *)
174 (* You can supply zero or as many tests as you want per API call.
176 * Note that the test environment has 3 block devices, of size 500MB,
177 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
178 * a fourth squashfs block device with some known files on it (/dev/sdd).
180 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
181 * Number of cylinders was 63 for IDE emulated disks with precisely
182 * the same size. How exactly this is calculated is a mystery.
184 * The squashfs block device (/dev/sdd) comes from images/test.sqsh.
186 * To be able to run the tests in a reasonable amount of time,
187 * the virtual machine and block devices are reused between tests.
188 * So don't try testing kill_subprocess :-x
190 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
192 * Don't assume anything about the previous contents of the block
193 * devices. Use 'Init*' to create some initial scenarios.
195 * You can add a prerequisite clause to any individual test. This
196 * is a run-time check, which, if it fails, causes the test to be
197 * skipped. Useful if testing a command which might not work on
198 * all variations of libguestfs builds. A test that has prerequisite
199 * of 'Always' is run unconditionally.
201 * In addition, packagers can skip individual tests by setting the
202 * environment variables: eg:
203 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
204 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
206 type tests = (test_init * test_prereq * test) list
208 (* Run the command sequence and just expect nothing to fail. *)
210 (* Run the command sequence and expect the output of the final
211 * command to be the string.
213 | TestOutput of seq * string
214 (* Run the command sequence and expect the output of the final
215 * command to be the list of strings.
217 | TestOutputList of seq * string list
218 (* Run the command sequence and expect the output of the final
219 * command to be the list of block devices (could be either
220 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
221 * character of each string).
223 | TestOutputListOfDevices of seq * string list
224 (* Run the command sequence and expect the output of the final
225 * command to be the integer.
227 | TestOutputInt of seq * int
228 (* Run the command sequence and expect the output of the final
229 * command to be <op> <int>, eg. ">=", "1".
231 | TestOutputIntOp of seq * string * int
232 (* Run the command sequence and expect the output of the final
233 * command to be a true value (!= 0 or != NULL).
235 | TestOutputTrue of seq
236 (* Run the command sequence and expect the output of the final
237 * command to be a false value (== 0 or == NULL, but not an error).
239 | TestOutputFalse of seq
240 (* Run the command sequence and expect the output of the final
241 * command to be a list of the given length (but don't care about
244 | TestOutputLength of seq * int
245 (* Run the command sequence and expect the output of the final
246 * command to be a buffer (RBufferOut), ie. string + size.
248 | TestOutputBuffer of seq * string
249 (* Run the command sequence and expect the output of the final
250 * command to be a structure.
252 | TestOutputStruct of seq * test_field_compare list
253 (* Run the command sequence and expect the final command (only)
256 | TestLastFail of seq
258 and test_field_compare =
259 | CompareWithInt of string * int
260 | CompareWithIntOp of string * string * int
261 | CompareWithString of string * string
262 | CompareFieldsIntEq of string * string
263 | CompareFieldsStrEq of string * string
265 (* Test prerequisites. *)
267 (* Test always runs. *)
269 (* Test is currently disabled - eg. it fails, or it tests some
270 * unimplemented feature.
273 (* 'string' is some C code (a function body) that should return
274 * true or false. The test will run if the code returns true.
277 (* As for 'If' but the test runs _unless_ the code returns true. *)
280 (* Some initial scenarios for testing. *)
282 (* Do nothing, block devices could contain random stuff including
283 * LVM PVs, and some filesystems might be mounted. This is usually
288 (* Block devices are empty and no filesystems are mounted. *)
291 (* /dev/sda contains a single partition /dev/sda1, which is formatted
292 * as ext2, empty [except for lost+found] and mounted on /.
293 * /dev/sdb and /dev/sdc may have random content.
299 * /dev/sda1 (is a PV):
300 * /dev/VG/LV (size 8MB):
301 * formatted as ext2, empty [except for lost+found], mounted on /
302 * /dev/sdb and /dev/sdc may have random content.
306 (* /dev/sdd (the squashfs, see images/ directory in source)
311 (* Sequence of commands for testing. *)
313 and cmd = string list
315 (* Note about long descriptions: When referring to another
316 * action, use the format C<guestfs_other> (ie. the full name of
317 * the C function). This will be replaced as appropriate in other
320 * Apart from that, long descriptions are just perldoc paragraphs.
323 (* These test functions are used in the language binding tests. *)
325 let test_all_args = [
328 StringList "strlist";
335 let test_all_rets = [
336 (* except for RErr, which is tested thoroughly elsewhere *)
337 "test0rint", RInt "valout";
338 "test0rint64", RInt64 "valout";
339 "test0rbool", RBool "valout";
340 "test0rconststring", RConstString "valout";
341 "test0rconstoptstring", RConstOptString "valout";
342 "test0rstring", RString "valout";
343 "test0rstringlist", RStringList "valout";
344 "test0rstruct", RStruct ("valout", "lvm_pv");
345 "test0rstructlist", RStructList ("valout", "lvm_pv");
346 "test0rhashtable", RHashtable "valout";
349 let test_functions = [
350 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
352 "internal test function - do not use",
354 This is an internal test function which is used to test whether
355 the automatically generated bindings can handle every possible
356 parameter type correctly.
358 It echos the contents of each parameter to stdout.
360 You probably don't want to call this function.");
364 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
366 "internal test function - do not use",
368 This is an internal test function which is used to test whether
369 the automatically generated bindings can handle every possible
370 return type correctly.
372 It converts string C<val> to the return type.
374 You probably don't want to call this function.");
375 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
377 "internal test function - do not use",
379 This is an internal test function which is used to test whether
380 the automatically generated bindings can handle every possible
381 return type correctly.
383 This function always returns an error.
385 You probably don't want to call this function.")]
389 (* non_daemon_functions are any functions which don't get processed
390 * in the daemon, eg. functions for setting and getting local
391 * configuration values.
394 let non_daemon_functions = test_functions @ [
395 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
397 "launch the qemu subprocess",
399 Internally libguestfs is implemented by running a virtual machine
402 You should call this after configuring the handle
403 (eg. adding drives) but before performing any actions.");
405 ("wait_ready", (RErr, []), -1, [NotInFish],
407 "wait until the qemu subprocess launches",
409 Internally libguestfs is implemented by running a virtual machine
412 You should call this after C<guestfs_launch> to wait for the launch
415 ("kill_subprocess", (RErr, []), -1, [],
417 "kill the qemu subprocess",
419 This kills the qemu subprocess. You should never need to call this.");
421 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
423 "add an image to examine or modify",
425 This function adds a virtual machine disk image C<filename> to the
426 guest. The first time you call this function, the disk appears as IDE
427 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
430 You don't necessarily need to be root when using libguestfs. However
431 you obviously do need sufficient permissions to access the filename
432 for whatever operations you want to perform (ie. read access if you
433 just want to read the image or write access if you want to modify the
436 This is equivalent to the qemu parameter
437 C<-drive file=filename,cache=off,if=...>.
439 Note that this call checks for the existence of C<filename>. This
440 stops you from specifying other types of drive which are supported
441 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
442 the general C<guestfs_config> call instead.");
444 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
446 "add a CD-ROM disk image to examine",
448 This function adds a virtual CD-ROM disk image to the guest.
450 This is equivalent to the qemu parameter C<-cdrom filename>.
452 Note that this call checks for the existence of C<filename>. This
453 stops you from specifying other types of drive which are supported
454 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
455 the general C<guestfs_config> call instead.");
457 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
459 "add a drive in snapshot mode (read-only)",
461 This adds a drive in snapshot mode, making it effectively
464 Note that writes to the device are allowed, and will be seen for
465 the duration of the guestfs handle, but they are written
466 to a temporary file which is discarded as soon as the guestfs
467 handle is closed. We don't currently have any method to enable
468 changes to be committed, although qemu can support this.
470 This is equivalent to the qemu parameter
471 C<-drive file=filename,snapshot=on,if=...>.
473 Note that this call checks for the existence of C<filename>. This
474 stops you from specifying other types of drive which are supported
475 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
476 the general C<guestfs_config> call instead.");
478 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
480 "add qemu parameters",
482 This can be used to add arbitrary qemu command line parameters
483 of the form C<-param value>. Actually it's not quite arbitrary - we
484 prevent you from setting some parameters which would interfere with
485 parameters that we use.
487 The first character of C<param> string must be a C<-> (dash).
489 C<value> can be NULL.");
491 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
493 "set the qemu binary",
495 Set the qemu binary that we will use.
497 The default is chosen when the library was compiled by the
500 You can also override this by setting the C<LIBGUESTFS_QEMU>
501 environment variable.
503 Setting C<qemu> to C<NULL> restores the default qemu binary.");
505 ("get_qemu", (RConstString "qemu", []), -1, [],
506 [InitNone, Always, TestRun (
508 "get the qemu binary",
510 Return the current qemu binary.
512 This is always non-NULL. If it wasn't set already, then this will
513 return the default qemu binary name.");
515 ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
517 "set the search path",
519 Set the path that libguestfs searches for kernel and initrd.img.
521 The default is C<$libdir/guestfs> unless overridden by setting
522 C<LIBGUESTFS_PATH> environment variable.
524 Setting C<path> to C<NULL> restores the default path.");
526 ("get_path", (RConstString "path", []), -1, [],
527 [InitNone, Always, TestRun (
529 "get the search path",
531 Return the current search path.
533 This is always non-NULL. If it wasn't set already, then this will
534 return the default path.");
536 ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
538 "add options to kernel command line",
540 This function is used to add additional options to the
541 guest kernel command line.
543 The default is C<NULL> unless overridden by setting
544 C<LIBGUESTFS_APPEND> environment variable.
546 Setting C<append> to C<NULL> means I<no> additional options
547 are passed (libguestfs always adds a few of its own).");
549 ("get_append", (RConstOptString "append", []), -1, [],
550 (* This cannot be tested with the current framework. The
551 * function can return NULL in normal operations, which the
552 * test framework interprets as an error.
555 "get the additional kernel options",
557 Return the additional kernel options which are added to the
558 guest kernel command line.
560 If C<NULL> then no options are added.");
562 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
566 If C<autosync> is true, this enables autosync. Libguestfs will make a
567 best effort attempt to run C<guestfs_umount_all> followed by
568 C<guestfs_sync> when the handle is closed
569 (also if the program exits without closing handles).
571 This is disabled by default (except in guestfish where it is
572 enabled by default).");
574 ("get_autosync", (RBool "autosync", []), -1, [],
575 [InitNone, Always, TestRun (
576 [["get_autosync"]])],
579 Get the autosync flag.");
581 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
585 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
587 Verbose messages are disabled unless the environment variable
588 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
590 ("get_verbose", (RBool "verbose", []), -1, [],
594 This returns the verbose messages flag.");
596 ("is_ready", (RBool "ready", []), -1, [],
597 [InitNone, Always, TestOutputTrue (
599 "is ready to accept commands",
601 This returns true iff this handle is ready to accept commands
602 (in the C<READY> state).
604 For more information on states, see L<guestfs(3)>.");
606 ("is_config", (RBool "config", []), -1, [],
607 [InitNone, Always, TestOutputFalse (
609 "is in configuration state",
611 This returns true iff this handle is being configured
612 (in the C<CONFIG> state).
614 For more information on states, see L<guestfs(3)>.");
616 ("is_launching", (RBool "launching", []), -1, [],
617 [InitNone, Always, TestOutputFalse (
618 [["is_launching"]])],
619 "is launching subprocess",
621 This returns true iff this handle is launching the subprocess
622 (in the C<LAUNCHING> state).
624 For more information on states, see L<guestfs(3)>.");
626 ("is_busy", (RBool "busy", []), -1, [],
627 [InitNone, Always, TestOutputFalse (
629 "is busy processing a command",
631 This returns true iff this handle is busy processing a command
632 (in the C<BUSY> state).
634 For more information on states, see L<guestfs(3)>.");
636 ("get_state", (RInt "state", []), -1, [],
638 "get the current state",
640 This returns the current state as an opaque integer. This is
641 only useful for printing debug and internal error messages.
643 For more information on states, see L<guestfs(3)>.");
645 ("set_busy", (RErr, []), -1, [NotInFish],
649 This sets the state to C<BUSY>. This is only used when implementing
650 actions using the low-level API.
652 For more information on states, see L<guestfs(3)>.");
654 ("set_ready", (RErr, []), -1, [NotInFish],
656 "set state to ready",
658 This sets the state to C<READY>. This is only used when implementing
659 actions using the low-level API.
661 For more information on states, see L<guestfs(3)>.");
663 ("end_busy", (RErr, []), -1, [NotInFish],
665 "leave the busy state",
667 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
668 state as is. This is only used when implementing
669 actions using the low-level API.
671 For more information on states, see L<guestfs(3)>.");
673 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
674 [InitNone, Always, TestOutputInt (
675 [["set_memsize"; "500"];
676 ["get_memsize"]], 500)],
677 "set memory allocated to the qemu subprocess",
679 This sets the memory size in megabytes allocated to the
680 qemu subprocess. This only has any effect if called before
683 You can also change this by setting the environment
684 variable C<LIBGUESTFS_MEMSIZE> before the handle is
687 For more information on the architecture of libguestfs,
688 see L<guestfs(3)>.");
690 ("get_memsize", (RInt "memsize", []), -1, [],
691 [InitNone, Always, TestOutputIntOp (
692 [["get_memsize"]], ">=", 256)],
693 "get memory allocated to the qemu subprocess",
695 This gets the memory size in megabytes allocated to the
698 If C<guestfs_set_memsize> was not called
699 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
700 then this returns the compiled-in default value for memsize.
702 For more information on the architecture of libguestfs,
703 see L<guestfs(3)>.");
705 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
706 [InitNone, Always, TestOutputIntOp (
707 [["get_pid"]], ">=", 1)],
708 "get PID of qemu subprocess",
710 Return the process ID of the qemu subprocess. If there is no
711 qemu subprocess, then this will return an error.
713 This is an internal call used for debugging and testing.");
715 ("version", (RStruct ("version", "version"), []), -1, [],
716 [InitNone, Always, TestOutputStruct (
717 [["version"]], [CompareWithInt ("major", 1)])],
718 "get the library version number",
720 Return the libguestfs version number that the program is linked
723 Note that because of dynamic linking this is not necessarily
724 the version of libguestfs that you compiled against. You can
725 compile the program, and then at runtime dynamically link
726 against a completely different C<libguestfs.so> library.
728 This call was added in version C<1.0.58>. In previous
729 versions of libguestfs there was no way to get the version
730 number. From C code you can use ELF weak linking tricks to find out if
731 this symbol exists (if it doesn't, then it's an earlier version).
733 The call returns a structure with four elements. The first
734 three (C<major>, C<minor> and C<release>) are numbers and
735 correspond to the usual version triplet. The fourth element
736 (C<extra>) is a string and is normally empty, but may be
737 used for distro-specific information.
739 To construct the original version string:
740 C<$major.$minor.$release$extra>
742 I<Note:> Don't use this call to test for availability
743 of features. Distro backports makes this unreliable.");
747 (* daemon_functions are any functions which cause some action
748 * to take place in the daemon.
751 let daemon_functions = [
752 ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
753 [InitEmpty, Always, TestOutput (
754 [["sfdiskM"; "/dev/sda"; ","];
755 ["mkfs"; "ext2"; "/dev/sda1"];
756 ["mount"; "/dev/sda1"; "/"];
757 ["write_file"; "/new"; "new file contents"; "0"];
758 ["cat"; "/new"]], "new file contents")],
759 "mount a guest disk at a position in the filesystem",
761 Mount a guest disk at a position in the filesystem. Block devices
762 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
763 the guest. If those block devices contain partitions, they will have
764 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
767 The rules are the same as for L<mount(2)>: A filesystem must
768 first be mounted on C</> before others can be mounted. Other
769 filesystems can only be mounted on directories which already
772 The mounted filesystem is writable, if we have sufficient permissions
773 on the underlying device.
775 The filesystem options C<sync> and C<noatime> are set with this
776 call, in order to improve reliability.");
778 ("sync", (RErr, []), 2, [],
779 [ InitEmpty, Always, TestRun [["sync"]]],
780 "sync disks, writes are flushed through to the disk image",
782 This syncs the disk, so that any writes are flushed through to the
783 underlying disk image.
785 You should always call this if you have modified a disk image, before
786 closing the handle.");
788 ("touch", (RErr, [String "path"]), 3, [],
789 [InitBasicFS, Always, TestOutputTrue (
791 ["exists"; "/new"]])],
792 "update file timestamps or create a new file",
794 Touch acts like the L<touch(1)> command. It can be used to
795 update the timestamps on a file, or, if the file does not exist,
796 to create a new zero-length file.");
798 ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
799 [InitSquashFS, Always, TestOutput (
800 [["cat"; "/known-2"]], "abcdef\n")],
801 "list the contents of a file",
803 Return the contents of the file named C<path>.
805 Note that this function cannot correctly handle binary files
806 (specifically, files containing C<\\0> character which is treated
807 as end of string). For those you need to use the C<guestfs_read_file>
808 or C<guestfs_download> functions which have a more complex interface.");
810 ("ll", (RString "listing", [String "directory"]), 5, [],
811 [], (* XXX Tricky to test because it depends on the exact format
812 * of the 'ls -l' command, which changes between F10 and F11.
814 "list the files in a directory (long format)",
816 List the files in C<directory> (relative to the root directory,
817 there is no cwd) in the format of 'ls -la'.
819 This command is mostly useful for interactive sessions. It
820 is I<not> intended that you try to parse the output string.");
822 ("ls", (RStringList "listing", [String "directory"]), 6, [],
823 [InitBasicFS, Always, TestOutputList (
826 ["touch"; "/newest"];
827 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
828 "list the files in a directory",
830 List the files in C<directory> (relative to the root directory,
831 there is no cwd). The '.' and '..' entries are not returned, but
832 hidden files are shown.
834 This command is mostly useful for interactive sessions. Programs
835 should probably use C<guestfs_readdir> instead.");
837 ("list_devices", (RStringList "devices", []), 7, [],
838 [InitEmpty, Always, TestOutputListOfDevices (
839 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
840 "list the block devices",
842 List all the block devices.
844 The full block device names are returned, eg. C</dev/sda>");
846 ("list_partitions", (RStringList "partitions", []), 8, [],
847 [InitBasicFS, Always, TestOutputListOfDevices (
848 [["list_partitions"]], ["/dev/sda1"]);
849 InitEmpty, Always, TestOutputListOfDevices (
850 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
851 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
852 "list the partitions",
854 List all the partitions detected on all block devices.
856 The full partition device names are returned, eg. C</dev/sda1>
858 This does not return logical volumes. For that you will need to
859 call C<guestfs_lvs>.");
861 ("pvs", (RStringList "physvols", []), 9, [],
862 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
863 [["pvs"]], ["/dev/sda1"]);
864 InitEmpty, Always, TestOutputListOfDevices (
865 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
866 ["pvcreate"; "/dev/sda1"];
867 ["pvcreate"; "/dev/sda2"];
868 ["pvcreate"; "/dev/sda3"];
869 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
870 "list the LVM physical volumes (PVs)",
872 List all the physical volumes detected. This is the equivalent
873 of the L<pvs(8)> command.
875 This returns a list of just the device names that contain
876 PVs (eg. C</dev/sda2>).
878 See also C<guestfs_pvs_full>.");
880 ("vgs", (RStringList "volgroups", []), 10, [],
881 [InitBasicFSonLVM, Always, TestOutputList (
883 InitEmpty, Always, TestOutputList (
884 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
885 ["pvcreate"; "/dev/sda1"];
886 ["pvcreate"; "/dev/sda2"];
887 ["pvcreate"; "/dev/sda3"];
888 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
889 ["vgcreate"; "VG2"; "/dev/sda3"];
890 ["vgs"]], ["VG1"; "VG2"])],
891 "list the LVM volume groups (VGs)",
893 List all the volumes groups detected. This is the equivalent
894 of the L<vgs(8)> command.
896 This returns a list of just the volume group names that were
897 detected (eg. C<VolGroup00>).
899 See also C<guestfs_vgs_full>.");
901 ("lvs", (RStringList "logvols", []), 11, [],
902 [InitBasicFSonLVM, Always, TestOutputList (
903 [["lvs"]], ["/dev/VG/LV"]);
904 InitEmpty, Always, TestOutputList (
905 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
906 ["pvcreate"; "/dev/sda1"];
907 ["pvcreate"; "/dev/sda2"];
908 ["pvcreate"; "/dev/sda3"];
909 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
910 ["vgcreate"; "VG2"; "/dev/sda3"];
911 ["lvcreate"; "LV1"; "VG1"; "50"];
912 ["lvcreate"; "LV2"; "VG1"; "50"];
913 ["lvcreate"; "LV3"; "VG2"; "50"];
914 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
915 "list the LVM logical volumes (LVs)",
917 List all the logical volumes detected. This is the equivalent
918 of the L<lvs(8)> command.
920 This returns a list of the logical volume device names
921 (eg. C</dev/VolGroup00/LogVol00>).
923 See also C<guestfs_lvs_full>.");
925 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
926 [], (* XXX how to test? *)
927 "list the LVM physical volumes (PVs)",
929 List all the physical volumes detected. This is the equivalent
930 of the L<pvs(8)> command. The \"full\" version includes all fields.");
932 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
933 [], (* XXX how to test? *)
934 "list the LVM volume groups (VGs)",
936 List all the volumes groups detected. This is the equivalent
937 of the L<vgs(8)> command. The \"full\" version includes all fields.");
939 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
940 [], (* XXX how to test? *)
941 "list the LVM logical volumes (LVs)",
943 List all the logical volumes detected. This is the equivalent
944 of the L<lvs(8)> command. The \"full\" version includes all fields.");
946 ("read_lines", (RStringList "lines", [String "path"]), 15, [],
947 [InitSquashFS, Always, TestOutputList (
948 [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
949 InitSquashFS, Always, TestOutputList (
950 [["read_lines"; "/empty"]], [])],
951 "read file as lines",
953 Return the contents of the file named C<path>.
955 The file contents are returned as a list of lines. Trailing
956 C<LF> and C<CRLF> character sequences are I<not> returned.
958 Note that this function cannot correctly handle binary files
959 (specifically, files containing C<\\0> character which is treated
960 as end of line). For those you need to use the C<guestfs_read_file>
961 function which has a more complex interface.");
963 ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
964 [], (* XXX Augeas code needs tests. *)
965 "create a new Augeas handle",
967 Create a new Augeas handle for editing configuration files.
968 If there was any previous Augeas handle associated with this
969 guestfs session, then it is closed.
971 You must call this before using any other C<guestfs_aug_*>
974 C<root> is the filesystem root. C<root> must not be NULL,
977 The flags are the same as the flags defined in
978 E<lt>augeas.hE<gt>, the logical I<or> of the following
983 =item C<AUG_SAVE_BACKUP> = 1
985 Keep the original file with a C<.augsave> extension.
987 =item C<AUG_SAVE_NEWFILE> = 2
989 Save changes into a file with extension C<.augnew>, and
990 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
992 =item C<AUG_TYPE_CHECK> = 4
994 Typecheck lenses (can be expensive).
996 =item C<AUG_NO_STDINC> = 8
998 Do not use standard load path for modules.
1000 =item C<AUG_SAVE_NOOP> = 16
1002 Make save a no-op, just record what would have been changed.
1004 =item C<AUG_NO_LOAD> = 32
1006 Do not load the tree in C<guestfs_aug_init>.
1010 To close the handle, you can call C<guestfs_aug_close>.
1012 To find out more about Augeas, see L<http://augeas.net/>.");
1014 ("aug_close", (RErr, []), 26, [],
1015 [], (* XXX Augeas code needs tests. *)
1016 "close the current Augeas handle",
1018 Close the current Augeas handle and free up any resources
1019 used by it. After calling this, you have to call
1020 C<guestfs_aug_init> again before you can use any other
1021 Augeas functions.");
1023 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
1024 [], (* XXX Augeas code needs tests. *)
1025 "define an Augeas variable",
1027 Defines an Augeas variable C<name> whose value is the result
1028 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
1031 On success this returns the number of nodes in C<expr>, or
1032 C<0> if C<expr> evaluates to something which is not a nodeset.");
1034 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
1035 [], (* XXX Augeas code needs tests. *)
1036 "define an Augeas node",
1038 Defines a variable C<name> whose value is the result of
1041 If C<expr> evaluates to an empty nodeset, a node is created,
1042 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1043 C<name> will be the nodeset containing that single node.
1045 On success this returns a pair containing the
1046 number of nodes in the nodeset, and a boolean flag
1047 if a node was created.");
1049 ("aug_get", (RString "val", [String "path"]), 19, [],
1050 [], (* XXX Augeas code needs tests. *)
1051 "look up the value of an Augeas path",
1053 Look up the value associated with C<path>. If C<path>
1054 matches exactly one node, the C<value> is returned.");
1056 ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
1057 [], (* XXX Augeas code needs tests. *)
1058 "set Augeas path to value",
1060 Set the value associated with C<path> to C<value>.");
1062 ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
1063 [], (* XXX Augeas code needs tests. *)
1064 "insert a sibling Augeas node",
1066 Create a new sibling C<label> for C<path>, inserting it into
1067 the tree before or after C<path> (depending on the boolean
1070 C<path> must match exactly one existing node in the tree, and
1071 C<label> must be a label, ie. not contain C</>, C<*> or end
1072 with a bracketed index C<[N]>.");
1074 ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
1075 [], (* XXX Augeas code needs tests. *)
1076 "remove an Augeas path",
1078 Remove C<path> and all of its children.
1080 On success this returns the number of entries which were removed.");
1082 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
1083 [], (* XXX Augeas code needs tests. *)
1086 Move the node C<src> to C<dest>. C<src> must match exactly
1087 one node. C<dest> is overwritten if it exists.");
1089 ("aug_match", (RStringList "matches", [String "path"]), 24, [],
1090 [], (* XXX Augeas code needs tests. *)
1091 "return Augeas nodes which match path",
1093 Returns a list of paths which match the path expression C<path>.
1094 The returned paths are sufficiently qualified so that they match
1095 exactly one node in the current tree.");
1097 ("aug_save", (RErr, []), 25, [],
1098 [], (* XXX Augeas code needs tests. *)
1099 "write all pending Augeas changes to disk",
1101 This writes all pending changes to disk.
1103 The flags which were passed to C<guestfs_aug_init> affect exactly
1104 how files are saved.");
1106 ("aug_load", (RErr, []), 27, [],
1107 [], (* XXX Augeas code needs tests. *)
1108 "load files into the tree",
1110 Load files into the tree.
1112 See C<aug_load> in the Augeas documentation for the full gory
1115 ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
1116 [], (* XXX Augeas code needs tests. *)
1117 "list Augeas nodes under a path",
1119 This is just a shortcut for listing C<guestfs_aug_match>
1120 C<path/*> and sorting the resulting nodes into alphabetical order.");
1122 ("rm", (RErr, [String "path"]), 29, [],
1123 [InitBasicFS, Always, TestRun
1126 InitBasicFS, Always, TestLastFail
1128 InitBasicFS, Always, TestLastFail
1133 Remove the single file C<path>.");
1135 ("rmdir", (RErr, [String "path"]), 30, [],
1136 [InitBasicFS, Always, TestRun
1139 InitBasicFS, Always, TestLastFail
1140 [["rmdir"; "/new"]];
1141 InitBasicFS, Always, TestLastFail
1143 ["rmdir"; "/new"]]],
1144 "remove a directory",
1146 Remove the single directory C<path>.");
1148 ("rm_rf", (RErr, [String "path"]), 31, [],
1149 [InitBasicFS, Always, TestOutputFalse
1151 ["mkdir"; "/new/foo"];
1152 ["touch"; "/new/foo/bar"];
1154 ["exists"; "/new"]]],
1155 "remove a file or directory recursively",
1157 Remove the file or directory C<path>, recursively removing the
1158 contents if its a directory. This is like the C<rm -rf> shell
1161 ("mkdir", (RErr, [String "path"]), 32, [],
1162 [InitBasicFS, Always, TestOutputTrue
1164 ["is_dir"; "/new"]];
1165 InitBasicFS, Always, TestLastFail
1166 [["mkdir"; "/new/foo/bar"]]],
1167 "create a directory",
1169 Create a directory named C<path>.");
1171 ("mkdir_p", (RErr, [String "path"]), 33, [],
1172 [InitBasicFS, Always, TestOutputTrue
1173 [["mkdir_p"; "/new/foo/bar"];
1174 ["is_dir"; "/new/foo/bar"]];
1175 InitBasicFS, Always, TestOutputTrue
1176 [["mkdir_p"; "/new/foo/bar"];
1177 ["is_dir"; "/new/foo"]];
1178 InitBasicFS, Always, TestOutputTrue
1179 [["mkdir_p"; "/new/foo/bar"];
1180 ["is_dir"; "/new"]];
1181 (* Regression tests for RHBZ#503133: *)
1182 InitBasicFS, Always, TestRun
1184 ["mkdir_p"; "/new"]];
1185 InitBasicFS, Always, TestLastFail
1187 ["mkdir_p"; "/new"]]],
1188 "create a directory and parents",
1190 Create a directory named C<path>, creating any parent directories
1191 as necessary. This is like the C<mkdir -p> shell command.");
1193 ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1194 [], (* XXX Need stat command to test *)
1197 Change the mode (permissions) of C<path> to C<mode>. Only
1198 numeric modes are supported.");
1200 ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1201 [], (* XXX Need stat command to test *)
1202 "change file owner and group",
1204 Change the file owner to C<owner> and group to C<group>.
1206 Only numeric uid and gid are supported. If you want to use
1207 names, you will need to locate and parse the password file
1208 yourself (Augeas support makes this relatively easy).");
1210 ("exists", (RBool "existsflag", [String "path"]), 36, [],
1211 [InitSquashFS, Always, TestOutputTrue (
1212 [["exists"; "/empty"]]);
1213 InitSquashFS, Always, TestOutputTrue (
1214 [["exists"; "/directory"]])],
1215 "test if file or directory exists",
1217 This returns C<true> if and only if there is a file, directory
1218 (or anything) with the given C<path> name.
1220 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1222 ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1223 [InitSquashFS, Always, TestOutputTrue (
1224 [["is_file"; "/known-1"]]);
1225 InitSquashFS, Always, TestOutputFalse (
1226 [["is_file"; "/directory"]])],
1227 "test if file exists",
1229 This returns C<true> if and only if there is a file
1230 with the given C<path> name. Note that it returns false for
1231 other objects like directories.
1233 See also C<guestfs_stat>.");
1235 ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1236 [InitSquashFS, Always, TestOutputFalse (
1237 [["is_dir"; "/known-3"]]);
1238 InitSquashFS, Always, TestOutputTrue (
1239 [["is_dir"; "/directory"]])],
1240 "test if file exists",
1242 This returns C<true> if and only if there is a directory
1243 with the given C<path> name. Note that it returns false for
1244 other objects like files.
1246 See also C<guestfs_stat>.");
1248 ("pvcreate", (RErr, [String "device"]), 39, [],
1249 [InitEmpty, Always, TestOutputListOfDevices (
1250 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1251 ["pvcreate"; "/dev/sda1"];
1252 ["pvcreate"; "/dev/sda2"];
1253 ["pvcreate"; "/dev/sda3"];
1254 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1255 "create an LVM physical volume",
1257 This creates an LVM physical volume on the named C<device>,
1258 where C<device> should usually be a partition name such
1261 ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1262 [InitEmpty, Always, TestOutputList (
1263 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1264 ["pvcreate"; "/dev/sda1"];
1265 ["pvcreate"; "/dev/sda2"];
1266 ["pvcreate"; "/dev/sda3"];
1267 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1268 ["vgcreate"; "VG2"; "/dev/sda3"];
1269 ["vgs"]], ["VG1"; "VG2"])],
1270 "create an LVM volume group",
1272 This creates an LVM volume group called C<volgroup>
1273 from the non-empty list of physical volumes C<physvols>.");
1275 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1276 [InitEmpty, Always, TestOutputList (
1277 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1278 ["pvcreate"; "/dev/sda1"];
1279 ["pvcreate"; "/dev/sda2"];
1280 ["pvcreate"; "/dev/sda3"];
1281 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1282 ["vgcreate"; "VG2"; "/dev/sda3"];
1283 ["lvcreate"; "LV1"; "VG1"; "50"];
1284 ["lvcreate"; "LV2"; "VG1"; "50"];
1285 ["lvcreate"; "LV3"; "VG2"; "50"];
1286 ["lvcreate"; "LV4"; "VG2"; "50"];
1287 ["lvcreate"; "LV5"; "VG2"; "50"];
1289 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1290 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1291 "create an LVM volume group",
1293 This creates an LVM volume group called C<logvol>
1294 on the volume group C<volgroup>, with C<size> megabytes.");
1296 ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1297 [InitEmpty, Always, TestOutput (
1298 [["sfdiskM"; "/dev/sda"; ","];
1299 ["mkfs"; "ext2"; "/dev/sda1"];
1300 ["mount"; "/dev/sda1"; "/"];
1301 ["write_file"; "/new"; "new file contents"; "0"];
1302 ["cat"; "/new"]], "new file contents")],
1303 "make a filesystem",
1305 This creates a filesystem on C<device> (usually a partition
1306 or LVM logical volume). The filesystem type is C<fstype>, for
1309 ("sfdisk", (RErr, [String "device";
1310 Int "cyls"; Int "heads"; Int "sectors";
1311 StringList "lines"]), 43, [DangerWillRobinson],
1313 "create partitions on a block device",
1315 This is a direct interface to the L<sfdisk(8)> program for creating
1316 partitions on block devices.
1318 C<device> should be a block device, for example C</dev/sda>.
1320 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1321 and sectors on the device, which are passed directly to sfdisk as
1322 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1323 of these, then the corresponding parameter is omitted. Usually for
1324 'large' disks, you can just pass C<0> for these, but for small
1325 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1326 out the right geometry and you will need to tell it.
1328 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1329 information refer to the L<sfdisk(8)> manpage.
1331 To create a single partition occupying the whole disk, you would
1332 pass C<lines> as a single element list, when the single element being
1333 the string C<,> (comma).
1335 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1337 ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1338 [InitBasicFS, Always, TestOutput (
1339 [["write_file"; "/new"; "new file contents"; "0"];
1340 ["cat"; "/new"]], "new file contents");
1341 InitBasicFS, Always, TestOutput (
1342 [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1343 ["cat"; "/new"]], "\nnew file contents\n");
1344 InitBasicFS, Always, TestOutput (
1345 [["write_file"; "/new"; "\n\n"; "0"];
1346 ["cat"; "/new"]], "\n\n");
1347 InitBasicFS, Always, TestOutput (
1348 [["write_file"; "/new"; ""; "0"];
1349 ["cat"; "/new"]], "");
1350 InitBasicFS, Always, TestOutput (
1351 [["write_file"; "/new"; "\n\n\n"; "0"];
1352 ["cat"; "/new"]], "\n\n\n");
1353 InitBasicFS, Always, TestOutput (
1354 [["write_file"; "/new"; "\n"; "0"];
1355 ["cat"; "/new"]], "\n")],
1358 This call creates a file called C<path>. The contents of the
1359 file is the string C<content> (which can contain any 8 bit data),
1360 with length C<size>.
1362 As a special case, if C<size> is C<0>
1363 then the length is calculated using C<strlen> (so in this case
1364 the content cannot contain embedded ASCII NULs).
1366 I<NB.> Owing to a bug, writing content containing ASCII NUL
1367 characters does I<not> work, even if the length is specified.
1368 We hope to resolve this bug in a future version. In the meantime
1369 use C<guestfs_upload>.");
1371 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1372 [InitEmpty, Always, TestOutputListOfDevices (
1373 [["sfdiskM"; "/dev/sda"; ","];
1374 ["mkfs"; "ext2"; "/dev/sda1"];
1375 ["mount"; "/dev/sda1"; "/"];
1376 ["mounts"]], ["/dev/sda1"]);
1377 InitEmpty, Always, TestOutputList (
1378 [["sfdiskM"; "/dev/sda"; ","];
1379 ["mkfs"; "ext2"; "/dev/sda1"];
1380 ["mount"; "/dev/sda1"; "/"];
1383 "unmount a filesystem",
1385 This unmounts the given filesystem. The filesystem may be
1386 specified either by its mountpoint (path) or the device which
1387 contains the filesystem.");
1389 ("mounts", (RStringList "devices", []), 46, [],
1390 [InitBasicFS, Always, TestOutputListOfDevices (
1391 [["mounts"]], ["/dev/sda1"])],
1392 "show mounted filesystems",
1394 This returns the list of currently mounted filesystems. It returns
1395 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1397 Some internal mounts are not shown.
1399 See also: C<guestfs_mountpoints>");
1401 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1402 [InitBasicFS, Always, TestOutputList (
1405 (* check that umount_all can unmount nested mounts correctly: *)
1406 InitEmpty, Always, TestOutputList (
1407 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1408 ["mkfs"; "ext2"; "/dev/sda1"];
1409 ["mkfs"; "ext2"; "/dev/sda2"];
1410 ["mkfs"; "ext2"; "/dev/sda3"];
1411 ["mount"; "/dev/sda1"; "/"];
1413 ["mount"; "/dev/sda2"; "/mp1"];
1414 ["mkdir"; "/mp1/mp2"];
1415 ["mount"; "/dev/sda3"; "/mp1/mp2"];
1416 ["mkdir"; "/mp1/mp2/mp3"];
1419 "unmount all filesystems",
1421 This unmounts all mounted filesystems.
1423 Some internal mounts are not unmounted by this call.");
1425 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1427 "remove all LVM LVs, VGs and PVs",
1429 This command removes all LVM logical volumes, volume groups
1430 and physical volumes.");
1432 ("file", (RString "description", [String "path"]), 49, [],
1433 [InitSquashFS, Always, TestOutput (
1434 [["file"; "/empty"]], "empty");
1435 InitSquashFS, Always, TestOutput (
1436 [["file"; "/known-1"]], "ASCII text");
1437 InitSquashFS, Always, TestLastFail (
1438 [["file"; "/notexists"]])],
1439 "determine file type",
1441 This call uses the standard L<file(1)> command to determine
1442 the type or contents of the file. This also works on devices,
1443 for example to find out whether a partition contains a filesystem.
1445 This call will also transparently look inside various types
1448 The exact command which runs is C<file -zbsL path>. Note in
1449 particular that the filename is not prepended to the output
1450 (the C<-b> option).");
1452 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1453 [InitBasicFS, Always, TestOutput (
1454 [["upload"; "test-command"; "/test-command"];
1455 ["chmod"; "0o755"; "/test-command"];
1456 ["command"; "/test-command 1"]], "Result1");
1457 InitBasicFS, Always, TestOutput (
1458 [["upload"; "test-command"; "/test-command"];
1459 ["chmod"; "0o755"; "/test-command"];
1460 ["command"; "/test-command 2"]], "Result2\n");
1461 InitBasicFS, Always, TestOutput (
1462 [["upload"; "test-command"; "/test-command"];
1463 ["chmod"; "0o755"; "/test-command"];
1464 ["command"; "/test-command 3"]], "\nResult3");
1465 InitBasicFS, Always, TestOutput (
1466 [["upload"; "test-command"; "/test-command"];
1467 ["chmod"; "0o755"; "/test-command"];
1468 ["command"; "/test-command 4"]], "\nResult4\n");
1469 InitBasicFS, Always, TestOutput (
1470 [["upload"; "test-command"; "/test-command"];
1471 ["chmod"; "0o755"; "/test-command"];
1472 ["command"; "/test-command 5"]], "\nResult5\n\n");
1473 InitBasicFS, Always, TestOutput (
1474 [["upload"; "test-command"; "/test-command"];
1475 ["chmod"; "0o755"; "/test-command"];
1476 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1477 InitBasicFS, Always, TestOutput (
1478 [["upload"; "test-command"; "/test-command"];
1479 ["chmod"; "0o755"; "/test-command"];
1480 ["command"; "/test-command 7"]], "");
1481 InitBasicFS, Always, TestOutput (
1482 [["upload"; "test-command"; "/test-command"];
1483 ["chmod"; "0o755"; "/test-command"];
1484 ["command"; "/test-command 8"]], "\n");
1485 InitBasicFS, Always, TestOutput (
1486 [["upload"; "test-command"; "/test-command"];
1487 ["chmod"; "0o755"; "/test-command"];
1488 ["command"; "/test-command 9"]], "\n\n");
1489 InitBasicFS, Always, TestOutput (
1490 [["upload"; "test-command"; "/test-command"];
1491 ["chmod"; "0o755"; "/test-command"];
1492 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1493 InitBasicFS, Always, TestOutput (
1494 [["upload"; "test-command"; "/test-command"];
1495 ["chmod"; "0o755"; "/test-command"];
1496 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1497 InitBasicFS, Always, TestLastFail (
1498 [["upload"; "test-command"; "/test-command"];
1499 ["chmod"; "0o755"; "/test-command"];
1500 ["command"; "/test-command"]])],
1501 "run a command from the guest filesystem",
1503 This call runs a command from the guest filesystem. The
1504 filesystem must be mounted, and must contain a compatible
1505 operating system (ie. something Linux, with the same
1506 or compatible processor architecture).
1508 The single parameter is an argv-style list of arguments.
1509 The first element is the name of the program to run.
1510 Subsequent elements are parameters. The list must be
1511 non-empty (ie. must contain a program name). Note that
1512 the command runs directly, and is I<not> invoked via
1513 the shell (see C<guestfs_sh>).
1515 The return value is anything printed to I<stdout> by
1518 If the command returns a non-zero exit status, then
1519 this function returns an error message. The error message
1520 string is the content of I<stderr> from the command.
1522 The C<$PATH> environment variable will contain at least
1523 C</usr/bin> and C</bin>. If you require a program from
1524 another location, you should provide the full path in the
1527 Shared libraries and data files required by the program
1528 must be available on filesystems which are mounted in the
1529 correct places. It is the caller's responsibility to ensure
1530 all filesystems that are needed are mounted at the right
1533 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1534 [InitBasicFS, Always, TestOutputList (
1535 [["upload"; "test-command"; "/test-command"];
1536 ["chmod"; "0o755"; "/test-command"];
1537 ["command_lines"; "/test-command 1"]], ["Result1"]);
1538 InitBasicFS, Always, TestOutputList (
1539 [["upload"; "test-command"; "/test-command"];
1540 ["chmod"; "0o755"; "/test-command"];
1541 ["command_lines"; "/test-command 2"]], ["Result2"]);
1542 InitBasicFS, Always, TestOutputList (
1543 [["upload"; "test-command"; "/test-command"];
1544 ["chmod"; "0o755"; "/test-command"];
1545 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1546 InitBasicFS, Always, TestOutputList (
1547 [["upload"; "test-command"; "/test-command"];
1548 ["chmod"; "0o755"; "/test-command"];
1549 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1550 InitBasicFS, Always, TestOutputList (
1551 [["upload"; "test-command"; "/test-command"];
1552 ["chmod"; "0o755"; "/test-command"];
1553 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1554 InitBasicFS, Always, TestOutputList (
1555 [["upload"; "test-command"; "/test-command"];
1556 ["chmod"; "0o755"; "/test-command"];
1557 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1558 InitBasicFS, Always, TestOutputList (
1559 [["upload"; "test-command"; "/test-command"];
1560 ["chmod"; "0o755"; "/test-command"];
1561 ["command_lines"; "/test-command 7"]], []);
1562 InitBasicFS, Always, TestOutputList (
1563 [["upload"; "test-command"; "/test-command"];
1564 ["chmod"; "0o755"; "/test-command"];
1565 ["command_lines"; "/test-command 8"]], [""]);
1566 InitBasicFS, Always, TestOutputList (
1567 [["upload"; "test-command"; "/test-command"];
1568 ["chmod"; "0o755"; "/test-command"];
1569 ["command_lines"; "/test-command 9"]], ["";""]);
1570 InitBasicFS, Always, TestOutputList (
1571 [["upload"; "test-command"; "/test-command"];
1572 ["chmod"; "0o755"; "/test-command"];
1573 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1574 InitBasicFS, Always, TestOutputList (
1575 [["upload"; "test-command"; "/test-command"];
1576 ["chmod"; "0o755"; "/test-command"];
1577 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1578 "run a command, returning lines",
1580 This is the same as C<guestfs_command>, but splits the
1581 result into a list of lines.
1583 See also: C<guestfs_sh_lines>");
1585 ("stat", (RStruct ("statbuf", "stat"), [String "path"]), 52, [],
1586 [InitSquashFS, Always, TestOutputStruct (
1587 [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
1588 "get file information",
1590 Returns file information for the given C<path>.
1592 This is the same as the C<stat(2)> system call.");
1594 ("lstat", (RStruct ("statbuf", "stat"), [String "path"]), 53, [],
1595 [InitSquashFS, Always, TestOutputStruct (
1596 [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
1597 "get file information for a symbolic link",
1599 Returns file information for the given C<path>.
1601 This is the same as C<guestfs_stat> except that if C<path>
1602 is a symbolic link, then the link is stat-ed, not the file it
1605 This is the same as the C<lstat(2)> system call.");
1607 ("statvfs", (RStruct ("statbuf", "statvfs"), [String "path"]), 54, [],
1608 [InitSquashFS, Always, TestOutputStruct (
1609 [["statvfs"; "/"]], [CompareWithInt ("namemax", 256);
1610 CompareWithInt ("bsize", 131072)])],
1611 "get file system statistics",
1613 Returns file system statistics for any mounted file system.
1614 C<path> should be a file or directory in the mounted file system
1615 (typically it is the mount point itself, but it doesn't need to be).
1617 This is the same as the C<statvfs(2)> system call.");
1619 ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1621 "get ext2/ext3/ext4 superblock details",
1623 This returns the contents of the ext2, ext3 or ext4 filesystem
1624 superblock on C<device>.
1626 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
1627 manpage for more details. The list of fields returned isn't
1628 clearly defined, and depends on both the version of C<tune2fs>
1629 that libguestfs was built against, and the filesystem itself.");
1631 ("blockdev_setro", (RErr, [String "device"]), 56, [],
1632 [InitEmpty, Always, TestOutputTrue (
1633 [["blockdev_setro"; "/dev/sda"];
1634 ["blockdev_getro"; "/dev/sda"]])],
1635 "set block device to read-only",
1637 Sets the block device named C<device> to read-only.
1639 This uses the L<blockdev(8)> command.");
1641 ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1642 [InitEmpty, Always, TestOutputFalse (
1643 [["blockdev_setrw"; "/dev/sda"];
1644 ["blockdev_getro"; "/dev/sda"]])],
1645 "set block device to read-write",
1647 Sets the block device named C<device> to read-write.
1649 This uses the L<blockdev(8)> command.");
1651 ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1652 [InitEmpty, Always, TestOutputTrue (
1653 [["blockdev_setro"; "/dev/sda"];
1654 ["blockdev_getro"; "/dev/sda"]])],
1655 "is block device set to read-only",
1657 Returns a boolean indicating if the block device is read-only
1658 (true if read-only, false if not).
1660 This uses the L<blockdev(8)> command.");
1662 ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1663 [InitEmpty, Always, TestOutputInt (
1664 [["blockdev_getss"; "/dev/sda"]], 512)],
1665 "get sectorsize of block device",
1667 This returns the size of sectors on a block device.
1668 Usually 512, but can be larger for modern devices.
1670 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1673 This uses the L<blockdev(8)> command.");
1675 ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1676 [InitEmpty, Always, TestOutputInt (
1677 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1678 "get blocksize of block device",
1680 This returns the block size of a device.
1682 (Note this is different from both I<size in blocks> and
1683 I<filesystem block size>).
1685 This uses the L<blockdev(8)> command.");
1687 ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1689 "set blocksize of block device",
1691 This sets the block size of a device.
1693 (Note this is different from both I<size in blocks> and
1694 I<filesystem block size>).
1696 This uses the L<blockdev(8)> command.");
1698 ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1699 [InitEmpty, Always, TestOutputInt (
1700 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1701 "get total size of device in 512-byte sectors",
1703 This returns the size of the device in units of 512-byte sectors
1704 (even if the sectorsize isn't 512 bytes ... weird).
1706 See also C<guestfs_blockdev_getss> for the real sector size of
1707 the device, and C<guestfs_blockdev_getsize64> for the more
1708 useful I<size in bytes>.
1710 This uses the L<blockdev(8)> command.");
1712 ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1713 [InitEmpty, Always, TestOutputInt (
1714 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1715 "get total size of device in bytes",
1717 This returns the size of the device in bytes.
1719 See also C<guestfs_blockdev_getsz>.
1721 This uses the L<blockdev(8)> command.");
1723 ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1724 [InitEmpty, Always, TestRun
1725 [["blockdev_flushbufs"; "/dev/sda"]]],
1726 "flush device buffers",
1728 This tells the kernel to flush internal buffers associated
1731 This uses the L<blockdev(8)> command.");
1733 ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1734 [InitEmpty, Always, TestRun
1735 [["blockdev_rereadpt"; "/dev/sda"]]],
1736 "reread partition table",
1738 Reread the partition table on C<device>.
1740 This uses the L<blockdev(8)> command.");
1742 ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1743 [InitBasicFS, Always, TestOutput (
1744 (* Pick a file from cwd which isn't likely to change. *)
1745 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1746 ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1747 "upload a file from the local machine",
1749 Upload local file C<filename> to C<remotefilename> on the
1752 C<filename> can also be a named pipe.
1754 See also C<guestfs_download>.");
1756 ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1757 [InitBasicFS, Always, TestOutput (
1758 (* Pick a file from cwd which isn't likely to change. *)
1759 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1760 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1761 ["upload"; "testdownload.tmp"; "/upload"];
1762 ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1763 "download a file to the local machine",
1765 Download file C<remotefilename> and save it as C<filename>
1766 on the local machine.
1768 C<filename> can also be a named pipe.
1770 See also C<guestfs_upload>, C<guestfs_cat>.");
1772 ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1773 [InitSquashFS, Always, TestOutput (
1774 [["checksum"; "crc"; "/known-3"]], "2891671662");
1775 InitSquashFS, Always, TestLastFail (
1776 [["checksum"; "crc"; "/notexists"]]);
1777 InitSquashFS, Always, TestOutput (
1778 [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
1779 InitSquashFS, Always, TestOutput (
1780 [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
1781 InitSquashFS, Always, TestOutput (
1782 [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
1783 InitSquashFS, Always, TestOutput (
1784 [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
1785 InitSquashFS, Always, TestOutput (
1786 [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
1787 InitSquashFS, Always, TestOutput (
1788 [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6")],
1789 "compute MD5, SHAx or CRC checksum of file",
1791 This call computes the MD5, SHAx or CRC checksum of the
1794 The type of checksum to compute is given by the C<csumtype>
1795 parameter which must have one of the following values:
1801 Compute the cyclic redundancy check (CRC) specified by POSIX
1802 for the C<cksum> command.
1806 Compute the MD5 hash (using the C<md5sum> program).
1810 Compute the SHA1 hash (using the C<sha1sum> program).
1814 Compute the SHA224 hash (using the C<sha224sum> program).
1818 Compute the SHA256 hash (using the C<sha256sum> program).
1822 Compute the SHA384 hash (using the C<sha384sum> program).
1826 Compute the SHA512 hash (using the C<sha512sum> program).
1830 The checksum is returned as a printable string.");
1832 ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1833 [InitBasicFS, Always, TestOutput (
1834 [["tar_in"; "../images/helloworld.tar"; "/"];
1835 ["cat"; "/hello"]], "hello\n")],
1836 "unpack tarfile to directory",
1838 This command uploads and unpacks local file C<tarfile> (an
1839 I<uncompressed> tar file) into C<directory>.
1841 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1843 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1845 "pack directory into tarfile",
1847 This command packs the contents of C<directory> and downloads
1848 it to local file C<tarfile>.
1850 To download a compressed tarball, use C<guestfs_tgz_out>.");
1852 ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1853 [InitBasicFS, Always, TestOutput (
1854 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1855 ["cat"; "/hello"]], "hello\n")],
1856 "unpack compressed tarball to directory",
1858 This command uploads and unpacks local file C<tarball> (a
1859 I<gzip compressed> tar file) into C<directory>.
1861 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1863 ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1865 "pack directory into compressed tarball",
1867 This command packs the contents of C<directory> and downloads
1868 it to local file C<tarball>.
1870 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1872 ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1873 [InitBasicFS, Always, TestLastFail (
1875 ["mount_ro"; "/dev/sda1"; "/"];
1876 ["touch"; "/new"]]);
1877 InitBasicFS, Always, TestOutput (
1878 [["write_file"; "/new"; "data"; "0"];
1880 ["mount_ro"; "/dev/sda1"; "/"];
1881 ["cat"; "/new"]], "data")],
1882 "mount a guest disk, read-only",
1884 This is the same as the C<guestfs_mount> command, but it
1885 mounts the filesystem with the read-only (I<-o ro>) flag.");
1887 ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1889 "mount a guest disk with mount options",
1891 This is the same as the C<guestfs_mount> command, but it
1892 allows you to set the mount options as for the
1893 L<mount(8)> I<-o> flag.");
1895 ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1897 "mount a guest disk with mount options and vfstype",
1899 This is the same as the C<guestfs_mount> command, but it
1900 allows you to set both the mount options and the vfstype
1901 as for the L<mount(8)> I<-o> and I<-t> flags.");
1903 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1905 "debugging and internals",
1907 The C<guestfs_debug> command exposes some internals of
1908 C<guestfsd> (the guestfs daemon) that runs inside the
1911 There is no comprehensive help for this command. You have
1912 to look at the file C<daemon/debug.c> in the libguestfs source
1913 to find out what you can do.");
1915 ("lvremove", (RErr, [String "device"]), 77, [],
1916 [InitEmpty, Always, TestOutputList (
1917 [["sfdiskM"; "/dev/sda"; ","];
1918 ["pvcreate"; "/dev/sda1"];
1919 ["vgcreate"; "VG"; "/dev/sda1"];
1920 ["lvcreate"; "LV1"; "VG"; "50"];
1921 ["lvcreate"; "LV2"; "VG"; "50"];
1922 ["lvremove"; "/dev/VG/LV1"];
1923 ["lvs"]], ["/dev/VG/LV2"]);
1924 InitEmpty, Always, TestOutputList (
1925 [["sfdiskM"; "/dev/sda"; ","];
1926 ["pvcreate"; "/dev/sda1"];
1927 ["vgcreate"; "VG"; "/dev/sda1"];
1928 ["lvcreate"; "LV1"; "VG"; "50"];
1929 ["lvcreate"; "LV2"; "VG"; "50"];
1930 ["lvremove"; "/dev/VG"];
1932 InitEmpty, Always, TestOutputList (
1933 [["sfdiskM"; "/dev/sda"; ","];
1934 ["pvcreate"; "/dev/sda1"];
1935 ["vgcreate"; "VG"; "/dev/sda1"];
1936 ["lvcreate"; "LV1"; "VG"; "50"];
1937 ["lvcreate"; "LV2"; "VG"; "50"];
1938 ["lvremove"; "/dev/VG"];
1940 "remove an LVM logical volume",
1942 Remove an LVM logical volume C<device>, where C<device> is
1943 the path to the LV, such as C</dev/VG/LV>.
1945 You can also remove all LVs in a volume group by specifying
1946 the VG name, C</dev/VG>.");
1948 ("vgremove", (RErr, [String "vgname"]), 78, [],
1949 [InitEmpty, Always, TestOutputList (
1950 [["sfdiskM"; "/dev/sda"; ","];
1951 ["pvcreate"; "/dev/sda1"];
1952 ["vgcreate"; "VG"; "/dev/sda1"];
1953 ["lvcreate"; "LV1"; "VG"; "50"];
1954 ["lvcreate"; "LV2"; "VG"; "50"];
1957 InitEmpty, Always, TestOutputList (
1958 [["sfdiskM"; "/dev/sda"; ","];
1959 ["pvcreate"; "/dev/sda1"];
1960 ["vgcreate"; "VG"; "/dev/sda1"];
1961 ["lvcreate"; "LV1"; "VG"; "50"];
1962 ["lvcreate"; "LV2"; "VG"; "50"];
1965 "remove an LVM volume group",
1967 Remove an LVM volume group C<vgname>, (for example C<VG>).
1969 This also forcibly removes all logical volumes in the volume
1972 ("pvremove", (RErr, [String "device"]), 79, [],
1973 [InitEmpty, Always, TestOutputListOfDevices (
1974 [["sfdiskM"; "/dev/sda"; ","];
1975 ["pvcreate"; "/dev/sda1"];
1976 ["vgcreate"; "VG"; "/dev/sda1"];
1977 ["lvcreate"; "LV1"; "VG"; "50"];
1978 ["lvcreate"; "LV2"; "VG"; "50"];
1980 ["pvremove"; "/dev/sda1"];
1982 InitEmpty, Always, TestOutputListOfDevices (
1983 [["sfdiskM"; "/dev/sda"; ","];
1984 ["pvcreate"; "/dev/sda1"];
1985 ["vgcreate"; "VG"; "/dev/sda1"];
1986 ["lvcreate"; "LV1"; "VG"; "50"];
1987 ["lvcreate"; "LV2"; "VG"; "50"];
1989 ["pvremove"; "/dev/sda1"];
1991 InitEmpty, Always, TestOutputListOfDevices (
1992 [["sfdiskM"; "/dev/sda"; ","];
1993 ["pvcreate"; "/dev/sda1"];
1994 ["vgcreate"; "VG"; "/dev/sda1"];
1995 ["lvcreate"; "LV1"; "VG"; "50"];
1996 ["lvcreate"; "LV2"; "VG"; "50"];
1998 ["pvremove"; "/dev/sda1"];
2000 "remove an LVM physical volume",
2002 This wipes a physical volume C<device> so that LVM will no longer
2005 The implementation uses the C<pvremove> command which refuses to
2006 wipe physical volumes that contain any volume groups, so you have
2007 to remove those first.");
2009 ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
2010 [InitBasicFS, Always, TestOutput (
2011 [["set_e2label"; "/dev/sda1"; "testlabel"];
2012 ["get_e2label"; "/dev/sda1"]], "testlabel")],
2013 "set the ext2/3/4 filesystem label",
2015 This sets the ext2/3/4 filesystem label of the filesystem on
2016 C<device> to C<label>. Filesystem labels are limited to
2019 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2020 to return the existing label on a filesystem.");
2022 ("get_e2label", (RString "label", [String "device"]), 81, [],
2024 "get the ext2/3/4 filesystem label",
2026 This returns the ext2/3/4 filesystem label of the filesystem on
2029 ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
2030 [InitBasicFS, Always, TestOutput (
2031 [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
2032 ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
2033 InitBasicFS, Always, TestOutput (
2034 [["set_e2uuid"; "/dev/sda1"; "clear"];
2035 ["get_e2uuid"; "/dev/sda1"]], "");
2036 (* We can't predict what UUIDs will be, so just check the commands run. *)
2037 InitBasicFS, Always, TestRun (
2038 [["set_e2uuid"; "/dev/sda1"; "random"]]);
2039 InitBasicFS, Always, TestRun (
2040 [["set_e2uuid"; "/dev/sda1"; "time"]])],
2041 "set the ext2/3/4 filesystem UUID",
2043 This sets the ext2/3/4 filesystem UUID of the filesystem on
2044 C<device> to C<uuid>. The format of the UUID and alternatives
2045 such as C<clear>, C<random> and C<time> are described in the
2046 L<tune2fs(8)> manpage.
2048 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2049 to return the existing UUID of a filesystem.");
2051 ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
2053 "get the ext2/3/4 filesystem UUID",
2055 This returns the ext2/3/4 filesystem UUID of the filesystem on
2058 ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
2059 [InitBasicFS, Always, TestOutputInt (
2060 [["umount"; "/dev/sda1"];
2061 ["fsck"; "ext2"; "/dev/sda1"]], 0);
2062 InitBasicFS, Always, TestOutputInt (
2063 [["umount"; "/dev/sda1"];
2064 ["zero"; "/dev/sda1"];
2065 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2066 "run the filesystem checker",
2068 This runs the filesystem checker (fsck) on C<device> which
2069 should have filesystem type C<fstype>.
2071 The returned integer is the status. See L<fsck(8)> for the
2072 list of status codes from C<fsck>.
2080 Multiple status codes can be summed together.
2084 A non-zero return code can mean \"success\", for example if
2085 errors have been corrected on the filesystem.
2089 Checking or repairing NTFS volumes is not supported
2094 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2096 ("zero", (RErr, [String "device"]), 85, [],
2097 [InitBasicFS, Always, TestOutput (
2098 [["umount"; "/dev/sda1"];
2099 ["zero"; "/dev/sda1"];
2100 ["file"; "/dev/sda1"]], "data")],
2101 "write zeroes to the device",
2103 This command writes zeroes over the first few blocks of C<device>.
2105 How many blocks are zeroed isn't specified (but it's I<not> enough
2106 to securely wipe the device). It should be sufficient to remove
2107 any partition tables, filesystem superblocks and so on.
2109 See also: C<guestfs_scrub_device>.");
2111 ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
2112 (* Test disabled because grub-install incompatible with virtio-blk driver.
2113 * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2115 [InitBasicFS, Disabled, TestOutputTrue (
2116 [["grub_install"; "/"; "/dev/sda1"];
2117 ["is_dir"; "/boot"]])],
2120 This command installs GRUB (the Grand Unified Bootloader) on
2121 C<device>, with the root directory being C<root>.");
2123 ("cp", (RErr, [String "src"; String "dest"]), 87, [],
2124 [InitBasicFS, Always, TestOutput (
2125 [["write_file"; "/old"; "file content"; "0"];
2126 ["cp"; "/old"; "/new"];
2127 ["cat"; "/new"]], "file content");
2128 InitBasicFS, Always, TestOutputTrue (
2129 [["write_file"; "/old"; "file content"; "0"];
2130 ["cp"; "/old"; "/new"];
2131 ["is_file"; "/old"]]);
2132 InitBasicFS, Always, TestOutput (
2133 [["write_file"; "/old"; "file content"; "0"];
2135 ["cp"; "/old"; "/dir/new"];
2136 ["cat"; "/dir/new"]], "file content")],
2139 This copies a file from C<src> to C<dest> where C<dest> is
2140 either a destination filename or destination directory.");
2142 ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
2143 [InitBasicFS, Always, TestOutput (
2144 [["mkdir"; "/olddir"];
2145 ["mkdir"; "/newdir"];
2146 ["write_file"; "/olddir/file"; "file content"; "0"];
2147 ["cp_a"; "/olddir"; "/newdir"];
2148 ["cat"; "/newdir/olddir/file"]], "file content")],
2149 "copy a file or directory recursively",
2151 This copies a file or directory from C<src> to C<dest>
2152 recursively using the C<cp -a> command.");
2154 ("mv", (RErr, [String "src"; String "dest"]), 89, [],
2155 [InitBasicFS, Always, TestOutput (
2156 [["write_file"; "/old"; "file content"; "0"];
2157 ["mv"; "/old"; "/new"];
2158 ["cat"; "/new"]], "file content");
2159 InitBasicFS, Always, TestOutputFalse (
2160 [["write_file"; "/old"; "file content"; "0"];
2161 ["mv"; "/old"; "/new"];
2162 ["is_file"; "/old"]])],
2165 This moves a file from C<src> to C<dest> where C<dest> is
2166 either a destination filename or destination directory.");
2168 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2169 [InitEmpty, Always, TestRun (
2170 [["drop_caches"; "3"]])],
2171 "drop kernel page cache, dentries and inodes",
2173 This instructs the guest kernel to drop its page cache,
2174 and/or dentries and inode caches. The parameter C<whattodrop>
2175 tells the kernel what precisely to drop, see
2176 L<http://linux-mm.org/Drop_Caches>
2178 Setting C<whattodrop> to 3 should drop everything.
2180 This automatically calls L<sync(2)> before the operation,
2181 so that the maximum guest memory is freed.");
2183 ("dmesg", (RString "kmsgs", []), 91, [],
2184 [InitEmpty, Always, TestRun (
2186 "return kernel messages",
2188 This returns the kernel messages (C<dmesg> output) from
2189 the guest kernel. This is sometimes useful for extended
2190 debugging of problems.
2192 Another way to get the same information is to enable
2193 verbose messages with C<guestfs_set_verbose> or by setting
2194 the environment variable C<LIBGUESTFS_DEBUG=1> before
2195 running the program.");
2197 ("ping_daemon", (RErr, []), 92, [],
2198 [InitEmpty, Always, TestRun (
2199 [["ping_daemon"]])],
2200 "ping the guest daemon",
2202 This is a test probe into the guestfs daemon running inside
2203 the qemu subprocess. Calling this function checks that the
2204 daemon responds to the ping message, without affecting the daemon
2205 or attached block device(s) in any other way.");
2207 ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2208 [InitBasicFS, Always, TestOutputTrue (
2209 [["write_file"; "/file1"; "contents of a file"; "0"];
2210 ["cp"; "/file1"; "/file2"];
2211 ["equal"; "/file1"; "/file2"]]);
2212 InitBasicFS, Always, TestOutputFalse (
2213 [["write_file"; "/file1"; "contents of a file"; "0"];
2214 ["write_file"; "/file2"; "contents of another file"; "0"];
2215 ["equal"; "/file1"; "/file2"]]);
2216 InitBasicFS, Always, TestLastFail (
2217 [["equal"; "/file1"; "/file2"]])],
2218 "test if two files have equal contents",
2220 This compares the two files C<file1> and C<file2> and returns
2221 true if their content is exactly equal, or false otherwise.
2223 The external L<cmp(1)> program is used for the comparison.");
2225 ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2226 [InitSquashFS, Always, TestOutputList (
2227 [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2228 InitSquashFS, Always, TestOutputList (
2229 [["strings"; "/empty"]], [])],
2230 "print the printable strings in a file",
2232 This runs the L<strings(1)> command on a file and returns
2233 the list of printable strings found.");
2235 ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2236 [InitSquashFS, Always, TestOutputList (
2237 [["strings_e"; "b"; "/known-5"]], []);
2238 InitBasicFS, Disabled, TestOutputList (
2239 [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2240 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2241 "print the printable strings in a file",
2243 This is like the C<guestfs_strings> command, but allows you to
2244 specify the encoding.
2246 See the L<strings(1)> manpage for the full list of encodings.
2248 Commonly useful encodings are C<l> (lower case L) which will
2249 show strings inside Windows/x86 files.
2251 The returned strings are transcoded to UTF-8.");
2253 ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2254 [InitSquashFS, Always, TestOutput (
2255 [["hexdump"; "/known-4"]], "00000000 61 62 63 0a 64 65 66 0a 67 68 69 |abc.def.ghi|\n0000000b\n");
2256 (* Test for RHBZ#501888c2 regression which caused large hexdump
2257 * commands to segfault.
2259 InitSquashFS, Always, TestRun (
2260 [["hexdump"; "/100krandom"]])],
2261 "dump a file in hexadecimal",
2263 This runs C<hexdump -C> on the given C<path>. The result is
2264 the human-readable, canonical hex dump of the file.");
2266 ("zerofree", (RErr, [String "device"]), 97, [],
2267 [InitNone, Always, TestOutput (
2268 [["sfdiskM"; "/dev/sda"; ","];
2269 ["mkfs"; "ext3"; "/dev/sda1"];
2270 ["mount"; "/dev/sda1"; "/"];
2271 ["write_file"; "/new"; "test file"; "0"];
2272 ["umount"; "/dev/sda1"];
2273 ["zerofree"; "/dev/sda1"];
2274 ["mount"; "/dev/sda1"; "/"];
2275 ["cat"; "/new"]], "test file")],
2276 "zero unused inodes and disk blocks on ext2/3 filesystem",
2278 This runs the I<zerofree> program on C<device>. This program
2279 claims to zero unused inodes and disk blocks on an ext2/3
2280 filesystem, thus making it possible to compress the filesystem
2283 You should B<not> run this program if the filesystem is
2286 It is possible that using this program can damage the filesystem
2287 or data on the filesystem.");
2289 ("pvresize", (RErr, [String "device"]), 98, [],
2291 "resize an LVM physical volume",
2293 This resizes (expands or shrinks) an existing LVM physical
2294 volume to match the new size of the underlying device.");
2296 ("sfdisk_N", (RErr, [String "device"; Int "partnum";
2297 Int "cyls"; Int "heads"; Int "sectors";
2298 String "line"]), 99, [DangerWillRobinson],
2300 "modify a single partition on a block device",
2302 This runs L<sfdisk(8)> option to modify just the single
2303 partition C<n> (note: C<n> counts from 1).
2305 For other parameters, see C<guestfs_sfdisk>. You should usually
2306 pass C<0> for the cyls/heads/sectors parameters.");
2308 ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2310 "display the partition table",
2312 This displays the partition table on C<device>, in the
2313 human-readable output of the L<sfdisk(8)> command. It is
2314 not intended to be parsed.");
2316 ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2318 "display the kernel geometry",
2320 This displays the kernel's idea of the geometry of C<device>.
2322 The result is in human-readable format, and not designed to
2325 ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2327 "display the disk geometry from the partition table",
2329 This displays the disk geometry of C<device> read from the
2330 partition table. Especially in the case where the underlying
2331 block device has been resized, this can be different from the
2332 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2334 The result is in human-readable format, and not designed to
2337 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2339 "activate or deactivate all volume groups",
2341 This command activates or (if C<activate> is false) deactivates
2342 all logical volumes in all volume groups.
2343 If activated, then they are made known to the
2344 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2345 then those devices disappear.
2347 This command is the same as running C<vgchange -a y|n>");
2349 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2351 "activate or deactivate some volume groups",
2353 This command activates or (if C<activate> is false) deactivates
2354 all logical volumes in the listed volume groups C<volgroups>.
2355 If activated, then they are made known to the
2356 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2357 then those devices disappear.
2359 This command is the same as running C<vgchange -a y|n volgroups...>
2361 Note that if C<volgroups> is an empty list then B<all> volume groups
2362 are activated or deactivated.");
2364 ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2365 [InitNone, Always, TestOutput (
2366 [["sfdiskM"; "/dev/sda"; ","];
2367 ["pvcreate"; "/dev/sda1"];
2368 ["vgcreate"; "VG"; "/dev/sda1"];
2369 ["lvcreate"; "LV"; "VG"; "10"];
2370 ["mkfs"; "ext2"; "/dev/VG/LV"];
2371 ["mount"; "/dev/VG/LV"; "/"];
2372 ["write_file"; "/new"; "test content"; "0"];
2374 ["lvresize"; "/dev/VG/LV"; "20"];
2375 ["e2fsck_f"; "/dev/VG/LV"];
2376 ["resize2fs"; "/dev/VG/LV"];
2377 ["mount"; "/dev/VG/LV"; "/"];
2378 ["cat"; "/new"]], "test content")],
2379 "resize an LVM logical volume",
2381 This resizes (expands or shrinks) an existing LVM logical
2382 volume to C<mbytes>. When reducing, data in the reduced part
2385 ("resize2fs", (RErr, [String "device"]), 106, [],
2386 [], (* lvresize tests this *)
2387 "resize an ext2/ext3 filesystem",
2389 This resizes an ext2 or ext3 filesystem to match the size of
2390 the underlying device.
2392 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2393 on the C<device> before calling this command. For unknown reasons
2394 C<resize2fs> sometimes gives an error about this and sometimes not.
2395 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2396 calling this function.");
2398 ("find", (RStringList "names", [String "directory"]), 107, [],
2399 [InitBasicFS, Always, TestOutputList (
2400 [["find"; "/"]], ["lost+found"]);
2401 InitBasicFS, Always, TestOutputList (
2405 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2406 InitBasicFS, Always, TestOutputList (
2407 [["mkdir_p"; "/a/b/c"];
2408 ["touch"; "/a/b/c/d"];
2409 ["find"; "/a/b/"]], ["c"; "c/d"])],
2410 "find all files and directories",
2412 This command lists out all files and directories, recursively,
2413 starting at C<directory>. It is essentially equivalent to
2414 running the shell command C<find directory -print> but some
2415 post-processing happens on the output, described below.
2417 This returns a list of strings I<without any prefix>. Thus
2418 if the directory structure was:
2424 then the returned list from C<guestfs_find> C</tmp> would be
2432 If C<directory> is not a directory, then this command returns
2435 The returned list is sorted.");
2437 ("e2fsck_f", (RErr, [String "device"]), 108, [],
2438 [], (* lvresize tests this *)
2439 "check an ext2/ext3 filesystem",
2441 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2442 filesystem checker on C<device>, noninteractively (C<-p>),
2443 even if the filesystem appears to be clean (C<-f>).
2445 This command is only needed because of C<guestfs_resize2fs>
2446 (q.v.). Normally you should use C<guestfs_fsck>.");
2448 ("sleep", (RErr, [Int "secs"]), 109, [],
2449 [InitNone, Always, TestRun (
2451 "sleep for some seconds",
2453 Sleep for C<secs> seconds.");
2455 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; String "device"]), 110, [],
2456 [InitNone, Always, TestOutputInt (
2457 [["sfdiskM"; "/dev/sda"; ","];
2458 ["mkfs"; "ntfs"; "/dev/sda1"];
2459 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2460 InitNone, Always, TestOutputInt (
2461 [["sfdiskM"; "/dev/sda"; ","];
2462 ["mkfs"; "ext2"; "/dev/sda1"];
2463 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2464 "probe NTFS volume",
2466 This command runs the L<ntfs-3g.probe(8)> command which probes
2467 an NTFS C<device> for mountability. (Not all NTFS volumes can
2468 be mounted read-write, and some cannot be mounted at all).
2470 C<rw> is a boolean flag. Set it to true if you want to test
2471 if the volume can be mounted read-write. Set it to false if
2472 you want to test if the volume can be mounted read-only.
2474 The return value is an integer which C<0> if the operation
2475 would succeed, or some non-zero value documented in the
2476 L<ntfs-3g.probe(8)> manual page.");
2478 ("sh", (RString "output", [String "command"]), 111, [],
2479 [], (* XXX needs tests *)
2480 "run a command via the shell",
2482 This call runs a command from the guest filesystem via the
2485 This is like C<guestfs_command>, but passes the command to:
2487 /bin/sh -c \"command\"
2489 Depending on the guest's shell, this usually results in
2490 wildcards being expanded, shell expressions being interpolated
2493 All the provisos about C<guestfs_command> apply to this call.");
2495 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2496 [], (* XXX needs tests *)
2497 "run a command via the shell returning lines",
2499 This is the same as C<guestfs_sh>, but splits the result
2500 into a list of lines.
2502 See also: C<guestfs_command_lines>");
2504 ("glob_expand", (RStringList "paths", [String "pattern"]), 113, [],
2505 [InitBasicFS, Always, TestOutputList (
2506 [["mkdir_p"; "/a/b/c"];
2507 ["touch"; "/a/b/c/d"];
2508 ["touch"; "/a/b/c/e"];
2509 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2510 InitBasicFS, Always, TestOutputList (
2511 [["mkdir_p"; "/a/b/c"];
2512 ["touch"; "/a/b/c/d"];
2513 ["touch"; "/a/b/c/e"];
2514 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2515 InitBasicFS, Always, TestOutputList (
2516 [["mkdir_p"; "/a/b/c"];
2517 ["touch"; "/a/b/c/d"];
2518 ["touch"; "/a/b/c/e"];
2519 ["glob_expand"; "/a/*/x/*"]], [])],
2520 "expand a wildcard path",
2522 This command searches for all the pathnames matching
2523 C<pattern> according to the wildcard expansion rules
2526 If no paths match, then this returns an empty list
2527 (note: not an error).
2529 It is just a wrapper around the C L<glob(3)> function
2530 with flags C<GLOB_MARK|GLOB_BRACE>.
2531 See that manual page for more details.");
2533 ("scrub_device", (RErr, [String "device"]), 114, [DangerWillRobinson],
2534 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2535 [["scrub_device"; "/dev/sdc"]])],
2536 "scrub (securely wipe) a device",
2538 This command writes patterns over C<device> to make data retrieval
2541 It is an interface to the L<scrub(1)> program. See that
2542 manual page for more details.");
2544 ("scrub_file", (RErr, [String "file"]), 115, [],
2545 [InitBasicFS, Always, TestRun (
2546 [["write_file"; "/file"; "content"; "0"];
2547 ["scrub_file"; "/file"]])],
2548 "scrub (securely wipe) a file",
2550 This command writes patterns over a file to make data retrieval
2553 The file is I<removed> after scrubbing.
2555 It is an interface to the L<scrub(1)> program. See that
2556 manual page for more details.");
2558 ("scrub_freespace", (RErr, [String "dir"]), 116, [],
2559 [], (* XXX needs testing *)
2560 "scrub (securely wipe) free space",
2562 This command creates the directory C<dir> and then fills it
2563 with files until the filesystem is full, and scrubs the files
2564 as for C<guestfs_scrub_file>, and deletes them.
2565 The intention is to scrub any free space on the partition
2568 It is an interface to the L<scrub(1)> program. See that
2569 manual page for more details.");
2571 ("mkdtemp", (RString "dir", [String "template"]), 117, [],
2572 [InitBasicFS, Always, TestRun (
2574 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2575 "create a temporary directory",
2577 This command creates a temporary directory. The
2578 C<template> parameter should be a full pathname for the
2579 temporary directory name with the final six characters being
2582 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2583 the second one being suitable for Windows filesystems.
2585 The name of the temporary directory that was created
2588 The temporary directory is created with mode 0700
2589 and is owned by root.
2591 The caller is responsible for deleting the temporary
2592 directory and its contents after use.
2594 See also: L<mkdtemp(3)>");
2596 ("wc_l", (RInt "lines", [String "path"]), 118, [],
2597 [InitSquashFS, Always, TestOutputInt (
2598 [["wc_l"; "/10klines"]], 10000)],
2599 "count lines in a file",
2601 This command counts the lines in a file, using the
2602 C<wc -l> external command.");
2604 ("wc_w", (RInt "words", [String "path"]), 119, [],
2605 [InitSquashFS, Always, TestOutputInt (
2606 [["wc_w"; "/10klines"]], 10000)],
2607 "count words in a file",
2609 This command counts the words in a file, using the
2610 C<wc -w> external command.");
2612 ("wc_c", (RInt "chars", [String "path"]), 120, [],
2613 [InitSquashFS, Always, TestOutputInt (
2614 [["wc_c"; "/100kallspaces"]], 102400)],
2615 "count characters in a file",
2617 This command counts the characters in a file, using the
2618 C<wc -c> external command.");
2620 ("head", (RStringList "lines", [String "path"]), 121, [ProtocolLimitWarning],
2621 [InitSquashFS, Always, TestOutputList (
2622 [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2623 "return first 10 lines of a file",
2625 This command returns up to the first 10 lines of a file as
2626 a list of strings.");
2628 ("head_n", (RStringList "lines", [Int "nrlines"; String "path"]), 122, [ProtocolLimitWarning],
2629 [InitSquashFS, Always, TestOutputList (
2630 [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2631 InitSquashFS, Always, TestOutputList (
2632 [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2633 InitSquashFS, Always, TestOutputList (
2634 [["head_n"; "0"; "/10klines"]], [])],
2635 "return first N lines of a file",
2637 If the parameter C<nrlines> is a positive number, this returns the first
2638 C<nrlines> lines of the file C<path>.
2640 If the parameter C<nrlines> is a negative number, this returns lines
2641 from the file C<path>, excluding the last C<nrlines> lines.
2643 If the parameter C<nrlines> is zero, this returns an empty list.");
2645 ("tail", (RStringList "lines", [String "path"]), 123, [ProtocolLimitWarning],
2646 [InitSquashFS, Always, TestOutputList (
2647 [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2648 "return last 10 lines of a file",
2650 This command returns up to the last 10 lines of a file as
2651 a list of strings.");
2653 ("tail_n", (RStringList "lines", [Int "nrlines"; String "path"]), 124, [ProtocolLimitWarning],
2654 [InitSquashFS, Always, TestOutputList (
2655 [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2656 InitSquashFS, Always, TestOutputList (
2657 [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2658 InitSquashFS, Always, TestOutputList (
2659 [["tail_n"; "0"; "/10klines"]], [])],
2660 "return last N lines of a file",
2662 If the parameter C<nrlines> is a positive number, this returns the last
2663 C<nrlines> lines of the file C<path>.
2665 If the parameter C<nrlines> is a negative number, this returns lines
2666 from the file C<path>, starting with the C<-nrlines>th line.
2668 If the parameter C<nrlines> is zero, this returns an empty list.");
2670 ("df", (RString "output", []), 125, [],
2671 [], (* XXX Tricky to test because it depends on the exact format
2672 * of the 'df' command and other imponderables.
2674 "report file system disk space usage",
2676 This command runs the C<df> command to report disk space used.
2678 This command is mostly useful for interactive sessions. It
2679 is I<not> intended that you try to parse the output string.
2680 Use C<statvfs> from programs.");
2682 ("df_h", (RString "output", []), 126, [],
2683 [], (* XXX Tricky to test because it depends on the exact format
2684 * of the 'df' command and other imponderables.
2686 "report file system disk space usage (human readable)",
2688 This command runs the C<df -h> command to report disk space used
2689 in human-readable format.
2691 This command is mostly useful for interactive sessions. It
2692 is I<not> intended that you try to parse the output string.
2693 Use C<statvfs> from programs.");
2695 ("du", (RInt64 "sizekb", [String "path"]), 127, [],
2696 [InitSquashFS, Always, TestOutputInt (
2697 [["du"; "/directory"]], 0 (* squashfs doesn't have blocks *))],
2698 "estimate file space usage",
2700 This command runs the C<du -s> command to estimate file space
2703 C<path> can be a file or a directory. If C<path> is a directory
2704 then the estimate includes the contents of the directory and all
2705 subdirectories (recursively).
2707 The result is the estimated size in I<kilobytes>
2708 (ie. units of 1024 bytes).");
2710 ("initrd_list", (RStringList "filenames", [String "path"]), 128, [],
2711 [InitSquashFS, Always, TestOutputList (
2712 [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
2713 "list files in an initrd",
2715 This command lists out files contained in an initrd.
2717 The files are listed without any initial C</> character. The
2718 files are listed in the order they appear (not necessarily
2719 alphabetical). Directory names are listed as separate items.
2721 Old Linux kernels (2.4 and earlier) used a compressed ext2
2722 filesystem as initrd. We I<only> support the newer initramfs
2723 format (compressed cpio files).");
2725 ("mount_loop", (RErr, [String "file"; String "mountpoint"]), 129, [],
2727 "mount a file using the loop device",
2729 This command lets you mount C<file> (a filesystem image
2730 in a file) on a mount point. It is entirely equivalent to
2731 the command C<mount -o loop file mountpoint>.");
2733 ("mkswap", (RErr, [String "device"]), 130, [],
2734 [InitEmpty, Always, TestRun (
2735 [["sfdiskM"; "/dev/sda"; ","];
2736 ["mkswap"; "/dev/sda1"]])],
2737 "create a swap partition",
2739 Create a swap partition on C<device>.");
2741 ("mkswap_L", (RErr, [String "label"; String "device"]), 131, [],
2742 [InitEmpty, Always, TestRun (
2743 [["sfdiskM"; "/dev/sda"; ","];
2744 ["mkswap_L"; "hello"; "/dev/sda1"]])],
2745 "create a swap partition with a label",
2747 Create a swap partition on C<device> with label C<label>.");
2749 ("mkswap_U", (RErr, [String "uuid"; String "device"]), 132, [],
2750 [InitEmpty, Always, TestRun (
2751 [["sfdiskM"; "/dev/sda"; ","];
2752 ["mkswap_U"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"; "/dev/sda1"]])],
2753 "create a swap partition with an explicit UUID",
2755 Create a swap partition on C<device> with UUID C<uuid>.");
2757 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 133, [],
2758 [InitBasicFS, Always, TestOutputStruct (
2759 [["mknod"; "0o10777"; "0"; "0"; "/node"];
2760 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2761 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2762 InitBasicFS, Always, TestOutputStruct (
2763 [["mknod"; "0o60777"; "66"; "99"; "/node"];
2764 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2765 "make block, character or FIFO devices",
2767 This call creates block or character special devices, or
2768 named pipes (FIFOs).
2770 The C<mode> parameter should be the mode, using the standard
2771 constants. C<devmajor> and C<devminor> are the
2772 device major and minor numbers, only used when creating block
2773 and character special devices.");
2775 ("mkfifo", (RErr, [Int "mode"; String "path"]), 134, [],
2776 [InitBasicFS, Always, TestOutputStruct (
2777 [["mkfifo"; "0o777"; "/node"];
2778 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2779 "make FIFO (named pipe)",
2781 This call creates a FIFO (named pipe) called C<path> with
2782 mode C<mode>. It is just a convenient wrapper around
2783 C<guestfs_mknod>.");
2785 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 135, [],
2786 [InitBasicFS, Always, TestOutputStruct (
2787 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2788 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2789 "make block device node",
2791 This call creates a block device node called C<path> with
2792 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2793 It is just a convenient wrapper around C<guestfs_mknod>.");
2795 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 136, [],
2796 [InitBasicFS, Always, TestOutputStruct (
2797 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2798 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2799 "make char device node",
2801 This call creates a char device node called C<path> with
2802 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2803 It is just a convenient wrapper around C<guestfs_mknod>.");
2805 ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2806 [], (* XXX umask is one of those stateful things that we should
2807 * reset between each test.
2809 "set file mode creation mask (umask)",
2811 This function sets the mask used for creating new files and
2812 device nodes to C<mask & 0777>.
2814 Typical umask values would be C<022> which creates new files
2815 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2816 C<002> which creates new files with permissions like
2817 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2819 The default umask is C<022>. This is important because it
2820 means that directories and device nodes will be created with
2821 C<0644> or C<0755> mode even if you specify C<0777>.
2823 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2825 This call returns the previous umask.");
2827 ("readdir", (RStructList ("entries", "dirent"), [String "dir"]), 138, [],
2829 "read directories entries",
2831 This returns the list of directory entries in directory C<dir>.
2833 All entries in the directory are returned, including C<.> and
2834 C<..>. The entries are I<not> sorted, but returned in the same
2835 order as the underlying filesystem.
2837 Also this call returns basic file type information about each
2838 file. The C<ftyp> field will contain one of the following characters:
2876 The L<readdir(3)> returned a C<d_type> field with an
2881 This function is primarily intended for use by programs. To
2882 get a simple list of names, use C<guestfs_ls>. To get a printable
2883 directory for human consumption, use C<guestfs_ll>.");
2885 ("sfdiskM", (RErr, [String "device"; StringList "lines"]), 139, [DangerWillRobinson],
2887 "create partitions on a block device",
2889 This is a simplified interface to the C<guestfs_sfdisk>
2890 command, where partition sizes are specified in megabytes
2891 only (rounded to the nearest cylinder) and you don't need
2892 to specify the cyls, heads and sectors parameters which
2893 were rarely if ever used anyway.
2895 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
2897 ("zfile", (RString "description", [String "method"; String "path"]), 140, [DeprecatedBy "file"],
2899 "determine file type inside a compressed file",
2901 This command runs C<file> after first decompressing C<path>
2904 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
2906 Since 1.0.63, use C<guestfs_file> instead which can now
2907 process compressed files.");
2909 ("getxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 141, [],
2911 "list extended attributes of a file or directory",
2913 This call lists the extended attributes of the file or directory
2916 At the system call level, this is a combination of the
2917 L<listxattr(2)> and L<getxattr(2)> calls.
2919 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
2921 ("lgetxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 142, [],
2923 "list extended attributes of a file or directory",
2925 This is the same as C<guestfs_getxattrs>, but if C<path>
2926 is a symbolic link, then it returns the extended attributes
2927 of the link itself.");
2929 ("setxattr", (RErr, [String "xattr";
2930 String "val"; Int "vallen"; (* will be BufferIn *)
2931 String "path"]), 143, [],
2933 "set extended attribute of a file or directory",
2935 This call sets the extended attribute named C<xattr>
2936 of the file C<path> to the value C<val> (of length C<vallen>).
2937 The value is arbitrary 8 bit data.
2939 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
2941 ("lsetxattr", (RErr, [String "xattr";
2942 String "val"; Int "vallen"; (* will be BufferIn *)
2943 String "path"]), 144, [],
2945 "set extended attribute of a file or directory",
2947 This is the same as C<guestfs_setxattr>, but if C<path>
2948 is a symbolic link, then it sets an extended attribute
2949 of the link itself.");
2951 ("removexattr", (RErr, [String "xattr"; String "path"]), 145, [],
2953 "remove extended attribute of a file or directory",
2955 This call removes the extended attribute named C<xattr>
2956 of the file C<path>.
2958 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
2960 ("lremovexattr", (RErr, [String "xattr"; String "path"]), 146, [],
2962 "remove extended attribute of a file or directory",
2964 This is the same as C<guestfs_removexattr>, but if C<path>
2965 is a symbolic link, then it removes an extended attribute
2966 of the link itself.");
2968 ("mountpoints", (RHashtable "mps", []), 147, [],
2972 This call is similar to C<guestfs_mounts>. That call returns
2973 a list of devices. This one returns a hash table (map) of
2974 device name to directory where the device is mounted.");
2976 ("mkmountpoint", (RErr, [String "path"]), 148, [],
2978 "create a mountpoint",
2980 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
2981 specialized calls that can be used to create extra mountpoints
2982 before mounting the first filesystem.
2984 These calls are I<only> necessary in some very limited circumstances,
2985 mainly the case where you want to mount a mix of unrelated and/or
2986 read-only filesystems together.
2988 For example, live CDs often contain a \"Russian doll\" nest of
2989 filesystems, an ISO outer layer, with a squashfs image inside, with
2990 an ext2/3 image inside that. You can unpack this as follows
2993 add-ro Fedora-11-i686-Live.iso
2996 mkmountpoint /squash
2999 mount-loop /cd/LiveOS/squashfs.img /squash
3000 mount-loop /squash/LiveOS/ext3fs.img /ext3
3002 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3004 ("rmmountpoint", (RErr, [String "path"]), 149, [],
3006 "remove a mountpoint",
3008 This calls removes a mountpoint that was previously created
3009 with C<guestfs_mkmountpoint>. See C<guestfs_mkmountpoint>
3010 for full details.");
3012 ("read_file", (RBufferOut "content", [String "path"]), 150, [ProtocolLimitWarning],
3013 [InitSquashFS, Always, TestOutputBuffer (
3014 [["read_file"; "/known-4"]], "abc\ndef\nghi")],
3017 This calls returns the contents of the file C<path> as a
3020 Unlike C<guestfs_cat>, this function can correctly
3021 handle files that contain embedded ASCII NUL characters.
3022 However unlike C<guestfs_download>, this function is limited
3023 in the total size of file that can be handled.");
3025 ("grep", (RStringList "lines", [String "regex"; String "path"]), 151, [ProtocolLimitWarning],
3026 [InitSquashFS, Always, TestOutputList (
3027 [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3028 InitSquashFS, Always, TestOutputList (
3029 [["grep"; "nomatch"; "/test-grep.txt"]], [])],
3030 "return lines matching a pattern",
3032 This calls the external C<grep> program and returns the
3035 ("egrep", (RStringList "lines", [String "regex"; String "path"]), 152, [ProtocolLimitWarning],
3036 [InitSquashFS, Always, TestOutputList (
3037 [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3038 "return lines matching a pattern",
3040 This calls the external C<egrep> program and returns the
3043 ("fgrep", (RStringList "lines", [String "pattern"; String "path"]), 153, [ProtocolLimitWarning],
3044 [InitSquashFS, Always, TestOutputList (
3045 [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3046 "return lines matching a pattern",
3048 This calls the external C<fgrep> program and returns the
3051 ("grepi", (RStringList "lines", [String "regex"; String "path"]), 154, [ProtocolLimitWarning],
3052 [InitSquashFS, Always, TestOutputList (
3053 [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3054 "return lines matching a pattern",
3056 This calls the external C<grep -i> program and returns the
3059 ("egrepi", (RStringList "lines", [String "regex"; String "path"]), 155, [ProtocolLimitWarning],
3060 [InitSquashFS, Always, TestOutputList (
3061 [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3062 "return lines matching a pattern",
3064 This calls the external C<egrep -i> program and returns the
3067 ("fgrepi", (RStringList "lines", [String "pattern"; String "path"]), 156, [ProtocolLimitWarning],
3068 [InitSquashFS, Always, TestOutputList (
3069 [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3070 "return lines matching a pattern",
3072 This calls the external C<fgrep -i> program and returns the
3075 ("zgrep", (RStringList "lines", [String "regex"; String "path"]), 157, [ProtocolLimitWarning],
3076 [InitSquashFS, Always, TestOutputList (
3077 [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3078 "return lines matching a pattern",
3080 This calls the external C<zgrep> program and returns the
3083 ("zegrep", (RStringList "lines", [String "regex"; String "path"]), 158, [ProtocolLimitWarning],
3084 [InitSquashFS, Always, TestOutputList (
3085 [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3086 "return lines matching a pattern",
3088 This calls the external C<zegrep> program and returns the
3091 ("zfgrep", (RStringList "lines", [String "pattern"; String "path"]), 159, [ProtocolLimitWarning],
3092 [InitSquashFS, Always, TestOutputList (
3093 [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3094 "return lines matching a pattern",
3096 This calls the external C<zfgrep> program and returns the
3099 ("zgrepi", (RStringList "lines", [String "regex"; String "path"]), 160, [ProtocolLimitWarning],
3100 [InitSquashFS, Always, TestOutputList (
3101 [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3102 "return lines matching a pattern",
3104 This calls the external C<zgrep -i> program and returns the
3107 ("zegrepi", (RStringList "lines", [String "regex"; String "path"]), 161, [ProtocolLimitWarning],
3108 [InitSquashFS, Always, TestOutputList (
3109 [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3110 "return lines matching a pattern",
3112 This calls the external C<zegrep -i> program and returns the
3115 ("zfgrepi", (RStringList "lines", [String "pattern"; String "path"]), 162, [ProtocolLimitWarning],
3116 [InitSquashFS, Always, TestOutputList (
3117 [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3118 "return lines matching a pattern",
3120 This calls the external C<zfgrep -i> program and returns the
3125 let all_functions = non_daemon_functions @ daemon_functions
3127 (* In some places we want the functions to be displayed sorted
3128 * alphabetically, so this is useful:
3130 let all_functions_sorted =
3131 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
3132 compare n1 n2) all_functions
3134 (* Field types for structures. *)
3136 | FChar (* C 'char' (really, a 7 bit byte). *)
3137 | FString (* nul-terminated ASCII string. *)
3138 | FBuffer (* opaque buffer of bytes, (char *, int) pair *)
3143 | FBytes (* Any int measure that counts bytes. *)
3144 | FUUID (* 32 bytes long, NOT nul-terminated. *)
3145 | FOptPercent (* [0..100], or -1 meaning "not present". *)
3147 (* Because we generate extra parsing code for LVM command line tools,
3148 * we have to pull out the LVM columns separately here.
3158 "pv_attr", FString (* XXX *);
3159 "pv_pe_count", FInt64;
3160 "pv_pe_alloc_count", FInt64;
3163 "pv_mda_count", FInt64;
3164 "pv_mda_free", FBytes;
3165 (* Not in Fedora 10:
3166 "pv_mda_size", FBytes;
3173 "vg_attr", FString (* XXX *);
3176 "vg_sysid", FString;
3177 "vg_extent_size", FBytes;
3178 "vg_extent_count", FInt64;
3179 "vg_free_count", FInt64;
3184 "snap_count", FInt64;
3187 "vg_mda_count", FInt64;
3188 "vg_mda_free", FBytes;
3189 (* Not in Fedora 10:
3190 "vg_mda_size", FBytes;
3196 "lv_attr", FString (* XXX *);
3199 "lv_kernel_major", FInt64;
3200 "lv_kernel_minor", FInt64;
3202 "seg_count", FInt64;
3204 "snap_percent", FOptPercent;
3205 "copy_percent", FOptPercent;
3208 "mirror_log", FString;
3212 (* Names and fields in all structures (in RStruct and RStructList)
3216 (* The old RIntBool return type, only ever used for aug_defnode. Do
3217 * not use this struct in any new code.
3220 "i", FInt32; (* for historical compatibility *)
3221 "b", FInt32; (* for historical compatibility *)
3224 (* LVM PVs, VGs, LVs. *)
3225 "lvm_pv", lvm_pv_cols;
3226 "lvm_vg", lvm_vg_cols;
3227 "lvm_lv", lvm_lv_cols;
3229 (* Column names and types from stat structures.
3230 * NB. Can't use things like 'st_atime' because glibc header files
3231 * define some of these as macros. Ugh.
3262 (* Column names in dirent structure. *)
3265 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
3270 (* Version numbers. *)
3278 (* Extended attribute. *)
3280 "attrname", FString;
3283 ] (* end of structs *)
3285 (* Ugh, Java has to be different ..
3286 * These names are also used by the Haskell bindings.
3288 let java_structs = [
3289 "int_bool", "IntBool";
3294 "statvfs", "StatVFS";
3296 "version", "Version";
3300 (* Used for testing language bindings. *)
3302 | CallString of string
3303 | CallOptString of string option
3304 | CallStringList of string list
3308 (* Used to memoize the result of pod2text. *)
3309 let pod2text_memo_filename = "src/.pod2text.data"
3310 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
3312 let chan = open_in pod2text_memo_filename in
3313 let v = input_value chan in
3317 _ -> Hashtbl.create 13
3319 (* Useful functions.
3320 * Note we don't want to use any external OCaml libraries which
3321 * makes this a bit harder than it should be.
3323 let failwithf fs = ksprintf failwith fs
3325 let replace_char s c1 c2 =
3326 let s2 = String.copy s in
3327 let r = ref false in
3328 for i = 0 to String.length s2 - 1 do
3329 if String.unsafe_get s2 i = c1 then (
3330 String.unsafe_set s2 i c2;
3334 if not !r then s else s2
3338 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
3340 let triml ?(test = isspace) str =
3342 let n = ref (String.length str) in
3343 while !n > 0 && test str.[!i]; do
3348 else String.sub str !i !n
3350 let trimr ?(test = isspace) str =
3351 let n = ref (String.length str) in
3352 while !n > 0 && test str.[!n-1]; do
3355 if !n = String.length str then str
3356 else String.sub str 0 !n
3358 let trim ?(test = isspace) str =
3359 trimr ~test (triml ~test str)
3361 let rec find s sub =
3362 let len = String.length s in
3363 let sublen = String.length sub in
3365 if i <= len-sublen then (
3367 if j < sublen then (
3368 if s.[i+j] = sub.[j] then loop2 (j+1)
3374 if r = -1 then loop (i+1) else r
3380 let rec replace_str s s1 s2 =
3381 let len = String.length s in
3382 let sublen = String.length s1 in
3383 let i = find s s1 in
3386 let s' = String.sub s 0 i in
3387 let s'' = String.sub s (i+sublen) (len-i-sublen) in
3388 s' ^ s2 ^ replace_str s'' s1 s2
3391 let rec string_split sep str =
3392 let len = String.length str in
3393 let seplen = String.length sep in
3394 let i = find str sep in
3395 if i = -1 then [str]
3397 let s' = String.sub str 0 i in
3398 let s'' = String.sub str (i+seplen) (len-i-seplen) in
3399 s' :: string_split sep s''
3402 let files_equal n1 n2 =
3403 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
3404 match Sys.command cmd with
3407 | i -> failwithf "%s: failed with error code %d" cmd i
3409 let rec find_map f = function
3410 | [] -> raise Not_found
3414 | None -> find_map f xs
3417 let rec loop i = function
3419 | x :: xs -> f i x; loop (i+1) xs
3424 let rec loop i = function
3426 | x :: xs -> let r = f i x in r :: loop (i+1) xs
3430 let name_of_argt = function
3431 | String n | OptString n | StringList n | Bool n | Int n
3432 | FileIn n | FileOut n -> n
3434 let java_name_of_struct typ =
3435 try List.assoc typ java_structs
3438 "java_name_of_struct: no java_structs entry corresponding to %s" typ
3440 let cols_of_struct typ =
3441 try List.assoc typ structs
3443 failwithf "cols_of_struct: unknown struct %s" typ
3445 let seq_of_test = function
3446 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
3447 | TestOutputListOfDevices (s, _)
3448 | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
3449 | TestOutputTrue s | TestOutputFalse s
3450 | TestOutputLength (s, _) | TestOutputBuffer (s, _)
3451 | TestOutputStruct (s, _)
3452 | TestLastFail s -> s
3454 (* Handling for function flags. *)
3455 let protocol_limit_warning =
3456 "Because of the message protocol, there is a transfer limit
3457 of somewhere between 2MB and 4MB. To transfer large files you should use
3460 let danger_will_robinson =
3461 "B<This command is dangerous. Without careful use you
3462 can easily destroy all your data>."
3464 let deprecation_notice flags =
3467 find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
3469 sprintf "This function is deprecated.
3470 In new code, use the C<%s> call instead.
3472 Deprecated functions will not be removed from the API, but the
3473 fact that they are deprecated indicates that there are problems
3474 with correct use of these functions." alt in
3479 (* Check function names etc. for consistency. *)
3480 let check_functions () =
3481 let contains_uppercase str =
3482 let len = String.length str in
3484 if i >= len then false
3487 if c >= 'A' && c <= 'Z' then true
3494 (* Check function names. *)
3496 fun (name, _, _, _, _, _, _) ->
3497 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
3498 failwithf "function name %s does not need 'guestfs' prefix" name;
3500 failwithf "function name is empty";
3501 if name.[0] < 'a' || name.[0] > 'z' then
3502 failwithf "function name %s must start with lowercase a-z" name;
3503 if String.contains name '-' then
3504 failwithf "function name %s should not contain '-', use '_' instead."
3508 (* Check function parameter/return names. *)
3510 fun (name, style, _, _, _, _, _) ->
3511 let check_arg_ret_name n =
3512 if contains_uppercase n then
3513 failwithf "%s param/ret %s should not contain uppercase chars"
3515 if String.contains n '-' || String.contains n '_' then
3516 failwithf "%s param/ret %s should not contain '-' or '_'"
3519 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;
3520 if n = "int" || n = "char" || n = "short" || n = "long" then
3521 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
3522 if n = "i" || n = "n" then
3523 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
3524 if n = "argv" || n = "args" then
3525 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
3528 (match fst style with
3530 | RInt n | RInt64 n | RBool n
3531 | RConstString n | RConstOptString n | RString n
3532 | RStringList n | RStruct (n, _) | RStructList (n, _)
3533 | RHashtable n | RBufferOut n ->
3534 check_arg_ret_name n
3536 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
3539 (* Check short descriptions. *)
3541 fun (name, _, _, _, _, shortdesc, _) ->
3542 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
3543 failwithf "short description of %s should begin with lowercase." name;
3544 let c = shortdesc.[String.length shortdesc-1] in
3545 if c = '\n' || c = '.' then
3546 failwithf "short description of %s should not end with . or \\n." name
3549 (* Check long dscriptions. *)
3551 fun (name, _, _, _, _, _, longdesc) ->
3552 if longdesc.[String.length longdesc-1] = '\n' then
3553 failwithf "long description of %s should not end with \\n." name
3556 (* Check proc_nrs. *)
3558 fun (name, _, proc_nr, _, _, _, _) ->
3559 if proc_nr <= 0 then
3560 failwithf "daemon function %s should have proc_nr > 0" name
3564 fun (name, _, proc_nr, _, _, _, _) ->
3565 if proc_nr <> -1 then
3566 failwithf "non-daemon function %s should have proc_nr -1" name
3567 ) non_daemon_functions;
3570 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
3573 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
3574 let rec loop = function
3577 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
3579 | (name1,nr1) :: (name2,nr2) :: _ ->
3580 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
3588 (* Ignore functions that have no tests. We generate a
3589 * warning when the user does 'make check' instead.
3591 | name, _, _, _, [], _, _ -> ()
3592 | name, _, _, _, tests, _, _ ->
3596 match seq_of_test test with
3598 failwithf "%s has a test containing an empty sequence" name
3599 | cmds -> List.map List.hd cmds
3601 let funcs = List.flatten funcs in
3603 let tested = List.mem name funcs in
3606 failwithf "function %s has tests but does not test itself" name
3609 (* 'pr' prints to the current output file. *)
3610 let chan = ref stdout
3611 let pr fs = ksprintf (output_string !chan) fs
3613 (* Generate a header block in a number of standard styles. *)
3614 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
3615 type license = GPLv2 | LGPLv2
3617 let generate_header comment license =
3618 let c = match comment with
3619 | CStyle -> pr "/* "; " *"
3620 | HashStyle -> pr "# "; "#"
3621 | OCamlStyle -> pr "(* "; " *"
3622 | HaskellStyle -> pr "{- "; " " in
3623 pr "libguestfs generated file\n";
3624 pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
3625 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
3627 pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
3631 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
3632 pr "%s it under the terms of the GNU General Public License as published by\n" c;
3633 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
3634 pr "%s (at your option) any later version.\n" c;
3636 pr "%s This program is distributed in the hope that it will be useful,\n" c;
3637 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3638 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
3639 pr "%s GNU General Public License for more details.\n" c;
3641 pr "%s You should have received a copy of the GNU General Public License along\n" c;
3642 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
3643 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
3646 pr "%s This library is free software; you can redistribute it and/or\n" c;
3647 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
3648 pr "%s License as published by the Free Software Foundation; either\n" c;
3649 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
3651 pr "%s This library is distributed in the hope that it will be useful,\n" c;
3652 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3653 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
3654 pr "%s Lesser General Public License for more details.\n" c;
3656 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
3657 pr "%s License along with this library; if not, write to the Free Software\n" c;
3658 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
3661 | CStyle -> pr " */\n"
3663 | OCamlStyle -> pr " *)\n"
3664 | HaskellStyle -> pr "-}\n"
3668 (* Start of main code generation functions below this line. *)
3670 (* Generate the pod documentation for the C API. *)
3671 let rec generate_actions_pod () =
3673 fun (shortname, style, _, flags, _, _, longdesc) ->
3674 if not (List.mem NotInDocs flags) then (
3675 let name = "guestfs_" ^ shortname in
3676 pr "=head2 %s\n\n" name;
3678 generate_prototype ~extern:false ~handle:"handle" name style;
3680 pr "%s\n\n" longdesc;
3681 (match fst style with
3683 pr "This function returns 0 on success or -1 on error.\n\n"
3685 pr "On error this function returns -1.\n\n"
3687 pr "On error this function returns -1.\n\n"
3689 pr "This function returns a C truth value on success or -1 on error.\n\n"
3691 pr "This function returns a string, or NULL on error.
3692 The string is owned by the guest handle and must I<not> be freed.\n\n"
3693 | RConstOptString _ ->
3694 pr "This function returns a string which may be NULL.
3695 There is way to return an error from this function.
3696 The string is owned by the guest handle and must I<not> be freed.\n\n"
3698 pr "This function returns a string, or NULL on error.
3699 I<The caller must free the returned string after use>.\n\n"
3701 pr "This function returns a NULL-terminated array of strings
3702 (like L<environ(3)>), or NULL if there was an error.
3703 I<The caller must free the strings and the array after use>.\n\n"
3704 | RStruct (_, typ) ->
3705 pr "This function returns a C<struct guestfs_%s *>,
3706 or NULL if there was an error.
3707 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
3708 | RStructList (_, typ) ->
3709 pr "This function returns a C<struct guestfs_%s_list *>
3710 (see E<lt>guestfs-structs.hE<gt>),
3711 or NULL if there was an error.
3712 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
3714 pr "This function returns a NULL-terminated array of
3715 strings, or NULL if there was an error.
3716 The array of strings will always have length C<2n+1>, where
3717 C<n> keys and values alternate, followed by the trailing NULL entry.
3718 I<The caller must free the strings and the array after use>.\n\n"
3720 pr "This function returns a buffer, or NULL on error.
3721 The size of the returned buffer is written to C<*size_r>.
3722 I<The caller must free the returned buffer after use>.\n\n"
3724 if List.mem ProtocolLimitWarning flags then
3725 pr "%s\n\n" protocol_limit_warning;
3726 if List.mem DangerWillRobinson flags then
3727 pr "%s\n\n" danger_will_robinson;
3728 match deprecation_notice flags with
3730 | Some txt -> pr "%s\n\n" txt
3732 ) all_functions_sorted
3734 and generate_structs_pod () =
3735 (* Structs documentation. *)
3738 pr "=head2 guestfs_%s\n" typ;
3740 pr " struct guestfs_%s {\n" typ;
3743 | name, FChar -> pr " char %s;\n" name
3744 | name, FUInt32 -> pr " uint32_t %s;\n" name
3745 | name, FInt32 -> pr " int32_t %s;\n" name
3746 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3747 | name, FInt64 -> pr " int64_t %s;\n" name
3748 | name, FString -> pr " char *%s;\n" name
3750 pr " /* The next two fields describe a byte array. */\n";
3751 pr " uint32_t %s_len;\n" name;
3752 pr " char *%s;\n" name
3754 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
3755 pr " char %s[32];\n" name
3756 | name, FOptPercent ->
3757 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
3758 pr " float %s;\n" name
3762 pr " struct guestfs_%s_list {\n" typ;
3763 pr " uint32_t len; /* Number of elements in list. */\n";
3764 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
3767 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
3768 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
3773 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
3774 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
3776 * We have to use an underscore instead of a dash because otherwise
3777 * rpcgen generates incorrect code.
3779 * This header is NOT exported to clients, but see also generate_structs_h.
3781 and generate_xdr () =
3782 generate_header CStyle LGPLv2;
3784 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
3785 pr "typedef string str<>;\n";
3788 (* Internal structures. *)
3792 pr "struct guestfs_int_%s {\n" typ;
3794 | name, FChar -> pr " char %s;\n" name
3795 | name, FString -> pr " string %s<>;\n" name
3796 | name, FBuffer -> pr " opaque %s<>;\n" name
3797 | name, FUUID -> pr " opaque %s[32];\n" name
3798 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
3799 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
3800 | name, FOptPercent -> pr " float %s;\n" name
3804 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
3809 fun (shortname, style, _, _, _, _, _) ->
3810 let name = "guestfs_" ^ shortname in
3812 (match snd style with
3815 pr "struct %s_args {\n" name;
3818 | String n -> pr " string %s<>;\n" n
3819 | OptString n -> pr " str *%s;\n" n
3820 | StringList n -> pr " str %s<>;\n" n
3821 | Bool n -> pr " bool %s;\n" n
3822 | Int n -> pr " int %s;\n" n
3823 | FileIn _ | FileOut _ -> ()
3827 (match fst style with
3830 pr "struct %s_ret {\n" name;
3834 pr "struct %s_ret {\n" name;
3835 pr " hyper %s;\n" n;
3838 pr "struct %s_ret {\n" name;
3841 | RConstString _ | RConstOptString _ ->
3842 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
3844 pr "struct %s_ret {\n" name;
3845 pr " string %s<>;\n" n;
3848 pr "struct %s_ret {\n" name;
3849 pr " str %s<>;\n" n;
3851 | RStruct (n, typ) ->
3852 pr "struct %s_ret {\n" name;
3853 pr " guestfs_int_%s %s;\n" typ n;
3855 | RStructList (n, typ) ->
3856 pr "struct %s_ret {\n" name;
3857 pr " guestfs_int_%s_list %s;\n" typ n;
3860 pr "struct %s_ret {\n" name;
3861 pr " str %s<>;\n" n;
3864 pr "struct %s_ret {\n" name;
3865 pr " opaque %s<>;\n" n;
3870 (* Table of procedure numbers. *)
3871 pr "enum guestfs_procedure {\n";
3873 fun (shortname, _, proc_nr, _, _, _, _) ->
3874 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
3876 pr " GUESTFS_PROC_NR_PROCS\n";
3880 (* Having to choose a maximum message size is annoying for several
3881 * reasons (it limits what we can do in the API), but it (a) makes
3882 * the protocol a lot simpler, and (b) provides a bound on the size
3883 * of the daemon which operates in limited memory space. For large
3884 * file transfers you should use FTP.
3886 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
3889 (* Message header, etc. *)
3891 /* The communication protocol is now documented in the guestfs(3)
3895 const GUESTFS_PROGRAM = 0x2000F5F5;
3896 const GUESTFS_PROTOCOL_VERSION = 1;
3898 /* These constants must be larger than any possible message length. */
3899 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
3900 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
3902 enum guestfs_message_direction {
3903 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
3904 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
3907 enum guestfs_message_status {
3908 GUESTFS_STATUS_OK = 0,
3909 GUESTFS_STATUS_ERROR = 1
3912 const GUESTFS_ERROR_LEN = 256;
3914 struct guestfs_message_error {
3915 string error_message<GUESTFS_ERROR_LEN>;
3918 struct guestfs_message_header {
3919 unsigned prog; /* GUESTFS_PROGRAM */
3920 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
3921 guestfs_procedure proc; /* GUESTFS_PROC_x */
3922 guestfs_message_direction direction;
3923 unsigned serial; /* message serial number */
3924 guestfs_message_status status;
3927 const GUESTFS_MAX_CHUNK_SIZE = 8192;
3929 struct guestfs_chunk {
3930 int cancel; /* if non-zero, transfer is cancelled */
3931 /* data size is 0 bytes if the transfer has finished successfully */
3932 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
3936 (* Generate the guestfs-structs.h file. *)
3937 and generate_structs_h () =
3938 generate_header CStyle LGPLv2;
3940 (* This is a public exported header file containing various
3941 * structures. The structures are carefully written to have
3942 * exactly the same in-memory format as the XDR structures that
3943 * we use on the wire to the daemon. The reason for creating
3944 * copies of these structures here is just so we don't have to
3945 * export the whole of guestfs_protocol.h (which includes much
3946 * unrelated and XDR-dependent stuff that we don't want to be
3947 * public, or required by clients).
3949 * To reiterate, we will pass these structures to and from the
3950 * client with a simple assignment or memcpy, so the format
3951 * must be identical to what rpcgen / the RFC defines.
3954 (* Public structures. *)
3957 pr "struct guestfs_%s {\n" typ;
3960 | name, FChar -> pr " char %s;\n" name
3961 | name, FString -> pr " char *%s;\n" name
3963 pr " uint32_t %s_len;\n" name;
3964 pr " char *%s;\n" name
3965 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3966 | name, FUInt32 -> pr " uint32_t %s;\n" name
3967 | name, FInt32 -> pr " int32_t %s;\n" name
3968 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3969 | name, FInt64 -> pr " int64_t %s;\n" name
3970 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
3974 pr "struct guestfs_%s_list {\n" typ;
3975 pr " uint32_t len;\n";
3976 pr " struct guestfs_%s *val;\n" typ;
3979 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
3980 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
3984 (* Generate the guestfs-actions.h file. *)
3985 and generate_actions_h () =
3986 generate_header CStyle LGPLv2;
3988 fun (shortname, style, _, _, _, _, _) ->
3989 let name = "guestfs_" ^ shortname in
3990 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3994 (* Generate the client-side dispatch stubs. *)
3995 and generate_client_actions () =
3996 generate_header CStyle LGPLv2;
4002 #include \"guestfs.h\"
4003 #include \"guestfs_protocol.h\"
4005 #define error guestfs_error
4006 #define perrorf guestfs_perrorf
4007 #define safe_malloc guestfs_safe_malloc
4008 #define safe_realloc guestfs_safe_realloc
4009 #define safe_strdup guestfs_safe_strdup
4010 #define safe_memdup guestfs_safe_memdup
4012 /* Check the return message from a call for validity. */
4014 check_reply_header (guestfs_h *g,
4015 const struct guestfs_message_header *hdr,
4016 int proc_nr, int serial)
4018 if (hdr->prog != GUESTFS_PROGRAM) {
4019 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
4022 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
4023 error (g, \"wrong protocol version (%%d/%%d)\",
4024 hdr->vers, GUESTFS_PROTOCOL_VERSION);
4027 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
4028 error (g, \"unexpected message direction (%%d/%%d)\",
4029 hdr->direction, GUESTFS_DIRECTION_REPLY);
4032 if (hdr->proc != proc_nr) {
4033 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
4036 if (hdr->serial != serial) {
4037 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
4044 /* Check we are in the right state to run a high-level action. */
4046 check_state (guestfs_h *g, const char *caller)
4048 if (!guestfs_is_ready (g)) {
4049 if (guestfs_is_config (g))
4050 error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
4052 else if (guestfs_is_launching (g))
4053 error (g, \"%%s: call wait_ready() before using this function\",
4056 error (g, \"%%s called from the wrong state, %%d != READY\",
4057 caller, guestfs_get_state (g));
4065 (* Client-side stubs for each function. *)
4067 fun (shortname, style, _, _, _, _, _) ->
4068 let name = "guestfs_" ^ shortname in
4070 (* Generate the context struct which stores the high-level
4071 * state between callback functions.
4073 pr "struct %s_ctx {\n" shortname;
4074 pr " /* This flag is set by the callbacks, so we know we've done\n";
4075 pr " * the callbacks as expected, and in the right sequence.\n";
4076 pr " * 0 = not called, 1 = reply_cb called.\n";
4078 pr " int cb_sequence;\n";
4079 pr " struct guestfs_message_header hdr;\n";
4080 pr " struct guestfs_message_error err;\n";
4081 (match fst style with
4083 | RConstString _ | RConstOptString _ ->
4084 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4086 | RBool _ | RString _ | RStringList _
4087 | RStruct _ | RStructList _
4088 | RHashtable _ | RBufferOut _ ->
4089 pr " struct %s_ret ret;\n" name
4094 (* Generate the reply callback function. *)
4095 pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
4097 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
4098 pr " struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
4100 pr " /* This should definitely not happen. */\n";
4101 pr " if (ctx->cb_sequence != 0) {\n";
4102 pr " ctx->cb_sequence = 9999;\n";
4103 pr " error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
4107 pr " ml->main_loop_quit (ml, g);\n";
4109 pr " if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
4110 pr " error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
4113 pr " if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
4114 pr " if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
4115 pr " error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
4122 (match fst style with
4124 | RConstString _ | RConstOptString _ ->
4125 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4127 | RBool _ | RString _ | RStringList _
4128 | RStruct _ | RStructList _
4129 | RHashtable _ | RBufferOut _ ->
4130 pr " if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
4131 pr " error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
4137 pr " ctx->cb_sequence = 1;\n";
4140 (* Generate the action stub. *)
4141 generate_prototype ~extern:false ~semicolon:false ~newline:true
4142 ~handle:"g" name style;
4145 match fst style with
4146 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
4147 | RConstString _ | RConstOptString _ ->
4148 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4149 | RString _ | RStringList _
4150 | RStruct _ | RStructList _
4151 | RHashtable _ | RBufferOut _ ->
4156 (match snd style with
4158 | _ -> pr " struct %s_args args;\n" name
4161 pr " struct %s_ctx ctx;\n" shortname;
4162 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
4163 pr " int serial;\n";
4165 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
4166 pr " guestfs_set_busy (g);\n";
4168 pr " memset (&ctx, 0, sizeof ctx);\n";
4171 (* Send the main header and arguments. *)
4172 (match snd style with
4174 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
4175 (String.uppercase shortname)
4180 pr " args.%s = (char *) %s;\n" n n
4182 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
4184 pr " args.%s.%s_val = (char **) %s;\n" n n n;
4185 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
4187 pr " args.%s = %s;\n" n n
4189 pr " args.%s = %s;\n" n n
4190 | FileIn _ | FileOut _ -> ()
4192 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
4193 (String.uppercase shortname);
4194 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
4197 pr " if (serial == -1) {\n";
4198 pr " guestfs_end_busy (g);\n";
4199 pr " return %s;\n" error_code;
4203 (* Send any additional files (FileIn) requested. *)
4204 let need_read_reply_label = ref false in
4211 pr " r = guestfs__send_file_sync (g, %s);\n" n;
4212 pr " if (r == -1) {\n";
4213 pr " guestfs_end_busy (g);\n";
4214 pr " return %s;\n" error_code;
4216 pr " if (r == -2) /* daemon cancelled */\n";
4217 pr " goto read_reply;\n";
4218 need_read_reply_label := true;
4224 (* Wait for the reply from the remote end. *)
4225 if !need_read_reply_label then pr " read_reply:\n";
4226 pr " guestfs__switch_to_receiving (g);\n";
4227 pr " ctx.cb_sequence = 0;\n";
4228 pr " guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
4229 pr " (void) ml->main_loop_run (ml, g);\n";
4230 pr " guestfs_set_reply_callback (g, NULL, NULL);\n";
4231 pr " if (ctx.cb_sequence != 1) {\n";
4232 pr " error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
4233 pr " guestfs_end_busy (g);\n";
4234 pr " return %s;\n" error_code;
4238 pr " if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
4239 (String.uppercase shortname);
4240 pr " guestfs_end_busy (g);\n";
4241 pr " return %s;\n" error_code;
4245 pr " if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
4246 pr " error (g, \"%%s\", ctx.err.error_message);\n";
4247 pr " free (ctx.err.error_message);\n";
4248 pr " guestfs_end_busy (g);\n";
4249 pr " return %s;\n" error_code;
4253 (* Expecting to receive further files (FileOut)? *)
4257 pr " if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
4258 pr " guestfs_end_busy (g);\n";
4259 pr " return %s;\n" error_code;
4265 pr " guestfs_end_busy (g);\n";
4267 (match fst style with
4268 | RErr -> pr " return 0;\n"
4269 | RInt n | RInt64 n | RBool n ->
4270 pr " return ctx.ret.%s;\n" n
4271 | RConstString _ | RConstOptString _ ->
4272 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4274 pr " return ctx.ret.%s; /* caller will free */\n" n
4275 | RStringList n | RHashtable n ->
4276 pr " /* caller will free this, but we need to add a NULL entry */\n";
4277 pr " ctx.ret.%s.%s_val =\n" n n;
4278 pr " safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
4279 pr " sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
4281 pr " ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
4282 pr " return ctx.ret.%s.%s_val;\n" n n
4284 pr " /* caller will free this */\n";
4285 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4286 | RStructList (n, _) ->
4287 pr " /* caller will free this */\n";
4288 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4290 pr " *size_r = ctx.ret.%s.%s_len;\n" n n;
4291 pr " return ctx.ret.%s.%s_val; /* caller will free */\n" n n
4297 (* Functions to free structures. *)
4298 pr "/* Structure-freeing functions. These rely on the fact that the\n";
4299 pr " * structure format is identical to the XDR format. See note in\n";
4300 pr " * generator.ml.\n";
4307 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
4309 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
4315 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
4317 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
4324 (* Generate daemon/actions.h. *)
4325 and generate_daemon_actions_h () =
4326 generate_header CStyle GPLv2;
4328 pr "#include \"../src/guestfs_protocol.h\"\n";
4332 fun (name, style, _, _, _, _, _) ->
4334 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
4338 (* Generate the server-side stubs. *)
4339 and generate_daemon_actions () =
4340 generate_header CStyle GPLv2;
4342 pr "#include <config.h>\n";
4344 pr "#include <stdio.h>\n";
4345 pr "#include <stdlib.h>\n";
4346 pr "#include <string.h>\n";
4347 pr "#include <inttypes.h>\n";
4348 pr "#include <ctype.h>\n";
4349 pr "#include <rpc/types.h>\n";
4350 pr "#include <rpc/xdr.h>\n";
4352 pr "#include \"daemon.h\"\n";
4353 pr "#include \"../src/guestfs_protocol.h\"\n";
4354 pr "#include \"actions.h\"\n";
4358 fun (name, style, _, _, _, _, _) ->
4359 (* Generate server-side stubs. *)
4360 pr "static void %s_stub (XDR *xdr_in)\n" name;
4363 match fst style with
4364 | RErr | RInt _ -> pr " int r;\n"; "-1"
4365 | RInt64 _ -> pr " int64_t r;\n"; "-1"
4366 | RBool _ -> pr " int r;\n"; "-1"
4367 | RConstString _ | RConstOptString _ ->
4368 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4369 | RString _ -> pr " char *r;\n"; "NULL"
4370 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
4371 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
4372 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL"
4374 pr " size_t size;\n";
4378 (match snd style with
4381 pr " struct guestfs_%s_args args;\n" name;
4384 (* Note we allow the string to be writable, in order to
4385 * allow device name translation. This is safe because
4386 * we can modify the string (passed from RPC).
4389 | OptString n -> pr " char *%s;\n" n
4390 | StringList n -> pr " char **%s;\n" n
4391 | Bool n -> pr " int %s;\n" n
4392 | Int n -> pr " int %s;\n" n
4393 | FileIn _ | FileOut _ -> ()
4398 (match snd style with
4401 pr " memset (&args, 0, sizeof args);\n";
4403 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
4404 pr " reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
4409 | String n -> pr " %s = args.%s;\n" n n
4410 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
4412 pr " %s = realloc (args.%s.%s_val,\n" n n n;
4413 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
4414 pr " if (%s == NULL) {\n" n;
4415 pr " reply_with_perror (\"realloc\");\n";
4418 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
4419 pr " args.%s.%s_val = %s;\n" n n n;
4420 | Bool n -> pr " %s = args.%s;\n" n n
4421 | Int n -> pr " %s = args.%s;\n" n n
4422 | FileIn _ | FileOut _ -> ()
4427 (* Don't want to call the impl with any FileIn or FileOut
4428 * parameters, since these go "outside" the RPC protocol.
4431 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
4433 pr " r = do_%s " name;
4434 generate_c_call_args (fst style, args');
4437 pr " if (r == %s)\n" error_code;
4438 pr " /* do_%s has already called reply_with_error */\n" name;
4442 (* If there are any FileOut parameters, then the impl must
4443 * send its own reply.
4446 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
4448 pr " /* do_%s has already sent a reply */\n" name
4450 match fst style with
4451 | RErr -> pr " reply (NULL, NULL);\n"
4452 | RInt n | RInt64 n | RBool n ->
4453 pr " struct guestfs_%s_ret ret;\n" name;
4454 pr " ret.%s = r;\n" n;
4455 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4457 | RConstString _ | RConstOptString _ ->
4458 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4460 pr " struct guestfs_%s_ret ret;\n" name;
4461 pr " ret.%s = r;\n" n;
4462 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4465 | RStringList n | RHashtable n ->
4466 pr " struct guestfs_%s_ret ret;\n" name;
4467 pr " ret.%s.%s_len = count_strings (r);\n" n n;
4468 pr " ret.%s.%s_val = r;\n" n n;
4469 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4471 pr " free_strings (r);\n"
4473 pr " struct guestfs_%s_ret ret;\n" name;
4474 pr " ret.%s = *r;\n" n;
4475 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4477 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4479 | RStructList (n, _) ->
4480 pr " struct guestfs_%s_ret ret;\n" name;
4481 pr " ret.%s = *r;\n" n;
4482 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4484 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4487 pr " struct guestfs_%s_ret ret;\n" name;
4488 pr " ret.%s.%s_val = r;\n" n n;
4489 pr " ret.%s.%s_len = size;\n" n n;
4490 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4495 (* Free the args. *)
4496 (match snd style with
4501 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
4508 (* Dispatch function. *)
4509 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
4511 pr " switch (proc_nr) {\n";
4514 fun (name, style, _, _, _, _, _) ->
4515 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
4516 pr " %s_stub (xdr_in);\n" name;
4521 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";
4526 (* LVM columns and tokenization functions. *)
4527 (* XXX This generates crap code. We should rethink how we
4533 pr "static const char *lvm_%s_cols = \"%s\";\n"
4534 typ (String.concat "," (List.map fst cols));
4537 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
4539 pr " char *tok, *p, *next;\n";
4543 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
4546 pr " if (!str) {\n";
4547 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
4550 pr " if (!*str || isspace (*str)) {\n";
4551 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
4556 fun (name, coltype) ->
4557 pr " if (!tok) {\n";
4558 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
4561 pr " p = strchrnul (tok, ',');\n";
4562 pr " if (*p) next = p+1; else next = NULL;\n";
4563 pr " *p = '\\0';\n";
4566 pr " r->%s = strdup (tok);\n" name;
4567 pr " if (r->%s == NULL) {\n" name;
4568 pr " perror (\"strdup\");\n";
4572 pr " for (i = j = 0; i < 32; ++j) {\n";
4573 pr " if (tok[j] == '\\0') {\n";
4574 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
4576 pr " } else if (tok[j] != '-')\n";
4577 pr " r->%s[i++] = tok[j];\n" name;
4580 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
4581 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4585 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
4586 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4590 pr " if (tok[0] == '\\0')\n";
4591 pr " r->%s = -1;\n" name;
4592 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
4593 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4596 | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
4597 assert false (* can never be an LVM column *)
4599 pr " tok = next;\n";
4602 pr " if (tok != NULL) {\n";
4603 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
4610 pr "guestfs_int_lvm_%s_list *\n" typ;
4611 pr "parse_command_line_%ss (void)\n" typ;
4613 pr " char *out, *err;\n";
4614 pr " char *p, *pend;\n";
4616 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
4617 pr " void *newp;\n";
4619 pr " ret = malloc (sizeof *ret);\n";
4620 pr " if (!ret) {\n";
4621 pr " reply_with_perror (\"malloc\");\n";
4622 pr " return NULL;\n";
4625 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
4626 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
4628 pr " r = command (&out, &err,\n";
4629 pr " \"/sbin/lvm\", \"%ss\",\n" typ;
4630 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
4631 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
4632 pr " if (r == -1) {\n";
4633 pr " reply_with_error (\"%%s\", err);\n";
4634 pr " free (out);\n";
4635 pr " free (err);\n";
4636 pr " free (ret);\n";
4637 pr " return NULL;\n";
4640 pr " free (err);\n";
4642 pr " /* Tokenize each line of the output. */\n";
4645 pr " while (p) {\n";
4646 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
4647 pr " if (pend) {\n";
4648 pr " *pend = '\\0';\n";
4652 pr " while (*p && isspace (*p)) /* Skip any leading whitespace. */\n";
4655 pr " if (!*p) { /* Empty line? Skip it. */\n";
4660 pr " /* Allocate some space to store this next entry. */\n";
4661 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
4662 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
4663 pr " if (newp == NULL) {\n";
4664 pr " reply_with_perror (\"realloc\");\n";
4665 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4666 pr " free (ret);\n";
4667 pr " free (out);\n";
4668 pr " return NULL;\n";
4670 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
4672 pr " /* Tokenize the next entry. */\n";
4673 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
4674 pr " if (r == -1) {\n";
4675 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
4676 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4677 pr " free (ret);\n";
4678 pr " free (out);\n";
4679 pr " return NULL;\n";
4686 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
4688 pr " free (out);\n";
4689 pr " return ret;\n";
4692 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
4694 (* Generate a list of function names, for debugging in the daemon.. *)
4695 and generate_daemon_names () =
4696 generate_header CStyle GPLv2;
4698 pr "#include <config.h>\n";
4700 pr "#include \"daemon.h\"\n";
4703 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
4704 pr "const char *function_names[] = {\n";
4706 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
4710 (* Generate the tests. *)
4711 and generate_tests () =
4712 generate_header CStyle GPLv2;
4719 #include <sys/types.h>
4722 #include \"guestfs.h\"
4724 static guestfs_h *g;
4725 static int suppress_error = 0;
4727 static void print_error (guestfs_h *g, void *data, const char *msg)
4729 if (!suppress_error)
4730 fprintf (stderr, \"%%s\\n\", msg);
4733 static void print_strings (char * const * const argv)
4737 for (argc = 0; argv[argc] != NULL; ++argc)
4738 printf (\"\\t%%s\\n\", argv[argc]);
4742 static void print_table (char * const * const argv)
4746 for (i = 0; argv[i] != NULL; i += 2)
4747 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
4751 static void no_test_warnings (void)
4757 | name, _, _, _, [], _, _ ->
4758 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
4759 | name, _, _, _, tests, _, _ -> ()
4765 (* Generate the actual tests. Note that we generate the tests
4766 * in reverse order, deliberately, so that (in general) the
4767 * newest tests run first. This makes it quicker and easier to
4772 fun (name, _, _, _, tests, _, _) ->
4773 mapi (generate_one_test name) tests
4774 ) (List.rev all_functions) in
4775 let test_names = List.concat test_names in
4776 let nr_tests = List.length test_names in
4779 int main (int argc, char *argv[])
4783 const char *filename;
4785 int nr_tests, test_num = 0;
4787 setbuf (stdout, NULL);
4789 no_test_warnings ();
4791 g = guestfs_create ();
4793 printf (\"guestfs_create FAILED\\n\");
4797 guestfs_set_error_handler (g, print_error, NULL);
4799 guestfs_set_path (g, \"../appliance\");
4801 filename = \"test1.img\";
4802 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4807 if (lseek (fd, %d, SEEK_SET) == -1) {
4813 if (write (fd, &c, 1) == -1) {
4819 if (close (fd) == -1) {
4824 if (guestfs_add_drive (g, filename) == -1) {
4825 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4829 filename = \"test2.img\";
4830 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4835 if (lseek (fd, %d, SEEK_SET) == -1) {
4841 if (write (fd, &c, 1) == -1) {
4847 if (close (fd) == -1) {
4852 if (guestfs_add_drive (g, filename) == -1) {
4853 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4857 filename = \"test3.img\";
4858 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4863 if (lseek (fd, %d, SEEK_SET) == -1) {
4869 if (write (fd, &c, 1) == -1) {
4875 if (close (fd) == -1) {
4880 if (guestfs_add_drive (g, filename) == -1) {
4881 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4885 if (guestfs_add_drive_ro (g, \"../images/test.sqsh\") == -1) {
4886 printf (\"guestfs_add_drive_ro ../images/test.sqsh FAILED\\n\");
4890 if (guestfs_launch (g) == -1) {
4891 printf (\"guestfs_launch FAILED\\n\");
4895 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
4898 if (guestfs_wait_ready (g) == -1) {
4899 printf (\"guestfs_wait_ready FAILED\\n\");
4903 /* Cancel previous alarm. */
4908 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
4912 pr " test_num++;\n";
4913 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
4914 pr " if (%s () == -1) {\n" test_name;
4915 pr " printf (\"%s FAILED\\n\");\n" test_name;
4921 pr " guestfs_close (g);\n";
4922 pr " unlink (\"test1.img\");\n";
4923 pr " unlink (\"test2.img\");\n";
4924 pr " unlink (\"test3.img\");\n";
4927 pr " if (failed > 0) {\n";
4928 pr " printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
4936 and generate_one_test name i (init, prereq, test) =
4937 let test_name = sprintf "test_%s_%d" name i in
4940 static int %s_skip (void)
4944 str = getenv (\"TEST_ONLY\");
4946 return strstr (str, \"%s\") == NULL;
4947 str = getenv (\"SKIP_%s\");
4948 if (str && strcmp (str, \"1\") == 0) return 1;
4949 str = getenv (\"SKIP_TEST_%s\");
4950 if (str && strcmp (str, \"1\") == 0) return 1;
4954 " test_name name (String.uppercase test_name) (String.uppercase name);
4957 | Disabled | Always -> ()
4958 | If code | Unless code ->
4959 pr "static int %s_prereq (void)\n" test_name;
4967 static int %s (void)
4970 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
4974 " test_name test_name test_name;
4978 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4980 pr " if (! %s_prereq ()) {\n" test_name;
4981 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4985 generate_one_test_body name i test_name init test;
4987 pr " if (%s_prereq ()) {\n" test_name;
4988 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4992 generate_one_test_body name i test_name init test;
4994 generate_one_test_body name i test_name init test
5002 and generate_one_test_body name i test_name init test =
5004 | InitNone (* XXX at some point, InitNone and InitEmpty became
5005 * folded together as the same thing. Really we should
5006 * make InitNone do nothing at all, but the tests may
5007 * need to be checked to make sure this is OK.
5010 pr " /* InitNone|InitEmpty for %s */\n" test_name;
5011 List.iter (generate_test_command_call test_name)
5012 [["blockdev_setrw"; "/dev/sda"];
5016 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
5017 List.iter (generate_test_command_call test_name)
5018 [["blockdev_setrw"; "/dev/sda"];
5021 ["sfdiskM"; "/dev/sda"; ","];
5022 ["mkfs"; "ext2"; "/dev/sda1"];
5023 ["mount"; "/dev/sda1"; "/"]]
5024 | InitBasicFSonLVM ->
5025 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
5027 List.iter (generate_test_command_call test_name)
5028 [["blockdev_setrw"; "/dev/sda"];
5031 ["sfdiskM"; "/dev/sda"; ","];
5032 ["pvcreate"; "/dev/sda1"];
5033 ["vgcreate"; "VG"; "/dev/sda1"];
5034 ["lvcreate"; "LV"; "VG"; "8"];
5035 ["mkfs"; "ext2"; "/dev/VG/LV"];
5036 ["mount"; "/dev/VG/LV"; "/"]]
5038 pr " /* InitSquashFS for %s */\n" test_name;
5039 List.iter (generate_test_command_call test_name)
5040 [["blockdev_setrw"; "/dev/sda"];
5043 ["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"]]
5046 let get_seq_last = function
5048 failwithf "%s: you cannot use [] (empty list) when expecting a command"
5051 let seq = List.rev seq in
5052 List.rev (List.tl seq), List.hd seq
5057 pr " /* TestRun for %s (%d) */\n" name i;
5058 List.iter (generate_test_command_call test_name) seq
5059 | TestOutput (seq, expected) ->
5060 pr " /* TestOutput for %s (%d) */\n" name i;
5061 pr " const char *expected = \"%s\";\n" (c_quote expected);
5062 let seq, last = get_seq_last seq in
5064 pr " if (strcmp (r, expected) != 0) {\n";
5065 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
5069 List.iter (generate_test_command_call test_name) seq;
5070 generate_test_command_call ~test test_name last
5071 | TestOutputList (seq, expected) ->
5072 pr " /* TestOutputList for %s (%d) */\n" name i;
5073 let seq, last = get_seq_last seq in
5077 pr " if (!r[%d]) {\n" i;
5078 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
5079 pr " print_strings (r);\n";
5083 pr " const char *expected = \"%s\";\n" (c_quote str);
5084 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
5085 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
5090 pr " if (r[%d] != NULL) {\n" (List.length expected);
5091 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
5093 pr " print_strings (r);\n";
5097 List.iter (generate_test_command_call test_name) seq;
5098 generate_test_command_call ~test test_name last
5099 | TestOutputListOfDevices (seq, expected) ->
5100 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
5101 let seq, last = get_seq_last seq in
5105 pr " if (!r[%d]) {\n" i;
5106 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
5107 pr " print_strings (r);\n";
5111 pr " const char *expected = \"%s\";\n" (c_quote str);
5112 pr " r[%d][5] = 's';\n" i;
5113 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
5114 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
5119 pr " if (r[%d] != NULL) {\n" (List.length expected);
5120 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
5122 pr " print_strings (r);\n";
5126 List.iter (generate_test_command_call test_name) seq;
5127 generate_test_command_call ~test test_name last
5128 | TestOutputInt (seq, expected) ->
5129 pr " /* TestOutputInt for %s (%d) */\n" name i;
5130 let seq, last = get_seq_last seq in
5132 pr " if (r != %d) {\n" expected;
5133 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
5139 List.iter (generate_test_command_call test_name) seq;
5140 generate_test_command_call ~test test_name last
5141 | TestOutputIntOp (seq, op, expected) ->
5142 pr " /* TestOutputIntOp for %s (%d) */\n" name i;
5143 let seq, last = get_seq_last seq in
5145 pr " if (! (r %s %d)) {\n" op expected;
5146 pr " fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
5147 test_name op expected;
5152 List.iter (generate_test_command_call test_name) seq;
5153 generate_test_command_call ~test test_name last
5154 | TestOutputTrue seq ->
5155 pr " /* TestOutputTrue for %s (%d) */\n" name i;
5156 let seq, last = get_seq_last seq in
5159 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
5164 List.iter (generate_test_command_call test_name) seq;
5165 generate_test_command_call ~test test_name last
5166 | TestOutputFalse seq ->
5167 pr " /* TestOutputFalse for %s (%d) */\n" name i;
5168 let seq, last = get_seq_last seq in
5171 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
5176 List.iter (generate_test_command_call test_name) seq;
5177 generate_test_command_call ~test test_name last
5178 | TestOutputLength (seq, expected) ->
5179 pr " /* TestOutputLength for %s (%d) */\n" name i;
5180 let seq, last = get_seq_last seq in
5183 pr " for (j = 0; j < %d; ++j)\n" expected;
5184 pr " if (r[j] == NULL) {\n";
5185 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
5187 pr " print_strings (r);\n";
5190 pr " if (r[j] != NULL) {\n";
5191 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
5193 pr " print_strings (r);\n";
5197 List.iter (generate_test_command_call test_name) seq;
5198 generate_test_command_call ~test test_name last
5199 | TestOutputBuffer (seq, expected) ->
5200 pr " /* TestOutputBuffer for %s (%d) */\n" name i;
5201 pr " const char *expected = \"%s\";\n" (c_quote expected);
5202 let seq, last = get_seq_last seq in
5203 let len = String.length expected in
5205 pr " if (size != %d) {\n" len;
5206 pr " fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
5209 pr " if (strncmp (r, expected, size) != 0) {\n";
5210 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
5214 List.iter (generate_test_command_call test_name) seq;
5215 generate_test_command_call ~test test_name last
5216 | TestOutputStruct (seq, checks) ->
5217 pr " /* TestOutputStruct for %s (%d) */\n" name i;
5218 let seq, last = get_seq_last seq in
5222 | CompareWithInt (field, expected) ->
5223 pr " if (r->%s != %d) {\n" field expected;
5224 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
5225 test_name field expected;
5226 pr " (int) r->%s);\n" field;
5229 | CompareWithIntOp (field, op, expected) ->
5230 pr " if (!(r->%s %s %d)) {\n" field op expected;
5231 pr " fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
5232 test_name field op expected;
5233 pr " (int) r->%s);\n" field;
5236 | CompareWithString (field, expected) ->
5237 pr " if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
5238 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
5239 test_name field expected;
5240 pr " r->%s);\n" field;
5243 | CompareFieldsIntEq (field1, field2) ->
5244 pr " if (r->%s != r->%s) {\n" field1 field2;
5245 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
5246 test_name field1 field2;
5247 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
5250 | CompareFieldsStrEq (field1, field2) ->
5251 pr " if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
5252 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
5253 test_name field1 field2;
5254 pr " r->%s, r->%s);\n" field1 field2;
5259 List.iter (generate_test_command_call test_name) seq;
5260 generate_test_command_call ~test test_name last
5261 | TestLastFail seq ->
5262 pr " /* TestLastFail for %s (%d) */\n" name i;
5263 let seq, last = get_seq_last seq in
5264 List.iter (generate_test_command_call test_name) seq;
5265 generate_test_command_call test_name ~expect_error:true last
5267 (* Generate the code to run a command, leaving the result in 'r'.
5268 * If you expect to get an error then you should set expect_error:true.
5270 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
5272 | [] -> assert false
5274 (* Look up the command to find out what args/ret it has. *)
5277 let _, style, _, _, _, _, _ =
5278 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
5281 failwithf "%s: in test, command %s was not found" test_name name in
5283 if List.length (snd style) <> List.length args then
5284 failwithf "%s: in test, wrong number of args given to %s"
5291 | OptString n, "NULL" -> ()
5293 | OptString n, arg ->
5294 pr " const char *%s = \"%s\";\n" n (c_quote arg);
5297 | FileIn _, _ | FileOut _, _ -> ()
5298 | StringList n, arg ->
5299 let strs = string_split " " arg in
5302 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
5304 pr " const char *%s[] = {\n" n;
5306 fun i _ -> pr " %s_%d,\n" n i
5310 ) (List.combine (snd style) args);
5313 match fst style with
5314 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
5315 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5316 | RConstString _ | RConstOptString _ ->
5317 pr " const char *r;\n"; "NULL"
5318 | RString _ -> pr " char *r;\n"; "NULL"
5319 | RStringList _ | RHashtable _ ->
5323 | RStruct (_, typ) ->
5324 pr " struct guestfs_%s *r;\n" typ; "NULL"
5325 | RStructList (_, typ) ->
5326 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
5329 pr " size_t size;\n";
5332 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
5333 pr " r = guestfs_%s (g" name;
5335 (* Generate the parameters. *)
5338 | OptString _, "NULL" -> pr ", NULL"
5342 | FileIn _, arg | FileOut _, arg ->
5343 pr ", \"%s\"" (c_quote arg)
5344 | StringList n, _ ->
5348 try int_of_string arg
5349 with Failure "int_of_string" ->
5350 failwithf "%s: expecting an int, but got '%s'" test_name arg in
5353 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
5354 ) (List.combine (snd style) args);
5356 (match fst style with
5357 | RBufferOut _ -> pr ", &size"
5363 if not expect_error then
5364 pr " if (r == %s)\n" error_code
5366 pr " if (r != %s)\n" error_code;
5369 (* Insert the test code. *)
5375 (match fst style with
5376 | RErr | RInt _ | RInt64 _ | RBool _
5377 | RConstString _ | RConstOptString _ -> ()
5378 | RString _ | RBufferOut _ -> pr " free (r);\n"
5379 | RStringList _ | RHashtable _ ->
5380 pr " for (i = 0; r[i] != NULL; ++i)\n";
5381 pr " free (r[i]);\n";
5383 | RStruct (_, typ) ->
5384 pr " guestfs_free_%s (r);\n" typ
5385 | RStructList (_, typ) ->
5386 pr " guestfs_free_%s_list (r);\n" typ
5392 let str = replace_str str "\r" "\\r" in
5393 let str = replace_str str "\n" "\\n" in
5394 let str = replace_str str "\t" "\\t" in
5395 let str = replace_str str "\000" "\\0" in
5398 (* Generate a lot of different functions for guestfish. *)
5399 and generate_fish_cmds () =
5400 generate_header CStyle GPLv2;
5404 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5406 let all_functions_sorted =
5408 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5409 ) all_functions_sorted in
5411 pr "#include <stdio.h>\n";
5412 pr "#include <stdlib.h>\n";
5413 pr "#include <string.h>\n";
5414 pr "#include <inttypes.h>\n";
5415 pr "#include <ctype.h>\n";
5417 pr "#include <guestfs.h>\n";
5418 pr "#include \"fish.h\"\n";
5421 (* list_commands function, which implements guestfish -h *)
5422 pr "void list_commands (void)\n";
5424 pr " printf (\" %%-16s %%s\\n\", \"Command\", \"Description\");\n";
5425 pr " list_builtin_commands ();\n";
5427 fun (name, _, _, flags, _, shortdesc, _) ->
5428 let name = replace_char name '_' '-' in
5429 pr " printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
5431 ) all_functions_sorted;
5432 pr " printf (\" Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
5436 (* display_command function, which implements guestfish -h cmd *)
5437 pr "void display_command (const char *cmd)\n";
5440 fun (name, style, _, flags, _, shortdesc, longdesc) ->
5441 let name2 = replace_char name '_' '-' in
5443 try find_map (function FishAlias n -> Some n | _ -> None) flags
5444 with Not_found -> name in
5445 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
5447 match snd style with
5451 name2 (String.concat "> <" (List.map name_of_argt args)) in
5454 if List.mem ProtocolLimitWarning flags then
5455 ("\n\n" ^ protocol_limit_warning)
5458 (* For DangerWillRobinson commands, we should probably have
5459 * guestfish prompt before allowing you to use them (especially
5460 * in interactive mode). XXX
5464 if List.mem DangerWillRobinson flags then
5465 ("\n\n" ^ danger_will_robinson)
5470 match deprecation_notice flags with
5472 | Some txt -> "\n\n" ^ txt in
5474 let describe_alias =
5475 if name <> alias then
5476 sprintf "\n\nYou can use '%s' as an alias for this command." alias
5480 pr "strcasecmp (cmd, \"%s\") == 0" name;
5481 if name <> name2 then
5482 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5483 if name <> alias then
5484 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5486 pr " pod2text (\"%s - %s\", %S);\n"
5488 (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
5491 pr " display_builtin_command (cmd);\n";
5495 (* print_* functions *)
5499 List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
5501 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
5510 pr " printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
5512 pr " printf (\"%s: \");\n" name;
5513 pr " for (i = 0; i < 32; ++i)\n";
5514 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
5515 pr " printf (\"\\n\");\n"
5517 pr " printf (\"%s: \");\n" name;
5518 pr " for (i = 0; i < %s->%s_len; ++i)\n" typ name;
5519 pr " if (isprint (%s->%s[i]))\n" typ name;
5520 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
5522 pr " printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
5523 pr " printf (\"\\n\");\n"
5524 | name, (FUInt64|FBytes) ->
5525 pr " printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
5527 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
5529 pr " printf (\"%s: %%\" PRIu32 \"\\n\", %s->%s);\n" name typ name
5531 pr " printf (\"%s: %%\" PRIi32 \"\\n\", %s->%s);\n" name typ name
5533 pr " printf (\"%s: %%c\\n\", %s->%s);\n" name typ name
5534 | name, FOptPercent ->
5535 pr " if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
5536 typ name name typ name;
5537 pr " else printf (\"%s: \\n\");\n" name
5541 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
5546 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
5547 pr " print_%s (&%ss->val[i]);\n" typ typ;
5552 (* run_<action> actions *)
5554 fun (name, style, _, flags, _, _, _) ->
5555 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
5557 (match fst style with
5560 | RBool _ -> pr " int r;\n"
5561 | RInt64 _ -> pr " int64_t r;\n"
5562 | RConstString _ | RConstOptString _ -> pr " const char *r;\n"
5563 | RString _ -> pr " char *r;\n"
5564 | RStringList _ | RHashtable _ -> pr " char **r;\n"
5565 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
5566 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
5569 pr " size_t size;\n";
5576 | FileOut n -> pr " const char *%s;\n" n
5577 | StringList n -> pr " char **%s;\n" n
5578 | Bool n -> pr " int %s;\n" n
5579 | Int n -> pr " int %s;\n" n
5582 (* Check and convert parameters. *)
5583 let argc_expected = List.length (snd style) in
5584 pr " if (argc != %d) {\n" argc_expected;
5585 pr " fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
5587 pr " fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
5593 | String name -> pr " %s = argv[%d];\n" name i
5595 pr " %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
5598 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
5601 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
5603 | StringList name ->
5604 pr " %s = parse_string_list (argv[%d]);\n" name i
5606 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
5608 pr " %s = atoi (argv[%d]);\n" name i
5611 (* Call C API function. *)
5613 try find_map (function FishAction n -> Some n | _ -> None) flags
5614 with Not_found -> sprintf "guestfs_%s" name in
5616 generate_c_call_args ~handle:"g" style;
5619 (* Check return value for errors and display command results. *)
5620 (match fst style with
5621 | RErr -> pr " return r;\n"
5623 pr " if (r == -1) return -1;\n";
5624 pr " printf (\"%%d\\n\", r);\n";
5627 pr " if (r == -1) return -1;\n";
5628 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
5631 pr " if (r == -1) return -1;\n";
5632 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
5635 pr " if (r == NULL) return -1;\n";
5636 pr " printf (\"%%s\\n\", r);\n";
5638 | RConstOptString _ ->
5639 pr " printf (\"%%s\\n\", r ? : \"(null)\");\n";
5642 pr " if (r == NULL) return -1;\n";
5643 pr " printf (\"%%s\\n\", r);\n";
5647 pr " if (r == NULL) return -1;\n";
5648 pr " print_strings (r);\n";
5649 pr " free_strings (r);\n";
5651 | RStruct (_, typ) ->
5652 pr " if (r == NULL) return -1;\n";
5653 pr " print_%s (r);\n" typ;
5654 pr " guestfs_free_%s (r);\n" typ;
5656 | RStructList (_, typ) ->
5657 pr " if (r == NULL) return -1;\n";
5658 pr " print_%s_list (r);\n" typ;
5659 pr " guestfs_free_%s_list (r);\n" typ;
5662 pr " if (r == NULL) return -1;\n";
5663 pr " print_table (r);\n";
5664 pr " free_strings (r);\n";
5667 pr " if (r == NULL) return -1;\n";
5668 pr " fwrite (r, size, 1, stdout);\n";
5676 (* run_action function *)
5677 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
5680 fun (name, _, _, flags, _, _, _) ->
5681 let name2 = replace_char name '_' '-' in
5683 try find_map (function FishAlias n -> Some n | _ -> None) flags
5684 with Not_found -> name in
5686 pr "strcasecmp (cmd, \"%s\") == 0" name;
5687 if name <> name2 then
5688 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5689 if name <> alias then
5690 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5692 pr " return run_%s (cmd, argc, argv);\n" name;
5696 pr " fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
5703 (* Readline completion for guestfish. *)
5704 and generate_fish_completion () =
5705 generate_header CStyle GPLv2;
5709 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5719 #ifdef HAVE_LIBREADLINE
5720 #include <readline/readline.h>
5725 #ifdef HAVE_LIBREADLINE
5727 static const char *const commands[] = {
5728 BUILTIN_COMMANDS_FOR_COMPLETION,
5731 (* Get the commands, including the aliases. They don't need to be
5732 * sorted - the generator() function just does a dumb linear search.
5736 fun (name, _, _, flags, _, _, _) ->
5737 let name2 = replace_char name '_' '-' in
5739 try find_map (function FishAlias n -> Some n | _ -> None) flags
5740 with Not_found -> name in
5742 if name <> alias then [name2; alias] else [name2]
5744 let commands = List.flatten commands in
5746 List.iter (pr " \"%s\",\n") commands;
5752 generator (const char *text, int state)
5754 static int index, len;
5759 len = strlen (text);
5762 rl_attempted_completion_over = 1;
5764 while ((name = commands[index]) != NULL) {
5766 if (strncasecmp (name, text, len) == 0)
5767 return strdup (name);
5773 #endif /* HAVE_LIBREADLINE */
5775 char **do_completion (const char *text, int start, int end)
5777 char **matches = NULL;
5779 #ifdef HAVE_LIBREADLINE
5780 rl_completion_append_character = ' ';
5783 matches = rl_completion_matches (text, generator);
5784 else if (complete_dest_paths)
5785 matches = rl_completion_matches (text, complete_dest_paths_generator);
5792 (* Generate the POD documentation for guestfish. *)
5793 and generate_fish_actions_pod () =
5794 let all_functions_sorted =
5796 fun (_, _, _, flags, _, _, _) ->
5797 not (List.mem NotInFish flags || List.mem NotInDocs flags)
5798 ) all_functions_sorted in
5800 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
5803 fun (name, style, _, flags, _, _, longdesc) ->
5805 Str.global_substitute rex (
5808 try Str.matched_group 1 s
5810 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
5811 "C<" ^ replace_char sub '_' '-' ^ ">"
5813 let name = replace_char name '_' '-' in
5815 try find_map (function FishAlias n -> Some n | _ -> None) flags
5816 with Not_found -> name in
5818 pr "=head2 %s" name;
5819 if name <> alias then
5826 | String n -> pr " %s" n
5827 | OptString n -> pr " %s" n
5828 | StringList n -> pr " '%s ...'" n
5829 | Bool _ -> pr " true|false"
5830 | Int n -> pr " %s" n
5831 | FileIn n | FileOut n -> pr " (%s|-)" n
5835 pr "%s\n\n" longdesc;
5837 if List.exists (function FileIn _ | FileOut _ -> true
5838 | _ -> false) (snd style) then
5839 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
5841 if List.mem ProtocolLimitWarning flags then
5842 pr "%s\n\n" protocol_limit_warning;
5844 if List.mem DangerWillRobinson flags then
5845 pr "%s\n\n" danger_will_robinson;
5847 match deprecation_notice flags with
5849 | Some txt -> pr "%s\n\n" txt
5850 ) all_functions_sorted
5852 (* Generate a C function prototype. *)
5853 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
5854 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
5856 ?handle name style =
5857 if extern then pr "extern ";
5858 if static then pr "static ";
5859 (match fst style with
5861 | RInt _ -> pr "int "
5862 | RInt64 _ -> pr "int64_t "
5863 | RBool _ -> pr "int "
5864 | RConstString _ | RConstOptString _ -> pr "const char *"
5865 | RString _ | RBufferOut _ -> pr "char *"
5866 | RStringList _ | RHashtable _ -> pr "char **"
5867 | RStruct (_, typ) ->
5868 if not in_daemon then pr "struct guestfs_%s *" typ
5869 else pr "guestfs_int_%s *" typ
5870 | RStructList (_, typ) ->
5871 if not in_daemon then pr "struct guestfs_%s_list *" typ
5872 else pr "guestfs_int_%s_list *" typ
5874 let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
5875 pr "%s%s (" prefix name;
5876 if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
5879 let comma = ref false in
5882 | Some handle -> pr "guestfs_h *%s" handle; comma := true
5886 if single_line then pr ", " else pr ",\n\t\t"
5895 if not in_daemon then pr "const char *%s" n
5896 else pr "char *%s" n
5899 if not in_daemon then pr "char * const* const %s" n
5900 else pr "char **%s" n
5901 | Bool n -> next (); pr "int %s" n
5902 | Int n -> next (); pr "int %s" n
5905 if not in_daemon then (next (); pr "const char *%s" n)
5907 if is_RBufferOut then (next (); pr "size_t *size_r");
5910 if semicolon then pr ";";
5911 if newline then pr "\n"
5913 (* Generate C call arguments, eg "(handle, foo, bar)" *)
5914 and generate_c_call_args ?handle ?(decl = false) style =
5916 let comma = ref false in
5918 if !comma then pr ", ";
5923 | Some handle -> pr "%s" handle; comma := true
5928 pr "%s" (name_of_argt arg)
5930 (* For RBufferOut calls, add implicit &size parameter. *)
5932 match fst style with
5940 (* Generate the OCaml bindings interface. *)
5941 and generate_ocaml_mli () =
5942 generate_header OCamlStyle LGPLv2;
5945 (** For API documentation you should refer to the C API
5946 in the guestfs(3) manual page. The OCaml API uses almost
5947 exactly the same calls. *)
5950 (** A [guestfs_h] handle. *)
5952 exception Error of string
5953 (** This exception is raised when there is an error. *)
5955 val create : unit -> t
5957 val close : t -> unit
5958 (** Handles are closed by the garbage collector when they become
5959 unreferenced, but callers can also call this in order to
5960 provide predictable cleanup. *)
5963 generate_ocaml_structure_decls ();
5967 fun (name, style, _, _, _, shortdesc, _) ->
5968 generate_ocaml_prototype name style;
5969 pr "(** %s *)\n" shortdesc;
5973 (* Generate the OCaml bindings implementation. *)
5974 and generate_ocaml_ml () =
5975 generate_header OCamlStyle LGPLv2;
5979 exception Error of string
5980 external create : unit -> t = \"ocaml_guestfs_create\"
5981 external close : t -> unit = \"ocaml_guestfs_close\"
5984 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
5988 generate_ocaml_structure_decls ();
5992 fun (name, style, _, _, _, shortdesc, _) ->
5993 generate_ocaml_prototype ~is_external:true name style;
5996 (* Generate the OCaml bindings C implementation. *)
5997 and generate_ocaml_c () =
5998 generate_header CStyle LGPLv2;
6005 #include <caml/config.h>
6006 #include <caml/alloc.h>
6007 #include <caml/callback.h>
6008 #include <caml/fail.h>
6009 #include <caml/memory.h>
6010 #include <caml/mlvalues.h>
6011 #include <caml/signals.h>
6013 #include <guestfs.h>
6015 #include \"guestfs_c.h\"
6017 /* Copy a hashtable of string pairs into an assoc-list. We return
6018 * the list in reverse order, but hashtables aren't supposed to be
6021 static CAMLprim value
6022 copy_table (char * const * argv)
6025 CAMLlocal5 (rv, pairv, kv, vv, cons);
6029 for (i = 0; argv[i] != NULL; i += 2) {
6030 kv = caml_copy_string (argv[i]);
6031 vv = caml_copy_string (argv[i+1]);
6032 pairv = caml_alloc (2, 0);
6033 Store_field (pairv, 0, kv);
6034 Store_field (pairv, 1, vv);
6035 cons = caml_alloc (2, 0);
6036 Store_field (cons, 1, rv);
6038 Store_field (cons, 0, pairv);
6046 (* Struct copy functions. *)
6049 let has_optpercent_col =
6050 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
6052 pr "static CAMLprim value\n";
6053 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
6055 pr " CAMLparam0 ();\n";
6056 if has_optpercent_col then
6057 pr " CAMLlocal3 (rv, v, v2);\n"
6059 pr " CAMLlocal2 (rv, v);\n";
6061 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
6066 pr " v = caml_copy_string (%s->%s);\n" typ name
6068 pr " v = caml_alloc_string (%s->%s_len);\n" typ name;
6069 pr " memcpy (String_val (v), %s->%s, %s->%s_len);\n"
6072 pr " v = caml_alloc_string (32);\n";
6073 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
6074 | name, (FBytes|FInt64|FUInt64) ->
6075 pr " v = caml_copy_int64 (%s->%s);\n" typ name
6076 | name, (FInt32|FUInt32) ->
6077 pr " v = caml_copy_int32 (%s->%s);\n" typ name
6078 | name, FOptPercent ->
6079 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
6080 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
6081 pr " v = caml_alloc (1, 0);\n";
6082 pr " Store_field (v, 0, v2);\n";
6083 pr " } else /* None */\n";
6084 pr " v = Val_int (0);\n";
6086 pr " v = Val_int (%s->%s);\n" typ name
6088 pr " Store_field (rv, %d, v);\n" i
6090 pr " CAMLreturn (rv);\n";
6094 pr "static CAMLprim value\n";
6095 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n"
6098 pr " CAMLparam0 ();\n";
6099 pr " CAMLlocal2 (rv, v);\n";
6102 pr " if (%ss->len == 0)\n" typ;
6103 pr " CAMLreturn (Atom (0));\n";
6105 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
6106 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
6107 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
6108 pr " caml_modify (&Field (rv, i), v);\n";
6110 pr " CAMLreturn (rv);\n";
6118 fun (name, style, _, _, _, _, _) ->
6120 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
6122 let needs_extra_vs =
6123 match fst style with RConstOptString _ -> true | _ -> false in
6125 pr "CAMLprim value\n";
6126 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
6127 List.iter (pr ", value %s") (List.tl params);
6132 | [p1; p2; p3; p4; p5] ->
6133 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
6134 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
6135 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
6136 pr " CAMLxparam%d (%s);\n"
6137 (List.length rest) (String.concat ", " rest)
6139 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
6141 if not needs_extra_vs then
6142 pr " CAMLlocal1 (rv);\n"
6144 pr " CAMLlocal3 (rv, v, v2);\n";
6147 pr " guestfs_h *g = Guestfs_val (gv);\n";
6148 pr " if (g == NULL)\n";
6149 pr " caml_failwith (\"%s: used handle after closing it\");\n" name;
6157 pr " const char *%s = String_val (%sv);\n" n n
6159 pr " const char *%s =\n" n;
6160 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
6163 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
6165 pr " int %s = Bool_val (%sv);\n" n n
6167 pr " int %s = Int_val (%sv);\n" n n
6170 match fst style with
6171 | RErr -> pr " int r;\n"; "-1"
6172 | RInt _ -> pr " int r;\n"; "-1"
6173 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6174 | RBool _ -> pr " int r;\n"; "-1"
6175 | RConstString _ | RConstOptString _ ->
6176 pr " const char *r;\n"; "NULL"
6177 | RString _ -> pr " char *r;\n"; "NULL"
6182 | RStruct (_, typ) ->
6183 pr " struct guestfs_%s *r;\n" typ; "NULL"
6184 | RStructList (_, typ) ->
6185 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
6192 pr " size_t size;\n";
6196 pr " caml_enter_blocking_section ();\n";
6197 pr " r = guestfs_%s " name;
6198 generate_c_call_args ~handle:"g" style;
6200 pr " caml_leave_blocking_section ();\n";
6205 pr " ocaml_guestfs_free_strings (%s);\n" n;
6206 | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
6209 pr " if (r == %s)\n" error_code;
6210 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
6213 (match fst style with
6214 | RErr -> pr " rv = Val_unit;\n"
6215 | RInt _ -> pr " rv = Val_int (r);\n"
6217 pr " rv = caml_copy_int64 (r);\n"
6218 | RBool _ -> pr " rv = Val_bool (r);\n"
6220 pr " rv = caml_copy_string (r);\n"
6221 | RConstOptString _ ->
6222 pr " if (r) { /* Some string */\n";
6223 pr " v = caml_alloc (1, 0);\n";
6224 pr " v2 = caml_copy_string (r);\n";
6225 pr " Store_field (v, 0, v2);\n";
6226 pr " } else /* None */\n";
6227 pr " v = Val_int (0);\n";
6229 pr " rv = caml_copy_string (r);\n";
6232 pr " rv = caml_copy_string_array ((const char **) r);\n";
6233 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6235 | RStruct (_, typ) ->
6236 pr " rv = copy_%s (r);\n" typ;
6237 pr " guestfs_free_%s (r);\n" typ;
6238 | RStructList (_, typ) ->
6239 pr " rv = copy_%s_list (r);\n" typ;
6240 pr " guestfs_free_%s_list (r);\n" typ;
6242 pr " rv = copy_table (r);\n";
6243 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6246 pr " rv = caml_alloc_string (size);\n";
6247 pr " memcpy (String_val (rv), r, size);\n";
6250 pr " CAMLreturn (rv);\n";
6254 if List.length params > 5 then (
6255 pr "CAMLprim value\n";
6256 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
6258 pr " return ocaml_guestfs_%s (argv[0]" name;
6259 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
6266 and generate_ocaml_structure_decls () =
6269 pr "type %s = {\n" typ;
6272 | name, FString -> pr " %s : string;\n" name
6273 | name, FBuffer -> pr " %s : string;\n" name
6274 | name, FUUID -> pr " %s : string;\n" name
6275 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
6276 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
6277 | name, FChar -> pr " %s : char;\n" name
6278 | name, FOptPercent -> pr " %s : float option;\n" name
6284 and generate_ocaml_prototype ?(is_external = false) name style =
6285 if is_external then pr "external " else pr "val ";
6286 pr "%s : t -> " name;
6289 | String _ | FileIn _ | FileOut _ -> pr "string -> "
6290 | OptString _ -> pr "string option -> "
6291 | StringList _ -> pr "string array -> "
6292 | Bool _ -> pr "bool -> "
6293 | Int _ -> pr "int -> "
6295 (match fst style with
6296 | RErr -> pr "unit" (* all errors are turned into exceptions *)
6297 | RInt _ -> pr "int"
6298 | RInt64 _ -> pr "int64"
6299 | RBool _ -> pr "bool"
6300 | RConstString _ -> pr "string"
6301 | RConstOptString _ -> pr "string option"
6302 | RString _ | RBufferOut _ -> pr "string"
6303 | RStringList _ -> pr "string array"
6304 | RStruct (_, typ) -> pr "%s" typ
6305 | RStructList (_, typ) -> pr "%s array" typ
6306 | RHashtable _ -> pr "(string * string) list"
6308 if is_external then (
6310 if List.length (snd style) + 1 > 5 then
6311 pr "\"ocaml_guestfs_%s_byte\" " name;
6312 pr "\"ocaml_guestfs_%s\"" name
6316 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
6317 and generate_perl_xs () =
6318 generate_header CStyle LGPLv2;
6321 #include \"EXTERN.h\"
6325 #include <guestfs.h>
6328 #define PRId64 \"lld\"
6332 my_newSVll(long long val) {
6333 #ifdef USE_64_BIT_ALL
6334 return newSViv(val);
6338 len = snprintf(buf, 100, \"%%\" PRId64, val);
6339 return newSVpv(buf, len);
6344 #define PRIu64 \"llu\"
6348 my_newSVull(unsigned long long val) {
6349 #ifdef USE_64_BIT_ALL
6350 return newSVuv(val);
6354 len = snprintf(buf, 100, \"%%\" PRIu64, val);
6355 return newSVpv(buf, len);
6359 /* http://www.perlmonks.org/?node_id=680842 */
6361 XS_unpack_charPtrPtr (SV *arg) {
6366 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
6367 croak (\"array reference expected\");
6369 av = (AV *)SvRV (arg);
6370 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
6372 croak (\"malloc failed\");
6374 for (i = 0; i <= av_len (av); i++) {
6375 SV **elem = av_fetch (av, i, 0);
6377 if (!elem || !*elem)
6378 croak (\"missing element in list\");
6380 ret[i] = SvPV_nolen (*elem);
6388 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
6395 RETVAL = guestfs_create ();
6397 croak (\"could not create guestfs handle\");
6398 guestfs_set_error_handler (RETVAL, NULL, NULL);
6411 fun (name, style, _, _, _, _, _) ->
6412 (match fst style with
6413 | RErr -> pr "void\n"
6414 | RInt _ -> pr "SV *\n"
6415 | RInt64 _ -> pr "SV *\n"
6416 | RBool _ -> pr "SV *\n"
6417 | RConstString _ -> pr "SV *\n"
6418 | RConstOptString _ -> pr "SV *\n"
6419 | RString _ -> pr "SV *\n"
6420 | RBufferOut _ -> pr "SV *\n"
6422 | RStruct _ | RStructList _
6424 pr "void\n" (* all lists returned implictly on the stack *)
6426 (* Call and arguments. *)
6428 generate_c_call_args ~handle:"g" ~decl:true style;
6430 pr " guestfs_h *g;\n";
6434 | String n | FileIn n | FileOut n -> pr " char *%s;\n" n
6436 (* http://www.perlmonks.org/?node_id=554277
6437 * Note that the implicit handle argument means we have
6438 * to add 1 to the ST(x) operator.
6440 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
6441 | StringList n -> pr " char **%s;\n" n
6442 | Bool n -> pr " int %s;\n" n
6443 | Int n -> pr " int %s;\n" n
6446 let do_cleanups () =
6449 | String _ | OptString _ | Bool _ | Int _
6450 | FileIn _ | FileOut _ -> ()
6451 | StringList n -> pr " free (%s);\n" n
6456 (match fst style with
6461 pr " r = guestfs_%s " name;
6462 generate_c_call_args ~handle:"g" style;
6465 pr " if (r == -1)\n";
6466 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6472 pr " %s = guestfs_%s " n name;
6473 generate_c_call_args ~handle:"g" style;
6476 pr " if (%s == -1)\n" n;
6477 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6478 pr " RETVAL = newSViv (%s);\n" n;
6483 pr " int64_t %s;\n" n;
6485 pr " %s = guestfs_%s " n name;
6486 generate_c_call_args ~handle:"g" style;
6489 pr " if (%s == -1)\n" n;
6490 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6491 pr " RETVAL = my_newSVll (%s);\n" n;
6496 pr " const char *%s;\n" n;
6498 pr " %s = guestfs_%s " n name;
6499 generate_c_call_args ~handle:"g" style;
6502 pr " if (%s == NULL)\n" n;
6503 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6504 pr " RETVAL = newSVpv (%s, 0);\n" n;
6507 | RConstOptString n ->
6509 pr " const char *%s;\n" n;
6511 pr " %s = guestfs_%s " n name;
6512 generate_c_call_args ~handle:"g" style;
6515 pr " if (%s == NULL)\n" n;
6516 pr " RETVAL = &PL_sv_undef;\n";
6518 pr " RETVAL = newSVpv (%s, 0);\n" n;
6523 pr " char *%s;\n" n;
6525 pr " %s = guestfs_%s " n name;
6526 generate_c_call_args ~handle:"g" style;
6529 pr " if (%s == NULL)\n" n;
6530 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6531 pr " RETVAL = newSVpv (%s, 0);\n" n;
6532 pr " free (%s);\n" n;
6535 | RStringList n | RHashtable n ->
6537 pr " char **%s;\n" n;
6540 pr " %s = guestfs_%s " n name;
6541 generate_c_call_args ~handle:"g" style;
6544 pr " if (%s == NULL)\n" n;
6545 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6546 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
6547 pr " EXTEND (SP, n);\n";
6548 pr " for (i = 0; i < n; ++i) {\n";
6549 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
6550 pr " free (%s[i]);\n" n;
6552 pr " free (%s);\n" n;
6553 | RStruct (n, typ) ->
6554 let cols = cols_of_struct typ in
6555 generate_perl_struct_code typ cols name style n do_cleanups
6556 | RStructList (n, typ) ->
6557 let cols = cols_of_struct typ in
6558 generate_perl_struct_list_code typ cols name style n do_cleanups
6561 pr " char *%s;\n" n;
6562 pr " size_t size;\n";
6564 pr " %s = guestfs_%s " n name;
6565 generate_c_call_args ~handle:"g" style;
6568 pr " if (%s == NULL)\n" n;
6569 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6570 pr " RETVAL = newSVpv (%s, size);\n" n;
6571 pr " free (%s);\n" n;
6579 and generate_perl_struct_list_code typ cols name style n do_cleanups =
6581 pr " struct guestfs_%s_list *%s;\n" typ n;
6585 pr " %s = guestfs_%s " n name;
6586 generate_c_call_args ~handle:"g" style;
6589 pr " if (%s == NULL)\n" n;
6590 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6591 pr " EXTEND (SP, %s->len);\n" n;
6592 pr " for (i = 0; i < %s->len; ++i) {\n" n;
6593 pr " hv = newHV ();\n";
6597 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
6598 name (String.length name) n name
6600 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
6601 name (String.length name) n name
6603 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
6604 name (String.length name) n name n name
6605 | name, (FBytes|FUInt64) ->
6606 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
6607 name (String.length name) n name
6609 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
6610 name (String.length name) n name
6611 | name, (FInt32|FUInt32) ->
6612 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6613 name (String.length name) n name
6615 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
6616 name (String.length name) n name
6617 | name, FOptPercent ->
6618 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6619 name (String.length name) n name
6621 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
6623 pr " guestfs_free_%s_list (%s);\n" typ n
6625 and generate_perl_struct_code typ cols name style n do_cleanups =
6627 pr " struct guestfs_%s *%s;\n" typ n;
6629 pr " %s = guestfs_%s " n name;
6630 generate_c_call_args ~handle:"g" style;
6633 pr " if (%s == NULL)\n" n;
6634 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6635 pr " EXTEND (SP, 2 * %d);\n" (List.length cols);
6637 fun ((name, _) as col) ->
6638 pr " PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
6642 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
6645 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, %s->%s_len)));\n"
6648 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
6650 | name, (FBytes|FUInt64) ->
6651 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
6654 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
6656 | name, (FInt32|FUInt32) ->
6657 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6660 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
6662 | name, FOptPercent ->
6663 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6666 pr " free (%s);\n" n
6668 (* Generate Sys/Guestfs.pm. *)
6669 and generate_perl_pm () =
6670 generate_header HashStyle LGPLv2;
6677 Sys::Guestfs - Perl bindings for libguestfs
6683 my $h = Sys::Guestfs->new ();
6684 $h->add_drive ('guest.img');
6687 $h->mount ('/dev/sda1', '/');
6688 $h->touch ('/hello');
6693 The C<Sys::Guestfs> module provides a Perl XS binding to the
6694 libguestfs API for examining and modifying virtual machine
6697 Amongst the things this is good for: making batch configuration
6698 changes to guests, getting disk used/free statistics (see also:
6699 virt-df), migrating between virtualization systems (see also:
6700 virt-p2v), performing partial backups, performing partial guest
6701 clones, cloning guests and changing registry/UUID/hostname info, and
6704 Libguestfs uses Linux kernel and qemu code, and can access any type of
6705 guest filesystem that Linux and qemu can, including but not limited
6706 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6707 schemes, qcow, qcow2, vmdk.
6709 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6710 LVs, what filesystem is in each LV, etc.). It can also run commands
6711 in the context of the guest. Also you can access filesystems over FTP.
6713 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
6714 functions for using libguestfs from Perl, including integration
6719 All errors turn into calls to C<croak> (see L<Carp(3)>).
6727 package Sys::Guestfs;
6733 XSLoader::load ('Sys::Guestfs');
6735 =item $h = Sys::Guestfs->new ();
6737 Create a new guestfs handle.
6743 my $class = ref ($proto) || $proto;
6745 my $self = Sys::Guestfs::_create ();
6746 bless $self, $class;
6752 (* Actions. We only need to print documentation for these as
6753 * they are pulled in from the XS code automatically.
6756 fun (name, style, _, flags, _, _, longdesc) ->
6757 if not (List.mem NotInDocs flags) then (
6758 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
6760 generate_perl_prototype name style;
6762 pr "%s\n\n" longdesc;
6763 if List.mem ProtocolLimitWarning flags then
6764 pr "%s\n\n" protocol_limit_warning;
6765 if List.mem DangerWillRobinson flags then
6766 pr "%s\n\n" danger_will_robinson;
6767 match deprecation_notice flags with
6769 | Some txt -> pr "%s\n\n" txt
6771 ) all_functions_sorted;
6783 Copyright (C) 2009 Red Hat Inc.
6787 Please see the file COPYING.LIB for the full license.
6793 L<http://libguestfs.org>,
6794 L<Sys::Guestfs::Lib(3)>.
6799 and generate_perl_prototype name style =
6800 (match fst style with
6808 | RBufferOut n -> pr "$%s = " n
6810 | RHashtable n -> pr "%%%s = " n
6812 | RStructList (n,_) -> pr "@%s = " n
6815 let comma = ref false in
6818 if !comma then pr ", ";
6821 | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
6828 (* Generate Python C module. *)
6829 and generate_python_c () =
6830 generate_header CStyle LGPLv2;
6839 #include \"guestfs.h\"
6847 get_handle (PyObject *obj)
6850 assert (obj != Py_None);
6851 return ((Pyguestfs_Object *) obj)->g;
6855 put_handle (guestfs_h *g)
6859 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
6862 /* This list should be freed (but not the strings) after use. */
6863 static const char **
6864 get_string_list (PyObject *obj)
6871 if (!PyList_Check (obj)) {
6872 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
6876 len = PyList_Size (obj);
6877 r = malloc (sizeof (char *) * (len+1));
6879 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
6883 for (i = 0; i < len; ++i)
6884 r[i] = PyString_AsString (PyList_GetItem (obj, i));
6891 put_string_list (char * const * const argv)
6896 for (argc = 0; argv[argc] != NULL; ++argc)
6899 list = PyList_New (argc);
6900 for (i = 0; i < argc; ++i)
6901 PyList_SetItem (list, i, PyString_FromString (argv[i]));
6907 put_table (char * const * const argv)
6909 PyObject *list, *item;
6912 for (argc = 0; argv[argc] != NULL; ++argc)
6915 list = PyList_New (argc >> 1);
6916 for (i = 0; i < argc; i += 2) {
6917 item = PyTuple_New (2);
6918 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
6919 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
6920 PyList_SetItem (list, i >> 1, item);
6927 free_strings (char **argv)
6931 for (argc = 0; argv[argc] != NULL; ++argc)
6937 py_guestfs_create (PyObject *self, PyObject *args)
6941 g = guestfs_create ();
6943 PyErr_SetString (PyExc_RuntimeError,
6944 \"guestfs.create: failed to allocate handle\");
6947 guestfs_set_error_handler (g, NULL, NULL);
6948 return put_handle (g);
6952 py_guestfs_close (PyObject *self, PyObject *args)
6957 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
6959 g = get_handle (py_g);
6963 Py_INCREF (Py_None);
6969 (* Structures, turned into Python dictionaries. *)
6972 pr "static PyObject *\n";
6973 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
6975 pr " PyObject *dict;\n";
6977 pr " dict = PyDict_New ();\n";
6981 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6982 pr " PyString_FromString (%s->%s));\n"
6985 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6986 pr " PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
6989 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6990 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
6992 | name, (FBytes|FUInt64) ->
6993 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6994 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
6997 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6998 pr " PyLong_FromLongLong (%s->%s));\n"
7001 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
7002 pr " PyLong_FromUnsignedLong (%s->%s));\n"
7005 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
7006 pr " PyLong_FromLong (%s->%s));\n"
7008 | name, FOptPercent ->
7009 pr " if (%s->%s >= 0)\n" typ name;
7010 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
7011 pr " PyFloat_FromDouble ((double) %s->%s));\n"
7014 pr " Py_INCREF (Py_None);\n";
7015 pr " PyDict_SetItemString (dict, \"%s\", Py_None);" name;
7018 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
7019 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
7021 pr " return dict;\n";
7025 pr "static PyObject *\n";
7026 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
7028 pr " PyObject *list;\n";
7031 pr " list = PyList_New (%ss->len);\n" typ;
7032 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
7033 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
7034 pr " return list;\n";
7039 (* Python wrapper functions. *)
7041 fun (name, style, _, _, _, _, _) ->
7042 pr "static PyObject *\n";
7043 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
7046 pr " PyObject *py_g;\n";
7047 pr " guestfs_h *g;\n";
7048 pr " PyObject *py_r;\n";
7051 match fst style with
7052 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
7053 | RInt64 _ -> pr " int64_t r;\n"; "-1"
7054 | RConstString _ | RConstOptString _ ->
7055 pr " const char *r;\n"; "NULL"
7056 | RString _ -> pr " char *r;\n"; "NULL"
7057 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
7058 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
7059 | RStructList (_, typ) ->
7060 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
7063 pr " size_t size;\n";
7068 | String n | FileIn n | FileOut n -> pr " const char *%s;\n" n
7069 | OptString n -> pr " const char *%s;\n" n
7071 pr " PyObject *py_%s;\n" n;
7072 pr " const char **%s;\n" n
7073 | Bool n -> pr " int %s;\n" n
7074 | Int n -> pr " int %s;\n" n
7079 (* Convert the parameters. *)
7080 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
7083 | String _ | FileIn _ | FileOut _ -> pr "s"
7084 | OptString _ -> pr "z"
7085 | StringList _ -> pr "O"
7086 | Bool _ -> pr "i" (* XXX Python has booleans? *)
7089 pr ":guestfs_%s\",\n" name;
7093 | String n | FileIn n | FileOut n -> pr ", &%s" n
7094 | OptString n -> pr ", &%s" n
7095 | StringList n -> pr ", &py_%s" n
7096 | Bool n -> pr ", &%s" n
7097 | Int n -> pr ", &%s" n
7101 pr " return NULL;\n";
7103 pr " g = get_handle (py_g);\n";
7106 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7108 pr " %s = get_string_list (py_%s);\n" n n;
7109 pr " if (!%s) return NULL;\n" n
7114 pr " r = guestfs_%s " name;
7115 generate_c_call_args ~handle:"g" style;
7120 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7122 pr " free (%s);\n" n
7125 pr " if (r == %s) {\n" error_code;
7126 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
7127 pr " return NULL;\n";
7131 (match fst style with
7133 pr " Py_INCREF (Py_None);\n";
7134 pr " py_r = Py_None;\n"
7136 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
7137 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
7138 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
7139 | RConstOptString _ ->
7141 pr " py_r = PyString_FromString (r);\n";
7143 pr " Py_INCREF (Py_None);\n";
7144 pr " py_r = Py_None;\n";
7147 pr " py_r = PyString_FromString (r);\n";
7150 pr " py_r = put_string_list (r);\n";
7151 pr " free_strings (r);\n"
7152 | RStruct (_, typ) ->
7153 pr " py_r = put_%s (r);\n" typ;
7154 pr " guestfs_free_%s (r);\n" typ
7155 | RStructList (_, typ) ->
7156 pr " py_r = put_%s_list (r);\n" typ;
7157 pr " guestfs_free_%s_list (r);\n" typ
7159 pr " py_r = put_table (r);\n";
7160 pr " free_strings (r);\n"
7162 pr " py_r = PyString_FromStringAndSize (r, size);\n";
7166 pr " return py_r;\n";
7171 (* Table of functions. *)
7172 pr "static PyMethodDef methods[] = {\n";
7173 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
7174 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
7176 fun (name, _, _, _, _, _, _) ->
7177 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
7180 pr " { NULL, NULL, 0, NULL }\n";
7184 (* Init function. *)
7187 initlibguestfsmod (void)
7189 static int initialized = 0;
7191 if (initialized) return;
7192 Py_InitModule ((char *) \"libguestfsmod\", methods);
7197 (* Generate Python module. *)
7198 and generate_python_py () =
7199 generate_header HashStyle LGPLv2;
7202 u\"\"\"Python bindings for libguestfs
7205 g = guestfs.GuestFS ()
7206 g.add_drive (\"guest.img\")
7209 parts = g.list_partitions ()
7211 The guestfs module provides a Python binding to the libguestfs API
7212 for examining and modifying virtual machine disk images.
7214 Amongst the things this is good for: making batch configuration
7215 changes to guests, getting disk used/free statistics (see also:
7216 virt-df), migrating between virtualization systems (see also:
7217 virt-p2v), performing partial backups, performing partial guest
7218 clones, cloning guests and changing registry/UUID/hostname info, and
7221 Libguestfs uses Linux kernel and qemu code, and can access any type of
7222 guest filesystem that Linux and qemu can, including but not limited
7223 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
7224 schemes, qcow, qcow2, vmdk.
7226 Libguestfs provides ways to enumerate guest storage (eg. partitions,
7227 LVs, what filesystem is in each LV, etc.). It can also run commands
7228 in the context of the guest. Also you can access filesystems over FTP.
7230 Errors which happen while using the API are turned into Python
7231 RuntimeError exceptions.
7233 To create a guestfs handle you usually have to perform the following
7236 # Create the handle, call add_drive at least once, and possibly
7237 # several times if the guest has multiple block devices:
7238 g = guestfs.GuestFS ()
7239 g.add_drive (\"guest.img\")
7241 # Launch the qemu subprocess and wait for it to become ready:
7245 # Now you can issue commands, for example:
7250 import libguestfsmod
7253 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
7255 def __init__ (self):
7256 \"\"\"Create a new libguestfs handle.\"\"\"
7257 self._o = libguestfsmod.create ()
7260 libguestfsmod.close (self._o)
7265 fun (name, style, _, flags, _, _, longdesc) ->
7267 generate_py_call_args ~handle:"self" (snd style);
7270 if not (List.mem NotInDocs flags) then (
7271 let doc = replace_str longdesc "C<guestfs_" "C<g." in
7273 match fst style with
7274 | RErr | RInt _ | RInt64 _ | RBool _
7275 | RConstOptString _ | RConstString _
7276 | RString _ | RBufferOut _ -> doc
7278 doc ^ "\n\nThis function returns a list of strings."
7279 | RStruct (_, typ) ->
7280 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
7281 | RStructList (_, typ) ->
7282 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
7284 doc ^ "\n\nThis function returns a dictionary." in
7286 if List.mem ProtocolLimitWarning flags then
7287 doc ^ "\n\n" ^ protocol_limit_warning
7290 if List.mem DangerWillRobinson flags then
7291 doc ^ "\n\n" ^ danger_will_robinson
7294 match deprecation_notice flags with
7296 | Some txt -> doc ^ "\n\n" ^ txt in
7297 let doc = pod2text ~width:60 name doc in
7298 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
7299 let doc = String.concat "\n " doc in
7300 pr " u\"\"\"%s\"\"\"\n" doc;
7302 pr " return libguestfsmod.%s " name;
7303 generate_py_call_args ~handle:"self._o" (snd style);
7308 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
7309 and generate_py_call_args ~handle args =
7311 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7314 (* Useful if you need the longdesc POD text as plain text. Returns a
7317 * Because this is very slow (the slowest part of autogeneration),
7318 * we memoize the results.
7320 and pod2text ~width name longdesc =
7321 let key = width, name, longdesc in
7322 try Hashtbl.find pod2text_memo key
7324 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
7325 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
7327 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
7328 let chan = Unix.open_process_in cmd in
7329 let lines = ref [] in
7331 let line = input_line chan in
7332 if i = 1 then (* discard the first line of output *)
7335 let line = triml line in
7336 lines := line :: !lines;
7339 let lines = try loop 1 with End_of_file -> List.rev !lines in
7340 Unix.unlink filename;
7341 (match Unix.close_process_in chan with
7342 | Unix.WEXITED 0 -> ()
7344 failwithf "pod2text: process exited with non-zero status (%d)" i
7345 | Unix.WSIGNALED i | Unix.WSTOPPED i ->
7346 failwithf "pod2text: process signalled or stopped by signal %d" i
7348 Hashtbl.add pod2text_memo key lines;
7349 let chan = open_out pod2text_memo_filename in
7350 output_value chan pod2text_memo;
7354 (* Generate ruby bindings. *)
7355 and generate_ruby_c () =
7356 generate_header CStyle LGPLv2;
7364 #include \"guestfs.h\"
7366 #include \"extconf.h\"
7368 /* For Ruby < 1.9 */
7370 #define RARRAY_LEN(r) (RARRAY((r))->len)
7373 static VALUE m_guestfs; /* guestfs module */
7374 static VALUE c_guestfs; /* guestfs_h handle */
7375 static VALUE e_Error; /* used for all errors */
7377 static void ruby_guestfs_free (void *p)
7380 guestfs_close ((guestfs_h *) p);
7383 static VALUE ruby_guestfs_create (VALUE m)
7387 g = guestfs_create ();
7389 rb_raise (e_Error, \"failed to create guestfs handle\");
7391 /* Don't print error messages to stderr by default. */
7392 guestfs_set_error_handler (g, NULL, NULL);
7394 /* Wrap it, and make sure the close function is called when the
7397 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
7400 static VALUE ruby_guestfs_close (VALUE gv)
7403 Data_Get_Struct (gv, guestfs_h, g);
7405 ruby_guestfs_free (g);
7406 DATA_PTR (gv) = NULL;
7414 fun (name, style, _, _, _, _, _) ->
7415 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
7416 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
7419 pr " guestfs_h *g;\n";
7420 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
7422 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
7428 | String n | FileIn n | FileOut n ->
7429 pr " Check_Type (%sv, T_STRING);\n" n;
7430 pr " const char *%s = StringValueCStr (%sv);\n" n n;
7432 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
7433 pr " \"%s\", \"%s\");\n" n name
7435 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
7437 pr " char **%s;\n" n;
7438 pr " Check_Type (%sv, T_ARRAY);\n" n;
7440 pr " int i, len;\n";
7441 pr " len = RARRAY_LEN (%sv);\n" n;
7442 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
7444 pr " for (i = 0; i < len; ++i) {\n";
7445 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
7446 pr " %s[i] = StringValueCStr (v);\n" n;
7448 pr " %s[len] = NULL;\n" n;
7451 pr " int %s = RTEST (%sv);\n" n n
7453 pr " int %s = NUM2INT (%sv);\n" n n
7458 match fst style with
7459 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
7460 | RInt64 _ -> pr " int64_t r;\n"; "-1"
7461 | RConstString _ | RConstOptString _ ->
7462 pr " const char *r;\n"; "NULL"
7463 | RString _ -> pr " char *r;\n"; "NULL"
7464 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
7465 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
7466 | RStructList (_, typ) ->
7467 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
7470 pr " size_t size;\n";
7474 pr " r = guestfs_%s " name;
7475 generate_c_call_args ~handle:"g" style;
7480 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7482 pr " free (%s);\n" n
7485 pr " if (r == %s)\n" error_code;
7486 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
7489 (match fst style with
7491 pr " return Qnil;\n"
7492 | RInt _ | RBool _ ->
7493 pr " return INT2NUM (r);\n"
7495 pr " return ULL2NUM (r);\n"
7497 pr " return rb_str_new2 (r);\n";
7498 | RConstOptString _ ->
7500 pr " return rb_str_new2 (r);\n";
7502 pr " return Qnil;\n";
7504 pr " VALUE rv = rb_str_new2 (r);\n";
7508 pr " int i, len = 0;\n";
7509 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
7510 pr " VALUE rv = rb_ary_new2 (len);\n";
7511 pr " for (i = 0; r[i] != NULL; ++i) {\n";
7512 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
7513 pr " free (r[i]);\n";
7517 | RStruct (_, typ) ->
7518 let cols = cols_of_struct typ in
7519 generate_ruby_struct_code typ cols
7520 | RStructList (_, typ) ->
7521 let cols = cols_of_struct typ in
7522 generate_ruby_struct_list_code typ cols
7524 pr " VALUE rv = rb_hash_new ();\n";
7526 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
7527 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
7528 pr " free (r[i]);\n";
7529 pr " free (r[i+1]);\n";
7534 pr " VALUE rv = rb_str_new (r, size);\n";
7544 /* Initialize the module. */
7545 void Init__guestfs ()
7547 m_guestfs = rb_define_module (\"Guestfs\");
7548 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
7549 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
7551 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
7552 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
7555 (* Define the rest of the methods. *)
7557 fun (name, style, _, _, _, _, _) ->
7558 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
7559 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
7564 (* Ruby code to return a struct. *)
7565 and generate_ruby_struct_code typ cols =
7566 pr " VALUE rv = rb_hash_new ();\n";
7570 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
7572 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
7574 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
7575 | name, (FBytes|FUInt64) ->
7576 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7578 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
7580 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
7582 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
7583 | name, FOptPercent ->
7584 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
7585 | name, FChar -> (* XXX wrong? *)
7586 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7588 pr " guestfs_free_%s (r);\n" typ;
7591 (* Ruby code to return a struct list. *)
7592 and generate_ruby_struct_list_code typ cols =
7593 pr " VALUE rv = rb_ary_new2 (r->len);\n";
7595 pr " for (i = 0; i < r->len; ++i) {\n";
7596 pr " VALUE hv = rb_hash_new ();\n";
7600 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
7602 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
7604 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
7605 | name, (FBytes|FUInt64) ->
7606 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7608 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
7610 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
7612 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
7613 | name, FOptPercent ->
7614 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
7615 | name, FChar -> (* XXX wrong? *)
7616 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7618 pr " rb_ary_push (rv, hv);\n";
7620 pr " guestfs_free_%s_list (r);\n" typ;
7623 (* Generate Java bindings GuestFS.java file. *)
7624 and generate_java_java () =
7625 generate_header CStyle LGPLv2;
7628 package com.redhat.et.libguestfs;
7630 import java.util.HashMap;
7631 import com.redhat.et.libguestfs.LibGuestFSException;
7632 import com.redhat.et.libguestfs.PV;
7633 import com.redhat.et.libguestfs.VG;
7634 import com.redhat.et.libguestfs.LV;
7635 import com.redhat.et.libguestfs.Stat;
7636 import com.redhat.et.libguestfs.StatVFS;
7637 import com.redhat.et.libguestfs.IntBool;
7638 import com.redhat.et.libguestfs.Dirent;
7641 * The GuestFS object is a libguestfs handle.
7645 public class GuestFS {
7646 // Load the native code.
7648 System.loadLibrary (\"guestfs_jni\");
7652 * The native guestfs_h pointer.
7657 * Create a libguestfs handle.
7659 * @throws LibGuestFSException
7661 public GuestFS () throws LibGuestFSException
7665 private native long _create () throws LibGuestFSException;
7668 * Close a libguestfs handle.
7670 * You can also leave handles to be collected by the garbage
7671 * collector, but this method ensures that the resources used
7672 * by the handle are freed up immediately. If you call any
7673 * other methods after closing the handle, you will get an
7676 * @throws LibGuestFSException
7678 public void close () throws LibGuestFSException
7684 private native void _close (long g) throws LibGuestFSException;
7686 public void finalize () throws LibGuestFSException
7694 fun (name, style, _, flags, _, shortdesc, longdesc) ->
7695 if not (List.mem NotInDocs flags); then (
7696 let doc = replace_str longdesc "C<guestfs_" "C<g." in
7698 if List.mem ProtocolLimitWarning flags then
7699 doc ^ "\n\n" ^ protocol_limit_warning
7702 if List.mem DangerWillRobinson flags then
7703 doc ^ "\n\n" ^ danger_will_robinson
7706 match deprecation_notice flags with
7708 | Some txt -> doc ^ "\n\n" ^ txt in
7709 let doc = pod2text ~width:60 name doc in
7710 let doc = List.map ( (* RHBZ#501883 *)
7713 | nonempty -> nonempty
7715 let doc = String.concat "\n * " doc in
7718 pr " * %s\n" shortdesc;
7721 pr " * @throws LibGuestFSException\n";
7725 generate_java_prototype ~public:true ~semicolon:false name style;
7728 pr " if (g == 0)\n";
7729 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
7732 if fst style <> RErr then pr "return ";
7734 generate_java_call_args ~handle:"g" (snd style);
7738 generate_java_prototype ~privat:true ~native:true name style;
7745 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
7746 and generate_java_call_args ~handle args =
7748 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7751 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
7752 ?(semicolon=true) name style =
7753 if privat then pr "private ";
7754 if public then pr "public ";
7755 if native then pr "native ";
7758 (match fst style with
7759 | RErr -> pr "void ";
7760 | RInt _ -> pr "int ";
7761 | RInt64 _ -> pr "long ";
7762 | RBool _ -> pr "boolean ";
7763 | RConstString _ | RConstOptString _ | RString _
7764 | RBufferOut _ -> pr "String ";
7765 | RStringList _ -> pr "String[] ";
7766 | RStruct (_, typ) ->
7767 let name = java_name_of_struct typ in
7769 | RStructList (_, typ) ->
7770 let name = java_name_of_struct typ in
7772 | RHashtable _ -> pr "HashMap<String,String> ";
7775 if native then pr "_%s " name else pr "%s " name;
7777 let needs_comma = ref false in
7786 if !needs_comma then pr ", ";
7787 needs_comma := true;
7804 pr " throws LibGuestFSException";
7805 if semicolon then pr ";"
7807 and generate_java_struct jtyp cols =
7808 generate_header CStyle LGPLv2;
7811 package com.redhat.et.libguestfs;
7814 * Libguestfs %s structure.
7826 | name, FBuffer -> pr " public String %s;\n" name
7827 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
7828 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
7829 | name, FChar -> pr " public char %s;\n" name
7830 | name, FOptPercent ->
7831 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
7832 pr " public float %s;\n" name
7837 and generate_java_c () =
7838 generate_header CStyle LGPLv2;
7845 #include \"com_redhat_et_libguestfs_GuestFS.h\"
7846 #include \"guestfs.h\"
7848 /* Note that this function returns. The exception is not thrown
7849 * until after the wrapper function returns.
7852 throw_exception (JNIEnv *env, const char *msg)
7855 cl = (*env)->FindClass (env,
7856 \"com/redhat/et/libguestfs/LibGuestFSException\");
7857 (*env)->ThrowNew (env, cl, msg);
7860 JNIEXPORT jlong JNICALL
7861 Java_com_redhat_et_libguestfs_GuestFS__1create
7862 (JNIEnv *env, jobject obj)
7866 g = guestfs_create ();
7868 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
7871 guestfs_set_error_handler (g, NULL, NULL);
7872 return (jlong) (long) g;
7875 JNIEXPORT void JNICALL
7876 Java_com_redhat_et_libguestfs_GuestFS__1close
7877 (JNIEnv *env, jobject obj, jlong jg)
7879 guestfs_h *g = (guestfs_h *) (long) jg;
7886 fun (name, style, _, _, _, _, _) ->
7888 (match fst style with
7889 | RErr -> pr "void ";
7890 | RInt _ -> pr "jint ";
7891 | RInt64 _ -> pr "jlong ";
7892 | RBool _ -> pr "jboolean ";
7893 | RConstString _ | RConstOptString _ | RString _
7894 | RBufferOut _ -> pr "jstring ";
7895 | RStruct _ | RHashtable _ ->
7897 | RStringList _ | RStructList _ ->
7901 pr "Java_com_redhat_et_libguestfs_GuestFS_";
7902 pr "%s" (replace_str ("_" ^ name) "_" "_1");
7904 pr " (JNIEnv *env, jobject obj, jlong jg";
7911 pr ", jstring j%s" n
7913 pr ", jobjectArray j%s" n
7915 pr ", jboolean j%s" n
7921 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
7922 let error_code, no_ret =
7923 match fst style with
7924 | RErr -> pr " int r;\n"; "-1", ""
7926 | RInt _ -> pr " int r;\n"; "-1", "0"
7927 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
7928 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
7929 | RConstOptString _ -> pr " const char *r;\n"; "NULL", "NULL"
7931 pr " jstring jr;\n";
7932 pr " char *r;\n"; "NULL", "NULL"
7934 pr " jobjectArray jr;\n";
7937 pr " jstring jstr;\n";
7938 pr " char **r;\n"; "NULL", "NULL"
7939 | RStruct (_, typ) ->
7940 pr " jobject jr;\n";
7942 pr " jfieldID fl;\n";
7943 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
7944 | RStructList (_, typ) ->
7945 pr " jobjectArray jr;\n";
7947 pr " jfieldID fl;\n";
7948 pr " jobject jfl;\n";
7949 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
7950 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL"
7952 pr " jstring jr;\n";
7954 pr " size_t size;\n";
7962 pr " const char *%s;\n" n
7964 pr " int %s_len;\n" n;
7965 pr " const char **%s;\n" n
7972 (match fst style with
7973 | RStringList _ | RStructList _ -> true
7974 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
7976 | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
7977 List.exists (function StringList _ -> true | _ -> false) (snd style) in
7983 (* Get the parameters. *)
7989 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
7991 (* This is completely undocumented, but Java null becomes
7994 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
7996 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
7997 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
7998 pr " for (i = 0; i < %s_len; ++i) {\n" n;
7999 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
8001 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
8003 pr " %s[%s_len] = NULL;\n" n n;
8006 pr " %s = j%s;\n" n n
8009 (* Make the call. *)
8010 pr " r = guestfs_%s " name;
8011 generate_c_call_args ~handle:"g" style;
8014 (* Release the parameters. *)
8020 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
8023 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
8025 pr " for (i = 0; i < %s_len; ++i) {\n" n;
8026 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
8028 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
8030 pr " free (%s);\n" n
8035 (* Check for errors. *)
8036 pr " if (r == %s) {\n" error_code;
8037 pr " throw_exception (env, guestfs_last_error (g));\n";
8038 pr " return %s;\n" no_ret;
8042 (match fst style with
8044 | RInt _ -> pr " return (jint) r;\n"
8045 | RBool _ -> pr " return (jboolean) r;\n"
8046 | RInt64 _ -> pr " return (jlong) r;\n"
8047 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
8048 | RConstOptString _ ->
8049 pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
8051 pr " jr = (*env)->NewStringUTF (env, r);\n";
8055 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
8056 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
8057 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
8058 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
8059 pr " for (i = 0; i < r_len; ++i) {\n";
8060 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
8061 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
8062 pr " free (r[i]);\n";
8066 | RStruct (_, typ) ->
8067 let jtyp = java_name_of_struct typ in
8068 let cols = cols_of_struct typ in
8069 generate_java_struct_return typ jtyp cols
8070 | RStructList (_, typ) ->
8071 let jtyp = java_name_of_struct typ in
8072 let cols = cols_of_struct typ in
8073 generate_java_struct_list_return typ jtyp cols
8076 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
8077 pr " return NULL;\n"
8079 pr " jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
8088 and generate_java_struct_return typ jtyp cols =
8089 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
8090 pr " jr = (*env)->AllocObject (env, cl);\n";
8094 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8095 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
8098 pr " char s[33];\n";
8099 pr " memcpy (s, r->%s, 32);\n" name;
8101 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8102 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
8106 pr " int len = r->%s_len;\n" name;
8107 pr " char s[len+1];\n";
8108 pr " memcpy (s, r->%s, len);\n" name;
8109 pr " s[len] = 0;\n";
8110 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8111 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
8113 | name, (FBytes|FUInt64|FInt64) ->
8114 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
8115 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8116 | name, (FUInt32|FInt32) ->
8117 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
8118 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8119 | name, FOptPercent ->
8120 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
8121 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
8123 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
8124 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8129 and generate_java_struct_list_return typ jtyp cols =
8130 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
8131 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
8132 pr " for (i = 0; i < r->len; ++i) {\n";
8133 pr " jfl = (*env)->AllocObject (env, cl);\n";
8137 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8138 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
8141 pr " char s[33];\n";
8142 pr " memcpy (s, r->val[i].%s, 32);\n" name;
8144 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8145 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8149 pr " int len = r->val[i].%s_len;\n" name;
8150 pr " char s[len+1];\n";
8151 pr " memcpy (s, r->val[i].%s, len);\n" name;
8152 pr " s[len] = 0;\n";
8153 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8154 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8156 | name, (FBytes|FUInt64|FInt64) ->
8157 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
8158 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8159 | name, (FUInt32|FInt32) ->
8160 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
8161 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8162 | name, FOptPercent ->
8163 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
8164 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
8166 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
8167 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8169 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
8171 pr " guestfs_free_%s_list (r);\n" typ;
8174 and generate_haskell_hs () =
8175 generate_header HaskellStyle LGPLv2;
8177 (* XXX We only know how to generate partial FFI for Haskell
8178 * at the moment. Please help out!
8180 let can_generate style =
8184 | RInt64 _, _ -> true
8187 | RConstOptString _, _
8193 | RBufferOut _, _ -> false in
8196 {-# INCLUDE <guestfs.h> #-}
8197 {-# LANGUAGE ForeignFunctionInterface #-}
8202 (* List out the names of the actions we want to export. *)
8204 fun (name, style, _, _, _, _, _) ->
8205 if can_generate style then pr ",\n %s" name
8212 import Foreign.C.Types
8214 import Control.Exception
8215 import Data.Typeable
8217 data GuestfsS = GuestfsS -- represents the opaque C struct
8218 type GuestfsP = Ptr GuestfsS -- guestfs_h *
8219 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
8221 -- XXX define properly later XXX
8225 data IntBool = IntBool
8227 data StatVFS = StatVFS
8228 data Hashtable = Hashtable
8230 foreign import ccall unsafe \"guestfs_create\" c_create
8232 foreign import ccall unsafe \"&guestfs_close\" c_close
8233 :: FunPtr (GuestfsP -> IO ())
8234 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
8235 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
8237 create :: IO GuestfsH
8240 c_set_error_handler p nullPtr nullPtr
8241 h <- newForeignPtr c_close p
8244 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
8245 :: GuestfsP -> IO CString
8247 -- last_error :: GuestfsH -> IO (Maybe String)
8248 -- last_error h = do
8249 -- str <- withForeignPtr h (\\p -> c_last_error p)
8250 -- maybePeek peekCString str
8252 last_error :: GuestfsH -> IO (String)
8254 str <- withForeignPtr h (\\p -> c_last_error p)
8256 then return \"no error\"
8257 else peekCString str
8261 (* Generate wrappers for each foreign function. *)
8263 fun (name, style, _, _, _, _, _) ->
8264 if can_generate style then (
8265 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
8267 generate_haskell_prototype ~handle:"GuestfsP" style;
8271 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
8273 pr "%s %s = do\n" name
8274 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
8276 (* Convert pointer arguments using with* functions. *)
8281 | String n -> pr "withCString %s $ \\%s -> " n n
8282 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
8283 | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
8284 | Bool _ | Int _ -> ()
8286 (* Convert integer arguments. *)
8290 | Bool n -> sprintf "(fromBool %s)" n
8291 | Int n -> sprintf "(fromIntegral %s)" n
8292 | FileIn n | FileOut n | String n | OptString n | StringList n -> n
8294 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
8295 (String.concat " " ("p" :: args));
8296 (match fst style with
8297 | RErr | RInt _ | RInt64 _ | RBool _ ->
8298 pr " if (r == -1)\n";
8300 pr " err <- last_error h\n";
8302 | RConstString _ | RConstOptString _ | RString _
8303 | RStringList _ | RStruct _
8304 | RStructList _ | RHashtable _ | RBufferOut _ ->
8305 pr " if (r == nullPtr)\n";
8307 pr " err <- last_error h\n";
8310 (match fst style with
8312 pr " else return ()\n"
8314 pr " else return (fromIntegral r)\n"
8316 pr " else return (fromIntegral r)\n"
8318 pr " else return (toBool r)\n"
8327 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
8333 and generate_haskell_prototype ~handle ?(hs = false) style =
8335 let string = if hs then "String" else "CString" in
8336 let int = if hs then "Int" else "CInt" in
8337 let bool = if hs then "Bool" else "CInt" in
8338 let int64 = if hs then "Integer" else "Int64" in
8342 | String _ -> pr "%s" string
8343 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
8344 | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
8345 | Bool _ -> pr "%s" bool
8346 | Int _ -> pr "%s" int
8347 | FileIn _ -> pr "%s" string
8348 | FileOut _ -> pr "%s" string
8353 (match fst style with
8354 | RErr -> if not hs then pr "CInt"
8355 | RInt _ -> pr "%s" int
8356 | RInt64 _ -> pr "%s" int64
8357 | RBool _ -> pr "%s" bool
8358 | RConstString _ -> pr "%s" string
8359 | RConstOptString _ -> pr "Maybe %s" string
8360 | RString _ -> pr "%s" string
8361 | RStringList _ -> pr "[%s]" string
8362 | RStruct (_, typ) ->
8363 let name = java_name_of_struct typ in
8365 | RStructList (_, typ) ->
8366 let name = java_name_of_struct typ in
8368 | RHashtable _ -> pr "Hashtable"
8369 | RBufferOut _ -> pr "%s" string
8373 and generate_bindtests () =
8374 generate_header CStyle LGPLv2;
8379 #include <inttypes.h>
8382 #include \"guestfs.h\"
8383 #include \"guestfs_protocol.h\"
8385 #define error guestfs_error
8386 #define safe_calloc guestfs_safe_calloc
8387 #define safe_malloc guestfs_safe_malloc
8390 print_strings (char * const* const argv)
8395 for (argc = 0; argv[argc] != NULL; ++argc) {
8396 if (argc > 0) printf (\", \");
8397 printf (\"\\\"%%s\\\"\", argv[argc]);
8402 /* The test0 function prints its parameters to stdout. */
8406 match test_functions with
8407 | [] -> assert false
8408 | test0 :: tests -> test0, tests in
8411 let (name, style, _, _, _, _, _) = test0 in
8412 generate_prototype ~extern:false ~semicolon:false ~newline:true
8413 ~handle:"g" ~prefix:"guestfs_" name style;
8419 | FileOut n -> pr " printf (\"%%s\\n\", %s);\n" n
8420 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
8421 | StringList n -> pr " print_strings (%s);\n" n
8422 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
8423 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
8425 pr " /* Java changes stdout line buffering so we need this: */\n";
8426 pr " fflush (stdout);\n";
8432 fun (name, style, _, _, _, _, _) ->
8433 if String.sub name (String.length name - 3) 3 <> "err" then (
8434 pr "/* Test normal return. */\n";
8435 generate_prototype ~extern:false ~semicolon:false ~newline:true
8436 ~handle:"g" ~prefix:"guestfs_" name style;
8438 (match fst style with
8443 pr " sscanf (val, \"%%d\", &r);\n";
8447 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
8450 pr " return strcmp (val, \"true\") == 0;\n"
8452 | RConstOptString _ ->
8453 (* Can't return the input string here. Return a static
8454 * string so we ensure we get a segfault if the caller
8457 pr " return \"static string\";\n"
8459 pr " return strdup (val);\n"
8461 pr " char **strs;\n";
8463 pr " sscanf (val, \"%%d\", &n);\n";
8464 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
8465 pr " for (i = 0; i < n; ++i) {\n";
8466 pr " strs[i] = safe_malloc (g, 16);\n";
8467 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
8469 pr " strs[n] = NULL;\n";
8470 pr " return strs;\n"
8471 | RStruct (_, typ) ->
8472 pr " struct guestfs_%s *r;\n" typ;
8473 pr " r = safe_calloc (g, sizeof *r, 1);\n";
8475 | RStructList (_, typ) ->
8476 pr " struct guestfs_%s_list *r;\n" typ;
8477 pr " r = safe_calloc (g, sizeof *r, 1);\n";
8478 pr " sscanf (val, \"%%d\", &r->len);\n";
8479 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
8482 pr " char **strs;\n";
8484 pr " sscanf (val, \"%%d\", &n);\n";
8485 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
8486 pr " for (i = 0; i < n; ++i) {\n";
8487 pr " strs[i*2] = safe_malloc (g, 16);\n";
8488 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
8489 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
8490 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
8492 pr " strs[n*2] = NULL;\n";
8493 pr " return strs;\n"
8495 pr " return strdup (val);\n"
8500 pr "/* Test error return. */\n";
8501 generate_prototype ~extern:false ~semicolon:false ~newline:true
8502 ~handle:"g" ~prefix:"guestfs_" name style;
8504 pr " error (g, \"error\");\n";
8505 (match fst style with
8506 | RErr | RInt _ | RInt64 _ | RBool _ ->
8508 | RConstString _ | RConstOptString _
8509 | RString _ | RStringList _ | RStruct _
8513 pr " return NULL;\n"
8520 and generate_ocaml_bindtests () =
8521 generate_header OCamlStyle GPLv2;
8525 let g = Guestfs.create () in
8532 | CallString s -> "\"" ^ s ^ "\""
8533 | CallOptString None -> "None"
8534 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
8535 | CallStringList xs ->
8536 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
8537 | CallInt i when i >= 0 -> string_of_int i
8538 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
8539 | CallBool b -> string_of_bool b
8544 generate_lang_bindtests (
8545 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
8548 pr "print_endline \"EOF\"\n"
8550 and generate_perl_bindtests () =
8551 pr "#!/usr/bin/perl -w\n";
8552 generate_header HashStyle GPLv2;
8559 my $g = Sys::Guestfs->new ();
8563 String.concat ", " (
8566 | CallString s -> "\"" ^ s ^ "\""
8567 | CallOptString None -> "undef"
8568 | CallOptString (Some s) -> sprintf "\"%s\"" s
8569 | CallStringList xs ->
8570 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8571 | CallInt i -> string_of_int i
8572 | CallBool b -> if b then "1" else "0"
8577 generate_lang_bindtests (
8578 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
8581 pr "print \"EOF\\n\"\n"
8583 and generate_python_bindtests () =
8584 generate_header HashStyle GPLv2;
8589 g = guestfs.GuestFS ()
8593 String.concat ", " (
8596 | CallString s -> "\"" ^ s ^ "\""
8597 | CallOptString None -> "None"
8598 | CallOptString (Some s) -> sprintf "\"%s\"" s
8599 | CallStringList xs ->
8600 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8601 | CallInt i -> string_of_int i
8602 | CallBool b -> if b then "1" else "0"
8607 generate_lang_bindtests (
8608 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
8611 pr "print \"EOF\"\n"
8613 and generate_ruby_bindtests () =
8614 generate_header HashStyle GPLv2;
8619 g = Guestfs::create()
8623 String.concat ", " (
8626 | CallString s -> "\"" ^ s ^ "\""
8627 | CallOptString None -> "nil"
8628 | CallOptString (Some s) -> sprintf "\"%s\"" s
8629 | CallStringList xs ->
8630 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8631 | CallInt i -> string_of_int i
8632 | CallBool b -> string_of_bool b
8637 generate_lang_bindtests (
8638 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
8641 pr "print \"EOF\\n\"\n"
8643 and generate_java_bindtests () =
8644 generate_header CStyle GPLv2;
8647 import com.redhat.et.libguestfs.*;
8649 public class Bindtests {
8650 public static void main (String[] argv)
8653 GuestFS g = new GuestFS ();
8657 String.concat ", " (
8660 | CallString s -> "\"" ^ s ^ "\""
8661 | CallOptString None -> "null"
8662 | CallOptString (Some s) -> sprintf "\"%s\"" s
8663 | CallStringList xs ->
8665 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
8666 | CallInt i -> string_of_int i
8667 | CallBool b -> string_of_bool b
8672 generate_lang_bindtests (
8673 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
8677 System.out.println (\"EOF\");
8679 catch (Exception exn) {
8680 System.err.println (exn);
8687 and generate_haskell_bindtests () =
8688 generate_header HaskellStyle GPLv2;
8691 module Bindtests where
8692 import qualified Guestfs
8702 | CallString s -> "\"" ^ s ^ "\""
8703 | CallOptString None -> "Nothing"
8704 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
8705 | CallStringList xs ->
8706 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8707 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
8708 | CallInt i -> string_of_int i
8709 | CallBool true -> "True"
8710 | CallBool false -> "False"
8715 generate_lang_bindtests (
8716 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
8719 pr " putStrLn \"EOF\"\n"
8721 (* Language-independent bindings tests - we do it this way to
8722 * ensure there is parity in testing bindings across all languages.
8724 and generate_lang_bindtests call =
8725 call "test0" [CallString "abc"; CallOptString (Some "def");
8726 CallStringList []; CallBool false;
8727 CallInt 0; CallString "123"; CallString "456"];
8728 call "test0" [CallString "abc"; CallOptString None;
8729 CallStringList []; CallBool false;
8730 CallInt 0; CallString "123"; CallString "456"];
8731 call "test0" [CallString ""; CallOptString (Some "def");
8732 CallStringList []; CallBool false;
8733 CallInt 0; CallString "123"; CallString "456"];
8734 call "test0" [CallString ""; CallOptString (Some "");
8735 CallStringList []; CallBool false;
8736 CallInt 0; CallString "123"; CallString "456"];
8737 call "test0" [CallString "abc"; CallOptString (Some "def");
8738 CallStringList ["1"]; CallBool false;
8739 CallInt 0; CallString "123"; CallString "456"];
8740 call "test0" [CallString "abc"; CallOptString (Some "def");
8741 CallStringList ["1"; "2"]; CallBool false;
8742 CallInt 0; CallString "123"; CallString "456"];
8743 call "test0" [CallString "abc"; CallOptString (Some "def");
8744 CallStringList ["1"]; CallBool true;
8745 CallInt 0; CallString "123"; CallString "456"];
8746 call "test0" [CallString "abc"; CallOptString (Some "def");
8747 CallStringList ["1"]; CallBool false;
8748 CallInt (-1); CallString "123"; CallString "456"];
8749 call "test0" [CallString "abc"; CallOptString (Some "def");
8750 CallStringList ["1"]; CallBool false;
8751 CallInt (-2); CallString "123"; CallString "456"];
8752 call "test0" [CallString "abc"; CallOptString (Some "def");
8753 CallStringList ["1"]; CallBool false;
8754 CallInt 1; CallString "123"; CallString "456"];
8755 call "test0" [CallString "abc"; CallOptString (Some "def");
8756 CallStringList ["1"]; CallBool false;
8757 CallInt 2; CallString "123"; CallString "456"];
8758 call "test0" [CallString "abc"; CallOptString (Some "def");
8759 CallStringList ["1"]; CallBool false;
8760 CallInt 4095; CallString "123"; CallString "456"];
8761 call "test0" [CallString "abc"; CallOptString (Some "def");
8762 CallStringList ["1"]; CallBool false;
8763 CallInt 0; CallString ""; CallString ""]
8765 (* XXX Add here tests of the return and error functions. *)
8767 (* This is used to generate the src/MAX_PROC_NR file which
8768 * contains the maximum procedure number, a surrogate for the
8769 * ABI version number. See src/Makefile.am for the details.
8771 and generate_max_proc_nr () =
8772 let proc_nrs = List.map (
8773 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
8774 ) daemon_functions in
8776 let max_proc_nr = List.fold_left max 0 proc_nrs in
8778 pr "%d\n" max_proc_nr
8780 let output_to filename =
8781 let filename_new = filename ^ ".new" in
8782 chan := open_out filename_new;
8787 (* Is the new file different from the current file? *)
8788 if Sys.file_exists filename && files_equal filename filename_new then
8789 Unix.unlink filename_new (* same, so skip it *)
8791 (* different, overwrite old one *)
8792 (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
8793 Unix.rename filename_new filename;
8794 Unix.chmod filename 0o444;
8795 printf "written %s\n%!" filename;
8804 if not (Sys.file_exists "HACKING") then (
8806 You are probably running this from the wrong directory.
8807 Run it from the top source directory using the command
8813 let close = output_to "src/guestfs_protocol.x" in
8817 let close = output_to "src/guestfs-structs.h" in
8818 generate_structs_h ();
8821 let close = output_to "src/guestfs-actions.h" in
8822 generate_actions_h ();
8825 let close = output_to "src/guestfs-actions.c" in
8826 generate_client_actions ();
8829 let close = output_to "daemon/actions.h" in
8830 generate_daemon_actions_h ();
8833 let close = output_to "daemon/stubs.c" in
8834 generate_daemon_actions ();
8837 let close = output_to "daemon/names.c" in
8838 generate_daemon_names ();
8841 let close = output_to "capitests/tests.c" in
8845 let close = output_to "src/guestfs-bindtests.c" in
8846 generate_bindtests ();
8849 let close = output_to "fish/cmds.c" in
8850 generate_fish_cmds ();
8853 let close = output_to "fish/completion.c" in
8854 generate_fish_completion ();
8857 let close = output_to "guestfs-structs.pod" in
8858 generate_structs_pod ();
8861 let close = output_to "guestfs-actions.pod" in
8862 generate_actions_pod ();
8865 let close = output_to "guestfish-actions.pod" in
8866 generate_fish_actions_pod ();
8869 let close = output_to "ocaml/guestfs.mli" in
8870 generate_ocaml_mli ();
8873 let close = output_to "ocaml/guestfs.ml" in
8874 generate_ocaml_ml ();
8877 let close = output_to "ocaml/guestfs_c_actions.c" in
8878 generate_ocaml_c ();
8881 let close = output_to "ocaml/bindtests.ml" in
8882 generate_ocaml_bindtests ();
8885 let close = output_to "perl/Guestfs.xs" in
8886 generate_perl_xs ();
8889 let close = output_to "perl/lib/Sys/Guestfs.pm" in
8890 generate_perl_pm ();
8893 let close = output_to "perl/bindtests.pl" in
8894 generate_perl_bindtests ();
8897 let close = output_to "python/guestfs-py.c" in
8898 generate_python_c ();
8901 let close = output_to "python/guestfs.py" in
8902 generate_python_py ();
8905 let close = output_to "python/bindtests.py" in
8906 generate_python_bindtests ();
8909 let close = output_to "ruby/ext/guestfs/_guestfs.c" in
8913 let close = output_to "ruby/bindtests.rb" in
8914 generate_ruby_bindtests ();
8917 let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
8918 generate_java_java ();
8923 let cols = cols_of_struct typ in
8924 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
8925 let close = output_to filename in
8926 generate_java_struct jtyp cols;
8930 let close = output_to "java/Makefile.inc" in
8931 pr "java_built_sources =";
8934 pr " com/redhat/et/libguestfs/%s.java" jtyp;
8936 pr " com/redhat/et/libguestfs/GuestFS.java\n";
8939 let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
8943 let close = output_to "java/Bindtests.java" in
8944 generate_java_bindtests ();
8947 let close = output_to "haskell/Guestfs.hs" in
8948 generate_haskell_hs ();
8951 let close = output_to "haskell/Bindtests.hs" in
8952 generate_haskell_bindtests ();
8955 let close = output_to "src/MAX_PROC_NR" in
8956 generate_max_proc_nr ();
8959 (* Always generate this file last, and unconditionally. It's used
8960 * by the Makefile to know when we must re-run the generator.
8962 let chan = open_out "src/stamp-generator" in