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 *)
173 let protocol_limit_warning =
174 "Because of the message protocol, there is a transfer limit
175 of somewhere between 2MB and 4MB. To transfer large files you should use
178 let danger_will_robinson =
179 "B<This command is dangerous. Without careful use you
180 can easily destroy all your data>."
182 (* You can supply zero or as many tests as you want per API call.
184 * Note that the test environment has 3 block devices, of size 500MB,
185 * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
186 * a fourth squashfs block device with some known files on it (/dev/sdd).
188 * Note for partitioning purposes, the 500MB device has 1015 cylinders.
189 * Number of cylinders was 63 for IDE emulated disks with precisely
190 * the same size. How exactly this is calculated is a mystery.
192 * The squashfs block device (/dev/sdd) comes from images/test.sqsh.
194 * To be able to run the tests in a reasonable amount of time,
195 * the virtual machine and block devices are reused between tests.
196 * So don't try testing kill_subprocess :-x
198 * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
200 * Don't assume anything about the previous contents of the block
201 * devices. Use 'Init*' to create some initial scenarios.
203 * You can add a prerequisite clause to any individual test. This
204 * is a run-time check, which, if it fails, causes the test to be
205 * skipped. Useful if testing a command which might not work on
206 * all variations of libguestfs builds. A test that has prerequisite
207 * of 'Always' is run unconditionally.
209 * In addition, packagers can skip individual tests by setting the
210 * environment variables: eg:
211 * SKIP_TEST_<CMD>_<NUM>=1 SKIP_TEST_COMMAND_3=1 (skips test #3 of command)
212 * SKIP_TEST_<CMD>=1 SKIP_TEST_ZEROFREE=1 (skips all zerofree tests)
214 type tests = (test_init * test_prereq * test) list
216 (* Run the command sequence and just expect nothing to fail. *)
218 (* Run the command sequence and expect the output of the final
219 * command to be the string.
221 | TestOutput of seq * string
222 (* Run the command sequence and expect the output of the final
223 * command to be the list of strings.
225 | TestOutputList of seq * string list
226 (* Run the command sequence and expect the output of the final
227 * command to be the list of block devices (could be either
228 * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
229 * character of each string).
231 | TestOutputListOfDevices of seq * string list
232 (* Run the command sequence and expect the output of the final
233 * command to be the integer.
235 | TestOutputInt of seq * int
236 (* Run the command sequence and expect the output of the final
237 * command to be <op> <int>, eg. ">=", "1".
239 | TestOutputIntOp of seq * string * int
240 (* Run the command sequence and expect the output of the final
241 * command to be a true value (!= 0 or != NULL).
243 | TestOutputTrue of seq
244 (* Run the command sequence and expect the output of the final
245 * command to be a false value (== 0 or == NULL, but not an error).
247 | TestOutputFalse of seq
248 (* Run the command sequence and expect the output of the final
249 * command to be a list of the given length (but don't care about
252 | TestOutputLength of seq * int
253 (* Run the command sequence and expect the output of the final
254 * command to be a structure.
256 | TestOutputStruct of seq * test_field_compare list
257 (* Run the command sequence and expect the final command (only)
260 | TestLastFail of seq
262 and test_field_compare =
263 | CompareWithInt of string * int
264 | CompareWithIntOp of string * string * int
265 | CompareWithString of string * string
266 | CompareFieldsIntEq of string * string
267 | CompareFieldsStrEq of string * string
269 (* Test prerequisites. *)
271 (* Test always runs. *)
273 (* Test is currently disabled - eg. it fails, or it tests some
274 * unimplemented feature.
277 (* 'string' is some C code (a function body) that should return
278 * true or false. The test will run if the code returns true.
281 (* As for 'If' but the test runs _unless_ the code returns true. *)
284 (* Some initial scenarios for testing. *)
286 (* Do nothing, block devices could contain random stuff including
287 * LVM PVs, and some filesystems might be mounted. This is usually
292 (* Block devices are empty and no filesystems are mounted. *)
295 (* /dev/sda contains a single partition /dev/sda1, which is formatted
296 * as ext2, empty [except for lost+found] and mounted on /.
297 * /dev/sdb and /dev/sdc may have random content.
303 * /dev/sda1 (is a PV):
304 * /dev/VG/LV (size 8MB):
305 * formatted as ext2, empty [except for lost+found], mounted on /
306 * /dev/sdb and /dev/sdc may have random content.
310 (* /dev/sdd (the squashfs, see images/ directory in source)
315 (* Sequence of commands for testing. *)
317 and cmd = string list
319 (* Note about long descriptions: When referring to another
320 * action, use the format C<guestfs_other> (ie. the full name of
321 * the C function). This will be replaced as appropriate in other
324 * Apart from that, long descriptions are just perldoc paragraphs.
327 (* These test functions are used in the language binding tests. *)
329 let test_all_args = [
332 StringList "strlist";
339 let test_all_rets = [
340 (* except for RErr, which is tested thoroughly elsewhere *)
341 "test0rint", RInt "valout";
342 "test0rint64", RInt64 "valout";
343 "test0rbool", RBool "valout";
344 "test0rconststring", RConstString "valout";
345 "test0rconstoptstring", RConstOptString "valout";
346 "test0rstring", RString "valout";
347 "test0rstringlist", RStringList "valout";
348 "test0rstruct", RStruct ("valout", "lvm_pv");
349 "test0rstructlist", RStructList ("valout", "lvm_pv");
350 "test0rhashtable", RHashtable "valout";
353 let test_functions = [
354 ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
356 "internal test function - do not use",
358 This is an internal test function which is used to test whether
359 the automatically generated bindings can handle every possible
360 parameter type correctly.
362 It echos the contents of each parameter to stdout.
364 You probably don't want to call this function.");
368 [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
370 "internal test function - do not use",
372 This is an internal test function which is used to test whether
373 the automatically generated bindings can handle every possible
374 return type correctly.
376 It converts string C<val> to the return type.
378 You probably don't want to call this function.");
379 (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
381 "internal test function - do not use",
383 This is an internal test function which is used to test whether
384 the automatically generated bindings can handle every possible
385 return type correctly.
387 This function always returns an error.
389 You probably don't want to call this function.")]
393 (* non_daemon_functions are any functions which don't get processed
394 * in the daemon, eg. functions for setting and getting local
395 * configuration values.
398 let non_daemon_functions = test_functions @ [
399 ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
401 "launch the qemu subprocess",
403 Internally libguestfs is implemented by running a virtual machine
406 You should call this after configuring the handle
407 (eg. adding drives) but before performing any actions.");
409 ("wait_ready", (RErr, []), -1, [NotInFish],
411 "wait until the qemu subprocess launches",
413 Internally libguestfs is implemented by running a virtual machine
416 You should call this after C<guestfs_launch> to wait for the launch
419 ("kill_subprocess", (RErr, []), -1, [],
421 "kill the qemu subprocess",
423 This kills the qemu subprocess. You should never need to call this.");
425 ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
427 "add an image to examine or modify",
429 This function adds a virtual machine disk image C<filename> to the
430 guest. The first time you call this function, the disk appears as IDE
431 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
434 You don't necessarily need to be root when using libguestfs. However
435 you obviously do need sufficient permissions to access the filename
436 for whatever operations you want to perform (ie. read access if you
437 just want to read the image or write access if you want to modify the
440 This is equivalent to the qemu parameter
441 C<-drive file=filename,cache=off,if=...>.
443 Note that this call checks for the existence of C<filename>. This
444 stops you from specifying other types of drive which are supported
445 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
446 the general C<guestfs_config> call instead.");
448 ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
450 "add a CD-ROM disk image to examine",
452 This function adds a virtual CD-ROM disk image to the guest.
454 This is equivalent to the qemu parameter C<-cdrom filename>.
456 Note that this call checks for the existence of C<filename>. This
457 stops you from specifying other types of drive which are supported
458 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
459 the general C<guestfs_config> call instead.");
461 ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
463 "add a drive in snapshot mode (read-only)",
465 This adds a drive in snapshot mode, making it effectively
468 Note that writes to the device are allowed, and will be seen for
469 the duration of the guestfs handle, but they are written
470 to a temporary file which is discarded as soon as the guestfs
471 handle is closed. We don't currently have any method to enable
472 changes to be committed, although qemu can support this.
474 This is equivalent to the qemu parameter
475 C<-drive file=filename,snapshot=on,if=...>.
477 Note that this call checks for the existence of C<filename>. This
478 stops you from specifying other types of drive which are supported
479 by qemu such as C<nbd:> and C<http:> URLs. To specify those, use
480 the general C<guestfs_config> call instead.");
482 ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
484 "add qemu parameters",
486 This can be used to add arbitrary qemu command line parameters
487 of the form C<-param value>. Actually it's not quite arbitrary - we
488 prevent you from setting some parameters which would interfere with
489 parameters that we use.
491 The first character of C<param> string must be a C<-> (dash).
493 C<value> can be NULL.");
495 ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
497 "set the qemu binary",
499 Set the qemu binary that we will use.
501 The default is chosen when the library was compiled by the
504 You can also override this by setting the C<LIBGUESTFS_QEMU>
505 environment variable.
507 Setting C<qemu> to C<NULL> restores the default qemu binary.");
509 ("get_qemu", (RConstString "qemu", []), -1, [],
510 [InitNone, Always, TestRun (
512 "get the qemu binary",
514 Return the current qemu binary.
516 This is always non-NULL. If it wasn't set already, then this will
517 return the default qemu binary name.");
519 ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
521 "set the search path",
523 Set the path that libguestfs searches for kernel and initrd.img.
525 The default is C<$libdir/guestfs> unless overridden by setting
526 C<LIBGUESTFS_PATH> environment variable.
528 Setting C<path> to C<NULL> restores the default path.");
530 ("get_path", (RConstString "path", []), -1, [],
531 [InitNone, Always, TestRun (
533 "get the search path",
535 Return the current search path.
537 This is always non-NULL. If it wasn't set already, then this will
538 return the default path.");
540 ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
542 "add options to kernel command line",
544 This function is used to add additional options to the
545 guest kernel command line.
547 The default is C<NULL> unless overridden by setting
548 C<LIBGUESTFS_APPEND> environment variable.
550 Setting C<append> to C<NULL> means I<no> additional options
551 are passed (libguestfs always adds a few of its own).");
553 ("get_append", (RConstOptString "append", []), -1, [],
554 (* This cannot be tested with the current framework. The
555 * function can return NULL in normal operations, which the
556 * test framework interprets as an error.
559 "get the additional kernel options",
561 Return the additional kernel options which are added to the
562 guest kernel command line.
564 If C<NULL> then no options are added.");
566 ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
570 If C<autosync> is true, this enables autosync. Libguestfs will make a
571 best effort attempt to run C<guestfs_umount_all> followed by
572 C<guestfs_sync> when the handle is closed
573 (also if the program exits without closing handles).
575 This is disabled by default (except in guestfish where it is
576 enabled by default).");
578 ("get_autosync", (RBool "autosync", []), -1, [],
579 [InitNone, Always, TestRun (
580 [["get_autosync"]])],
583 Get the autosync flag.");
585 ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
589 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
591 Verbose messages are disabled unless the environment variable
592 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
594 ("get_verbose", (RBool "verbose", []), -1, [],
598 This returns the verbose messages flag.");
600 ("is_ready", (RBool "ready", []), -1, [],
601 [InitNone, Always, TestOutputTrue (
603 "is ready to accept commands",
605 This returns true iff this handle is ready to accept commands
606 (in the C<READY> state).
608 For more information on states, see L<guestfs(3)>.");
610 ("is_config", (RBool "config", []), -1, [],
611 [InitNone, Always, TestOutputFalse (
613 "is in configuration state",
615 This returns true iff this handle is being configured
616 (in the C<CONFIG> state).
618 For more information on states, see L<guestfs(3)>.");
620 ("is_launching", (RBool "launching", []), -1, [],
621 [InitNone, Always, TestOutputFalse (
622 [["is_launching"]])],
623 "is launching subprocess",
625 This returns true iff this handle is launching the subprocess
626 (in the C<LAUNCHING> state).
628 For more information on states, see L<guestfs(3)>.");
630 ("is_busy", (RBool "busy", []), -1, [],
631 [InitNone, Always, TestOutputFalse (
633 "is busy processing a command",
635 This returns true iff this handle is busy processing a command
636 (in the C<BUSY> state).
638 For more information on states, see L<guestfs(3)>.");
640 ("get_state", (RInt "state", []), -1, [],
642 "get the current state",
644 This returns the current state as an opaque integer. This is
645 only useful for printing debug and internal error messages.
647 For more information on states, see L<guestfs(3)>.");
649 ("set_busy", (RErr, []), -1, [NotInFish],
653 This sets the state to C<BUSY>. This is only used when implementing
654 actions using the low-level API.
656 For more information on states, see L<guestfs(3)>.");
658 ("set_ready", (RErr, []), -1, [NotInFish],
660 "set state to ready",
662 This sets the state to C<READY>. This is only used when implementing
663 actions using the low-level API.
665 For more information on states, see L<guestfs(3)>.");
667 ("end_busy", (RErr, []), -1, [NotInFish],
669 "leave the busy state",
671 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
672 state as is. This is only used when implementing
673 actions using the low-level API.
675 For more information on states, see L<guestfs(3)>.");
677 ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
678 [InitNone, Always, TestOutputInt (
679 [["set_memsize"; "500"];
680 ["get_memsize"]], 500)],
681 "set memory allocated to the qemu subprocess",
683 This sets the memory size in megabytes allocated to the
684 qemu subprocess. This only has any effect if called before
687 You can also change this by setting the environment
688 variable C<LIBGUESTFS_MEMSIZE> before the handle is
691 For more information on the architecture of libguestfs,
692 see L<guestfs(3)>.");
694 ("get_memsize", (RInt "memsize", []), -1, [],
695 [InitNone, Always, TestOutputIntOp (
696 [["get_memsize"]], ">=", 256)],
697 "get memory allocated to the qemu subprocess",
699 This gets the memory size in megabytes allocated to the
702 If C<guestfs_set_memsize> was not called
703 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
704 then this returns the compiled-in default value for memsize.
706 For more information on the architecture of libguestfs,
707 see L<guestfs(3)>.");
709 ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
710 [InitNone, Always, TestOutputIntOp (
711 [["get_pid"]], ">=", 1)],
712 "get PID of qemu subprocess",
714 Return the process ID of the qemu subprocess. If there is no
715 qemu subprocess, then this will return an error.
717 This is an internal call used for debugging and testing.");
719 ("version", (RStruct ("version", "version"), []), -1, [],
720 [InitNone, Always, TestOutputStruct (
721 [["version"]], [CompareWithInt ("major", 1)])],
722 "get the library version number",
724 Return the libguestfs version number that the program is linked
727 Note that because of dynamic linking this is not necessarily
728 the version of libguestfs that you compiled against. You can
729 compile the program, and then at runtime dynamically link
730 against a completely different C<libguestfs.so> library.
732 This call was added in version C<1.0.58>. In previous
733 versions of libguestfs there was no way to get the version
734 number. From C code you can use ELF weak linking tricks to find out if
735 this symbol exists (if it doesn't, then it's an earlier version).
737 The call returns a structure with four elements. The first
738 three (C<major>, C<minor> and C<release>) are numbers and
739 correspond to the usual version triplet. The fourth element
740 (C<extra>) is a string and is normally empty, but may be
741 used for distro-specific information.
743 To construct the original version string:
744 C<$major.$minor.$release$extra>
746 I<Note:> Don't use this call to test for availability
747 of features. Distro backports makes this unreliable.");
751 (* daemon_functions are any functions which cause some action
752 * to take place in the daemon.
755 let daemon_functions = [
756 ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
757 [InitEmpty, Always, TestOutput (
758 [["sfdiskM"; "/dev/sda"; ","];
759 ["mkfs"; "ext2"; "/dev/sda1"];
760 ["mount"; "/dev/sda1"; "/"];
761 ["write_file"; "/new"; "new file contents"; "0"];
762 ["cat"; "/new"]], "new file contents")],
763 "mount a guest disk at a position in the filesystem",
765 Mount a guest disk at a position in the filesystem. Block devices
766 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
767 the guest. If those block devices contain partitions, they will have
768 the usual names (eg. C</dev/sda1>). Also LVM C</dev/VG/LV>-style
771 The rules are the same as for L<mount(2)>: A filesystem must
772 first be mounted on C</> before others can be mounted. Other
773 filesystems can only be mounted on directories which already
776 The mounted filesystem is writable, if we have sufficient permissions
777 on the underlying device.
779 The filesystem options C<sync> and C<noatime> are set with this
780 call, in order to improve reliability.");
782 ("sync", (RErr, []), 2, [],
783 [ InitEmpty, Always, TestRun [["sync"]]],
784 "sync disks, writes are flushed through to the disk image",
786 This syncs the disk, so that any writes are flushed through to the
787 underlying disk image.
789 You should always call this if you have modified a disk image, before
790 closing the handle.");
792 ("touch", (RErr, [String "path"]), 3, [],
793 [InitBasicFS, Always, TestOutputTrue (
795 ["exists"; "/new"]])],
796 "update file timestamps or create a new file",
798 Touch acts like the L<touch(1)> command. It can be used to
799 update the timestamps on a file, or, if the file does not exist,
800 to create a new zero-length file.");
802 ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
803 [InitBasicFS, Always, TestOutput (
804 [["write_file"; "/new"; "new file contents"; "0"];
805 ["cat"; "/new"]], "new file contents")],
806 "list the contents of a file",
808 Return the contents of the file named C<path>.
810 Note that this function cannot correctly handle binary files
811 (specifically, files containing C<\\0> character which is treated
812 as end of string). For those you need to use the C<guestfs_read_file>
813 or C<guestfs_download> functions which have a more complex interface.");
815 ("ll", (RString "listing", [String "directory"]), 5, [],
816 [], (* XXX Tricky to test because it depends on the exact format
817 * of the 'ls -l' command, which changes between F10 and F11.
819 "list the files in a directory (long format)",
821 List the files in C<directory> (relative to the root directory,
822 there is no cwd) in the format of 'ls -la'.
824 This command is mostly useful for interactive sessions. It
825 is I<not> intended that you try to parse the output string.");
827 ("ls", (RStringList "listing", [String "directory"]), 6, [],
828 [InitBasicFS, Always, TestOutputList (
831 ["touch"; "/newest"];
832 ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
833 "list the files in a directory",
835 List the files in C<directory> (relative to the root directory,
836 there is no cwd). The '.' and '..' entries are not returned, but
837 hidden files are shown.
839 This command is mostly useful for interactive sessions. Programs
840 should probably use C<guestfs_readdir> instead.");
842 ("list_devices", (RStringList "devices", []), 7, [],
843 [InitEmpty, Always, TestOutputListOfDevices (
844 [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
845 "list the block devices",
847 List all the block devices.
849 The full block device names are returned, eg. C</dev/sda>");
851 ("list_partitions", (RStringList "partitions", []), 8, [],
852 [InitBasicFS, Always, TestOutputListOfDevices (
853 [["list_partitions"]], ["/dev/sda1"]);
854 InitEmpty, Always, TestOutputListOfDevices (
855 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
856 ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
857 "list the partitions",
859 List all the partitions detected on all block devices.
861 The full partition device names are returned, eg. C</dev/sda1>
863 This does not return logical volumes. For that you will need to
864 call C<guestfs_lvs>.");
866 ("pvs", (RStringList "physvols", []), 9, [],
867 [InitBasicFSonLVM, Always, TestOutputListOfDevices (
868 [["pvs"]], ["/dev/sda1"]);
869 InitEmpty, Always, TestOutputListOfDevices (
870 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
871 ["pvcreate"; "/dev/sda1"];
872 ["pvcreate"; "/dev/sda2"];
873 ["pvcreate"; "/dev/sda3"];
874 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
875 "list the LVM physical volumes (PVs)",
877 List all the physical volumes detected. This is the equivalent
878 of the L<pvs(8)> command.
880 This returns a list of just the device names that contain
881 PVs (eg. C</dev/sda2>).
883 See also C<guestfs_pvs_full>.");
885 ("vgs", (RStringList "volgroups", []), 10, [],
886 [InitBasicFSonLVM, Always, TestOutputList (
888 InitEmpty, Always, TestOutputList (
889 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
890 ["pvcreate"; "/dev/sda1"];
891 ["pvcreate"; "/dev/sda2"];
892 ["pvcreate"; "/dev/sda3"];
893 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
894 ["vgcreate"; "VG2"; "/dev/sda3"];
895 ["vgs"]], ["VG1"; "VG2"])],
896 "list the LVM volume groups (VGs)",
898 List all the volumes groups detected. This is the equivalent
899 of the L<vgs(8)> command.
901 This returns a list of just the volume group names that were
902 detected (eg. C<VolGroup00>).
904 See also C<guestfs_vgs_full>.");
906 ("lvs", (RStringList "logvols", []), 11, [],
907 [InitBasicFSonLVM, Always, TestOutputList (
908 [["lvs"]], ["/dev/VG/LV"]);
909 InitEmpty, Always, TestOutputList (
910 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
911 ["pvcreate"; "/dev/sda1"];
912 ["pvcreate"; "/dev/sda2"];
913 ["pvcreate"; "/dev/sda3"];
914 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
915 ["vgcreate"; "VG2"; "/dev/sda3"];
916 ["lvcreate"; "LV1"; "VG1"; "50"];
917 ["lvcreate"; "LV2"; "VG1"; "50"];
918 ["lvcreate"; "LV3"; "VG2"; "50"];
919 ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
920 "list the LVM logical volumes (LVs)",
922 List all the logical volumes detected. This is the equivalent
923 of the L<lvs(8)> command.
925 This returns a list of the logical volume device names
926 (eg. C</dev/VolGroup00/LogVol00>).
928 See also C<guestfs_lvs_full>.");
930 ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
931 [], (* XXX how to test? *)
932 "list the LVM physical volumes (PVs)",
934 List all the physical volumes detected. This is the equivalent
935 of the L<pvs(8)> command. The \"full\" version includes all fields.");
937 ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
938 [], (* XXX how to test? *)
939 "list the LVM volume groups (VGs)",
941 List all the volumes groups detected. This is the equivalent
942 of the L<vgs(8)> command. The \"full\" version includes all fields.");
944 ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
945 [], (* XXX how to test? *)
946 "list the LVM logical volumes (LVs)",
948 List all the logical volumes detected. This is the equivalent
949 of the L<lvs(8)> command. The \"full\" version includes all fields.");
951 ("read_lines", (RStringList "lines", [String "path"]), 15, [],
952 [InitBasicFS, Always, TestOutputList (
953 [["write_file"; "/new"; "line1\r\nline2\nline3"; "0"];
954 ["read_lines"; "/new"]], ["line1"; "line2"; "line3"]);
955 InitBasicFS, Always, TestOutputList (
956 [["write_file"; "/new"; ""; "0"];
957 ["read_lines"; "/new"]], [])],
958 "read file as lines",
960 Return the contents of the file named C<path>.
962 The file contents are returned as a list of lines. Trailing
963 C<LF> and C<CRLF> character sequences are I<not> returned.
965 Note that this function cannot correctly handle binary files
966 (specifically, files containing C<\\0> character which is treated
967 as end of line). For those you need to use the C<guestfs_read_file>
968 function which has a more complex interface.");
970 ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
971 [], (* XXX Augeas code needs tests. *)
972 "create a new Augeas handle",
974 Create a new Augeas handle for editing configuration files.
975 If there was any previous Augeas handle associated with this
976 guestfs session, then it is closed.
978 You must call this before using any other C<guestfs_aug_*>
981 C<root> is the filesystem root. C<root> must not be NULL,
984 The flags are the same as the flags defined in
985 E<lt>augeas.hE<gt>, the logical I<or> of the following
990 =item C<AUG_SAVE_BACKUP> = 1
992 Keep the original file with a C<.augsave> extension.
994 =item C<AUG_SAVE_NEWFILE> = 2
996 Save changes into a file with extension C<.augnew>, and
997 do not overwrite original. Overrides C<AUG_SAVE_BACKUP>.
999 =item C<AUG_TYPE_CHECK> = 4
1001 Typecheck lenses (can be expensive).
1003 =item C<AUG_NO_STDINC> = 8
1005 Do not use standard load path for modules.
1007 =item C<AUG_SAVE_NOOP> = 16
1009 Make save a no-op, just record what would have been changed.
1011 =item C<AUG_NO_LOAD> = 32
1013 Do not load the tree in C<guestfs_aug_init>.
1017 To close the handle, you can call C<guestfs_aug_close>.
1019 To find out more about Augeas, see L<http://augeas.net/>.");
1021 ("aug_close", (RErr, []), 26, [],
1022 [], (* XXX Augeas code needs tests. *)
1023 "close the current Augeas handle",
1025 Close the current Augeas handle and free up any resources
1026 used by it. After calling this, you have to call
1027 C<guestfs_aug_init> again before you can use any other
1028 Augeas functions.");
1030 ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
1031 [], (* XXX Augeas code needs tests. *)
1032 "define an Augeas variable",
1034 Defines an Augeas variable C<name> whose value is the result
1035 of evaluating C<expr>. If C<expr> is NULL, then C<name> is
1038 On success this returns the number of nodes in C<expr>, or
1039 C<0> if C<expr> evaluates to something which is not a nodeset.");
1041 ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
1042 [], (* XXX Augeas code needs tests. *)
1043 "define an Augeas node",
1045 Defines a variable C<name> whose value is the result of
1048 If C<expr> evaluates to an empty nodeset, a node is created,
1049 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1050 C<name> will be the nodeset containing that single node.
1052 On success this returns a pair containing the
1053 number of nodes in the nodeset, and a boolean flag
1054 if a node was created.");
1056 ("aug_get", (RString "val", [String "path"]), 19, [],
1057 [], (* XXX Augeas code needs tests. *)
1058 "look up the value of an Augeas path",
1060 Look up the value associated with C<path>. If C<path>
1061 matches exactly one node, the C<value> is returned.");
1063 ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
1064 [], (* XXX Augeas code needs tests. *)
1065 "set Augeas path to value",
1067 Set the value associated with C<path> to C<value>.");
1069 ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
1070 [], (* XXX Augeas code needs tests. *)
1071 "insert a sibling Augeas node",
1073 Create a new sibling C<label> for C<path>, inserting it into
1074 the tree before or after C<path> (depending on the boolean
1077 C<path> must match exactly one existing node in the tree, and
1078 C<label> must be a label, ie. not contain C</>, C<*> or end
1079 with a bracketed index C<[N]>.");
1081 ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
1082 [], (* XXX Augeas code needs tests. *)
1083 "remove an Augeas path",
1085 Remove C<path> and all of its children.
1087 On success this returns the number of entries which were removed.");
1089 ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
1090 [], (* XXX Augeas code needs tests. *)
1093 Move the node C<src> to C<dest>. C<src> must match exactly
1094 one node. C<dest> is overwritten if it exists.");
1096 ("aug_match", (RStringList "matches", [String "path"]), 24, [],
1097 [], (* XXX Augeas code needs tests. *)
1098 "return Augeas nodes which match path",
1100 Returns a list of paths which match the path expression C<path>.
1101 The returned paths are sufficiently qualified so that they match
1102 exactly one node in the current tree.");
1104 ("aug_save", (RErr, []), 25, [],
1105 [], (* XXX Augeas code needs tests. *)
1106 "write all pending Augeas changes to disk",
1108 This writes all pending changes to disk.
1110 The flags which were passed to C<guestfs_aug_init> affect exactly
1111 how files are saved.");
1113 ("aug_load", (RErr, []), 27, [],
1114 [], (* XXX Augeas code needs tests. *)
1115 "load files into the tree",
1117 Load files into the tree.
1119 See C<aug_load> in the Augeas documentation for the full gory
1122 ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
1123 [], (* XXX Augeas code needs tests. *)
1124 "list Augeas nodes under a path",
1126 This is just a shortcut for listing C<guestfs_aug_match>
1127 C<path/*> and sorting the resulting nodes into alphabetical order.");
1129 ("rm", (RErr, [String "path"]), 29, [],
1130 [InitBasicFS, Always, TestRun
1133 InitBasicFS, Always, TestLastFail
1135 InitBasicFS, Always, TestLastFail
1140 Remove the single file C<path>.");
1142 ("rmdir", (RErr, [String "path"]), 30, [],
1143 [InitBasicFS, Always, TestRun
1146 InitBasicFS, Always, TestLastFail
1147 [["rmdir"; "/new"]];
1148 InitBasicFS, Always, TestLastFail
1150 ["rmdir"; "/new"]]],
1151 "remove a directory",
1153 Remove the single directory C<path>.");
1155 ("rm_rf", (RErr, [String "path"]), 31, [],
1156 [InitBasicFS, Always, TestOutputFalse
1158 ["mkdir"; "/new/foo"];
1159 ["touch"; "/new/foo/bar"];
1161 ["exists"; "/new"]]],
1162 "remove a file or directory recursively",
1164 Remove the file or directory C<path>, recursively removing the
1165 contents if its a directory. This is like the C<rm -rf> shell
1168 ("mkdir", (RErr, [String "path"]), 32, [],
1169 [InitBasicFS, Always, TestOutputTrue
1171 ["is_dir"; "/new"]];
1172 InitBasicFS, Always, TestLastFail
1173 [["mkdir"; "/new/foo/bar"]]],
1174 "create a directory",
1176 Create a directory named C<path>.");
1178 ("mkdir_p", (RErr, [String "path"]), 33, [],
1179 [InitBasicFS, Always, TestOutputTrue
1180 [["mkdir_p"; "/new/foo/bar"];
1181 ["is_dir"; "/new/foo/bar"]];
1182 InitBasicFS, Always, TestOutputTrue
1183 [["mkdir_p"; "/new/foo/bar"];
1184 ["is_dir"; "/new/foo"]];
1185 InitBasicFS, Always, TestOutputTrue
1186 [["mkdir_p"; "/new/foo/bar"];
1187 ["is_dir"; "/new"]];
1188 (* Regression tests for RHBZ#503133: *)
1189 InitBasicFS, Always, TestRun
1191 ["mkdir_p"; "/new"]];
1192 InitBasicFS, Always, TestLastFail
1194 ["mkdir_p"; "/new"]]],
1195 "create a directory and parents",
1197 Create a directory named C<path>, creating any parent directories
1198 as necessary. This is like the C<mkdir -p> shell command.");
1200 ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1201 [], (* XXX Need stat command to test *)
1204 Change the mode (permissions) of C<path> to C<mode>. Only
1205 numeric modes are supported.");
1207 ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1208 [], (* XXX Need stat command to test *)
1209 "change file owner and group",
1211 Change the file owner to C<owner> and group to C<group>.
1213 Only numeric uid and gid are supported. If you want to use
1214 names, you will need to locate and parse the password file
1215 yourself (Augeas support makes this relatively easy).");
1217 ("exists", (RBool "existsflag", [String "path"]), 36, [],
1218 [InitBasicFS, Always, TestOutputTrue (
1220 ["exists"; "/new"]]);
1221 InitBasicFS, Always, TestOutputTrue (
1223 ["exists"; "/new"]])],
1224 "test if file or directory exists",
1226 This returns C<true> if and only if there is a file, directory
1227 (or anything) with the given C<path> name.
1229 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1231 ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1232 [InitBasicFS, Always, TestOutputTrue (
1234 ["is_file"; "/new"]]);
1235 InitBasicFS, Always, TestOutputFalse (
1237 ["is_file"; "/new"]])],
1238 "test if file exists",
1240 This returns C<true> if and only if there is a file
1241 with the given C<path> name. Note that it returns false for
1242 other objects like directories.
1244 See also C<guestfs_stat>.");
1246 ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1247 [InitBasicFS, Always, TestOutputFalse (
1249 ["is_dir"; "/new"]]);
1250 InitBasicFS, Always, TestOutputTrue (
1252 ["is_dir"; "/new"]])],
1253 "test if file exists",
1255 This returns C<true> if and only if there is a directory
1256 with the given C<path> name. Note that it returns false for
1257 other objects like files.
1259 See also C<guestfs_stat>.");
1261 ("pvcreate", (RErr, [String "device"]), 39, [],
1262 [InitEmpty, Always, TestOutputListOfDevices (
1263 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1264 ["pvcreate"; "/dev/sda1"];
1265 ["pvcreate"; "/dev/sda2"];
1266 ["pvcreate"; "/dev/sda3"];
1267 ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1268 "create an LVM physical volume",
1270 This creates an LVM physical volume on the named C<device>,
1271 where C<device> should usually be a partition name such
1274 ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1275 [InitEmpty, Always, TestOutputList (
1276 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1277 ["pvcreate"; "/dev/sda1"];
1278 ["pvcreate"; "/dev/sda2"];
1279 ["pvcreate"; "/dev/sda3"];
1280 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1281 ["vgcreate"; "VG2"; "/dev/sda3"];
1282 ["vgs"]], ["VG1"; "VG2"])],
1283 "create an LVM volume group",
1285 This creates an LVM volume group called C<volgroup>
1286 from the non-empty list of physical volumes C<physvols>.");
1288 ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1289 [InitEmpty, Always, TestOutputList (
1290 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1291 ["pvcreate"; "/dev/sda1"];
1292 ["pvcreate"; "/dev/sda2"];
1293 ["pvcreate"; "/dev/sda3"];
1294 ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1295 ["vgcreate"; "VG2"; "/dev/sda3"];
1296 ["lvcreate"; "LV1"; "VG1"; "50"];
1297 ["lvcreate"; "LV2"; "VG1"; "50"];
1298 ["lvcreate"; "LV3"; "VG2"; "50"];
1299 ["lvcreate"; "LV4"; "VG2"; "50"];
1300 ["lvcreate"; "LV5"; "VG2"; "50"];
1302 ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1303 "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1304 "create an LVM volume group",
1306 This creates an LVM volume group called C<logvol>
1307 on the volume group C<volgroup>, with C<size> megabytes.");
1309 ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1310 [InitEmpty, Always, TestOutput (
1311 [["sfdiskM"; "/dev/sda"; ","];
1312 ["mkfs"; "ext2"; "/dev/sda1"];
1313 ["mount"; "/dev/sda1"; "/"];
1314 ["write_file"; "/new"; "new file contents"; "0"];
1315 ["cat"; "/new"]], "new file contents")],
1316 "make a filesystem",
1318 This creates a filesystem on C<device> (usually a partition
1319 or LVM logical volume). The filesystem type is C<fstype>, for
1322 ("sfdisk", (RErr, [String "device";
1323 Int "cyls"; Int "heads"; Int "sectors";
1324 StringList "lines"]), 43, [DangerWillRobinson],
1326 "create partitions on a block device",
1328 This is a direct interface to the L<sfdisk(8)> program for creating
1329 partitions on block devices.
1331 C<device> should be a block device, for example C</dev/sda>.
1333 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1334 and sectors on the device, which are passed directly to sfdisk as
1335 the I<-C>, I<-H> and I<-S> parameters. If you pass C<0> for any
1336 of these, then the corresponding parameter is omitted. Usually for
1337 'large' disks, you can just pass C<0> for these, but for small
1338 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1339 out the right geometry and you will need to tell it.
1341 C<lines> is a list of lines that we feed to C<sfdisk>. For more
1342 information refer to the L<sfdisk(8)> manpage.
1344 To create a single partition occupying the whole disk, you would
1345 pass C<lines> as a single element list, when the single element being
1346 the string C<,> (comma).
1348 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1350 ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1351 [InitBasicFS, Always, TestOutput (
1352 [["write_file"; "/new"; "new file contents"; "0"];
1353 ["cat"; "/new"]], "new file contents");
1354 InitBasicFS, Always, TestOutput (
1355 [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1356 ["cat"; "/new"]], "\nnew file contents\n");
1357 InitBasicFS, Always, TestOutput (
1358 [["write_file"; "/new"; "\n\n"; "0"];
1359 ["cat"; "/new"]], "\n\n");
1360 InitBasicFS, Always, TestOutput (
1361 [["write_file"; "/new"; ""; "0"];
1362 ["cat"; "/new"]], "");
1363 InitBasicFS, Always, TestOutput (
1364 [["write_file"; "/new"; "\n\n\n"; "0"];
1365 ["cat"; "/new"]], "\n\n\n");
1366 InitBasicFS, Always, TestOutput (
1367 [["write_file"; "/new"; "\n"; "0"];
1368 ["cat"; "/new"]], "\n")],
1371 This call creates a file called C<path>. The contents of the
1372 file is the string C<content> (which can contain any 8 bit data),
1373 with length C<size>.
1375 As a special case, if C<size> is C<0>
1376 then the length is calculated using C<strlen> (so in this case
1377 the content cannot contain embedded ASCII NULs).
1379 I<NB.> Owing to a bug, writing content containing ASCII NUL
1380 characters does I<not> work, even if the length is specified.
1381 We hope to resolve this bug in a future version. In the meantime
1382 use C<guestfs_upload>.");
1384 ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1385 [InitEmpty, Always, TestOutputListOfDevices (
1386 [["sfdiskM"; "/dev/sda"; ","];
1387 ["mkfs"; "ext2"; "/dev/sda1"];
1388 ["mount"; "/dev/sda1"; "/"];
1389 ["mounts"]], ["/dev/sda1"]);
1390 InitEmpty, Always, TestOutputList (
1391 [["sfdiskM"; "/dev/sda"; ","];
1392 ["mkfs"; "ext2"; "/dev/sda1"];
1393 ["mount"; "/dev/sda1"; "/"];
1396 "unmount a filesystem",
1398 This unmounts the given filesystem. The filesystem may be
1399 specified either by its mountpoint (path) or the device which
1400 contains the filesystem.");
1402 ("mounts", (RStringList "devices", []), 46, [],
1403 [InitBasicFS, Always, TestOutputListOfDevices (
1404 [["mounts"]], ["/dev/sda1"])],
1405 "show mounted filesystems",
1407 This returns the list of currently mounted filesystems. It returns
1408 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1410 Some internal mounts are not shown.
1412 See also: C<guestfs_mountpoints>");
1414 ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1415 [InitBasicFS, Always, TestOutputList (
1418 (* check that umount_all can unmount nested mounts correctly: *)
1419 InitEmpty, Always, TestOutputList (
1420 [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1421 ["mkfs"; "ext2"; "/dev/sda1"];
1422 ["mkfs"; "ext2"; "/dev/sda2"];
1423 ["mkfs"; "ext2"; "/dev/sda3"];
1424 ["mount"; "/dev/sda1"; "/"];
1426 ["mount"; "/dev/sda2"; "/mp1"];
1427 ["mkdir"; "/mp1/mp2"];
1428 ["mount"; "/dev/sda3"; "/mp1/mp2"];
1429 ["mkdir"; "/mp1/mp2/mp3"];
1432 "unmount all filesystems",
1434 This unmounts all mounted filesystems.
1436 Some internal mounts are not unmounted by this call.");
1438 ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1440 "remove all LVM LVs, VGs and PVs",
1442 This command removes all LVM logical volumes, volume groups
1443 and physical volumes.");
1445 ("file", (RString "description", [String "path"]), 49, [],
1446 [InitBasicFS, Always, TestOutput (
1448 ["file"; "/new"]], "empty");
1449 InitBasicFS, Always, TestOutput (
1450 [["write_file"; "/new"; "some content\n"; "0"];
1451 ["file"; "/new"]], "ASCII text");
1452 InitBasicFS, Always, TestLastFail (
1453 [["file"; "/nofile"]])],
1454 "determine file type",
1456 This call uses the standard L<file(1)> command to determine
1457 the type or contents of the file. This also works on devices,
1458 for example to find out whether a partition contains a filesystem.
1460 The exact command which runs is C<file -bsL path>. Note in
1461 particular that the filename is not prepended to the output
1462 (the C<-b> option).");
1464 ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1465 [InitBasicFS, Always, TestOutput (
1466 [["upload"; "test-command"; "/test-command"];
1467 ["chmod"; "0o755"; "/test-command"];
1468 ["command"; "/test-command 1"]], "Result1");
1469 InitBasicFS, Always, TestOutput (
1470 [["upload"; "test-command"; "/test-command"];
1471 ["chmod"; "0o755"; "/test-command"];
1472 ["command"; "/test-command 2"]], "Result2\n");
1473 InitBasicFS, Always, TestOutput (
1474 [["upload"; "test-command"; "/test-command"];
1475 ["chmod"; "0o755"; "/test-command"];
1476 ["command"; "/test-command 3"]], "\nResult3");
1477 InitBasicFS, Always, TestOutput (
1478 [["upload"; "test-command"; "/test-command"];
1479 ["chmod"; "0o755"; "/test-command"];
1480 ["command"; "/test-command 4"]], "\nResult4\n");
1481 InitBasicFS, Always, TestOutput (
1482 [["upload"; "test-command"; "/test-command"];
1483 ["chmod"; "0o755"; "/test-command"];
1484 ["command"; "/test-command 5"]], "\nResult5\n\n");
1485 InitBasicFS, Always, TestOutput (
1486 [["upload"; "test-command"; "/test-command"];
1487 ["chmod"; "0o755"; "/test-command"];
1488 ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1489 InitBasicFS, Always, TestOutput (
1490 [["upload"; "test-command"; "/test-command"];
1491 ["chmod"; "0o755"; "/test-command"];
1492 ["command"; "/test-command 7"]], "");
1493 InitBasicFS, Always, TestOutput (
1494 [["upload"; "test-command"; "/test-command"];
1495 ["chmod"; "0o755"; "/test-command"];
1496 ["command"; "/test-command 8"]], "\n");
1497 InitBasicFS, Always, TestOutput (
1498 [["upload"; "test-command"; "/test-command"];
1499 ["chmod"; "0o755"; "/test-command"];
1500 ["command"; "/test-command 9"]], "\n\n");
1501 InitBasicFS, Always, TestOutput (
1502 [["upload"; "test-command"; "/test-command"];
1503 ["chmod"; "0o755"; "/test-command"];
1504 ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1505 InitBasicFS, Always, TestOutput (
1506 [["upload"; "test-command"; "/test-command"];
1507 ["chmod"; "0o755"; "/test-command"];
1508 ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1509 InitBasicFS, Always, TestLastFail (
1510 [["upload"; "test-command"; "/test-command"];
1511 ["chmod"; "0o755"; "/test-command"];
1512 ["command"; "/test-command"]])],
1513 "run a command from the guest filesystem",
1515 This call runs a command from the guest filesystem. The
1516 filesystem must be mounted, and must contain a compatible
1517 operating system (ie. something Linux, with the same
1518 or compatible processor architecture).
1520 The single parameter is an argv-style list of arguments.
1521 The first element is the name of the program to run.
1522 Subsequent elements are parameters. The list must be
1523 non-empty (ie. must contain a program name). Note that
1524 the command runs directly, and is I<not> invoked via
1525 the shell (see C<guestfs_sh>).
1527 The return value is anything printed to I<stdout> by
1530 If the command returns a non-zero exit status, then
1531 this function returns an error message. The error message
1532 string is the content of I<stderr> from the command.
1534 The C<$PATH> environment variable will contain at least
1535 C</usr/bin> and C</bin>. If you require a program from
1536 another location, you should provide the full path in the
1539 Shared libraries and data files required by the program
1540 must be available on filesystems which are mounted in the
1541 correct places. It is the caller's responsibility to ensure
1542 all filesystems that are needed are mounted at the right
1545 ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1546 [InitBasicFS, Always, TestOutputList (
1547 [["upload"; "test-command"; "/test-command"];
1548 ["chmod"; "0o755"; "/test-command"];
1549 ["command_lines"; "/test-command 1"]], ["Result1"]);
1550 InitBasicFS, Always, TestOutputList (
1551 [["upload"; "test-command"; "/test-command"];
1552 ["chmod"; "0o755"; "/test-command"];
1553 ["command_lines"; "/test-command 2"]], ["Result2"]);
1554 InitBasicFS, Always, TestOutputList (
1555 [["upload"; "test-command"; "/test-command"];
1556 ["chmod"; "0o755"; "/test-command"];
1557 ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1558 InitBasicFS, Always, TestOutputList (
1559 [["upload"; "test-command"; "/test-command"];
1560 ["chmod"; "0o755"; "/test-command"];
1561 ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1562 InitBasicFS, Always, TestOutputList (
1563 [["upload"; "test-command"; "/test-command"];
1564 ["chmod"; "0o755"; "/test-command"];
1565 ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1566 InitBasicFS, Always, TestOutputList (
1567 [["upload"; "test-command"; "/test-command"];
1568 ["chmod"; "0o755"; "/test-command"];
1569 ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1570 InitBasicFS, Always, TestOutputList (
1571 [["upload"; "test-command"; "/test-command"];
1572 ["chmod"; "0o755"; "/test-command"];
1573 ["command_lines"; "/test-command 7"]], []);
1574 InitBasicFS, Always, TestOutputList (
1575 [["upload"; "test-command"; "/test-command"];
1576 ["chmod"; "0o755"; "/test-command"];
1577 ["command_lines"; "/test-command 8"]], [""]);
1578 InitBasicFS, Always, TestOutputList (
1579 [["upload"; "test-command"; "/test-command"];
1580 ["chmod"; "0o755"; "/test-command"];
1581 ["command_lines"; "/test-command 9"]], ["";""]);
1582 InitBasicFS, Always, TestOutputList (
1583 [["upload"; "test-command"; "/test-command"];
1584 ["chmod"; "0o755"; "/test-command"];
1585 ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1586 InitBasicFS, Always, TestOutputList (
1587 [["upload"; "test-command"; "/test-command"];
1588 ["chmod"; "0o755"; "/test-command"];
1589 ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1590 "run a command, returning lines",
1592 This is the same as C<guestfs_command>, but splits the
1593 result into a list of lines.
1595 See also: C<guestfs_sh_lines>");
1597 ("stat", (RStruct ("statbuf", "stat"), [String "path"]), 52, [],
1598 [InitBasicFS, Always, TestOutputStruct (
1600 ["stat"; "/new"]], [CompareWithInt ("size", 0)])],
1601 "get file information",
1603 Returns file information for the given C<path>.
1605 This is the same as the C<stat(2)> system call.");
1607 ("lstat", (RStruct ("statbuf", "stat"), [String "path"]), 53, [],
1608 [InitBasicFS, Always, TestOutputStruct (
1610 ["lstat"; "/new"]], [CompareWithInt ("size", 0)])],
1611 "get file information for a symbolic link",
1613 Returns file information for the given C<path>.
1615 This is the same as C<guestfs_stat> except that if C<path>
1616 is a symbolic link, then the link is stat-ed, not the file it
1619 This is the same as the C<lstat(2)> system call.");
1621 ("statvfs", (RStruct ("statbuf", "statvfs"), [String "path"]), 54, [],
1622 [InitBasicFS, Always, TestOutputStruct (
1623 [["statvfs"; "/"]], [CompareWithInt ("namemax", 255);
1624 CompareWithInt ("bsize", 1024)])],
1625 "get file system statistics",
1627 Returns file system statistics for any mounted file system.
1628 C<path> should be a file or directory in the mounted file system
1629 (typically it is the mount point itself, but it doesn't need to be).
1631 This is the same as the C<statvfs(2)> system call.");
1633 ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1635 "get ext2/ext3/ext4 superblock details",
1637 This returns the contents of the ext2, ext3 or ext4 filesystem
1638 superblock on C<device>.
1640 It is the same as running C<tune2fs -l device>. See L<tune2fs(8)>
1641 manpage for more details. The list of fields returned isn't
1642 clearly defined, and depends on both the version of C<tune2fs>
1643 that libguestfs was built against, and the filesystem itself.");
1645 ("blockdev_setro", (RErr, [String "device"]), 56, [],
1646 [InitEmpty, Always, TestOutputTrue (
1647 [["blockdev_setro"; "/dev/sda"];
1648 ["blockdev_getro"; "/dev/sda"]])],
1649 "set block device to read-only",
1651 Sets the block device named C<device> to read-only.
1653 This uses the L<blockdev(8)> command.");
1655 ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1656 [InitEmpty, Always, TestOutputFalse (
1657 [["blockdev_setrw"; "/dev/sda"];
1658 ["blockdev_getro"; "/dev/sda"]])],
1659 "set block device to read-write",
1661 Sets the block device named C<device> to read-write.
1663 This uses the L<blockdev(8)> command.");
1665 ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1666 [InitEmpty, Always, TestOutputTrue (
1667 [["blockdev_setro"; "/dev/sda"];
1668 ["blockdev_getro"; "/dev/sda"]])],
1669 "is block device set to read-only",
1671 Returns a boolean indicating if the block device is read-only
1672 (true if read-only, false if not).
1674 This uses the L<blockdev(8)> command.");
1676 ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1677 [InitEmpty, Always, TestOutputInt (
1678 [["blockdev_getss"; "/dev/sda"]], 512)],
1679 "get sectorsize of block device",
1681 This returns the size of sectors on a block device.
1682 Usually 512, but can be larger for modern devices.
1684 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1687 This uses the L<blockdev(8)> command.");
1689 ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1690 [InitEmpty, Always, TestOutputInt (
1691 [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1692 "get blocksize of block device",
1694 This returns the block size of a device.
1696 (Note this is different from both I<size in blocks> and
1697 I<filesystem block size>).
1699 This uses the L<blockdev(8)> command.");
1701 ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1703 "set blocksize of block device",
1705 This sets the block size of a device.
1707 (Note this is different from both I<size in blocks> and
1708 I<filesystem block size>).
1710 This uses the L<blockdev(8)> command.");
1712 ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1713 [InitEmpty, Always, TestOutputInt (
1714 [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1715 "get total size of device in 512-byte sectors",
1717 This returns the size of the device in units of 512-byte sectors
1718 (even if the sectorsize isn't 512 bytes ... weird).
1720 See also C<guestfs_blockdev_getss> for the real sector size of
1721 the device, and C<guestfs_blockdev_getsize64> for the more
1722 useful I<size in bytes>.
1724 This uses the L<blockdev(8)> command.");
1726 ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1727 [InitEmpty, Always, TestOutputInt (
1728 [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1729 "get total size of device in bytes",
1731 This returns the size of the device in bytes.
1733 See also C<guestfs_blockdev_getsz>.
1735 This uses the L<blockdev(8)> command.");
1737 ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1738 [InitEmpty, Always, TestRun
1739 [["blockdev_flushbufs"; "/dev/sda"]]],
1740 "flush device buffers",
1742 This tells the kernel to flush internal buffers associated
1745 This uses the L<blockdev(8)> command.");
1747 ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1748 [InitEmpty, Always, TestRun
1749 [["blockdev_rereadpt"; "/dev/sda"]]],
1750 "reread partition table",
1752 Reread the partition table on C<device>.
1754 This uses the L<blockdev(8)> command.");
1756 ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1757 [InitBasicFS, Always, TestOutput (
1758 (* Pick a file from cwd which isn't likely to change. *)
1759 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1760 ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1761 "upload a file from the local machine",
1763 Upload local file C<filename> to C<remotefilename> on the
1766 C<filename> can also be a named pipe.
1768 See also C<guestfs_download>.");
1770 ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1771 [InitBasicFS, Always, TestOutput (
1772 (* Pick a file from cwd which isn't likely to change. *)
1773 [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1774 ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1775 ["upload"; "testdownload.tmp"; "/upload"];
1776 ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1777 "download a file to the local machine",
1779 Download file C<remotefilename> and save it as C<filename>
1780 on the local machine.
1782 C<filename> can also be a named pipe.
1784 See also C<guestfs_upload>, C<guestfs_cat>.");
1786 ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1787 [InitBasicFS, Always, TestOutput (
1788 [["write_file"; "/new"; "test\n"; "0"];
1789 ["checksum"; "crc"; "/new"]], "935282863");
1790 InitBasicFS, Always, TestLastFail (
1791 [["checksum"; "crc"; "/new"]]);
1792 InitBasicFS, Always, TestOutput (
1793 [["write_file"; "/new"; "test\n"; "0"];
1794 ["checksum"; "md5"; "/new"]], "d8e8fca2dc0f896fd7cb4cb0031ba249");
1795 InitBasicFS, Always, TestOutput (
1796 [["write_file"; "/new"; "test\n"; "0"];
1797 ["checksum"; "sha1"; "/new"]], "4e1243bd22c66e76c2ba9eddc1f91394e57f9f83");
1798 InitBasicFS, Always, TestOutput (
1799 [["write_file"; "/new"; "test\n"; "0"];
1800 ["checksum"; "sha224"; "/new"]], "52f1bf093f4b7588726035c176c0cdb4376cfea53819f1395ac9e6ec");
1801 InitBasicFS, Always, TestOutput (
1802 [["write_file"; "/new"; "test\n"; "0"];
1803 ["checksum"; "sha256"; "/new"]], "f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2");
1804 InitBasicFS, Always, TestOutput (
1805 [["write_file"; "/new"; "test\n"; "0"];
1806 ["checksum"; "sha384"; "/new"]], "109bb6b5b6d5547c1ce03c7a8bd7d8f80c1cb0957f50c4f7fda04692079917e4f9cad52b878f3d8234e1a170b154b72d");
1807 InitBasicFS, Always, TestOutput (
1808 [["write_file"; "/new"; "test\n"; "0"];
1809 ["checksum"; "sha512"; "/new"]], "0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123");
1810 InitSquashFS, Always, TestOutput (
1811 [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c")],
1812 "compute MD5, SHAx or CRC checksum of file",
1814 This call computes the MD5, SHAx or CRC checksum of the
1817 The type of checksum to compute is given by the C<csumtype>
1818 parameter which must have one of the following values:
1824 Compute the cyclic redundancy check (CRC) specified by POSIX
1825 for the C<cksum> command.
1829 Compute the MD5 hash (using the C<md5sum> program).
1833 Compute the SHA1 hash (using the C<sha1sum> program).
1837 Compute the SHA224 hash (using the C<sha224sum> program).
1841 Compute the SHA256 hash (using the C<sha256sum> program).
1845 Compute the SHA384 hash (using the C<sha384sum> program).
1849 Compute the SHA512 hash (using the C<sha512sum> program).
1853 The checksum is returned as a printable string.");
1855 ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1856 [InitBasicFS, Always, TestOutput (
1857 [["tar_in"; "../images/helloworld.tar"; "/"];
1858 ["cat"; "/hello"]], "hello\n")],
1859 "unpack tarfile to directory",
1861 This command uploads and unpacks local file C<tarfile> (an
1862 I<uncompressed> tar file) into C<directory>.
1864 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1866 ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1868 "pack directory into tarfile",
1870 This command packs the contents of C<directory> and downloads
1871 it to local file C<tarfile>.
1873 To download a compressed tarball, use C<guestfs_tgz_out>.");
1875 ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1876 [InitBasicFS, Always, TestOutput (
1877 [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1878 ["cat"; "/hello"]], "hello\n")],
1879 "unpack compressed tarball to directory",
1881 This command uploads and unpacks local file C<tarball> (a
1882 I<gzip compressed> tar file) into C<directory>.
1884 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1886 ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1888 "pack directory into compressed tarball",
1890 This command packs the contents of C<directory> and downloads
1891 it to local file C<tarball>.
1893 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1895 ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1896 [InitBasicFS, Always, TestLastFail (
1898 ["mount_ro"; "/dev/sda1"; "/"];
1899 ["touch"; "/new"]]);
1900 InitBasicFS, Always, TestOutput (
1901 [["write_file"; "/new"; "data"; "0"];
1903 ["mount_ro"; "/dev/sda1"; "/"];
1904 ["cat"; "/new"]], "data")],
1905 "mount a guest disk, read-only",
1907 This is the same as the C<guestfs_mount> command, but it
1908 mounts the filesystem with the read-only (I<-o ro>) flag.");
1910 ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1912 "mount a guest disk with mount options",
1914 This is the same as the C<guestfs_mount> command, but it
1915 allows you to set the mount options as for the
1916 L<mount(8)> I<-o> flag.");
1918 ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1920 "mount a guest disk with mount options and vfstype",
1922 This is the same as the C<guestfs_mount> command, but it
1923 allows you to set both the mount options and the vfstype
1924 as for the L<mount(8)> I<-o> and I<-t> flags.");
1926 ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1928 "debugging and internals",
1930 The C<guestfs_debug> command exposes some internals of
1931 C<guestfsd> (the guestfs daemon) that runs inside the
1934 There is no comprehensive help for this command. You have
1935 to look at the file C<daemon/debug.c> in the libguestfs source
1936 to find out what you can do.");
1938 ("lvremove", (RErr, [String "device"]), 77, [],
1939 [InitEmpty, Always, TestOutputList (
1940 [["sfdiskM"; "/dev/sda"; ","];
1941 ["pvcreate"; "/dev/sda1"];
1942 ["vgcreate"; "VG"; "/dev/sda1"];
1943 ["lvcreate"; "LV1"; "VG"; "50"];
1944 ["lvcreate"; "LV2"; "VG"; "50"];
1945 ["lvremove"; "/dev/VG/LV1"];
1946 ["lvs"]], ["/dev/VG/LV2"]);
1947 InitEmpty, Always, TestOutputList (
1948 [["sfdiskM"; "/dev/sda"; ","];
1949 ["pvcreate"; "/dev/sda1"];
1950 ["vgcreate"; "VG"; "/dev/sda1"];
1951 ["lvcreate"; "LV1"; "VG"; "50"];
1952 ["lvcreate"; "LV2"; "VG"; "50"];
1953 ["lvremove"; "/dev/VG"];
1955 InitEmpty, Always, TestOutputList (
1956 [["sfdiskM"; "/dev/sda"; ","];
1957 ["pvcreate"; "/dev/sda1"];
1958 ["vgcreate"; "VG"; "/dev/sda1"];
1959 ["lvcreate"; "LV1"; "VG"; "50"];
1960 ["lvcreate"; "LV2"; "VG"; "50"];
1961 ["lvremove"; "/dev/VG"];
1963 "remove an LVM logical volume",
1965 Remove an LVM logical volume C<device>, where C<device> is
1966 the path to the LV, such as C</dev/VG/LV>.
1968 You can also remove all LVs in a volume group by specifying
1969 the VG name, C</dev/VG>.");
1971 ("vgremove", (RErr, [String "vgname"]), 78, [],
1972 [InitEmpty, Always, TestOutputList (
1973 [["sfdiskM"; "/dev/sda"; ","];
1974 ["pvcreate"; "/dev/sda1"];
1975 ["vgcreate"; "VG"; "/dev/sda1"];
1976 ["lvcreate"; "LV1"; "VG"; "50"];
1977 ["lvcreate"; "LV2"; "VG"; "50"];
1980 InitEmpty, Always, TestOutputList (
1981 [["sfdiskM"; "/dev/sda"; ","];
1982 ["pvcreate"; "/dev/sda1"];
1983 ["vgcreate"; "VG"; "/dev/sda1"];
1984 ["lvcreate"; "LV1"; "VG"; "50"];
1985 ["lvcreate"; "LV2"; "VG"; "50"];
1988 "remove an LVM volume group",
1990 Remove an LVM volume group C<vgname>, (for example C<VG>).
1992 This also forcibly removes all logical volumes in the volume
1995 ("pvremove", (RErr, [String "device"]), 79, [],
1996 [InitEmpty, Always, TestOutputListOfDevices (
1997 [["sfdiskM"; "/dev/sda"; ","];
1998 ["pvcreate"; "/dev/sda1"];
1999 ["vgcreate"; "VG"; "/dev/sda1"];
2000 ["lvcreate"; "LV1"; "VG"; "50"];
2001 ["lvcreate"; "LV2"; "VG"; "50"];
2003 ["pvremove"; "/dev/sda1"];
2005 InitEmpty, Always, TestOutputListOfDevices (
2006 [["sfdiskM"; "/dev/sda"; ","];
2007 ["pvcreate"; "/dev/sda1"];
2008 ["vgcreate"; "VG"; "/dev/sda1"];
2009 ["lvcreate"; "LV1"; "VG"; "50"];
2010 ["lvcreate"; "LV2"; "VG"; "50"];
2012 ["pvremove"; "/dev/sda1"];
2014 InitEmpty, Always, TestOutputListOfDevices (
2015 [["sfdiskM"; "/dev/sda"; ","];
2016 ["pvcreate"; "/dev/sda1"];
2017 ["vgcreate"; "VG"; "/dev/sda1"];
2018 ["lvcreate"; "LV1"; "VG"; "50"];
2019 ["lvcreate"; "LV2"; "VG"; "50"];
2021 ["pvremove"; "/dev/sda1"];
2023 "remove an LVM physical volume",
2025 This wipes a physical volume C<device> so that LVM will no longer
2028 The implementation uses the C<pvremove> command which refuses to
2029 wipe physical volumes that contain any volume groups, so you have
2030 to remove those first.");
2032 ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
2033 [InitBasicFS, Always, TestOutput (
2034 [["set_e2label"; "/dev/sda1"; "testlabel"];
2035 ["get_e2label"; "/dev/sda1"]], "testlabel")],
2036 "set the ext2/3/4 filesystem label",
2038 This sets the ext2/3/4 filesystem label of the filesystem on
2039 C<device> to C<label>. Filesystem labels are limited to
2042 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2043 to return the existing label on a filesystem.");
2045 ("get_e2label", (RString "label", [String "device"]), 81, [],
2047 "get the ext2/3/4 filesystem label",
2049 This returns the ext2/3/4 filesystem label of the filesystem on
2052 ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
2053 [InitBasicFS, Always, TestOutput (
2054 [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
2055 ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
2056 InitBasicFS, Always, TestOutput (
2057 [["set_e2uuid"; "/dev/sda1"; "clear"];
2058 ["get_e2uuid"; "/dev/sda1"]], "");
2059 (* We can't predict what UUIDs will be, so just check the commands run. *)
2060 InitBasicFS, Always, TestRun (
2061 [["set_e2uuid"; "/dev/sda1"; "random"]]);
2062 InitBasicFS, Always, TestRun (
2063 [["set_e2uuid"; "/dev/sda1"; "time"]])],
2064 "set the ext2/3/4 filesystem UUID",
2066 This sets the ext2/3/4 filesystem UUID of the filesystem on
2067 C<device> to C<uuid>. The format of the UUID and alternatives
2068 such as C<clear>, C<random> and C<time> are described in the
2069 L<tune2fs(8)> manpage.
2071 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2072 to return the existing UUID of a filesystem.");
2074 ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
2076 "get the ext2/3/4 filesystem UUID",
2078 This returns the ext2/3/4 filesystem UUID of the filesystem on
2081 ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
2082 [InitBasicFS, Always, TestOutputInt (
2083 [["umount"; "/dev/sda1"];
2084 ["fsck"; "ext2"; "/dev/sda1"]], 0);
2085 InitBasicFS, Always, TestOutputInt (
2086 [["umount"; "/dev/sda1"];
2087 ["zero"; "/dev/sda1"];
2088 ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2089 "run the filesystem checker",
2091 This runs the filesystem checker (fsck) on C<device> which
2092 should have filesystem type C<fstype>.
2094 The returned integer is the status. See L<fsck(8)> for the
2095 list of status codes from C<fsck>.
2103 Multiple status codes can be summed together.
2107 A non-zero return code can mean \"success\", for example if
2108 errors have been corrected on the filesystem.
2112 Checking or repairing NTFS volumes is not supported
2117 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2119 ("zero", (RErr, [String "device"]), 85, [],
2120 [InitBasicFS, Always, TestOutput (
2121 [["umount"; "/dev/sda1"];
2122 ["zero"; "/dev/sda1"];
2123 ["file"; "/dev/sda1"]], "data")],
2124 "write zeroes to the device",
2126 This command writes zeroes over the first few blocks of C<device>.
2128 How many blocks are zeroed isn't specified (but it's I<not> enough
2129 to securely wipe the device). It should be sufficient to remove
2130 any partition tables, filesystem superblocks and so on.
2132 See also: C<guestfs_scrub_device>.");
2134 ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
2135 (* Test disabled because grub-install incompatible with virtio-blk driver.
2136 * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2138 [InitBasicFS, Disabled, TestOutputTrue (
2139 [["grub_install"; "/"; "/dev/sda1"];
2140 ["is_dir"; "/boot"]])],
2143 This command installs GRUB (the Grand Unified Bootloader) on
2144 C<device>, with the root directory being C<root>.");
2146 ("cp", (RErr, [String "src"; String "dest"]), 87, [],
2147 [InitBasicFS, Always, TestOutput (
2148 [["write_file"; "/old"; "file content"; "0"];
2149 ["cp"; "/old"; "/new"];
2150 ["cat"; "/new"]], "file content");
2151 InitBasicFS, Always, TestOutputTrue (
2152 [["write_file"; "/old"; "file content"; "0"];
2153 ["cp"; "/old"; "/new"];
2154 ["is_file"; "/old"]]);
2155 InitBasicFS, Always, TestOutput (
2156 [["write_file"; "/old"; "file content"; "0"];
2158 ["cp"; "/old"; "/dir/new"];
2159 ["cat"; "/dir/new"]], "file content")],
2162 This copies a file from C<src> to C<dest> where C<dest> is
2163 either a destination filename or destination directory.");
2165 ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
2166 [InitBasicFS, Always, TestOutput (
2167 [["mkdir"; "/olddir"];
2168 ["mkdir"; "/newdir"];
2169 ["write_file"; "/olddir/file"; "file content"; "0"];
2170 ["cp_a"; "/olddir"; "/newdir"];
2171 ["cat"; "/newdir/olddir/file"]], "file content")],
2172 "copy a file or directory recursively",
2174 This copies a file or directory from C<src> to C<dest>
2175 recursively using the C<cp -a> command.");
2177 ("mv", (RErr, [String "src"; String "dest"]), 89, [],
2178 [InitBasicFS, Always, TestOutput (
2179 [["write_file"; "/old"; "file content"; "0"];
2180 ["mv"; "/old"; "/new"];
2181 ["cat"; "/new"]], "file content");
2182 InitBasicFS, Always, TestOutputFalse (
2183 [["write_file"; "/old"; "file content"; "0"];
2184 ["mv"; "/old"; "/new"];
2185 ["is_file"; "/old"]])],
2188 This moves a file from C<src> to C<dest> where C<dest> is
2189 either a destination filename or destination directory.");
2191 ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2192 [InitEmpty, Always, TestRun (
2193 [["drop_caches"; "3"]])],
2194 "drop kernel page cache, dentries and inodes",
2196 This instructs the guest kernel to drop its page cache,
2197 and/or dentries and inode caches. The parameter C<whattodrop>
2198 tells the kernel what precisely to drop, see
2199 L<http://linux-mm.org/Drop_Caches>
2201 Setting C<whattodrop> to 3 should drop everything.
2203 This automatically calls L<sync(2)> before the operation,
2204 so that the maximum guest memory is freed.");
2206 ("dmesg", (RString "kmsgs", []), 91, [],
2207 [InitEmpty, Always, TestRun (
2209 "return kernel messages",
2211 This returns the kernel messages (C<dmesg> output) from
2212 the guest kernel. This is sometimes useful for extended
2213 debugging of problems.
2215 Another way to get the same information is to enable
2216 verbose messages with C<guestfs_set_verbose> or by setting
2217 the environment variable C<LIBGUESTFS_DEBUG=1> before
2218 running the program.");
2220 ("ping_daemon", (RErr, []), 92, [],
2221 [InitEmpty, Always, TestRun (
2222 [["ping_daemon"]])],
2223 "ping the guest daemon",
2225 This is a test probe into the guestfs daemon running inside
2226 the qemu subprocess. Calling this function checks that the
2227 daemon responds to the ping message, without affecting the daemon
2228 or attached block device(s) in any other way.");
2230 ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2231 [InitBasicFS, Always, TestOutputTrue (
2232 [["write_file"; "/file1"; "contents of a file"; "0"];
2233 ["cp"; "/file1"; "/file2"];
2234 ["equal"; "/file1"; "/file2"]]);
2235 InitBasicFS, Always, TestOutputFalse (
2236 [["write_file"; "/file1"; "contents of a file"; "0"];
2237 ["write_file"; "/file2"; "contents of another file"; "0"];
2238 ["equal"; "/file1"; "/file2"]]);
2239 InitBasicFS, Always, TestLastFail (
2240 [["equal"; "/file1"; "/file2"]])],
2241 "test if two files have equal contents",
2243 This compares the two files C<file1> and C<file2> and returns
2244 true if their content is exactly equal, or false otherwise.
2246 The external L<cmp(1)> program is used for the comparison.");
2248 ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2249 [InitBasicFS, Always, TestOutputList (
2250 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2251 ["strings"; "/new"]], ["hello"; "world"]);
2252 InitBasicFS, Always, TestOutputList (
2254 ["strings"; "/new"]], [])],
2255 "print the printable strings in a file",
2257 This runs the L<strings(1)> command on a file and returns
2258 the list of printable strings found.");
2260 ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2261 [InitBasicFS, Always, TestOutputList (
2262 [["write_file"; "/new"; "hello\nworld\n"; "0"];
2263 ["strings_e"; "b"; "/new"]], []);
2264 InitBasicFS, Disabled, TestOutputList (
2265 [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2266 ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2267 "print the printable strings in a file",
2269 This is like the C<guestfs_strings> command, but allows you to
2270 specify the encoding.
2272 See the L<strings(1)> manpage for the full list of encodings.
2274 Commonly useful encodings are C<l> (lower case L) which will
2275 show strings inside Windows/x86 files.
2277 The returned strings are transcoded to UTF-8.");
2279 ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2280 [InitBasicFS, Always, TestOutput (
2281 [["write_file"; "/new"; "hello\nworld\n"; "12"];
2282 ["hexdump"; "/new"]], "00000000 68 65 6c 6c 6f 0a 77 6f 72 6c 64 0a |hello.world.|\n0000000c\n");
2283 (* Test for RHBZ#501888c2 regression which caused large hexdump
2284 * commands to segfault.
2286 InitSquashFS, Always, TestRun (
2287 [["hexdump"; "/100krandom"]])],
2288 "dump a file in hexadecimal",
2290 This runs C<hexdump -C> on the given C<path>. The result is
2291 the human-readable, canonical hex dump of the file.");
2293 ("zerofree", (RErr, [String "device"]), 97, [],
2294 [InitNone, Always, TestOutput (
2295 [["sfdiskM"; "/dev/sda"; ","];
2296 ["mkfs"; "ext3"; "/dev/sda1"];
2297 ["mount"; "/dev/sda1"; "/"];
2298 ["write_file"; "/new"; "test file"; "0"];
2299 ["umount"; "/dev/sda1"];
2300 ["zerofree"; "/dev/sda1"];
2301 ["mount"; "/dev/sda1"; "/"];
2302 ["cat"; "/new"]], "test file")],
2303 "zero unused inodes and disk blocks on ext2/3 filesystem",
2305 This runs the I<zerofree> program on C<device>. This program
2306 claims to zero unused inodes and disk blocks on an ext2/3
2307 filesystem, thus making it possible to compress the filesystem
2310 You should B<not> run this program if the filesystem is
2313 It is possible that using this program can damage the filesystem
2314 or data on the filesystem.");
2316 ("pvresize", (RErr, [String "device"]), 98, [],
2318 "resize an LVM physical volume",
2320 This resizes (expands or shrinks) an existing LVM physical
2321 volume to match the new size of the underlying device.");
2323 ("sfdisk_N", (RErr, [String "device"; Int "partnum";
2324 Int "cyls"; Int "heads"; Int "sectors";
2325 String "line"]), 99, [DangerWillRobinson],
2327 "modify a single partition on a block device",
2329 This runs L<sfdisk(8)> option to modify just the single
2330 partition C<n> (note: C<n> counts from 1).
2332 For other parameters, see C<guestfs_sfdisk>. You should usually
2333 pass C<0> for the cyls/heads/sectors parameters.");
2335 ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2337 "display the partition table",
2339 This displays the partition table on C<device>, in the
2340 human-readable output of the L<sfdisk(8)> command. It is
2341 not intended to be parsed.");
2343 ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2345 "display the kernel geometry",
2347 This displays the kernel's idea of the geometry of C<device>.
2349 The result is in human-readable format, and not designed to
2352 ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2354 "display the disk geometry from the partition table",
2356 This displays the disk geometry of C<device> read from the
2357 partition table. Especially in the case where the underlying
2358 block device has been resized, this can be different from the
2359 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2361 The result is in human-readable format, and not designed to
2364 ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2366 "activate or deactivate all volume groups",
2368 This command activates or (if C<activate> is false) deactivates
2369 all logical volumes in all volume groups.
2370 If activated, then they are made known to the
2371 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2372 then those devices disappear.
2374 This command is the same as running C<vgchange -a y|n>");
2376 ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2378 "activate or deactivate some volume groups",
2380 This command activates or (if C<activate> is false) deactivates
2381 all logical volumes in the listed volume groups C<volgroups>.
2382 If activated, then they are made known to the
2383 kernel, ie. they appear as C</dev/mapper> devices. If deactivated,
2384 then those devices disappear.
2386 This command is the same as running C<vgchange -a y|n volgroups...>
2388 Note that if C<volgroups> is an empty list then B<all> volume groups
2389 are activated or deactivated.");
2391 ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2392 [InitNone, Always, TestOutput (
2393 [["sfdiskM"; "/dev/sda"; ","];
2394 ["pvcreate"; "/dev/sda1"];
2395 ["vgcreate"; "VG"; "/dev/sda1"];
2396 ["lvcreate"; "LV"; "VG"; "10"];
2397 ["mkfs"; "ext2"; "/dev/VG/LV"];
2398 ["mount"; "/dev/VG/LV"; "/"];
2399 ["write_file"; "/new"; "test content"; "0"];
2401 ["lvresize"; "/dev/VG/LV"; "20"];
2402 ["e2fsck_f"; "/dev/VG/LV"];
2403 ["resize2fs"; "/dev/VG/LV"];
2404 ["mount"; "/dev/VG/LV"; "/"];
2405 ["cat"; "/new"]], "test content")],
2406 "resize an LVM logical volume",
2408 This resizes (expands or shrinks) an existing LVM logical
2409 volume to C<mbytes>. When reducing, data in the reduced part
2412 ("resize2fs", (RErr, [String "device"]), 106, [],
2413 [], (* lvresize tests this *)
2414 "resize an ext2/ext3 filesystem",
2416 This resizes an ext2 or ext3 filesystem to match the size of
2417 the underlying device.
2419 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2420 on the C<device> before calling this command. For unknown reasons
2421 C<resize2fs> sometimes gives an error about this and sometimes not.
2422 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2423 calling this function.");
2425 ("find", (RStringList "names", [String "directory"]), 107, [],
2426 [InitBasicFS, Always, TestOutputList (
2427 [["find"; "/"]], ["lost+found"]);
2428 InitBasicFS, Always, TestOutputList (
2432 ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2433 InitBasicFS, Always, TestOutputList (
2434 [["mkdir_p"; "/a/b/c"];
2435 ["touch"; "/a/b/c/d"];
2436 ["find"; "/a/b/"]], ["c"; "c/d"])],
2437 "find all files and directories",
2439 This command lists out all files and directories, recursively,
2440 starting at C<directory>. It is essentially equivalent to
2441 running the shell command C<find directory -print> but some
2442 post-processing happens on the output, described below.
2444 This returns a list of strings I<without any prefix>. Thus
2445 if the directory structure was:
2451 then the returned list from C<guestfs_find> C</tmp> would be
2459 If C<directory> is not a directory, then this command returns
2462 The returned list is sorted.");
2464 ("e2fsck_f", (RErr, [String "device"]), 108, [],
2465 [], (* lvresize tests this *)
2466 "check an ext2/ext3 filesystem",
2468 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2469 filesystem checker on C<device>, noninteractively (C<-p>),
2470 even if the filesystem appears to be clean (C<-f>).
2472 This command is only needed because of C<guestfs_resize2fs>
2473 (q.v.). Normally you should use C<guestfs_fsck>.");
2475 ("sleep", (RErr, [Int "secs"]), 109, [],
2476 [InitNone, Always, TestRun (
2478 "sleep for some seconds",
2480 Sleep for C<secs> seconds.");
2482 ("ntfs_3g_probe", (RInt "status", [Bool "rw"; String "device"]), 110, [],
2483 [InitNone, Always, TestOutputInt (
2484 [["sfdiskM"; "/dev/sda"; ","];
2485 ["mkfs"; "ntfs"; "/dev/sda1"];
2486 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2487 InitNone, Always, TestOutputInt (
2488 [["sfdiskM"; "/dev/sda"; ","];
2489 ["mkfs"; "ext2"; "/dev/sda1"];
2490 ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2491 "probe NTFS volume",
2493 This command runs the L<ntfs-3g.probe(8)> command which probes
2494 an NTFS C<device> for mountability. (Not all NTFS volumes can
2495 be mounted read-write, and some cannot be mounted at all).
2497 C<rw> is a boolean flag. Set it to true if you want to test
2498 if the volume can be mounted read-write. Set it to false if
2499 you want to test if the volume can be mounted read-only.
2501 The return value is an integer which C<0> if the operation
2502 would succeed, or some non-zero value documented in the
2503 L<ntfs-3g.probe(8)> manual page.");
2505 ("sh", (RString "output", [String "command"]), 111, [],
2506 [], (* XXX needs tests *)
2507 "run a command via the shell",
2509 This call runs a command from the guest filesystem via the
2512 This is like C<guestfs_command>, but passes the command to:
2514 /bin/sh -c \"command\"
2516 Depending on the guest's shell, this usually results in
2517 wildcards being expanded, shell expressions being interpolated
2520 All the provisos about C<guestfs_command> apply to this call.");
2522 ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2523 [], (* XXX needs tests *)
2524 "run a command via the shell returning lines",
2526 This is the same as C<guestfs_sh>, but splits the result
2527 into a list of lines.
2529 See also: C<guestfs_command_lines>");
2531 ("glob_expand", (RStringList "paths", [String "pattern"]), 113, [],
2532 [InitBasicFS, Always, TestOutputList (
2533 [["mkdir_p"; "/a/b/c"];
2534 ["touch"; "/a/b/c/d"];
2535 ["touch"; "/a/b/c/e"];
2536 ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2537 InitBasicFS, Always, TestOutputList (
2538 [["mkdir_p"; "/a/b/c"];
2539 ["touch"; "/a/b/c/d"];
2540 ["touch"; "/a/b/c/e"];
2541 ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2542 InitBasicFS, Always, TestOutputList (
2543 [["mkdir_p"; "/a/b/c"];
2544 ["touch"; "/a/b/c/d"];
2545 ["touch"; "/a/b/c/e"];
2546 ["glob_expand"; "/a/*/x/*"]], [])],
2547 "expand a wildcard path",
2549 This command searches for all the pathnames matching
2550 C<pattern> according to the wildcard expansion rules
2553 If no paths match, then this returns an empty list
2554 (note: not an error).
2556 It is just a wrapper around the C L<glob(3)> function
2557 with flags C<GLOB_MARK|GLOB_BRACE>.
2558 See that manual page for more details.");
2560 ("scrub_device", (RErr, [String "device"]), 114, [DangerWillRobinson],
2561 [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2562 [["scrub_device"; "/dev/sdc"]])],
2563 "scrub (securely wipe) a device",
2565 This command writes patterns over C<device> to make data retrieval
2568 It is an interface to the L<scrub(1)> program. See that
2569 manual page for more details.");
2571 ("scrub_file", (RErr, [String "file"]), 115, [],
2572 [InitBasicFS, Always, TestRun (
2573 [["write_file"; "/file"; "content"; "0"];
2574 ["scrub_file"; "/file"]])],
2575 "scrub (securely wipe) a file",
2577 This command writes patterns over a file to make data retrieval
2580 The file is I<removed> after scrubbing.
2582 It is an interface to the L<scrub(1)> program. See that
2583 manual page for more details.");
2585 ("scrub_freespace", (RErr, [String "dir"]), 116, [],
2586 [], (* XXX needs testing *)
2587 "scrub (securely wipe) free space",
2589 This command creates the directory C<dir> and then fills it
2590 with files until the filesystem is full, and scrubs the files
2591 as for C<guestfs_scrub_file>, and deletes them.
2592 The intention is to scrub any free space on the partition
2595 It is an interface to the L<scrub(1)> program. See that
2596 manual page for more details.");
2598 ("mkdtemp", (RString "dir", [String "template"]), 117, [],
2599 [InitBasicFS, Always, TestRun (
2601 ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2602 "create a temporary directory",
2604 This command creates a temporary directory. The
2605 C<template> parameter should be a full pathname for the
2606 temporary directory name with the final six characters being
2609 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2610 the second one being suitable for Windows filesystems.
2612 The name of the temporary directory that was created
2615 The temporary directory is created with mode 0700
2616 and is owned by root.
2618 The caller is responsible for deleting the temporary
2619 directory and its contents after use.
2621 See also: L<mkdtemp(3)>");
2623 ("wc_l", (RInt "lines", [String "path"]), 118, [],
2624 [InitSquashFS, Always, TestOutputInt (
2625 [["wc_l"; "/10klines"]], 10000)],
2626 "count lines in a file",
2628 This command counts the lines in a file, using the
2629 C<wc -l> external command.");
2631 ("wc_w", (RInt "words", [String "path"]), 119, [],
2632 [InitSquashFS, Always, TestOutputInt (
2633 [["wc_w"; "/10klines"]], 10000)],
2634 "count words in a file",
2636 This command counts the words in a file, using the
2637 C<wc -w> external command.");
2639 ("wc_c", (RInt "chars", [String "path"]), 120, [],
2640 [InitSquashFS, Always, TestOutputInt (
2641 [["wc_c"; "/100kallspaces"]], 102400)],
2642 "count characters in a file",
2644 This command counts the characters in a file, using the
2645 C<wc -c> external command.");
2647 ("head", (RStringList "lines", [String "path"]), 121, [ProtocolLimitWarning],
2648 [InitSquashFS, Always, TestOutputList (
2649 [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2650 "return first 10 lines of a file",
2652 This command returns up to the first 10 lines of a file as
2653 a list of strings.");
2655 ("head_n", (RStringList "lines", [Int "nrlines"; String "path"]), 122, [ProtocolLimitWarning],
2656 [InitSquashFS, Always, TestOutputList (
2657 [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2658 InitSquashFS, Always, TestOutputList (
2659 [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2660 InitSquashFS, Always, TestOutputList (
2661 [["head_n"; "0"; "/10klines"]], [])],
2662 "return first N lines of a file",
2664 If the parameter C<nrlines> is a positive number, this returns the first
2665 C<nrlines> lines of the file C<path>.
2667 If the parameter C<nrlines> is a negative number, this returns lines
2668 from the file C<path>, excluding the last C<nrlines> lines.
2670 If the parameter C<nrlines> is zero, this returns an empty list.");
2672 ("tail", (RStringList "lines", [String "path"]), 123, [ProtocolLimitWarning],
2673 [InitSquashFS, Always, TestOutputList (
2674 [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2675 "return last 10 lines of a file",
2677 This command returns up to the last 10 lines of a file as
2678 a list of strings.");
2680 ("tail_n", (RStringList "lines", [Int "nrlines"; String "path"]), 124, [ProtocolLimitWarning],
2681 [InitSquashFS, Always, TestOutputList (
2682 [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2683 InitSquashFS, Always, TestOutputList (
2684 [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2685 InitSquashFS, Always, TestOutputList (
2686 [["tail_n"; "0"; "/10klines"]], [])],
2687 "return last N lines of a file",
2689 If the parameter C<nrlines> is a positive number, this returns the last
2690 C<nrlines> lines of the file C<path>.
2692 If the parameter C<nrlines> is a negative number, this returns lines
2693 from the file C<path>, starting with the C<-nrlines>th line.
2695 If the parameter C<nrlines> is zero, this returns an empty list.");
2697 ("df", (RString "output", []), 125, [],
2698 [], (* XXX Tricky to test because it depends on the exact format
2699 * of the 'df' command and other imponderables.
2701 "report file system disk space usage",
2703 This command runs the C<df> command to report disk space used.
2705 This command is mostly useful for interactive sessions. It
2706 is I<not> intended that you try to parse the output string.
2707 Use C<statvfs> from programs.");
2709 ("df_h", (RString "output", []), 126, [],
2710 [], (* XXX Tricky to test because it depends on the exact format
2711 * of the 'df' command and other imponderables.
2713 "report file system disk space usage (human readable)",
2715 This command runs the C<df -h> command to report disk space used
2716 in human-readable format.
2718 This command is mostly useful for interactive sessions. It
2719 is I<not> intended that you try to parse the output string.
2720 Use C<statvfs> from programs.");
2722 ("du", (RInt64 "sizekb", [String "path"]), 127, [],
2723 [InitBasicFS, Always, TestOutputInt (
2725 ["du"; "/p"]], 1 (* ie. 1 block, so depends on ext3 blocksize *))],
2726 "estimate file space usage",
2728 This command runs the C<du -s> command to estimate file space
2731 C<path> can be a file or a directory. If C<path> is a directory
2732 then the estimate includes the contents of the directory and all
2733 subdirectories (recursively).
2735 The result is the estimated size in I<kilobytes>
2736 (ie. units of 1024 bytes).");
2738 ("initrd_list", (RStringList "filenames", [String "path"]), 128, [],
2739 [InitSquashFS, Always, TestOutputList (
2740 [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3"])],
2741 "list files in an initrd",
2743 This command lists out files contained in an initrd.
2745 The files are listed without any initial C</> character. The
2746 files are listed in the order they appear (not necessarily
2747 alphabetical). Directory names are listed as separate items.
2749 Old Linux kernels (2.4 and earlier) used a compressed ext2
2750 filesystem as initrd. We I<only> support the newer initramfs
2751 format (compressed cpio files).");
2753 ("mount_loop", (RErr, [String "file"; String "mountpoint"]), 129, [],
2755 "mount a file using the loop device",
2757 This command lets you mount C<file> (a filesystem image
2758 in a file) on a mount point. It is entirely equivalent to
2759 the command C<mount -o loop file mountpoint>.");
2761 ("mkswap", (RErr, [String "device"]), 130, [],
2762 [InitEmpty, Always, TestRun (
2763 [["sfdiskM"; "/dev/sda"; ","];
2764 ["mkswap"; "/dev/sda1"]])],
2765 "create a swap partition",
2767 Create a swap partition on C<device>.");
2769 ("mkswap_L", (RErr, [String "label"; String "device"]), 131, [],
2770 [InitEmpty, Always, TestRun (
2771 [["sfdiskM"; "/dev/sda"; ","];
2772 ["mkswap_L"; "hello"; "/dev/sda1"]])],
2773 "create a swap partition with a label",
2775 Create a swap partition on C<device> with label C<label>.");
2777 ("mkswap_U", (RErr, [String "uuid"; String "device"]), 132, [],
2778 [InitEmpty, Always, TestRun (
2779 [["sfdiskM"; "/dev/sda"; ","];
2780 ["mkswap_U"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"; "/dev/sda1"]])],
2781 "create a swap partition with an explicit UUID",
2783 Create a swap partition on C<device> with UUID C<uuid>.");
2785 ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 133, [],
2786 [InitBasicFS, Always, TestOutputStruct (
2787 [["mknod"; "0o10777"; "0"; "0"; "/node"];
2788 (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2789 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2790 InitBasicFS, Always, TestOutputStruct (
2791 [["mknod"; "0o60777"; "66"; "99"; "/node"];
2792 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2793 "make block, character or FIFO devices",
2795 This call creates block or character special devices, or
2796 named pipes (FIFOs).
2798 The C<mode> parameter should be the mode, using the standard
2799 constants. C<devmajor> and C<devminor> are the
2800 device major and minor numbers, only used when creating block
2801 and character special devices.");
2803 ("mkfifo", (RErr, [Int "mode"; String "path"]), 134, [],
2804 [InitBasicFS, Always, TestOutputStruct (
2805 [["mkfifo"; "0o777"; "/node"];
2806 ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2807 "make FIFO (named pipe)",
2809 This call creates a FIFO (named pipe) called C<path> with
2810 mode C<mode>. It is just a convenient wrapper around
2811 C<guestfs_mknod>.");
2813 ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 135, [],
2814 [InitBasicFS, Always, TestOutputStruct (
2815 [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2816 ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2817 "make block device node",
2819 This call creates a block device node called C<path> with
2820 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2821 It is just a convenient wrapper around C<guestfs_mknod>.");
2823 ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 136, [],
2824 [InitBasicFS, Always, TestOutputStruct (
2825 [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2826 ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2827 "make char device node",
2829 This call creates a char device node called C<path> with
2830 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2831 It is just a convenient wrapper around C<guestfs_mknod>.");
2833 ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2834 [], (* XXX umask is one of those stateful things that we should
2835 * reset between each test.
2837 "set file mode creation mask (umask)",
2839 This function sets the mask used for creating new files and
2840 device nodes to C<mask & 0777>.
2842 Typical umask values would be C<022> which creates new files
2843 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2844 C<002> which creates new files with permissions like
2845 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2847 The default umask is C<022>. This is important because it
2848 means that directories and device nodes will be created with
2849 C<0644> or C<0755> mode even if you specify C<0777>.
2851 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2853 This call returns the previous umask.");
2855 ("readdir", (RStructList ("entries", "dirent"), [String "dir"]), 138, [],
2857 "read directories entries",
2859 This returns the list of directory entries in directory C<dir>.
2861 All entries in the directory are returned, including C<.> and
2862 C<..>. The entries are I<not> sorted, but returned in the same
2863 order as the underlying filesystem.
2865 Also this call returns basic file type information about each
2866 file. The C<ftyp> field will contain one of the following characters:
2904 The L<readdir(3)> returned a C<d_type> field with an
2909 This function is primarily intended for use by programs. To
2910 get a simple list of names, use C<guestfs_ls>. To get a printable
2911 directory for human consumption, use C<guestfs_ll>.");
2913 ("sfdiskM", (RErr, [String "device"; StringList "lines"]), 139, [DangerWillRobinson],
2915 "create partitions on a block device",
2917 This is a simplified interface to the C<guestfs_sfdisk>
2918 command, where partition sizes are specified in megabytes
2919 only (rounded to the nearest cylinder) and you don't need
2920 to specify the cyls, heads and sectors parameters which
2921 were rarely if ever used anyway.
2923 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
2925 ("zfile", (RString "description", [String "method"; String "path"]), 140, [],
2927 "determine file type inside a compressed file",
2929 This command runs C<file> after first decompressing C<path>
2932 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
2934 See also: C<guestfs_file>");
2936 ("getxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 141, [],
2938 "list extended attributes of a file or directory",
2940 This call lists the extended attributes of the file or directory
2943 At the system call level, this is a combination of the
2944 L<listxattr(2)> and L<getxattr(2)> calls.
2946 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
2948 ("lgetxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 142, [],
2950 "list extended attributes of a file or directory",
2952 This is the same as C<guestfs_getxattrs>, but if C<path>
2953 is a symbolic link, then it returns the extended attributes
2954 of the link itself.");
2956 ("setxattr", (RErr, [String "xattr";
2957 String "val"; Int "vallen"; (* will be BufferIn *)
2958 String "path"]), 143, [],
2960 "set extended attribute of a file or directory",
2962 This call sets the extended attribute named C<xattr>
2963 of the file C<path> to the value C<val> (of length C<vallen>).
2964 The value is arbitrary 8 bit data.
2966 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
2968 ("lsetxattr", (RErr, [String "xattr";
2969 String "val"; Int "vallen"; (* will be BufferIn *)
2970 String "path"]), 144, [],
2972 "set extended attribute of a file or directory",
2974 This is the same as C<guestfs_setxattr>, but if C<path>
2975 is a symbolic link, then it sets an extended attribute
2976 of the link itself.");
2978 ("removexattr", (RErr, [String "xattr"; String "path"]), 145, [],
2980 "remove extended attribute of a file or directory",
2982 This call removes the extended attribute named C<xattr>
2983 of the file C<path>.
2985 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
2987 ("lremovexattr", (RErr, [String "xattr"; String "path"]), 146, [],
2989 "remove extended attribute of a file or directory",
2991 This is the same as C<guestfs_removexattr>, but if C<path>
2992 is a symbolic link, then it removes an extended attribute
2993 of the link itself.");
2995 ("mountpoints", (RHashtable "mps", []), 147, [],
2999 This call is similar to C<guestfs_mounts>. That call returns
3000 a list of devices. This one returns a hash table (map) of
3001 device name to directory where the device is mounted.");
3003 ("mkmountpoint", (RErr, [String "path"]), 148, [],
3005 "create a mountpoint",
3007 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3008 specialized calls that can be used to create extra mountpoints
3009 before mounting the first filesystem.
3011 These calls are I<only> necessary in some very limited circumstances,
3012 mainly the case where you want to mount a mix of unrelated and/or
3013 read-only filesystems together.
3015 For example, live CDs often contain a \"Russian doll\" nest of
3016 filesystems, an ISO outer layer, with a squashfs image inside, with
3017 an ext2/3 image inside that. You can unpack this as follows
3020 add-ro Fedora-11-i686-Live.iso
3023 mkmountpoint /squash
3026 mount-loop /cd/LiveOS/squashfs.img /squash
3027 mount-loop /squash/LiveOS/ext3fs.img /ext3
3029 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3031 ("rmmountpoint", (RErr, [String "path"]), 149, [],
3033 "remove a mountpoint",
3035 This calls removes a mountpoint that was previously created
3036 with C<guestfs_mkmountpoint>. See C<guestfs_mkmountpoint>
3037 for full details.");
3039 ("read_file", (RBufferOut "content", [String "path"]), 150, [ProtocolLimitWarning],
3040 [InitBasicFS, Always, TestOutput (
3041 [["write_file"; "/new"; "new file contents"; "0"];
3042 ["read_file"; "/new"]], "new file contents")],
3045 This calls returns the contents of the file C<path> as a
3048 Unlike C<guestfs_cat>, this function can correctly
3049 handle files that contain embedded ASCII NUL characters.
3050 However unlike C<guestfs_download>, this function is limited
3051 in the total size of file that can be handled.");
3055 let all_functions = non_daemon_functions @ daemon_functions
3057 (* In some places we want the functions to be displayed sorted
3058 * alphabetically, so this is useful:
3060 let all_functions_sorted =
3061 List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
3062 compare n1 n2) all_functions
3064 (* Field types for structures. *)
3066 | FChar (* C 'char' (really, a 7 bit byte). *)
3067 | FString (* nul-terminated ASCII string. *)
3068 | FBuffer (* opaque buffer of bytes, (char *, int) pair *)
3073 | FBytes (* Any int measure that counts bytes. *)
3074 | FUUID (* 32 bytes long, NOT nul-terminated. *)
3075 | FOptPercent (* [0..100], or -1 meaning "not present". *)
3077 (* Because we generate extra parsing code for LVM command line tools,
3078 * we have to pull out the LVM columns separately here.
3088 "pv_attr", FString (* XXX *);
3089 "pv_pe_count", FInt64;
3090 "pv_pe_alloc_count", FInt64;
3093 "pv_mda_count", FInt64;
3094 "pv_mda_free", FBytes;
3095 (* Not in Fedora 10:
3096 "pv_mda_size", FBytes;
3103 "vg_attr", FString (* XXX *);
3106 "vg_sysid", FString;
3107 "vg_extent_size", FBytes;
3108 "vg_extent_count", FInt64;
3109 "vg_free_count", FInt64;
3114 "snap_count", FInt64;
3117 "vg_mda_count", FInt64;
3118 "vg_mda_free", FBytes;
3119 (* Not in Fedora 10:
3120 "vg_mda_size", FBytes;
3126 "lv_attr", FString (* XXX *);
3129 "lv_kernel_major", FInt64;
3130 "lv_kernel_minor", FInt64;
3132 "seg_count", FInt64;
3134 "snap_percent", FOptPercent;
3135 "copy_percent", FOptPercent;
3138 "mirror_log", FString;
3142 (* Names and fields in all structures (in RStruct and RStructList)
3146 (* The old RIntBool return type, only ever used for aug_defnode. Do
3147 * not use this struct in any new code.
3150 "i", FInt32; (* for historical compatibility *)
3151 "b", FInt32; (* for historical compatibility *)
3154 (* LVM PVs, VGs, LVs. *)
3155 "lvm_pv", lvm_pv_cols;
3156 "lvm_vg", lvm_vg_cols;
3157 "lvm_lv", lvm_lv_cols;
3159 (* Column names and types from stat structures.
3160 * NB. Can't use things like 'st_atime' because glibc header files
3161 * define some of these as macros. Ugh.
3192 (* Column names in dirent structure. *)
3195 (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
3200 (* Version numbers. *)
3208 (* Extended attribute. *)
3210 "attrname", FString;
3213 ] (* end of structs *)
3215 (* Ugh, Java has to be different ..
3216 * These names are also used by the Haskell bindings.
3218 let java_structs = [
3219 "int_bool", "IntBool";
3224 "statvfs", "StatVFS";
3226 "version", "Version";
3230 (* Used for testing language bindings. *)
3232 | CallString of string
3233 | CallOptString of string option
3234 | CallStringList of string list
3238 (* Used to memoize the result of pod2text. *)
3239 let pod2text_memo_filename = "src/.pod2text.data"
3240 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
3242 let chan = open_in pod2text_memo_filename in
3243 let v = input_value chan in
3247 _ -> Hashtbl.create 13
3249 (* Useful functions.
3250 * Note we don't want to use any external OCaml libraries which
3251 * makes this a bit harder than it should be.
3253 let failwithf fs = ksprintf failwith fs
3255 let replace_char s c1 c2 =
3256 let s2 = String.copy s in
3257 let r = ref false in
3258 for i = 0 to String.length s2 - 1 do
3259 if String.unsafe_get s2 i = c1 then (
3260 String.unsafe_set s2 i c2;
3264 if not !r then s else s2
3268 (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
3270 let triml ?(test = isspace) str =
3272 let n = ref (String.length str) in
3273 while !n > 0 && test str.[!i]; do
3278 else String.sub str !i !n
3280 let trimr ?(test = isspace) str =
3281 let n = ref (String.length str) in
3282 while !n > 0 && test str.[!n-1]; do
3285 if !n = String.length str then str
3286 else String.sub str 0 !n
3288 let trim ?(test = isspace) str =
3289 trimr ~test (triml ~test str)
3291 let rec find s sub =
3292 let len = String.length s in
3293 let sublen = String.length sub in
3295 if i <= len-sublen then (
3297 if j < sublen then (
3298 if s.[i+j] = sub.[j] then loop2 (j+1)
3304 if r = -1 then loop (i+1) else r
3310 let rec replace_str s s1 s2 =
3311 let len = String.length s in
3312 let sublen = String.length s1 in
3313 let i = find s s1 in
3316 let s' = String.sub s 0 i in
3317 let s'' = String.sub s (i+sublen) (len-i-sublen) in
3318 s' ^ s2 ^ replace_str s'' s1 s2
3321 let rec string_split sep str =
3322 let len = String.length str in
3323 let seplen = String.length sep in
3324 let i = find str sep in
3325 if i = -1 then [str]
3327 let s' = String.sub str 0 i in
3328 let s'' = String.sub str (i+seplen) (len-i-seplen) in
3329 s' :: string_split sep s''
3332 let files_equal n1 n2 =
3333 let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
3334 match Sys.command cmd with
3337 | i -> failwithf "%s: failed with error code %d" cmd i
3339 let rec find_map f = function
3340 | [] -> raise Not_found
3344 | None -> find_map f xs
3347 let rec loop i = function
3349 | x :: xs -> f i x; loop (i+1) xs
3354 let rec loop i = function
3356 | x :: xs -> let r = f i x in r :: loop (i+1) xs
3360 let name_of_argt = function
3361 | String n | OptString n | StringList n | Bool n | Int n
3362 | FileIn n | FileOut n -> n
3364 let java_name_of_struct typ =
3365 try List.assoc typ java_structs
3368 "java_name_of_struct: no java_structs entry corresponding to %s" typ
3370 let cols_of_struct typ =
3371 try List.assoc typ structs
3373 failwithf "cols_of_struct: unknown struct %s" typ
3375 let seq_of_test = function
3376 | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
3377 | TestOutputListOfDevices (s, _)
3378 | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
3379 | TestOutputTrue s | TestOutputFalse s
3380 | TestOutputLength (s, _) | TestOutputStruct (s, _)
3381 | TestLastFail s -> s
3383 (* Check function names etc. for consistency. *)
3384 let check_functions () =
3385 let contains_uppercase str =
3386 let len = String.length str in
3388 if i >= len then false
3391 if c >= 'A' && c <= 'Z' then true
3398 (* Check function names. *)
3400 fun (name, _, _, _, _, _, _) ->
3401 if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
3402 failwithf "function name %s does not need 'guestfs' prefix" name;
3404 failwithf "function name is empty";
3405 if name.[0] < 'a' || name.[0] > 'z' then
3406 failwithf "function name %s must start with lowercase a-z" name;
3407 if String.contains name '-' then
3408 failwithf "function name %s should not contain '-', use '_' instead."
3412 (* Check function parameter/return names. *)
3414 fun (name, style, _, _, _, _, _) ->
3415 let check_arg_ret_name n =
3416 if contains_uppercase n then
3417 failwithf "%s param/ret %s should not contain uppercase chars"
3419 if String.contains n '-' || String.contains n '_' then
3420 failwithf "%s param/ret %s should not contain '-' or '_'"
3423 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;
3424 if n = "int" || n = "char" || n = "short" || n = "long" then
3425 failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
3426 if n = "i" || n = "n" then
3427 failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
3428 if n = "argv" || n = "args" then
3429 failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
3432 (match fst style with
3434 | RInt n | RInt64 n | RBool n
3435 | RConstString n | RConstOptString n | RString n
3436 | RStringList n | RStruct (n, _) | RStructList (n, _)
3437 | RHashtable n | RBufferOut n ->
3438 check_arg_ret_name n
3440 List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
3443 (* Check short descriptions. *)
3445 fun (name, _, _, _, _, shortdesc, _) ->
3446 if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
3447 failwithf "short description of %s should begin with lowercase." name;
3448 let c = shortdesc.[String.length shortdesc-1] in
3449 if c = '\n' || c = '.' then
3450 failwithf "short description of %s should not end with . or \\n." name
3453 (* Check long dscriptions. *)
3455 fun (name, _, _, _, _, _, longdesc) ->
3456 if longdesc.[String.length longdesc-1] = '\n' then
3457 failwithf "long description of %s should not end with \\n." name
3460 (* Check proc_nrs. *)
3462 fun (name, _, proc_nr, _, _, _, _) ->
3463 if proc_nr <= 0 then
3464 failwithf "daemon function %s should have proc_nr > 0" name
3468 fun (name, _, proc_nr, _, _, _, _) ->
3469 if proc_nr <> -1 then
3470 failwithf "non-daemon function %s should have proc_nr -1" name
3471 ) non_daemon_functions;
3474 List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
3477 List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
3478 let rec loop = function
3481 | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
3483 | (name1,nr1) :: (name2,nr2) :: _ ->
3484 failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
3492 (* Ignore functions that have no tests. We generate a
3493 * warning when the user does 'make check' instead.
3495 | name, _, _, _, [], _, _ -> ()
3496 | name, _, _, _, tests, _, _ ->
3500 match seq_of_test test with
3502 failwithf "%s has a test containing an empty sequence" name
3503 | cmds -> List.map List.hd cmds
3505 let funcs = List.flatten funcs in
3507 let tested = List.mem name funcs in
3510 failwithf "function %s has tests but does not test itself" name
3513 (* 'pr' prints to the current output file. *)
3514 let chan = ref stdout
3515 let pr fs = ksprintf (output_string !chan) fs
3517 (* Generate a header block in a number of standard styles. *)
3518 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
3519 type license = GPLv2 | LGPLv2
3521 let generate_header comment license =
3522 let c = match comment with
3523 | CStyle -> pr "/* "; " *"
3524 | HashStyle -> pr "# "; "#"
3525 | OCamlStyle -> pr "(* "; " *"
3526 | HaskellStyle -> pr "{- "; " " in
3527 pr "libguestfs generated file\n";
3528 pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
3529 pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
3531 pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
3535 pr "%s This program is free software; you can redistribute it and/or modify\n" c;
3536 pr "%s it under the terms of the GNU General Public License as published by\n" c;
3537 pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
3538 pr "%s (at your option) any later version.\n" c;
3540 pr "%s This program is distributed in the hope that it will be useful,\n" c;
3541 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3542 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" c;
3543 pr "%s GNU General Public License for more details.\n" c;
3545 pr "%s You should have received a copy of the GNU General Public License along\n" c;
3546 pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
3547 pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
3550 pr "%s This library is free software; you can redistribute it and/or\n" c;
3551 pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
3552 pr "%s License as published by the Free Software Foundation; either\n" c;
3553 pr "%s version 2 of the License, or (at your option) any later version.\n" c;
3555 pr "%s This library is distributed in the hope that it will be useful,\n" c;
3556 pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3557 pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" c;
3558 pr "%s Lesser General Public License for more details.\n" c;
3560 pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
3561 pr "%s License along with this library; if not, write to the Free Software\n" c;
3562 pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
3565 | CStyle -> pr " */\n"
3567 | OCamlStyle -> pr " *)\n"
3568 | HaskellStyle -> pr "-}\n"
3572 (* Start of main code generation functions below this line. *)
3574 (* Generate the pod documentation for the C API. *)
3575 let rec generate_actions_pod () =
3577 fun (shortname, style, _, flags, _, _, longdesc) ->
3578 if not (List.mem NotInDocs flags) then (
3579 let name = "guestfs_" ^ shortname in
3580 pr "=head2 %s\n\n" name;
3582 generate_prototype ~extern:false ~handle:"handle" name style;
3584 pr "%s\n\n" longdesc;
3585 (match fst style with
3587 pr "This function returns 0 on success or -1 on error.\n\n"
3589 pr "On error this function returns -1.\n\n"
3591 pr "On error this function returns -1.\n\n"
3593 pr "This function returns a C truth value on success or -1 on error.\n\n"
3595 pr "This function returns a string, or NULL on error.
3596 The string is owned by the guest handle and must I<not> be freed.\n\n"
3597 | RConstOptString _ ->
3598 pr "This function returns a string which may be NULL.
3599 There is way to return an error from this function.
3600 The string is owned by the guest handle and must I<not> be freed.\n\n"
3602 pr "This function returns a string, or NULL on error.
3603 I<The caller must free the returned string after use>.\n\n"
3605 pr "This function returns a NULL-terminated array of strings
3606 (like L<environ(3)>), or NULL if there was an error.
3607 I<The caller must free the strings and the array after use>.\n\n"
3608 | RStruct (_, typ) ->
3609 pr "This function returns a C<struct guestfs_%s *>,
3610 or NULL if there was an error.
3611 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
3612 | RStructList (_, typ) ->
3613 pr "This function returns a C<struct guestfs_%s_list *>
3614 (see E<lt>guestfs-structs.hE<gt>),
3615 or NULL if there was an error.
3616 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
3618 pr "This function returns a NULL-terminated array of
3619 strings, or NULL if there was an error.
3620 The array of strings will always have length C<2n+1>, where
3621 C<n> keys and values alternate, followed by the trailing NULL entry.
3622 I<The caller must free the strings and the array after use>.\n\n"
3624 pr "This function returns a buffer, or NULL on error.
3625 The size of the returned buffer is written to C<*size_r>.
3626 I<The caller must free the returned buffer after use>.\n\n"
3628 if List.mem ProtocolLimitWarning flags then
3629 pr "%s\n\n" protocol_limit_warning;
3630 if List.mem DangerWillRobinson flags then
3631 pr "%s\n\n" danger_will_robinson
3633 ) all_functions_sorted
3635 and generate_structs_pod () =
3636 (* Structs documentation. *)
3639 pr "=head2 guestfs_%s\n" typ;
3641 pr " struct guestfs_%s {\n" typ;
3644 | name, FChar -> pr " char %s;\n" name
3645 | name, FUInt32 -> pr " uint32_t %s;\n" name
3646 | name, FInt32 -> pr " int32_t %s;\n" name
3647 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3648 | name, FInt64 -> pr " int64_t %s;\n" name
3649 | name, FString -> pr " char *%s;\n" name
3651 pr " /* The next two fields describe a byte array. */\n";
3652 pr " uint32_t %s_len;\n" name;
3653 pr " char *%s;\n" name
3655 pr " /* The next field is NOT nul-terminated, be careful when printing it: */\n";
3656 pr " char %s[32];\n" name
3657 | name, FOptPercent ->
3658 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
3659 pr " float %s;\n" name
3663 pr " struct guestfs_%s_list {\n" typ;
3664 pr " uint32_t len; /* Number of elements in list. */\n";
3665 pr " struct guestfs_%s *val; /* Elements. */\n" typ;
3668 pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
3669 pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
3674 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
3675 * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
3677 * We have to use an underscore instead of a dash because otherwise
3678 * rpcgen generates incorrect code.
3680 * This header is NOT exported to clients, but see also generate_structs_h.
3682 and generate_xdr () =
3683 generate_header CStyle LGPLv2;
3685 (* This has to be defined to get around a limitation in Sun's rpcgen. *)
3686 pr "typedef string str<>;\n";
3689 (* Internal structures. *)
3693 pr "struct guestfs_int_%s {\n" typ;
3695 | name, FChar -> pr " char %s;\n" name
3696 | name, FString -> pr " string %s<>;\n" name
3697 | name, FBuffer -> pr " opaque %s<>;\n" name
3698 | name, FUUID -> pr " opaque %s[32];\n" name
3699 | name, (FInt32|FUInt32) -> pr " int %s;\n" name
3700 | name, (FInt64|FUInt64|FBytes) -> pr " hyper %s;\n" name
3701 | name, FOptPercent -> pr " float %s;\n" name
3705 pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
3710 fun (shortname, style, _, _, _, _, _) ->
3711 let name = "guestfs_" ^ shortname in
3713 (match snd style with
3716 pr "struct %s_args {\n" name;
3719 | String n -> pr " string %s<>;\n" n
3720 | OptString n -> pr " str *%s;\n" n
3721 | StringList n -> pr " str %s<>;\n" n
3722 | Bool n -> pr " bool %s;\n" n
3723 | Int n -> pr " int %s;\n" n
3724 | FileIn _ | FileOut _ -> ()
3728 (match fst style with
3731 pr "struct %s_ret {\n" name;
3735 pr "struct %s_ret {\n" name;
3736 pr " hyper %s;\n" n;
3739 pr "struct %s_ret {\n" name;
3742 | RConstString _ | RConstOptString _ ->
3743 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
3745 pr "struct %s_ret {\n" name;
3746 pr " string %s<>;\n" n;
3749 pr "struct %s_ret {\n" name;
3750 pr " str %s<>;\n" n;
3752 | RStruct (n, typ) ->
3753 pr "struct %s_ret {\n" name;
3754 pr " guestfs_int_%s %s;\n" typ n;
3756 | RStructList (n, typ) ->
3757 pr "struct %s_ret {\n" name;
3758 pr " guestfs_int_%s_list %s;\n" typ n;
3761 pr "struct %s_ret {\n" name;
3762 pr " str %s<>;\n" n;
3765 pr "struct %s_ret {\n" name;
3766 pr " opaque %s<>;\n" n;
3771 (* Table of procedure numbers. *)
3772 pr "enum guestfs_procedure {\n";
3774 fun (shortname, _, proc_nr, _, _, _, _) ->
3775 pr " GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
3777 pr " GUESTFS_PROC_NR_PROCS\n";
3781 (* Having to choose a maximum message size is annoying for several
3782 * reasons (it limits what we can do in the API), but it (a) makes
3783 * the protocol a lot simpler, and (b) provides a bound on the size
3784 * of the daemon which operates in limited memory space. For large
3785 * file transfers you should use FTP.
3787 pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
3790 (* Message header, etc. *)
3792 /* The communication protocol is now documented in the guestfs(3)
3796 const GUESTFS_PROGRAM = 0x2000F5F5;
3797 const GUESTFS_PROTOCOL_VERSION = 1;
3799 /* These constants must be larger than any possible message length. */
3800 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
3801 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
3803 enum guestfs_message_direction {
3804 GUESTFS_DIRECTION_CALL = 0, /* client -> daemon */
3805 GUESTFS_DIRECTION_REPLY = 1 /* daemon -> client */
3808 enum guestfs_message_status {
3809 GUESTFS_STATUS_OK = 0,
3810 GUESTFS_STATUS_ERROR = 1
3813 const GUESTFS_ERROR_LEN = 256;
3815 struct guestfs_message_error {
3816 string error_message<GUESTFS_ERROR_LEN>;
3819 struct guestfs_message_header {
3820 unsigned prog; /* GUESTFS_PROGRAM */
3821 unsigned vers; /* GUESTFS_PROTOCOL_VERSION */
3822 guestfs_procedure proc; /* GUESTFS_PROC_x */
3823 guestfs_message_direction direction;
3824 unsigned serial; /* message serial number */
3825 guestfs_message_status status;
3828 const GUESTFS_MAX_CHUNK_SIZE = 8192;
3830 struct guestfs_chunk {
3831 int cancel; /* if non-zero, transfer is cancelled */
3832 /* data size is 0 bytes if the transfer has finished successfully */
3833 opaque data<GUESTFS_MAX_CHUNK_SIZE>;
3837 (* Generate the guestfs-structs.h file. *)
3838 and generate_structs_h () =
3839 generate_header CStyle LGPLv2;
3841 (* This is a public exported header file containing various
3842 * structures. The structures are carefully written to have
3843 * exactly the same in-memory format as the XDR structures that
3844 * we use on the wire to the daemon. The reason for creating
3845 * copies of these structures here is just so we don't have to
3846 * export the whole of guestfs_protocol.h (which includes much
3847 * unrelated and XDR-dependent stuff that we don't want to be
3848 * public, or required by clients).
3850 * To reiterate, we will pass these structures to and from the
3851 * client with a simple assignment or memcpy, so the format
3852 * must be identical to what rpcgen / the RFC defines.
3855 (* Public structures. *)
3858 pr "struct guestfs_%s {\n" typ;
3861 | name, FChar -> pr " char %s;\n" name
3862 | name, FString -> pr " char *%s;\n" name
3864 pr " uint32_t %s_len;\n" name;
3865 pr " char *%s;\n" name
3866 | name, FUUID -> pr " char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3867 | name, FUInt32 -> pr " uint32_t %s;\n" name
3868 | name, FInt32 -> pr " int32_t %s;\n" name
3869 | name, (FUInt64|FBytes) -> pr " uint64_t %s;\n" name
3870 | name, FInt64 -> pr " int64_t %s;\n" name
3871 | name, FOptPercent -> pr " float %s; /* [0..100] or -1 */\n" name
3875 pr "struct guestfs_%s_list {\n" typ;
3876 pr " uint32_t len;\n";
3877 pr " struct guestfs_%s *val;\n" typ;
3880 pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
3881 pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
3885 (* Generate the guestfs-actions.h file. *)
3886 and generate_actions_h () =
3887 generate_header CStyle LGPLv2;
3889 fun (shortname, style, _, _, _, _, _) ->
3890 let name = "guestfs_" ^ shortname in
3891 generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3895 (* Generate the client-side dispatch stubs. *)
3896 and generate_client_actions () =
3897 generate_header CStyle LGPLv2;
3903 #include \"guestfs.h\"
3904 #include \"guestfs_protocol.h\"
3906 #define error guestfs_error
3907 #define perrorf guestfs_perrorf
3908 #define safe_malloc guestfs_safe_malloc
3909 #define safe_realloc guestfs_safe_realloc
3910 #define safe_strdup guestfs_safe_strdup
3911 #define safe_memdup guestfs_safe_memdup
3913 /* Check the return message from a call for validity. */
3915 check_reply_header (guestfs_h *g,
3916 const struct guestfs_message_header *hdr,
3917 int proc_nr, int serial)
3919 if (hdr->prog != GUESTFS_PROGRAM) {
3920 error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
3923 if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
3924 error (g, \"wrong protocol version (%%d/%%d)\",
3925 hdr->vers, GUESTFS_PROTOCOL_VERSION);
3928 if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
3929 error (g, \"unexpected message direction (%%d/%%d)\",
3930 hdr->direction, GUESTFS_DIRECTION_REPLY);
3933 if (hdr->proc != proc_nr) {
3934 error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
3937 if (hdr->serial != serial) {
3938 error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
3945 /* Check we are in the right state to run a high-level action. */
3947 check_state (guestfs_h *g, const char *caller)
3949 if (!guestfs_is_ready (g)) {
3950 if (guestfs_is_config (g))
3951 error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
3953 else if (guestfs_is_launching (g))
3954 error (g, \"%%s: call wait_ready() before using this function\",
3957 error (g, \"%%s called from the wrong state, %%d != READY\",
3958 caller, guestfs_get_state (g));
3966 (* Client-side stubs for each function. *)
3968 fun (shortname, style, _, _, _, _, _) ->
3969 let name = "guestfs_" ^ shortname in
3971 (* Generate the context struct which stores the high-level
3972 * state between callback functions.
3974 pr "struct %s_ctx {\n" shortname;
3975 pr " /* This flag is set by the callbacks, so we know we've done\n";
3976 pr " * the callbacks as expected, and in the right sequence.\n";
3977 pr " * 0 = not called, 1 = reply_cb called.\n";
3979 pr " int cb_sequence;\n";
3980 pr " struct guestfs_message_header hdr;\n";
3981 pr " struct guestfs_message_error err;\n";
3982 (match fst style with
3984 | RConstString _ | RConstOptString _ ->
3985 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
3987 | RBool _ | RString _ | RStringList _
3988 | RStruct _ | RStructList _
3989 | RHashtable _ | RBufferOut _ ->
3990 pr " struct %s_ret ret;\n" name
3995 (* Generate the reply callback function. *)
3996 pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
3998 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
3999 pr " struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
4001 pr " /* This should definitely not happen. */\n";
4002 pr " if (ctx->cb_sequence != 0) {\n";
4003 pr " ctx->cb_sequence = 9999;\n";
4004 pr " error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
4008 pr " ml->main_loop_quit (ml, g);\n";
4010 pr " if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
4011 pr " error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
4014 pr " if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
4015 pr " if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
4016 pr " error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
4023 (match fst style with
4025 | RConstString _ | RConstOptString _ ->
4026 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4028 | RBool _ | RString _ | RStringList _
4029 | RStruct _ | RStructList _
4030 | RHashtable _ | RBufferOut _ ->
4031 pr " if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
4032 pr " error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
4038 pr " ctx->cb_sequence = 1;\n";
4041 (* Generate the action stub. *)
4042 generate_prototype ~extern:false ~semicolon:false ~newline:true
4043 ~handle:"g" name style;
4046 match fst style with
4047 | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
4048 | RConstString _ | RConstOptString _ ->
4049 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4050 | RString _ | RStringList _
4051 | RStruct _ | RStructList _
4052 | RHashtable _ | RBufferOut _ ->
4057 (match snd style with
4059 | _ -> pr " struct %s_args args;\n" name
4062 pr " struct %s_ctx ctx;\n" shortname;
4063 pr " guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
4064 pr " int serial;\n";
4066 pr " if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
4067 pr " guestfs_set_busy (g);\n";
4069 pr " memset (&ctx, 0, sizeof ctx);\n";
4072 (* Send the main header and arguments. *)
4073 (match snd style with
4075 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
4076 (String.uppercase shortname)
4081 pr " args.%s = (char *) %s;\n" n n
4083 pr " args.%s = %s ? (char **) &%s : NULL;\n" n n n
4085 pr " args.%s.%s_val = (char **) %s;\n" n n n;
4086 pr " for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
4088 pr " args.%s = %s;\n" n n
4090 pr " args.%s = %s;\n" n n
4091 | FileIn _ | FileOut _ -> ()
4093 pr " serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
4094 (String.uppercase shortname);
4095 pr " (xdrproc_t) xdr_%s_args, (char *) &args);\n"
4098 pr " if (serial == -1) {\n";
4099 pr " guestfs_end_busy (g);\n";
4100 pr " return %s;\n" error_code;
4104 (* Send any additional files (FileIn) requested. *)
4105 let need_read_reply_label = ref false in
4112 pr " r = guestfs__send_file_sync (g, %s);\n" n;
4113 pr " if (r == -1) {\n";
4114 pr " guestfs_end_busy (g);\n";
4115 pr " return %s;\n" error_code;
4117 pr " if (r == -2) /* daemon cancelled */\n";
4118 pr " goto read_reply;\n";
4119 need_read_reply_label := true;
4125 (* Wait for the reply from the remote end. *)
4126 if !need_read_reply_label then pr " read_reply:\n";
4127 pr " guestfs__switch_to_receiving (g);\n";
4128 pr " ctx.cb_sequence = 0;\n";
4129 pr " guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
4130 pr " (void) ml->main_loop_run (ml, g);\n";
4131 pr " guestfs_set_reply_callback (g, NULL, NULL);\n";
4132 pr " if (ctx.cb_sequence != 1) {\n";
4133 pr " error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
4134 pr " guestfs_end_busy (g);\n";
4135 pr " return %s;\n" error_code;
4139 pr " if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
4140 (String.uppercase shortname);
4141 pr " guestfs_end_busy (g);\n";
4142 pr " return %s;\n" error_code;
4146 pr " if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
4147 pr " error (g, \"%%s\", ctx.err.error_message);\n";
4148 pr " free (ctx.err.error_message);\n";
4149 pr " guestfs_end_busy (g);\n";
4150 pr " return %s;\n" error_code;
4154 (* Expecting to receive further files (FileOut)? *)
4158 pr " if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
4159 pr " guestfs_end_busy (g);\n";
4160 pr " return %s;\n" error_code;
4166 pr " guestfs_end_busy (g);\n";
4168 (match fst style with
4169 | RErr -> pr " return 0;\n"
4170 | RInt n | RInt64 n | RBool n ->
4171 pr " return ctx.ret.%s;\n" n
4172 | RConstString _ | RConstOptString _ ->
4173 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4175 pr " return ctx.ret.%s; /* caller will free */\n" n
4176 | RStringList n | RHashtable n ->
4177 pr " /* caller will free this, but we need to add a NULL entry */\n";
4178 pr " ctx.ret.%s.%s_val =\n" n n;
4179 pr " safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
4180 pr " sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
4182 pr " ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
4183 pr " return ctx.ret.%s.%s_val;\n" n n
4185 pr " /* caller will free this */\n";
4186 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4187 | RStructList (n, _) ->
4188 pr " /* caller will free this */\n";
4189 pr " return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4191 pr " *size_r = ctx.ret.%s.%s_len;\n" n n;
4192 pr " return ctx.ret.%s.%s_val; /* caller will free */\n" n n
4198 (* Functions to free structures. *)
4199 pr "/* Structure-freeing functions. These rely on the fact that the\n";
4200 pr " * structure format is identical to the XDR format. See note in\n";
4201 pr " * generator.ml.\n";
4208 pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
4210 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
4216 pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
4218 pr " xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
4225 (* Generate daemon/actions.h. *)
4226 and generate_daemon_actions_h () =
4227 generate_header CStyle GPLv2;
4229 pr "#include \"../src/guestfs_protocol.h\"\n";
4233 fun (name, style, _, _, _, _, _) ->
4235 ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
4239 (* Generate the server-side stubs. *)
4240 and generate_daemon_actions () =
4241 generate_header CStyle GPLv2;
4243 pr "#include <config.h>\n";
4245 pr "#include <stdio.h>\n";
4246 pr "#include <stdlib.h>\n";
4247 pr "#include <string.h>\n";
4248 pr "#include <inttypes.h>\n";
4249 pr "#include <ctype.h>\n";
4250 pr "#include <rpc/types.h>\n";
4251 pr "#include <rpc/xdr.h>\n";
4253 pr "#include \"daemon.h\"\n";
4254 pr "#include \"../src/guestfs_protocol.h\"\n";
4255 pr "#include \"actions.h\"\n";
4259 fun (name, style, _, _, _, _, _) ->
4260 (* Generate server-side stubs. *)
4261 pr "static void %s_stub (XDR *xdr_in)\n" name;
4264 match fst style with
4265 | RErr | RInt _ -> pr " int r;\n"; "-1"
4266 | RInt64 _ -> pr " int64_t r;\n"; "-1"
4267 | RBool _ -> pr " int r;\n"; "-1"
4268 | RConstString _ | RConstOptString _ ->
4269 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4270 | RString _ -> pr " char *r;\n"; "NULL"
4271 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
4272 | RStruct (_, typ) -> pr " guestfs_int_%s *r;\n" typ; "NULL"
4273 | RStructList (_, typ) -> pr " guestfs_int_%s_list *r;\n" typ; "NULL"
4275 pr " size_t size;\n";
4279 (match snd style with
4282 pr " struct guestfs_%s_args args;\n" name;
4285 (* Note we allow the string to be writable, in order to
4286 * allow device name translation. This is safe because
4287 * we can modify the string (passed from RPC).
4290 | OptString n -> pr " char *%s;\n" n
4291 | StringList n -> pr " char **%s;\n" n
4292 | Bool n -> pr " int %s;\n" n
4293 | Int n -> pr " int %s;\n" n
4294 | FileIn _ | FileOut _ -> ()
4299 (match snd style with
4302 pr " memset (&args, 0, sizeof args);\n";
4304 pr " if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
4305 pr " reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
4310 | String n -> pr " %s = args.%s;\n" n n
4311 | OptString n -> pr " %s = args.%s ? *args.%s : NULL;\n" n n n
4313 pr " %s = realloc (args.%s.%s_val,\n" n n n;
4314 pr " sizeof (char *) * (args.%s.%s_len+1));\n" n n;
4315 pr " if (%s == NULL) {\n" n;
4316 pr " reply_with_perror (\"realloc\");\n";
4319 pr " %s[args.%s.%s_len] = NULL;\n" n n n;
4320 pr " args.%s.%s_val = %s;\n" n n n;
4321 | Bool n -> pr " %s = args.%s;\n" n n
4322 | Int n -> pr " %s = args.%s;\n" n n
4323 | FileIn _ | FileOut _ -> ()
4328 (* Don't want to call the impl with any FileIn or FileOut
4329 * parameters, since these go "outside" the RPC protocol.
4332 List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
4334 pr " r = do_%s " name;
4335 generate_c_call_args (fst style, args');
4338 pr " if (r == %s)\n" error_code;
4339 pr " /* do_%s has already called reply_with_error */\n" name;
4343 (* If there are any FileOut parameters, then the impl must
4344 * send its own reply.
4347 List.exists (function FileOut _ -> true | _ -> false) (snd style) in
4349 pr " /* do_%s has already sent a reply */\n" name
4351 match fst style with
4352 | RErr -> pr " reply (NULL, NULL);\n"
4353 | RInt n | RInt64 n | RBool n ->
4354 pr " struct guestfs_%s_ret ret;\n" name;
4355 pr " ret.%s = r;\n" n;
4356 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4358 | RConstString _ | RConstOptString _ ->
4359 failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4361 pr " struct guestfs_%s_ret ret;\n" name;
4362 pr " ret.%s = r;\n" n;
4363 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4366 | RStringList n | RHashtable n ->
4367 pr " struct guestfs_%s_ret ret;\n" name;
4368 pr " ret.%s.%s_len = count_strings (r);\n" n n;
4369 pr " ret.%s.%s_val = r;\n" n n;
4370 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4372 pr " free_strings (r);\n"
4374 pr " struct guestfs_%s_ret ret;\n" name;
4375 pr " ret.%s = *r;\n" n;
4376 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4378 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4380 | RStructList (n, _) ->
4381 pr " struct guestfs_%s_ret ret;\n" name;
4382 pr " ret.%s = *r;\n" n;
4383 pr " reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4385 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4388 pr " struct guestfs_%s_ret ret;\n" name;
4389 pr " ret.%s.%s_val = r;\n" n n;
4390 pr " ret.%s.%s_len = size;\n" n n;
4391 pr " reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4396 (* Free the args. *)
4397 (match snd style with
4402 pr " xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
4409 (* Dispatch function. *)
4410 pr "void dispatch_incoming_message (XDR *xdr_in)\n";
4412 pr " switch (proc_nr) {\n";
4415 fun (name, style, _, _, _, _, _) ->
4416 pr " case GUESTFS_PROC_%s:\n" (String.uppercase name);
4417 pr " %s_stub (xdr_in);\n" name;
4422 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";
4427 (* LVM columns and tokenization functions. *)
4428 (* XXX This generates crap code. We should rethink how we
4434 pr "static const char *lvm_%s_cols = \"%s\";\n"
4435 typ (String.concat "," (List.map fst cols));
4438 pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
4440 pr " char *tok, *p, *next;\n";
4444 pr " fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
4447 pr " if (!str) {\n";
4448 pr " fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
4451 pr " if (!*str || isspace (*str)) {\n";
4452 pr " fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
4457 fun (name, coltype) ->
4458 pr " if (!tok) {\n";
4459 pr " fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
4462 pr " p = strchrnul (tok, ',');\n";
4463 pr " if (*p) next = p+1; else next = NULL;\n";
4464 pr " *p = '\\0';\n";
4467 pr " r->%s = strdup (tok);\n" name;
4468 pr " if (r->%s == NULL) {\n" name;
4469 pr " perror (\"strdup\");\n";
4473 pr " for (i = j = 0; i < 32; ++j) {\n";
4474 pr " if (tok[j] == '\\0') {\n";
4475 pr " fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
4477 pr " } else if (tok[j] != '-')\n";
4478 pr " r->%s[i++] = tok[j];\n" name;
4481 pr " if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
4482 pr " fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4486 pr " if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
4487 pr " fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4491 pr " if (tok[0] == '\\0')\n";
4492 pr " r->%s = -1;\n" name;
4493 pr " else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
4494 pr " fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4497 | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
4498 assert false (* can never be an LVM column *)
4500 pr " tok = next;\n";
4503 pr " if (tok != NULL) {\n";
4504 pr " fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
4511 pr "guestfs_int_lvm_%s_list *\n" typ;
4512 pr "parse_command_line_%ss (void)\n" typ;
4514 pr " char *out, *err;\n";
4515 pr " char *p, *pend;\n";
4517 pr " guestfs_int_lvm_%s_list *ret;\n" typ;
4518 pr " void *newp;\n";
4520 pr " ret = malloc (sizeof *ret);\n";
4521 pr " if (!ret) {\n";
4522 pr " reply_with_perror (\"malloc\");\n";
4523 pr " return NULL;\n";
4526 pr " ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
4527 pr " ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
4529 pr " r = command (&out, &err,\n";
4530 pr " \"/sbin/lvm\", \"%ss\",\n" typ;
4531 pr " \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
4532 pr " \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
4533 pr " if (r == -1) {\n";
4534 pr " reply_with_error (\"%%s\", err);\n";
4535 pr " free (out);\n";
4536 pr " free (err);\n";
4537 pr " free (ret);\n";
4538 pr " return NULL;\n";
4541 pr " free (err);\n";
4543 pr " /* Tokenize each line of the output. */\n";
4546 pr " while (p) {\n";
4547 pr " pend = strchr (p, '\\n'); /* Get the next line of output. */\n";
4548 pr " if (pend) {\n";
4549 pr " *pend = '\\0';\n";
4553 pr " while (*p && isspace (*p)) /* Skip any leading whitespace. */\n";
4556 pr " if (!*p) { /* Empty line? Skip it. */\n";
4561 pr " /* Allocate some space to store this next entry. */\n";
4562 pr " newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
4563 pr " sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
4564 pr " if (newp == NULL) {\n";
4565 pr " reply_with_perror (\"realloc\");\n";
4566 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4567 pr " free (ret);\n";
4568 pr " free (out);\n";
4569 pr " return NULL;\n";
4571 pr " ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
4573 pr " /* Tokenize the next entry. */\n";
4574 pr " r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
4575 pr " if (r == -1) {\n";
4576 pr " reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
4577 pr " free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4578 pr " free (ret);\n";
4579 pr " free (out);\n";
4580 pr " return NULL;\n";
4587 pr " ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
4589 pr " free (out);\n";
4590 pr " return ret;\n";
4593 ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
4595 (* Generate a list of function names, for debugging in the daemon.. *)
4596 and generate_daemon_names () =
4597 generate_header CStyle GPLv2;
4599 pr "#include <config.h>\n";
4601 pr "#include \"daemon.h\"\n";
4604 pr "/* This array is indexed by proc_nr. See guestfs_protocol.x. */\n";
4605 pr "const char *function_names[] = {\n";
4607 fun (name, _, proc_nr, _, _, _, _) -> pr " [%d] = \"%s\",\n" proc_nr name
4611 (* Generate the tests. *)
4612 and generate_tests () =
4613 generate_header CStyle GPLv2;
4620 #include <sys/types.h>
4623 #include \"guestfs.h\"
4625 static guestfs_h *g;
4626 static int suppress_error = 0;
4628 static void print_error (guestfs_h *g, void *data, const char *msg)
4630 if (!suppress_error)
4631 fprintf (stderr, \"%%s\\n\", msg);
4634 static void print_strings (char * const * const argv)
4638 for (argc = 0; argv[argc] != NULL; ++argc)
4639 printf (\"\\t%%s\\n\", argv[argc]);
4643 static void print_table (char * const * const argv)
4647 for (i = 0; argv[i] != NULL; i += 2)
4648 printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
4652 static void no_test_warnings (void)
4658 | name, _, _, _, [], _, _ ->
4659 pr " fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
4660 | name, _, _, _, tests, _, _ -> ()
4666 (* Generate the actual tests. Note that we generate the tests
4667 * in reverse order, deliberately, so that (in general) the
4668 * newest tests run first. This makes it quicker and easier to
4673 fun (name, _, _, _, tests, _, _) ->
4674 mapi (generate_one_test name) tests
4675 ) (List.rev all_functions) in
4676 let test_names = List.concat test_names in
4677 let nr_tests = List.length test_names in
4680 int main (int argc, char *argv[])
4684 const char *filename;
4686 int nr_tests, test_num = 0;
4688 setbuf (stdout, NULL);
4690 no_test_warnings ();
4692 g = guestfs_create ();
4694 printf (\"guestfs_create FAILED\\n\");
4698 guestfs_set_error_handler (g, print_error, NULL);
4700 guestfs_set_path (g, \"../appliance\");
4702 filename = \"test1.img\";
4703 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4708 if (lseek (fd, %d, SEEK_SET) == -1) {
4714 if (write (fd, &c, 1) == -1) {
4720 if (close (fd) == -1) {
4725 if (guestfs_add_drive (g, filename) == -1) {
4726 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4730 filename = \"test2.img\";
4731 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4736 if (lseek (fd, %d, SEEK_SET) == -1) {
4742 if (write (fd, &c, 1) == -1) {
4748 if (close (fd) == -1) {
4753 if (guestfs_add_drive (g, filename) == -1) {
4754 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4758 filename = \"test3.img\";
4759 fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4764 if (lseek (fd, %d, SEEK_SET) == -1) {
4770 if (write (fd, &c, 1) == -1) {
4776 if (close (fd) == -1) {
4781 if (guestfs_add_drive (g, filename) == -1) {
4782 printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4786 if (guestfs_add_drive_ro (g, \"../images/test.sqsh\") == -1) {
4787 printf (\"guestfs_add_drive_ro ../images/test.sqsh FAILED\\n\");
4791 if (guestfs_launch (g) == -1) {
4792 printf (\"guestfs_launch FAILED\\n\");
4796 /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
4799 if (guestfs_wait_ready (g) == -1) {
4800 printf (\"guestfs_wait_ready FAILED\\n\");
4804 /* Cancel previous alarm. */
4809 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
4813 pr " test_num++;\n";
4814 pr " printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
4815 pr " if (%s () == -1) {\n" test_name;
4816 pr " printf (\"%s FAILED\\n\");\n" test_name;
4822 pr " guestfs_close (g);\n";
4823 pr " unlink (\"test1.img\");\n";
4824 pr " unlink (\"test2.img\");\n";
4825 pr " unlink (\"test3.img\");\n";
4828 pr " if (failed > 0) {\n";
4829 pr " printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
4837 and generate_one_test name i (init, prereq, test) =
4838 let test_name = sprintf "test_%s_%d" name i in
4841 static int %s_skip (void)
4845 str = getenv (\"TEST_ONLY\");
4847 return strstr (str, \"%s\") == NULL;
4848 str = getenv (\"SKIP_%s\");
4849 if (str && strcmp (str, \"1\") == 0) return 1;
4850 str = getenv (\"SKIP_TEST_%s\");
4851 if (str && strcmp (str, \"1\") == 0) return 1;
4855 " test_name name (String.uppercase test_name) (String.uppercase name);
4858 | Disabled | Always -> ()
4859 | If code | Unless code ->
4860 pr "static int %s_prereq (void)\n" test_name;
4868 static int %s (void)
4871 printf (\" %%s skipped (reason: environment variable set)\\n\", \"%s\");
4875 " test_name test_name test_name;
4879 pr " printf (\" %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4881 pr " if (! %s_prereq ()) {\n" test_name;
4882 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4886 generate_one_test_body name i test_name init test;
4888 pr " if (%s_prereq ()) {\n" test_name;
4889 pr " printf (\" %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4893 generate_one_test_body name i test_name init test;
4895 generate_one_test_body name i test_name init test
4903 and generate_one_test_body name i test_name init test =
4905 | InitNone (* XXX at some point, InitNone and InitEmpty became
4906 * folded together as the same thing. Really we should
4907 * make InitNone do nothing at all, but the tests may
4908 * need to be checked to make sure this is OK.
4911 pr " /* InitNone|InitEmpty for %s */\n" test_name;
4912 List.iter (generate_test_command_call test_name)
4913 [["blockdev_setrw"; "/dev/sda"];
4917 pr " /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
4918 List.iter (generate_test_command_call test_name)
4919 [["blockdev_setrw"; "/dev/sda"];
4922 ["sfdiskM"; "/dev/sda"; ","];
4923 ["mkfs"; "ext2"; "/dev/sda1"];
4924 ["mount"; "/dev/sda1"; "/"]]
4925 | InitBasicFSonLVM ->
4926 pr " /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
4928 List.iter (generate_test_command_call test_name)
4929 [["blockdev_setrw"; "/dev/sda"];
4932 ["sfdiskM"; "/dev/sda"; ","];
4933 ["pvcreate"; "/dev/sda1"];
4934 ["vgcreate"; "VG"; "/dev/sda1"];
4935 ["lvcreate"; "LV"; "VG"; "8"];
4936 ["mkfs"; "ext2"; "/dev/VG/LV"];
4937 ["mount"; "/dev/VG/LV"; "/"]]
4939 pr " /* InitSquashFS for %s */\n" test_name;
4940 List.iter (generate_test_command_call test_name)
4941 [["blockdev_setrw"; "/dev/sda"];
4944 ["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"]]
4947 let get_seq_last = function
4949 failwithf "%s: you cannot use [] (empty list) when expecting a command"
4952 let seq = List.rev seq in
4953 List.rev (List.tl seq), List.hd seq
4958 pr " /* TestRun for %s (%d) */\n" name i;
4959 List.iter (generate_test_command_call test_name) seq
4960 | TestOutput (seq, expected) ->
4961 pr " /* TestOutput for %s (%d) */\n" name i;
4962 pr " const char *expected = \"%s\";\n" (c_quote expected);
4963 let seq, last = get_seq_last seq in
4965 pr " if (strcmp (r, expected) != 0) {\n";
4966 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
4970 List.iter (generate_test_command_call test_name) seq;
4971 generate_test_command_call ~test test_name last
4972 | TestOutputList (seq, expected) ->
4973 pr " /* TestOutputList for %s (%d) */\n" name i;
4974 let seq, last = get_seq_last seq in
4978 pr " if (!r[%d]) {\n" i;
4979 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
4980 pr " print_strings (r);\n";
4984 pr " const char *expected = \"%s\";\n" (c_quote str);
4985 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
4986 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
4991 pr " if (r[%d] != NULL) {\n" (List.length expected);
4992 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
4994 pr " print_strings (r);\n";
4998 List.iter (generate_test_command_call test_name) seq;
4999 generate_test_command_call ~test test_name last
5000 | TestOutputListOfDevices (seq, expected) ->
5001 pr " /* TestOutputListOfDevices for %s (%d) */\n" name i;
5002 let seq, last = get_seq_last seq in
5006 pr " if (!r[%d]) {\n" i;
5007 pr " fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
5008 pr " print_strings (r);\n";
5012 pr " const char *expected = \"%s\";\n" (c_quote str);
5013 pr " r[%d][5] = 's';\n" i;
5014 pr " if (strcmp (r[%d], expected) != 0) {\n" i;
5015 pr " fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
5020 pr " if (r[%d] != NULL) {\n" (List.length expected);
5021 pr " fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
5023 pr " print_strings (r);\n";
5027 List.iter (generate_test_command_call test_name) seq;
5028 generate_test_command_call ~test test_name last
5029 | TestOutputInt (seq, expected) ->
5030 pr " /* TestOutputInt for %s (%d) */\n" name i;
5031 let seq, last = get_seq_last seq in
5033 pr " if (r != %d) {\n" expected;
5034 pr " fprintf (stderr, \"%s: expected %d but got %%d\\n\","
5040 List.iter (generate_test_command_call test_name) seq;
5041 generate_test_command_call ~test test_name last
5042 | TestOutputIntOp (seq, op, expected) ->
5043 pr " /* TestOutputIntOp for %s (%d) */\n" name i;
5044 let seq, last = get_seq_last seq in
5046 pr " if (! (r %s %d)) {\n" op expected;
5047 pr " fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
5048 test_name op expected;
5053 List.iter (generate_test_command_call test_name) seq;
5054 generate_test_command_call ~test test_name last
5055 | TestOutputTrue seq ->
5056 pr " /* TestOutputTrue for %s (%d) */\n" name i;
5057 let seq, last = get_seq_last seq in
5060 pr " fprintf (stderr, \"%s: expected true, got false\\n\");\n"
5065 List.iter (generate_test_command_call test_name) seq;
5066 generate_test_command_call ~test test_name last
5067 | TestOutputFalse seq ->
5068 pr " /* TestOutputFalse for %s (%d) */\n" name i;
5069 let seq, last = get_seq_last seq in
5072 pr " fprintf (stderr, \"%s: expected false, got true\\n\");\n"
5077 List.iter (generate_test_command_call test_name) seq;
5078 generate_test_command_call ~test test_name last
5079 | TestOutputLength (seq, expected) ->
5080 pr " /* TestOutputLength for %s (%d) */\n" name i;
5081 let seq, last = get_seq_last seq in
5084 pr " for (j = 0; j < %d; ++j)\n" expected;
5085 pr " if (r[j] == NULL) {\n";
5086 pr " fprintf (stderr, \"%s: short list returned\\n\");\n"
5088 pr " print_strings (r);\n";
5091 pr " if (r[j] != NULL) {\n";
5092 pr " fprintf (stderr, \"%s: long list returned\\n\");\n"
5094 pr " print_strings (r);\n";
5098 List.iter (generate_test_command_call test_name) seq;
5099 generate_test_command_call ~test test_name last
5100 | TestOutputStruct (seq, checks) ->
5101 pr " /* TestOutputStruct for %s (%d) */\n" name i;
5102 let seq, last = get_seq_last seq in
5106 | CompareWithInt (field, expected) ->
5107 pr " if (r->%s != %d) {\n" field expected;
5108 pr " fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
5109 test_name field expected;
5110 pr " (int) r->%s);\n" field;
5113 | CompareWithIntOp (field, op, expected) ->
5114 pr " if (!(r->%s %s %d)) {\n" field op expected;
5115 pr " fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
5116 test_name field op expected;
5117 pr " (int) r->%s);\n" field;
5120 | CompareWithString (field, expected) ->
5121 pr " if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
5122 pr " fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
5123 test_name field expected;
5124 pr " r->%s);\n" field;
5127 | CompareFieldsIntEq (field1, field2) ->
5128 pr " if (r->%s != r->%s) {\n" field1 field2;
5129 pr " fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
5130 test_name field1 field2;
5131 pr " (int) r->%s, (int) r->%s);\n" field1 field2;
5134 | CompareFieldsStrEq (field1, field2) ->
5135 pr " if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
5136 pr " fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
5137 test_name field1 field2;
5138 pr " r->%s, r->%s);\n" field1 field2;
5143 List.iter (generate_test_command_call test_name) seq;
5144 generate_test_command_call ~test test_name last
5145 | TestLastFail seq ->
5146 pr " /* TestLastFail for %s (%d) */\n" name i;
5147 let seq, last = get_seq_last seq in
5148 List.iter (generate_test_command_call test_name) seq;
5149 generate_test_command_call test_name ~expect_error:true last
5151 (* Generate the code to run a command, leaving the result in 'r'.
5152 * If you expect to get an error then you should set expect_error:true.
5154 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
5156 | [] -> assert false
5158 (* Look up the command to find out what args/ret it has. *)
5161 let _, style, _, _, _, _, _ =
5162 List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
5165 failwithf "%s: in test, command %s was not found" test_name name in
5167 if List.length (snd style) <> List.length args then
5168 failwithf "%s: in test, wrong number of args given to %s"
5175 | OptString n, "NULL" -> ()
5177 | OptString n, arg ->
5178 pr " const char *%s = \"%s\";\n" n (c_quote arg);
5181 | FileIn _, _ | FileOut _, _ -> ()
5182 | StringList n, arg ->
5183 let strs = string_split " " arg in
5186 pr " const char *%s_%d = \"%s\";\n" n i (c_quote str);
5188 pr " const char *%s[] = {\n" n;
5190 fun i _ -> pr " %s_%d,\n" n i
5194 ) (List.combine (snd style) args);
5197 match fst style with
5198 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
5199 | RInt64 _ -> pr " int64_t r;\n"; "-1"
5200 | RConstString _ | RConstOptString _ ->
5201 pr " const char *r;\n"; "NULL"
5202 | RString _ -> pr " char *r;\n"; "NULL"
5203 | RStringList _ | RHashtable _ ->
5207 | RStruct (_, typ) ->
5208 pr " struct guestfs_%s *r;\n" typ; "NULL"
5209 | RStructList (_, typ) ->
5210 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
5213 pr " size_t size;\n";
5216 pr " suppress_error = %d;\n" (if expect_error then 1 else 0);
5217 pr " r = guestfs_%s (g" name;
5219 (* Generate the parameters. *)
5222 | OptString _, "NULL" -> pr ", NULL"
5226 | FileIn _, arg | FileOut _, arg ->
5227 pr ", \"%s\"" (c_quote arg)
5228 | StringList n, _ ->
5232 try int_of_string arg
5233 with Failure "int_of_string" ->
5234 failwithf "%s: expecting an int, but got '%s'" test_name arg in
5237 let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
5238 ) (List.combine (snd style) args);
5240 (match fst style with
5241 | RBufferOut _ -> pr ", &size"
5247 if not expect_error then
5248 pr " if (r == %s)\n" error_code
5250 pr " if (r != %s)\n" error_code;
5253 (* Insert the test code. *)
5259 (match fst style with
5260 | RErr | RInt _ | RInt64 _ | RBool _
5261 | RConstString _ | RConstOptString _ -> ()
5262 | RString _ | RBufferOut _ -> pr " free (r);\n"
5263 | RStringList _ | RHashtable _ ->
5264 pr " for (i = 0; r[i] != NULL; ++i)\n";
5265 pr " free (r[i]);\n";
5267 | RStruct (_, typ) ->
5268 pr " guestfs_free_%s (r);\n" typ
5269 | RStructList (_, typ) ->
5270 pr " guestfs_free_%s_list (r);\n" typ
5276 let str = replace_str str "\r" "\\r" in
5277 let str = replace_str str "\n" "\\n" in
5278 let str = replace_str str "\t" "\\t" in
5279 let str = replace_str str "\000" "\\0" in
5282 (* Generate a lot of different functions for guestfish. *)
5283 and generate_fish_cmds () =
5284 generate_header CStyle GPLv2;
5288 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5290 let all_functions_sorted =
5292 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5293 ) all_functions_sorted in
5295 pr "#include <stdio.h>\n";
5296 pr "#include <stdlib.h>\n";
5297 pr "#include <string.h>\n";
5298 pr "#include <inttypes.h>\n";
5299 pr "#include <ctype.h>\n";
5301 pr "#include <guestfs.h>\n";
5302 pr "#include \"fish.h\"\n";
5305 (* list_commands function, which implements guestfish -h *)
5306 pr "void list_commands (void)\n";
5308 pr " printf (\" %%-16s %%s\\n\", \"Command\", \"Description\");\n";
5309 pr " list_builtin_commands ();\n";
5311 fun (name, _, _, flags, _, shortdesc, _) ->
5312 let name = replace_char name '_' '-' in
5313 pr " printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
5315 ) all_functions_sorted;
5316 pr " printf (\" Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
5320 (* display_command function, which implements guestfish -h cmd *)
5321 pr "void display_command (const char *cmd)\n";
5324 fun (name, style, _, flags, _, shortdesc, longdesc) ->
5325 let name2 = replace_char name '_' '-' in
5327 try find_map (function FishAlias n -> Some n | _ -> None) flags
5328 with Not_found -> name in
5329 let longdesc = replace_str longdesc "C<guestfs_" "C<" in
5331 match snd style with
5335 name2 (String.concat "> <" (List.map name_of_argt args)) in
5338 if List.mem ProtocolLimitWarning flags then
5339 ("\n\n" ^ protocol_limit_warning)
5342 (* For DangerWillRobinson commands, we should probably have
5343 * guestfish prompt before allowing you to use them (especially
5344 * in interactive mode). XXX
5348 if List.mem DangerWillRobinson flags then
5349 ("\n\n" ^ danger_will_robinson)
5352 let describe_alias =
5353 if name <> alias then
5354 sprintf "\n\nYou can use '%s' as an alias for this command." alias
5358 pr "strcasecmp (cmd, \"%s\") == 0" name;
5359 if name <> name2 then
5360 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5361 if name <> alias then
5362 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5364 pr " pod2text (\"%s - %s\", %S);\n"
5366 (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
5369 pr " display_builtin_command (cmd);\n";
5373 (* print_* functions *)
5377 List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
5379 pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
5388 pr " printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
5390 pr " printf (\"%s: \");\n" name;
5391 pr " for (i = 0; i < 32; ++i)\n";
5392 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
5393 pr " printf (\"\\n\");\n"
5395 pr " printf (\"%s: \");\n" name;
5396 pr " for (i = 0; i < %s->%s_len; ++i)\n" typ name;
5397 pr " if (isprint (%s->%s[i]))\n" typ name;
5398 pr " printf (\"%%c\", %s->%s[i]);\n" typ name;
5400 pr " printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
5401 pr " printf (\"\\n\");\n"
5402 | name, (FUInt64|FBytes) ->
5403 pr " printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
5405 pr " printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
5407 pr " printf (\"%s: %%\" PRIu32 \"\\n\", %s->%s);\n" name typ name
5409 pr " printf (\"%s: %%\" PRIi32 \"\\n\", %s->%s);\n" name typ name
5411 pr " printf (\"%s: %%c\\n\", %s->%s);\n" name typ name
5412 | name, FOptPercent ->
5413 pr " if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
5414 typ name name typ name;
5415 pr " else printf (\"%s: \\n\");\n" name
5419 pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
5424 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
5425 pr " print_%s (&%ss->val[i]);\n" typ typ;
5430 (* run_<action> actions *)
5432 fun (name, style, _, flags, _, _, _) ->
5433 pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
5435 (match fst style with
5438 | RBool _ -> pr " int r;\n"
5439 | RInt64 _ -> pr " int64_t r;\n"
5440 | RConstString _ | RConstOptString _ -> pr " const char *r;\n"
5441 | RString _ -> pr " char *r;\n"
5442 | RStringList _ | RHashtable _ -> pr " char **r;\n"
5443 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ
5444 | RStructList (_, typ) -> pr " struct guestfs_%s_list *r;\n" typ
5447 pr " size_t size;\n";
5454 | FileOut n -> pr " const char *%s;\n" n
5455 | StringList n -> pr " char **%s;\n" n
5456 | Bool n -> pr " int %s;\n" n
5457 | Int n -> pr " int %s;\n" n
5460 (* Check and convert parameters. *)
5461 let argc_expected = List.length (snd style) in
5462 pr " if (argc != %d) {\n" argc_expected;
5463 pr " fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
5465 pr " fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
5471 | String name -> pr " %s = argv[%d];\n" name i
5473 pr " %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
5476 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
5479 pr " %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
5481 | StringList name ->
5482 pr " %s = parse_string_list (argv[%d]);\n" name i
5484 pr " %s = is_true (argv[%d]) ? 1 : 0;\n" name i
5486 pr " %s = atoi (argv[%d]);\n" name i
5489 (* Call C API function. *)
5491 try find_map (function FishAction n -> Some n | _ -> None) flags
5492 with Not_found -> sprintf "guestfs_%s" name in
5494 generate_c_call_args ~handle:"g" style;
5497 (* Check return value for errors and display command results. *)
5498 (match fst style with
5499 | RErr -> pr " return r;\n"
5501 pr " if (r == -1) return -1;\n";
5502 pr " printf (\"%%d\\n\", r);\n";
5505 pr " if (r == -1) return -1;\n";
5506 pr " printf (\"%%\" PRIi64 \"\\n\", r);\n";
5509 pr " if (r == -1) return -1;\n";
5510 pr " if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
5513 pr " if (r == NULL) return -1;\n";
5514 pr " printf (\"%%s\\n\", r);\n";
5516 | RConstOptString _ ->
5517 pr " printf (\"%%s\\n\", r ? : \"(null)\");\n";
5520 pr " if (r == NULL) return -1;\n";
5521 pr " printf (\"%%s\\n\", r);\n";
5525 pr " if (r == NULL) return -1;\n";
5526 pr " print_strings (r);\n";
5527 pr " free_strings (r);\n";
5529 | RStruct (_, typ) ->
5530 pr " if (r == NULL) return -1;\n";
5531 pr " print_%s (r);\n" typ;
5532 pr " guestfs_free_%s (r);\n" typ;
5534 | RStructList (_, typ) ->
5535 pr " if (r == NULL) return -1;\n";
5536 pr " print_%s_list (r);\n" typ;
5537 pr " guestfs_free_%s_list (r);\n" typ;
5540 pr " if (r == NULL) return -1;\n";
5541 pr " print_table (r);\n";
5542 pr " free_strings (r);\n";
5545 pr " if (r == NULL) return -1;\n";
5546 pr " fwrite (r, size, 1, stdout);\n";
5554 (* run_action function *)
5555 pr "int run_action (const char *cmd, int argc, char *argv[])\n";
5558 fun (name, _, _, flags, _, _, _) ->
5559 let name2 = replace_char name '_' '-' in
5561 try find_map (function FishAlias n -> Some n | _ -> None) flags
5562 with Not_found -> name in
5564 pr "strcasecmp (cmd, \"%s\") == 0" name;
5565 if name <> name2 then
5566 pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5567 if name <> alias then
5568 pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5570 pr " return run_%s (cmd, argc, argv);\n" name;
5574 pr " fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
5581 (* Readline completion for guestfish. *)
5582 and generate_fish_completion () =
5583 generate_header CStyle GPLv2;
5587 fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5597 #ifdef HAVE_LIBREADLINE
5598 #include <readline/readline.h>
5603 #ifdef HAVE_LIBREADLINE
5605 static const char *const commands[] = {
5606 BUILTIN_COMMANDS_FOR_COMPLETION,
5609 (* Get the commands, including the aliases. They don't need to be
5610 * sorted - the generator() function just does a dumb linear search.
5614 fun (name, _, _, flags, _, _, _) ->
5615 let name2 = replace_char name '_' '-' in
5617 try find_map (function FishAlias n -> Some n | _ -> None) flags
5618 with Not_found -> name in
5620 if name <> alias then [name2; alias] else [name2]
5622 let commands = List.flatten commands in
5624 List.iter (pr " \"%s\",\n") commands;
5630 generator (const char *text, int state)
5632 static int index, len;
5637 len = strlen (text);
5640 rl_attempted_completion_over = 1;
5642 while ((name = commands[index]) != NULL) {
5644 if (strncasecmp (name, text, len) == 0)
5645 return strdup (name);
5651 #endif /* HAVE_LIBREADLINE */
5653 char **do_completion (const char *text, int start, int end)
5655 char **matches = NULL;
5657 #ifdef HAVE_LIBREADLINE
5658 rl_completion_append_character = ' ';
5661 matches = rl_completion_matches (text, generator);
5662 else if (complete_dest_paths)
5663 matches = rl_completion_matches (text, complete_dest_paths_generator);
5670 (* Generate the POD documentation for guestfish. *)
5671 and generate_fish_actions_pod () =
5672 let all_functions_sorted =
5674 fun (_, _, _, flags, _, _, _) ->
5675 not (List.mem NotInFish flags || List.mem NotInDocs flags)
5676 ) all_functions_sorted in
5678 let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
5681 fun (name, style, _, flags, _, _, longdesc) ->
5683 Str.global_substitute rex (
5686 try Str.matched_group 1 s
5688 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
5689 "C<" ^ replace_char sub '_' '-' ^ ">"
5691 let name = replace_char name '_' '-' in
5693 try find_map (function FishAlias n -> Some n | _ -> None) flags
5694 with Not_found -> name in
5696 pr "=head2 %s" name;
5697 if name <> alias then
5704 | String n -> pr " %s" n
5705 | OptString n -> pr " %s" n
5706 | StringList n -> pr " '%s ...'" n
5707 | Bool _ -> pr " true|false"
5708 | Int n -> pr " %s" n
5709 | FileIn n | FileOut n -> pr " (%s|-)" n
5713 pr "%s\n\n" longdesc;
5715 if List.exists (function FileIn _ | FileOut _ -> true
5716 | _ -> false) (snd style) then
5717 pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
5719 if List.mem ProtocolLimitWarning flags then
5720 pr "%s\n\n" protocol_limit_warning;
5722 if List.mem DangerWillRobinson flags then
5723 pr "%s\n\n" danger_will_robinson
5724 ) all_functions_sorted
5726 (* Generate a C function prototype. *)
5727 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
5728 ?(single_line = false) ?(newline = false) ?(in_daemon = false)
5730 ?handle name style =
5731 if extern then pr "extern ";
5732 if static then pr "static ";
5733 (match fst style with
5735 | RInt _ -> pr "int "
5736 | RInt64 _ -> pr "int64_t "
5737 | RBool _ -> pr "int "
5738 | RConstString _ | RConstOptString _ -> pr "const char *"
5739 | RString _ | RBufferOut _ -> pr "char *"
5740 | RStringList _ | RHashtable _ -> pr "char **"
5741 | RStruct (_, typ) ->
5742 if not in_daemon then pr "struct guestfs_%s *" typ
5743 else pr "guestfs_int_%s *" typ
5744 | RStructList (_, typ) ->
5745 if not in_daemon then pr "struct guestfs_%s_list *" typ
5746 else pr "guestfs_int_%s_list *" typ
5748 let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
5749 pr "%s%s (" prefix name;
5750 if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
5753 let comma = ref false in
5756 | Some handle -> pr "guestfs_h *%s" handle; comma := true
5760 if single_line then pr ", " else pr ",\n\t\t"
5769 if not in_daemon then pr "const char *%s" n
5770 else pr "char *%s" n
5773 if not in_daemon then pr "char * const* const %s" n
5774 else pr "char **%s" n
5775 | Bool n -> next (); pr "int %s" n
5776 | Int n -> next (); pr "int %s" n
5779 if not in_daemon then (next (); pr "const char *%s" n)
5781 if is_RBufferOut then (next (); pr "size_t *size_r");
5784 if semicolon then pr ";";
5785 if newline then pr "\n"
5787 (* Generate C call arguments, eg "(handle, foo, bar)" *)
5788 and generate_c_call_args ?handle ?(decl = false) style =
5790 let comma = ref false in
5792 if !comma then pr ", ";
5797 | Some handle -> pr "%s" handle; comma := true
5802 pr "%s" (name_of_argt arg)
5804 (* For RBufferOut calls, add implicit &size parameter. *)
5806 match fst style with
5814 (* Generate the OCaml bindings interface. *)
5815 and generate_ocaml_mli () =
5816 generate_header OCamlStyle LGPLv2;
5819 (** For API documentation you should refer to the C API
5820 in the guestfs(3) manual page. The OCaml API uses almost
5821 exactly the same calls. *)
5824 (** A [guestfs_h] handle. *)
5826 exception Error of string
5827 (** This exception is raised when there is an error. *)
5829 val create : unit -> t
5831 val close : t -> unit
5832 (** Handles are closed by the garbage collector when they become
5833 unreferenced, but callers can also call this in order to
5834 provide predictable cleanup. *)
5837 generate_ocaml_structure_decls ();
5841 fun (name, style, _, _, _, shortdesc, _) ->
5842 generate_ocaml_prototype name style;
5843 pr "(** %s *)\n" shortdesc;
5847 (* Generate the OCaml bindings implementation. *)
5848 and generate_ocaml_ml () =
5849 generate_header OCamlStyle LGPLv2;
5853 exception Error of string
5854 external create : unit -> t = \"ocaml_guestfs_create\"
5855 external close : t -> unit = \"ocaml_guestfs_close\"
5858 Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
5862 generate_ocaml_structure_decls ();
5866 fun (name, style, _, _, _, shortdesc, _) ->
5867 generate_ocaml_prototype ~is_external:true name style;
5870 (* Generate the OCaml bindings C implementation. *)
5871 and generate_ocaml_c () =
5872 generate_header CStyle LGPLv2;
5879 #include <caml/config.h>
5880 #include <caml/alloc.h>
5881 #include <caml/callback.h>
5882 #include <caml/fail.h>
5883 #include <caml/memory.h>
5884 #include <caml/mlvalues.h>
5885 #include <caml/signals.h>
5887 #include <guestfs.h>
5889 #include \"guestfs_c.h\"
5891 /* Copy a hashtable of string pairs into an assoc-list. We return
5892 * the list in reverse order, but hashtables aren't supposed to be
5895 static CAMLprim value
5896 copy_table (char * const * argv)
5899 CAMLlocal5 (rv, pairv, kv, vv, cons);
5903 for (i = 0; argv[i] != NULL; i += 2) {
5904 kv = caml_copy_string (argv[i]);
5905 vv = caml_copy_string (argv[i+1]);
5906 pairv = caml_alloc (2, 0);
5907 Store_field (pairv, 0, kv);
5908 Store_field (pairv, 1, vv);
5909 cons = caml_alloc (2, 0);
5910 Store_field (cons, 1, rv);
5912 Store_field (cons, 0, pairv);
5920 (* Struct copy functions. *)
5923 let has_optpercent_col =
5924 List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
5926 pr "static CAMLprim value\n";
5927 pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
5929 pr " CAMLparam0 ();\n";
5930 if has_optpercent_col then
5931 pr " CAMLlocal3 (rv, v, v2);\n"
5933 pr " CAMLlocal2 (rv, v);\n";
5935 pr " rv = caml_alloc (%d, 0);\n" (List.length cols);
5940 pr " v = caml_copy_string (%s->%s);\n" typ name
5942 pr " v = caml_alloc_string (%s->%s_len);\n" typ name;
5943 pr " memcpy (String_val (v), %s->%s, %s->%s_len);\n"
5946 pr " v = caml_alloc_string (32);\n";
5947 pr " memcpy (String_val (v), %s->%s, 32);\n" typ name
5948 | name, (FBytes|FInt64|FUInt64) ->
5949 pr " v = caml_copy_int64 (%s->%s);\n" typ name
5950 | name, (FInt32|FUInt32) ->
5951 pr " v = caml_copy_int32 (%s->%s);\n" typ name
5952 | name, FOptPercent ->
5953 pr " if (%s->%s >= 0) { /* Some %s */\n" typ name name;
5954 pr " v2 = caml_copy_double (%s->%s);\n" typ name;
5955 pr " v = caml_alloc (1, 0);\n";
5956 pr " Store_field (v, 0, v2);\n";
5957 pr " } else /* None */\n";
5958 pr " v = Val_int (0);\n";
5960 pr " v = Val_int (%s->%s);\n" typ name
5962 pr " Store_field (rv, %d, v);\n" i
5964 pr " CAMLreturn (rv);\n";
5968 pr "static CAMLprim value\n";
5969 pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n"
5972 pr " CAMLparam0 ();\n";
5973 pr " CAMLlocal2 (rv, v);\n";
5976 pr " if (%ss->len == 0)\n" typ;
5977 pr " CAMLreturn (Atom (0));\n";
5979 pr " rv = caml_alloc (%ss->len, 0);\n" typ;
5980 pr " for (i = 0; i < %ss->len; ++i) {\n" typ;
5981 pr " v = copy_%s (&%ss->val[i]);\n" typ typ;
5982 pr " caml_modify (&Field (rv, i), v);\n";
5984 pr " CAMLreturn (rv);\n";
5992 fun (name, style, _, _, _, _, _) ->
5994 "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
5996 let needs_extra_vs =
5997 match fst style with RConstOptString _ -> true | _ -> false in
5999 pr "CAMLprim value\n";
6000 pr "ocaml_guestfs_%s (value %s" name (List.hd params);
6001 List.iter (pr ", value %s") (List.tl params);
6006 | [p1; p2; p3; p4; p5] ->
6007 pr " CAMLparam5 (%s);\n" (String.concat ", " params)
6008 | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
6009 pr " CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
6010 pr " CAMLxparam%d (%s);\n"
6011 (List.length rest) (String.concat ", " rest)
6013 pr " CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
6015 if not needs_extra_vs then
6016 pr " CAMLlocal1 (rv);\n"
6018 pr " CAMLlocal3 (rv, v, v2);\n";
6021 pr " guestfs_h *g = Guestfs_val (gv);\n";
6022 pr " if (g == NULL)\n";
6023 pr " caml_failwith (\"%s: used handle after closing it\");\n" name;
6031 pr " const char *%s = String_val (%sv);\n" n n
6033 pr " const char *%s =\n" n;
6034 pr " %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
6037 pr " char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
6039 pr " int %s = Bool_val (%sv);\n" n n
6041 pr " int %s = Int_val (%sv);\n" n n
6044 match fst style with
6045 | RErr -> pr " int r;\n"; "-1"
6046 | RInt _ -> pr " int r;\n"; "-1"
6047 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6048 | RBool _ -> pr " int r;\n"; "-1"
6049 | RConstString _ | RConstOptString _ ->
6050 pr " const char *r;\n"; "NULL"
6051 | RString _ -> pr " char *r;\n"; "NULL"
6056 | RStruct (_, typ) ->
6057 pr " struct guestfs_%s *r;\n" typ; "NULL"
6058 | RStructList (_, typ) ->
6059 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
6066 pr " size_t size;\n";
6070 pr " caml_enter_blocking_section ();\n";
6071 pr " r = guestfs_%s " name;
6072 generate_c_call_args ~handle:"g" style;
6074 pr " caml_leave_blocking_section ();\n";
6079 pr " ocaml_guestfs_free_strings (%s);\n" n;
6080 | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
6083 pr " if (r == %s)\n" error_code;
6084 pr " ocaml_guestfs_raise_error (g, \"%s\");\n" name;
6087 (match fst style with
6088 | RErr -> pr " rv = Val_unit;\n"
6089 | RInt _ -> pr " rv = Val_int (r);\n"
6091 pr " rv = caml_copy_int64 (r);\n"
6092 | RBool _ -> pr " rv = Val_bool (r);\n"
6094 pr " rv = caml_copy_string (r);\n"
6095 | RConstOptString _ ->
6096 pr " if (r) { /* Some string */\n";
6097 pr " v = caml_alloc (1, 0);\n";
6098 pr " v2 = caml_copy_string (r);\n";
6099 pr " Store_field (v, 0, v2);\n";
6100 pr " } else /* None */\n";
6101 pr " v = Val_int (0);\n";
6103 pr " rv = caml_copy_string (r);\n";
6106 pr " rv = caml_copy_string_array ((const char **) r);\n";
6107 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6109 | RStruct (_, typ) ->
6110 pr " rv = copy_%s (r);\n" typ;
6111 pr " guestfs_free_%s (r);\n" typ;
6112 | RStructList (_, typ) ->
6113 pr " rv = copy_%s_list (r);\n" typ;
6114 pr " guestfs_free_%s_list (r);\n" typ;
6116 pr " rv = copy_table (r);\n";
6117 pr " for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6120 pr " rv = caml_alloc_string (size);\n";
6121 pr " memcpy (String_val (rv), r, size);\n";
6124 pr " CAMLreturn (rv);\n";
6128 if List.length params > 5 then (
6129 pr "CAMLprim value\n";
6130 pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
6132 pr " return ocaml_guestfs_%s (argv[0]" name;
6133 iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
6140 and generate_ocaml_structure_decls () =
6143 pr "type %s = {\n" typ;
6146 | name, FString -> pr " %s : string;\n" name
6147 | name, FBuffer -> pr " %s : string;\n" name
6148 | name, FUUID -> pr " %s : string;\n" name
6149 | name, (FBytes|FInt64|FUInt64) -> pr " %s : int64;\n" name
6150 | name, (FInt32|FUInt32) -> pr " %s : int32;\n" name
6151 | name, FChar -> pr " %s : char;\n" name
6152 | name, FOptPercent -> pr " %s : float option;\n" name
6158 and generate_ocaml_prototype ?(is_external = false) name style =
6159 if is_external then pr "external " else pr "val ";
6160 pr "%s : t -> " name;
6163 | String _ | FileIn _ | FileOut _ -> pr "string -> "
6164 | OptString _ -> pr "string option -> "
6165 | StringList _ -> pr "string array -> "
6166 | Bool _ -> pr "bool -> "
6167 | Int _ -> pr "int -> "
6169 (match fst style with
6170 | RErr -> pr "unit" (* all errors are turned into exceptions *)
6171 | RInt _ -> pr "int"
6172 | RInt64 _ -> pr "int64"
6173 | RBool _ -> pr "bool"
6174 | RConstString _ -> pr "string"
6175 | RConstOptString _ -> pr "string option"
6176 | RString _ | RBufferOut _ -> pr "string"
6177 | RStringList _ -> pr "string array"
6178 | RStruct (_, typ) -> pr "%s" typ
6179 | RStructList (_, typ) -> pr "%s array" typ
6180 | RHashtable _ -> pr "(string * string) list"
6182 if is_external then (
6184 if List.length (snd style) + 1 > 5 then
6185 pr "\"ocaml_guestfs_%s_byte\" " name;
6186 pr "\"ocaml_guestfs_%s\"" name
6190 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
6191 and generate_perl_xs () =
6192 generate_header CStyle LGPLv2;
6195 #include \"EXTERN.h\"
6199 #include <guestfs.h>
6202 #define PRId64 \"lld\"
6206 my_newSVll(long long val) {
6207 #ifdef USE_64_BIT_ALL
6208 return newSViv(val);
6212 len = snprintf(buf, 100, \"%%\" PRId64, val);
6213 return newSVpv(buf, len);
6218 #define PRIu64 \"llu\"
6222 my_newSVull(unsigned long long val) {
6223 #ifdef USE_64_BIT_ALL
6224 return newSVuv(val);
6228 len = snprintf(buf, 100, \"%%\" PRIu64, val);
6229 return newSVpv(buf, len);
6233 /* http://www.perlmonks.org/?node_id=680842 */
6235 XS_unpack_charPtrPtr (SV *arg) {
6240 if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
6241 croak (\"array reference expected\");
6243 av = (AV *)SvRV (arg);
6244 ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
6246 croak (\"malloc failed\");
6248 for (i = 0; i <= av_len (av); i++) {
6249 SV **elem = av_fetch (av, i, 0);
6251 if (!elem || !*elem)
6252 croak (\"missing element in list\");
6254 ret[i] = SvPV_nolen (*elem);
6262 MODULE = Sys::Guestfs PACKAGE = Sys::Guestfs
6269 RETVAL = guestfs_create ();
6271 croak (\"could not create guestfs handle\");
6272 guestfs_set_error_handler (RETVAL, NULL, NULL);
6285 fun (name, style, _, _, _, _, _) ->
6286 (match fst style with
6287 | RErr -> pr "void\n"
6288 | RInt _ -> pr "SV *\n"
6289 | RInt64 _ -> pr "SV *\n"
6290 | RBool _ -> pr "SV *\n"
6291 | RConstString _ -> pr "SV *\n"
6292 | RConstOptString _ -> pr "SV *\n"
6293 | RString _ -> pr "SV *\n"
6294 | RBufferOut _ -> pr "SV *\n"
6296 | RStruct _ | RStructList _
6298 pr "void\n" (* all lists returned implictly on the stack *)
6300 (* Call and arguments. *)
6302 generate_c_call_args ~handle:"g" ~decl:true style;
6304 pr " guestfs_h *g;\n";
6308 | String n | FileIn n | FileOut n -> pr " char *%s;\n" n
6310 (* http://www.perlmonks.org/?node_id=554277
6311 * Note that the implicit handle argument means we have
6312 * to add 1 to the ST(x) operator.
6314 pr " char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
6315 | StringList n -> pr " char **%s;\n" n
6316 | Bool n -> pr " int %s;\n" n
6317 | Int n -> pr " int %s;\n" n
6320 let do_cleanups () =
6323 | String _ | OptString _ | Bool _ | Int _
6324 | FileIn _ | FileOut _ -> ()
6325 | StringList n -> pr " free (%s);\n" n
6330 (match fst style with
6335 pr " r = guestfs_%s " name;
6336 generate_c_call_args ~handle:"g" style;
6339 pr " if (r == -1)\n";
6340 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6346 pr " %s = guestfs_%s " n name;
6347 generate_c_call_args ~handle:"g" style;
6350 pr " if (%s == -1)\n" n;
6351 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6352 pr " RETVAL = newSViv (%s);\n" n;
6357 pr " int64_t %s;\n" n;
6359 pr " %s = guestfs_%s " n name;
6360 generate_c_call_args ~handle:"g" style;
6363 pr " if (%s == -1)\n" n;
6364 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6365 pr " RETVAL = my_newSVll (%s);\n" n;
6370 pr " const char *%s;\n" n;
6372 pr " %s = guestfs_%s " n name;
6373 generate_c_call_args ~handle:"g" style;
6376 pr " if (%s == NULL)\n" n;
6377 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6378 pr " RETVAL = newSVpv (%s, 0);\n" n;
6381 | RConstOptString n ->
6383 pr " const char *%s;\n" n;
6385 pr " %s = guestfs_%s " n name;
6386 generate_c_call_args ~handle:"g" style;
6389 pr " if (%s == NULL)\n" n;
6390 pr " RETVAL = &PL_sv_undef;\n";
6392 pr " RETVAL = newSVpv (%s, 0);\n" n;
6397 pr " char *%s;\n" n;
6399 pr " %s = guestfs_%s " n name;
6400 generate_c_call_args ~handle:"g" style;
6403 pr " if (%s == NULL)\n" n;
6404 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6405 pr " RETVAL = newSVpv (%s, 0);\n" n;
6406 pr " free (%s);\n" n;
6409 | RStringList n | RHashtable n ->
6411 pr " char **%s;\n" n;
6414 pr " %s = guestfs_%s " n name;
6415 generate_c_call_args ~handle:"g" style;
6418 pr " if (%s == NULL)\n" n;
6419 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6420 pr " for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
6421 pr " EXTEND (SP, n);\n";
6422 pr " for (i = 0; i < n; ++i) {\n";
6423 pr " PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
6424 pr " free (%s[i]);\n" n;
6426 pr " free (%s);\n" n;
6427 | RStruct (n, typ) ->
6428 let cols = cols_of_struct typ in
6429 generate_perl_struct_code typ cols name style n do_cleanups
6430 | RStructList (n, typ) ->
6431 let cols = cols_of_struct typ in
6432 generate_perl_struct_list_code typ cols name style n do_cleanups
6435 pr " char *%s;\n" n;
6436 pr " size_t size;\n";
6438 pr " %s = guestfs_%s " n name;
6439 generate_c_call_args ~handle:"g" style;
6442 pr " if (%s == NULL)\n" n;
6443 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6444 pr " RETVAL = newSVpv (%s, size);\n" n;
6445 pr " free (%s);\n" n;
6453 and generate_perl_struct_list_code typ cols name style n do_cleanups =
6455 pr " struct guestfs_%s_list *%s;\n" typ n;
6459 pr " %s = guestfs_%s " n name;
6460 generate_c_call_args ~handle:"g" style;
6463 pr " if (%s == NULL)\n" n;
6464 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6465 pr " EXTEND (SP, %s->len);\n" n;
6466 pr " for (i = 0; i < %s->len; ++i) {\n" n;
6467 pr " hv = newHV ();\n";
6471 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
6472 name (String.length name) n name
6474 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
6475 name (String.length name) n name
6477 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
6478 name (String.length name) n name n name
6479 | name, (FBytes|FUInt64) ->
6480 pr " (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
6481 name (String.length name) n name
6483 pr " (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
6484 name (String.length name) n name
6485 | name, (FInt32|FUInt32) ->
6486 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6487 name (String.length name) n name
6489 pr " (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
6490 name (String.length name) n name
6491 | name, FOptPercent ->
6492 pr " (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6493 name (String.length name) n name
6495 pr " PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
6497 pr " guestfs_free_%s_list (%s);\n" typ n
6499 and generate_perl_struct_code typ cols name style n do_cleanups =
6501 pr " struct guestfs_%s *%s;\n" typ n;
6503 pr " %s = guestfs_%s " n name;
6504 generate_c_call_args ~handle:"g" style;
6507 pr " if (%s == NULL)\n" n;
6508 pr " croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6509 pr " EXTEND (SP, 2 * %d);\n" (List.length cols);
6511 fun ((name, _) as col) ->
6512 pr " PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
6516 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
6519 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, %s->%s_len)));\n"
6522 pr " PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
6524 | name, (FBytes|FUInt64) ->
6525 pr " PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
6528 pr " PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
6530 | name, (FInt32|FUInt32) ->
6531 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6534 pr " PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
6536 | name, FOptPercent ->
6537 pr " PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6540 pr " free (%s);\n" n
6542 (* Generate Sys/Guestfs.pm. *)
6543 and generate_perl_pm () =
6544 generate_header HashStyle LGPLv2;
6551 Sys::Guestfs - Perl bindings for libguestfs
6557 my $h = Sys::Guestfs->new ();
6558 $h->add_drive ('guest.img');
6561 $h->mount ('/dev/sda1', '/');
6562 $h->touch ('/hello');
6567 The C<Sys::Guestfs> module provides a Perl XS binding to the
6568 libguestfs API for examining and modifying virtual machine
6571 Amongst the things this is good for: making batch configuration
6572 changes to guests, getting disk used/free statistics (see also:
6573 virt-df), migrating between virtualization systems (see also:
6574 virt-p2v), performing partial backups, performing partial guest
6575 clones, cloning guests and changing registry/UUID/hostname info, and
6578 Libguestfs uses Linux kernel and qemu code, and can access any type of
6579 guest filesystem that Linux and qemu can, including but not limited
6580 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6581 schemes, qcow, qcow2, vmdk.
6583 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6584 LVs, what filesystem is in each LV, etc.). It can also run commands
6585 in the context of the guest. Also you can access filesystems over FTP.
6587 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
6588 functions for using libguestfs from Perl, including integration
6593 All errors turn into calls to C<croak> (see L<Carp(3)>).
6601 package Sys::Guestfs;
6607 XSLoader::load ('Sys::Guestfs');
6609 =item $h = Sys::Guestfs->new ();
6611 Create a new guestfs handle.
6617 my $class = ref ($proto) || $proto;
6619 my $self = Sys::Guestfs::_create ();
6620 bless $self, $class;
6626 (* Actions. We only need to print documentation for these as
6627 * they are pulled in from the XS code automatically.
6630 fun (name, style, _, flags, _, _, longdesc) ->
6631 if not (List.mem NotInDocs flags) then (
6632 let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
6634 generate_perl_prototype name style;
6636 pr "%s\n\n" longdesc;
6637 if List.mem ProtocolLimitWarning flags then
6638 pr "%s\n\n" protocol_limit_warning;
6639 if List.mem DangerWillRobinson flags then
6640 pr "%s\n\n" danger_will_robinson
6642 ) all_functions_sorted;
6654 Copyright (C) 2009 Red Hat Inc.
6658 Please see the file COPYING.LIB for the full license.
6664 L<http://libguestfs.org>,
6665 L<Sys::Guestfs::Lib(3)>.
6670 and generate_perl_prototype name style =
6671 (match fst style with
6679 | RBufferOut n -> pr "$%s = " n
6681 | RHashtable n -> pr "%%%s = " n
6683 | RStructList (n,_) -> pr "@%s = " n
6686 let comma = ref false in
6689 if !comma then pr ", ";
6692 | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
6699 (* Generate Python C module. *)
6700 and generate_python_c () =
6701 generate_header CStyle LGPLv2;
6710 #include \"guestfs.h\"
6718 get_handle (PyObject *obj)
6721 assert (obj != Py_None);
6722 return ((Pyguestfs_Object *) obj)->g;
6726 put_handle (guestfs_h *g)
6730 PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
6733 /* This list should be freed (but not the strings) after use. */
6734 static const char **
6735 get_string_list (PyObject *obj)
6742 if (!PyList_Check (obj)) {
6743 PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
6747 len = PyList_Size (obj);
6748 r = malloc (sizeof (char *) * (len+1));
6750 PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
6754 for (i = 0; i < len; ++i)
6755 r[i] = PyString_AsString (PyList_GetItem (obj, i));
6762 put_string_list (char * const * const argv)
6767 for (argc = 0; argv[argc] != NULL; ++argc)
6770 list = PyList_New (argc);
6771 for (i = 0; i < argc; ++i)
6772 PyList_SetItem (list, i, PyString_FromString (argv[i]));
6778 put_table (char * const * const argv)
6780 PyObject *list, *item;
6783 for (argc = 0; argv[argc] != NULL; ++argc)
6786 list = PyList_New (argc >> 1);
6787 for (i = 0; i < argc; i += 2) {
6788 item = PyTuple_New (2);
6789 PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
6790 PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
6791 PyList_SetItem (list, i >> 1, item);
6798 free_strings (char **argv)
6802 for (argc = 0; argv[argc] != NULL; ++argc)
6808 py_guestfs_create (PyObject *self, PyObject *args)
6812 g = guestfs_create ();
6814 PyErr_SetString (PyExc_RuntimeError,
6815 \"guestfs.create: failed to allocate handle\");
6818 guestfs_set_error_handler (g, NULL, NULL);
6819 return put_handle (g);
6823 py_guestfs_close (PyObject *self, PyObject *args)
6828 if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
6830 g = get_handle (py_g);
6834 Py_INCREF (Py_None);
6840 (* Structures, turned into Python dictionaries. *)
6843 pr "static PyObject *\n";
6844 pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
6846 pr " PyObject *dict;\n";
6848 pr " dict = PyDict_New ();\n";
6852 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6853 pr " PyString_FromString (%s->%s));\n"
6856 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6857 pr " PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
6860 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6861 pr " PyString_FromStringAndSize (%s->%s, 32));\n"
6863 | name, (FBytes|FUInt64) ->
6864 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6865 pr " PyLong_FromUnsignedLongLong (%s->%s));\n"
6868 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6869 pr " PyLong_FromLongLong (%s->%s));\n"
6872 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6873 pr " PyLong_FromUnsignedLong (%s->%s));\n"
6876 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6877 pr " PyLong_FromLong (%s->%s));\n"
6879 | name, FOptPercent ->
6880 pr " if (%s->%s >= 0)\n" typ name;
6881 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6882 pr " PyFloat_FromDouble ((double) %s->%s));\n"
6885 pr " Py_INCREF (Py_None);\n";
6886 pr " PyDict_SetItemString (dict, \"%s\", Py_None);" name;
6889 pr " PyDict_SetItemString (dict, \"%s\",\n" name;
6890 pr " PyString_FromStringAndSize (&dirent->%s, 1));\n" name
6892 pr " return dict;\n";
6896 pr "static PyObject *\n";
6897 pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
6899 pr " PyObject *list;\n";
6902 pr " list = PyList_New (%ss->len);\n" typ;
6903 pr " for (i = 0; i < %ss->len; ++i)\n" typ;
6904 pr " PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
6905 pr " return list;\n";
6910 (* Python wrapper functions. *)
6912 fun (name, style, _, _, _, _, _) ->
6913 pr "static PyObject *\n";
6914 pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
6917 pr " PyObject *py_g;\n";
6918 pr " guestfs_h *g;\n";
6919 pr " PyObject *py_r;\n";
6922 match fst style with
6923 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
6924 | RInt64 _ -> pr " int64_t r;\n"; "-1"
6925 | RConstString _ | RConstOptString _ ->
6926 pr " const char *r;\n"; "NULL"
6927 | RString _ -> pr " char *r;\n"; "NULL"
6928 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
6929 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
6930 | RStructList (_, typ) ->
6931 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
6934 pr " size_t size;\n";
6939 | String n | FileIn n | FileOut n -> pr " const char *%s;\n" n
6940 | OptString n -> pr " const char *%s;\n" n
6942 pr " PyObject *py_%s;\n" n;
6943 pr " const char **%s;\n" n
6944 | Bool n -> pr " int %s;\n" n
6945 | Int n -> pr " int %s;\n" n
6950 (* Convert the parameters. *)
6951 pr " if (!PyArg_ParseTuple (args, (char *) \"O";
6954 | String _ | FileIn _ | FileOut _ -> pr "s"
6955 | OptString _ -> pr "z"
6956 | StringList _ -> pr "O"
6957 | Bool _ -> pr "i" (* XXX Python has booleans? *)
6960 pr ":guestfs_%s\",\n" name;
6964 | String n | FileIn n | FileOut n -> pr ", &%s" n
6965 | OptString n -> pr ", &%s" n
6966 | StringList n -> pr ", &py_%s" n
6967 | Bool n -> pr ", &%s" n
6968 | Int n -> pr ", &%s" n
6972 pr " return NULL;\n";
6974 pr " g = get_handle (py_g);\n";
6977 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6979 pr " %s = get_string_list (py_%s);\n" n n;
6980 pr " if (!%s) return NULL;\n" n
6985 pr " r = guestfs_%s " name;
6986 generate_c_call_args ~handle:"g" style;
6991 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
6993 pr " free (%s);\n" n
6996 pr " if (r == %s) {\n" error_code;
6997 pr " PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
6998 pr " return NULL;\n";
7002 (match fst style with
7004 pr " Py_INCREF (Py_None);\n";
7005 pr " py_r = Py_None;\n"
7007 | RBool _ -> pr " py_r = PyInt_FromLong ((long) r);\n"
7008 | RInt64 _ -> pr " py_r = PyLong_FromLongLong (r);\n"
7009 | RConstString _ -> pr " py_r = PyString_FromString (r);\n"
7010 | RConstOptString _ ->
7012 pr " py_r = PyString_FromString (r);\n";
7014 pr " Py_INCREF (Py_None);\n";
7015 pr " py_r = Py_None;\n";
7018 pr " py_r = PyString_FromString (r);\n";
7021 pr " py_r = put_string_list (r);\n";
7022 pr " free_strings (r);\n"
7023 | RStruct (_, typ) ->
7024 pr " py_r = put_%s (r);\n" typ;
7025 pr " guestfs_free_%s (r);\n" typ
7026 | RStructList (_, typ) ->
7027 pr " py_r = put_%s_list (r);\n" typ;
7028 pr " guestfs_free_%s_list (r);\n" typ
7030 pr " py_r = put_table (r);\n";
7031 pr " free_strings (r);\n"
7033 pr " py_r = PyString_FromStringAndSize (r, size);\n";
7037 pr " return py_r;\n";
7042 (* Table of functions. *)
7043 pr "static PyMethodDef methods[] = {\n";
7044 pr " { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
7045 pr " { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
7047 fun (name, _, _, _, _, _, _) ->
7048 pr " { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
7051 pr " { NULL, NULL, 0, NULL }\n";
7055 (* Init function. *)
7058 initlibguestfsmod (void)
7060 static int initialized = 0;
7062 if (initialized) return;
7063 Py_InitModule ((char *) \"libguestfsmod\", methods);
7068 (* Generate Python module. *)
7069 and generate_python_py () =
7070 generate_header HashStyle LGPLv2;
7073 u\"\"\"Python bindings for libguestfs
7076 g = guestfs.GuestFS ()
7077 g.add_drive (\"guest.img\")
7080 parts = g.list_partitions ()
7082 The guestfs module provides a Python binding to the libguestfs API
7083 for examining and modifying virtual machine disk images.
7085 Amongst the things this is good for: making batch configuration
7086 changes to guests, getting disk used/free statistics (see also:
7087 virt-df), migrating between virtualization systems (see also:
7088 virt-p2v), performing partial backups, performing partial guest
7089 clones, cloning guests and changing registry/UUID/hostname info, and
7092 Libguestfs uses Linux kernel and qemu code, and can access any type of
7093 guest filesystem that Linux and qemu can, including but not limited
7094 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
7095 schemes, qcow, qcow2, vmdk.
7097 Libguestfs provides ways to enumerate guest storage (eg. partitions,
7098 LVs, what filesystem is in each LV, etc.). It can also run commands
7099 in the context of the guest. Also you can access filesystems over FTP.
7101 Errors which happen while using the API are turned into Python
7102 RuntimeError exceptions.
7104 To create a guestfs handle you usually have to perform the following
7107 # Create the handle, call add_drive at least once, and possibly
7108 # several times if the guest has multiple block devices:
7109 g = guestfs.GuestFS ()
7110 g.add_drive (\"guest.img\")
7112 # Launch the qemu subprocess and wait for it to become ready:
7116 # Now you can issue commands, for example:
7121 import libguestfsmod
7124 \"\"\"Instances of this class are libguestfs API handles.\"\"\"
7126 def __init__ (self):
7127 \"\"\"Create a new libguestfs handle.\"\"\"
7128 self._o = libguestfsmod.create ()
7131 libguestfsmod.close (self._o)
7136 fun (name, style, _, flags, _, _, longdesc) ->
7138 generate_py_call_args ~handle:"self" (snd style);
7141 if not (List.mem NotInDocs flags) then (
7142 let doc = replace_str longdesc "C<guestfs_" "C<g." in
7144 match fst style with
7145 | RErr | RInt _ | RInt64 _ | RBool _
7146 | RConstOptString _ | RConstString _
7147 | RString _ | RBufferOut _ -> doc
7149 doc ^ "\n\nThis function returns a list of strings."
7150 | RStruct (_, typ) ->
7151 doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
7152 | RStructList (_, typ) ->
7153 doc ^ sprintf "\n\nThis function returns a list of %ss. Each %s is represented as a dictionary." typ typ
7155 doc ^ "\n\nThis function returns a dictionary." in
7157 if List.mem ProtocolLimitWarning flags then
7158 doc ^ "\n\n" ^ protocol_limit_warning
7161 if List.mem DangerWillRobinson flags then
7162 doc ^ "\n\n" ^ danger_will_robinson
7164 let doc = pod2text ~width:60 name doc in
7165 let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
7166 let doc = String.concat "\n " doc in
7167 pr " u\"\"\"%s\"\"\"\n" doc;
7169 pr " return libguestfsmod.%s " name;
7170 generate_py_call_args ~handle:"self._o" (snd style);
7175 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
7176 and generate_py_call_args ~handle args =
7178 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7181 (* Useful if you need the longdesc POD text as plain text. Returns a
7184 * Because this is very slow (the slowest part of autogeneration),
7185 * we memoize the results.
7187 and pod2text ~width name longdesc =
7188 let key = width, name, longdesc in
7189 try Hashtbl.find pod2text_memo key
7191 let filename, chan = Filename.open_temp_file "gen" ".tmp" in
7192 fprintf chan "=head1 %s\n\n%s\n" name longdesc;
7194 let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
7195 let chan = Unix.open_process_in cmd in
7196 let lines = ref [] in
7198 let line = input_line chan in
7199 if i = 1 then (* discard the first line of output *)
7202 let line = triml line in
7203 lines := line :: !lines;
7206 let lines = try loop 1 with End_of_file -> List.rev !lines in
7207 Unix.unlink filename;
7208 (match Unix.close_process_in chan with
7209 | Unix.WEXITED 0 -> ()
7211 failwithf "pod2text: process exited with non-zero status (%d)" i
7212 | Unix.WSIGNALED i | Unix.WSTOPPED i ->
7213 failwithf "pod2text: process signalled or stopped by signal %d" i
7215 Hashtbl.add pod2text_memo key lines;
7216 let chan = open_out pod2text_memo_filename in
7217 output_value chan pod2text_memo;
7221 (* Generate ruby bindings. *)
7222 and generate_ruby_c () =
7223 generate_header CStyle LGPLv2;
7231 #include \"guestfs.h\"
7233 #include \"extconf.h\"
7235 /* For Ruby < 1.9 */
7237 #define RARRAY_LEN(r) (RARRAY((r))->len)
7240 static VALUE m_guestfs; /* guestfs module */
7241 static VALUE c_guestfs; /* guestfs_h handle */
7242 static VALUE e_Error; /* used for all errors */
7244 static void ruby_guestfs_free (void *p)
7247 guestfs_close ((guestfs_h *) p);
7250 static VALUE ruby_guestfs_create (VALUE m)
7254 g = guestfs_create ();
7256 rb_raise (e_Error, \"failed to create guestfs handle\");
7258 /* Don't print error messages to stderr by default. */
7259 guestfs_set_error_handler (g, NULL, NULL);
7261 /* Wrap it, and make sure the close function is called when the
7264 return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
7267 static VALUE ruby_guestfs_close (VALUE gv)
7270 Data_Get_Struct (gv, guestfs_h, g);
7272 ruby_guestfs_free (g);
7273 DATA_PTR (gv) = NULL;
7281 fun (name, style, _, _, _, _, _) ->
7282 pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
7283 List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
7286 pr " guestfs_h *g;\n";
7287 pr " Data_Get_Struct (gv, guestfs_h, g);\n";
7289 pr " rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
7295 | String n | FileIn n | FileOut n ->
7296 pr " Check_Type (%sv, T_STRING);\n" n;
7297 pr " const char *%s = StringValueCStr (%sv);\n" n n;
7299 pr " rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
7300 pr " \"%s\", \"%s\");\n" n name
7302 pr " const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
7304 pr " char **%s;\n" n;
7305 pr " Check_Type (%sv, T_ARRAY);\n" n;
7307 pr " int i, len;\n";
7308 pr " len = RARRAY_LEN (%sv);\n" n;
7309 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
7311 pr " for (i = 0; i < len; ++i) {\n";
7312 pr " VALUE v = rb_ary_entry (%sv, i);\n" n;
7313 pr " %s[i] = StringValueCStr (v);\n" n;
7315 pr " %s[len] = NULL;\n" n;
7318 pr " int %s = RTEST (%sv);\n" n n
7320 pr " int %s = NUM2INT (%sv);\n" n n
7325 match fst style with
7326 | RErr | RInt _ | RBool _ -> pr " int r;\n"; "-1"
7327 | RInt64 _ -> pr " int64_t r;\n"; "-1"
7328 | RConstString _ | RConstOptString _ ->
7329 pr " const char *r;\n"; "NULL"
7330 | RString _ -> pr " char *r;\n"; "NULL"
7331 | RStringList _ | RHashtable _ -> pr " char **r;\n"; "NULL"
7332 | RStruct (_, typ) -> pr " struct guestfs_%s *r;\n" typ; "NULL"
7333 | RStructList (_, typ) ->
7334 pr " struct guestfs_%s_list *r;\n" typ; "NULL"
7337 pr " size_t size;\n";
7341 pr " r = guestfs_%s " name;
7342 generate_c_call_args ~handle:"g" style;
7347 | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7349 pr " free (%s);\n" n
7352 pr " if (r == %s)\n" error_code;
7353 pr " rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
7356 (match fst style with
7358 pr " return Qnil;\n"
7359 | RInt _ | RBool _ ->
7360 pr " return INT2NUM (r);\n"
7362 pr " return ULL2NUM (r);\n"
7364 pr " return rb_str_new2 (r);\n";
7365 | RConstOptString _ ->
7367 pr " return rb_str_new2 (r);\n";
7369 pr " return Qnil;\n";
7371 pr " VALUE rv = rb_str_new2 (r);\n";
7375 pr " int i, len = 0;\n";
7376 pr " for (i = 0; r[i] != NULL; ++i) len++;\n";
7377 pr " VALUE rv = rb_ary_new2 (len);\n";
7378 pr " for (i = 0; r[i] != NULL; ++i) {\n";
7379 pr " rb_ary_push (rv, rb_str_new2 (r[i]));\n";
7380 pr " free (r[i]);\n";
7384 | RStruct (_, typ) ->
7385 let cols = cols_of_struct typ in
7386 generate_ruby_struct_code typ cols
7387 | RStructList (_, typ) ->
7388 let cols = cols_of_struct typ in
7389 generate_ruby_struct_list_code typ cols
7391 pr " VALUE rv = rb_hash_new ();\n";
7393 pr " for (i = 0; r[i] != NULL; i+=2) {\n";
7394 pr " rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
7395 pr " free (r[i]);\n";
7396 pr " free (r[i+1]);\n";
7401 pr " VALUE rv = rb_str_new (r, size);\n";
7411 /* Initialize the module. */
7412 void Init__guestfs ()
7414 m_guestfs = rb_define_module (\"Guestfs\");
7415 c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
7416 e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
7418 rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
7419 rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
7422 (* Define the rest of the methods. *)
7424 fun (name, style, _, _, _, _, _) ->
7425 pr " rb_define_method (c_guestfs, \"%s\",\n" name;
7426 pr " ruby_guestfs_%s, %d);\n" name (List.length (snd style))
7431 (* Ruby code to return a struct. *)
7432 and generate_ruby_struct_code typ cols =
7433 pr " VALUE rv = rb_hash_new ();\n";
7437 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
7439 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
7441 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
7442 | name, (FBytes|FUInt64) ->
7443 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7445 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
7447 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
7449 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
7450 | name, FOptPercent ->
7451 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
7452 | name, FChar -> (* XXX wrong? *)
7453 pr " rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7455 pr " guestfs_free_%s (r);\n" typ;
7458 (* Ruby code to return a struct list. *)
7459 and generate_ruby_struct_list_code typ cols =
7460 pr " VALUE rv = rb_ary_new2 (r->len);\n";
7462 pr " for (i = 0; i < r->len; ++i) {\n";
7463 pr " VALUE hv = rb_hash_new ();\n";
7467 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
7469 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
7471 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
7472 | name, (FBytes|FUInt64) ->
7473 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7475 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
7477 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
7479 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
7480 | name, FOptPercent ->
7481 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
7482 | name, FChar -> (* XXX wrong? *)
7483 pr " rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7485 pr " rb_ary_push (rv, hv);\n";
7487 pr " guestfs_free_%s_list (r);\n" typ;
7490 (* Generate Java bindings GuestFS.java file. *)
7491 and generate_java_java () =
7492 generate_header CStyle LGPLv2;
7495 package com.redhat.et.libguestfs;
7497 import java.util.HashMap;
7498 import com.redhat.et.libguestfs.LibGuestFSException;
7499 import com.redhat.et.libguestfs.PV;
7500 import com.redhat.et.libguestfs.VG;
7501 import com.redhat.et.libguestfs.LV;
7502 import com.redhat.et.libguestfs.Stat;
7503 import com.redhat.et.libguestfs.StatVFS;
7504 import com.redhat.et.libguestfs.IntBool;
7505 import com.redhat.et.libguestfs.Dirent;
7508 * The GuestFS object is a libguestfs handle.
7512 public class GuestFS {
7513 // Load the native code.
7515 System.loadLibrary (\"guestfs_jni\");
7519 * The native guestfs_h pointer.
7524 * Create a libguestfs handle.
7526 * @throws LibGuestFSException
7528 public GuestFS () throws LibGuestFSException
7532 private native long _create () throws LibGuestFSException;
7535 * Close a libguestfs handle.
7537 * You can also leave handles to be collected by the garbage
7538 * collector, but this method ensures that the resources used
7539 * by the handle are freed up immediately. If you call any
7540 * other methods after closing the handle, you will get an
7543 * @throws LibGuestFSException
7545 public void close () throws LibGuestFSException
7551 private native void _close (long g) throws LibGuestFSException;
7553 public void finalize () throws LibGuestFSException
7561 fun (name, style, _, flags, _, shortdesc, longdesc) ->
7562 if not (List.mem NotInDocs flags); then (
7563 let doc = replace_str longdesc "C<guestfs_" "C<g." in
7565 if List.mem ProtocolLimitWarning flags then
7566 doc ^ "\n\n" ^ protocol_limit_warning
7569 if List.mem DangerWillRobinson flags then
7570 doc ^ "\n\n" ^ danger_will_robinson
7572 let doc = pod2text ~width:60 name doc in
7573 let doc = List.map ( (* RHBZ#501883 *)
7576 | nonempty -> nonempty
7578 let doc = String.concat "\n * " doc in
7581 pr " * %s\n" shortdesc;
7584 pr " * @throws LibGuestFSException\n";
7588 generate_java_prototype ~public:true ~semicolon:false name style;
7591 pr " if (g == 0)\n";
7592 pr " throw new LibGuestFSException (\"%s: handle is closed\");\n"
7595 if fst style <> RErr then pr "return ";
7597 generate_java_call_args ~handle:"g" (snd style);
7601 generate_java_prototype ~privat:true ~native:true name style;
7608 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
7609 and generate_java_call_args ~handle args =
7611 List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7614 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
7615 ?(semicolon=true) name style =
7616 if privat then pr "private ";
7617 if public then pr "public ";
7618 if native then pr "native ";
7621 (match fst style with
7622 | RErr -> pr "void ";
7623 | RInt _ -> pr "int ";
7624 | RInt64 _ -> pr "long ";
7625 | RBool _ -> pr "boolean ";
7626 | RConstString _ | RConstOptString _ | RString _
7627 | RBufferOut _ -> pr "String ";
7628 | RStringList _ -> pr "String[] ";
7629 | RStruct (_, typ) ->
7630 let name = java_name_of_struct typ in
7632 | RStructList (_, typ) ->
7633 let name = java_name_of_struct typ in
7635 | RHashtable _ -> pr "HashMap<String,String> ";
7638 if native then pr "_%s " name else pr "%s " name;
7640 let needs_comma = ref false in
7649 if !needs_comma then pr ", ";
7650 needs_comma := true;
7667 pr " throws LibGuestFSException";
7668 if semicolon then pr ";"
7670 and generate_java_struct jtyp cols =
7671 generate_header CStyle LGPLv2;
7674 package com.redhat.et.libguestfs;
7677 * Libguestfs %s structure.
7689 | name, FBuffer -> pr " public String %s;\n" name
7690 | name, (FBytes|FUInt64|FInt64) -> pr " public long %s;\n" name
7691 | name, (FUInt32|FInt32) -> pr " public int %s;\n" name
7692 | name, FChar -> pr " public char %s;\n" name
7693 | name, FOptPercent ->
7694 pr " /* The next field is [0..100] or -1 meaning 'not present': */\n";
7695 pr " public float %s;\n" name
7700 and generate_java_c () =
7701 generate_header CStyle LGPLv2;
7708 #include \"com_redhat_et_libguestfs_GuestFS.h\"
7709 #include \"guestfs.h\"
7711 /* Note that this function returns. The exception is not thrown
7712 * until after the wrapper function returns.
7715 throw_exception (JNIEnv *env, const char *msg)
7718 cl = (*env)->FindClass (env,
7719 \"com/redhat/et/libguestfs/LibGuestFSException\");
7720 (*env)->ThrowNew (env, cl, msg);
7723 JNIEXPORT jlong JNICALL
7724 Java_com_redhat_et_libguestfs_GuestFS__1create
7725 (JNIEnv *env, jobject obj)
7729 g = guestfs_create ();
7731 throw_exception (env, \"GuestFS.create: failed to allocate handle\");
7734 guestfs_set_error_handler (g, NULL, NULL);
7735 return (jlong) (long) g;
7738 JNIEXPORT void JNICALL
7739 Java_com_redhat_et_libguestfs_GuestFS__1close
7740 (JNIEnv *env, jobject obj, jlong jg)
7742 guestfs_h *g = (guestfs_h *) (long) jg;
7749 fun (name, style, _, _, _, _, _) ->
7751 (match fst style with
7752 | RErr -> pr "void ";
7753 | RInt _ -> pr "jint ";
7754 | RInt64 _ -> pr "jlong ";
7755 | RBool _ -> pr "jboolean ";
7756 | RConstString _ | RConstOptString _ | RString _
7757 | RBufferOut _ -> pr "jstring ";
7758 | RStruct _ | RHashtable _ ->
7760 | RStringList _ | RStructList _ ->
7764 pr "Java_com_redhat_et_libguestfs_GuestFS_";
7765 pr "%s" (replace_str ("_" ^ name) "_" "_1");
7767 pr " (JNIEnv *env, jobject obj, jlong jg";
7774 pr ", jstring j%s" n
7776 pr ", jobjectArray j%s" n
7778 pr ", jboolean j%s" n
7784 pr " guestfs_h *g = (guestfs_h *) (long) jg;\n";
7785 let error_code, no_ret =
7786 match fst style with
7787 | RErr -> pr " int r;\n"; "-1", ""
7789 | RInt _ -> pr " int r;\n"; "-1", "0"
7790 | RInt64 _ -> pr " int64_t r;\n"; "-1", "0"
7791 | RConstString _ -> pr " const char *r;\n"; "NULL", "NULL"
7792 | RConstOptString _ -> pr " const char *r;\n"; "NULL", "NULL"
7794 pr " jstring jr;\n";
7795 pr " char *r;\n"; "NULL", "NULL"
7797 pr " jobjectArray jr;\n";
7800 pr " jstring jstr;\n";
7801 pr " char **r;\n"; "NULL", "NULL"
7802 | RStruct (_, typ) ->
7803 pr " jobject jr;\n";
7805 pr " jfieldID fl;\n";
7806 pr " struct guestfs_%s *r;\n" typ; "NULL", "NULL"
7807 | RStructList (_, typ) ->
7808 pr " jobjectArray jr;\n";
7810 pr " jfieldID fl;\n";
7811 pr " jobject jfl;\n";
7812 pr " struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
7813 | RHashtable _ -> pr " char **r;\n"; "NULL", "NULL"
7815 pr " jstring jr;\n";
7817 pr " size_t size;\n";
7825 pr " const char *%s;\n" n
7827 pr " int %s_len;\n" n;
7828 pr " const char **%s;\n" n
7835 (match fst style with
7836 | RStringList _ | RStructList _ -> true
7837 | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
7839 | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
7840 List.exists (function StringList _ -> true | _ -> false) (snd style) in
7846 (* Get the parameters. *)
7852 pr " %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
7854 (* This is completely undocumented, but Java null becomes
7857 pr " %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
7859 pr " %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
7860 pr " %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
7861 pr " for (i = 0; i < %s_len; ++i) {\n" n;
7862 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
7864 pr " %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
7866 pr " %s[%s_len] = NULL;\n" n n;
7869 pr " %s = j%s;\n" n n
7872 (* Make the call. *)
7873 pr " r = guestfs_%s " name;
7874 generate_c_call_args ~handle:"g" style;
7877 (* Release the parameters. *)
7883 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
7886 pr " (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
7888 pr " for (i = 0; i < %s_len; ++i) {\n" n;
7889 pr " jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
7891 pr " (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
7893 pr " free (%s);\n" n
7898 (* Check for errors. *)
7899 pr " if (r == %s) {\n" error_code;
7900 pr " throw_exception (env, guestfs_last_error (g));\n";
7901 pr " return %s;\n" no_ret;
7905 (match fst style with
7907 | RInt _ -> pr " return (jint) r;\n"
7908 | RBool _ -> pr " return (jboolean) r;\n"
7909 | RInt64 _ -> pr " return (jlong) r;\n"
7910 | RConstString _ -> pr " return (*env)->NewStringUTF (env, r);\n"
7911 | RConstOptString _ ->
7912 pr " return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
7914 pr " jr = (*env)->NewStringUTF (env, r);\n";
7918 pr " for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
7919 pr " cl = (*env)->FindClass (env, \"java/lang/String\");\n";
7920 pr " jstr = (*env)->NewStringUTF (env, \"\");\n";
7921 pr " jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
7922 pr " for (i = 0; i < r_len; ++i) {\n";
7923 pr " jstr = (*env)->NewStringUTF (env, r[i]);\n";
7924 pr " (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
7925 pr " free (r[i]);\n";
7929 | RStruct (_, typ) ->
7930 let jtyp = java_name_of_struct typ in
7931 let cols = cols_of_struct typ in
7932 generate_java_struct_return typ jtyp cols
7933 | RStructList (_, typ) ->
7934 let jtyp = java_name_of_struct typ in
7935 let cols = cols_of_struct typ in
7936 generate_java_struct_list_return typ jtyp cols
7939 pr " throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
7940 pr " return NULL;\n"
7942 pr " jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
7951 and generate_java_struct_return typ jtyp cols =
7952 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
7953 pr " jr = (*env)->AllocObject (env, cl);\n";
7957 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7958 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
7961 pr " char s[33];\n";
7962 pr " memcpy (s, r->%s, 32);\n" name;
7964 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7965 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
7969 pr " int len = r->%s_len;\n" name;
7970 pr " char s[len+1];\n";
7971 pr " memcpy (s, r->%s, len);\n" name;
7972 pr " s[len] = 0;\n";
7973 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
7974 pr " (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
7976 | name, (FBytes|FUInt64|FInt64) ->
7977 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
7978 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7979 | name, (FUInt32|FInt32) ->
7980 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
7981 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7982 | name, FOptPercent ->
7983 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
7984 pr " (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
7986 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
7987 pr " (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
7992 and generate_java_struct_list_return typ jtyp cols =
7993 pr " cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
7994 pr " jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
7995 pr " for (i = 0; i < r->len; ++i) {\n";
7996 pr " jfl = (*env)->AllocObject (env, cl);\n";
8000 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8001 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
8004 pr " char s[33];\n";
8005 pr " memcpy (s, r->val[i].%s, 32);\n" name;
8007 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8008 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8012 pr " int len = r->val[i].%s_len;\n" name;
8013 pr " char s[len+1];\n";
8014 pr " memcpy (s, r->val[i].%s, len);\n" name;
8015 pr " s[len] = 0;\n";
8016 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8017 pr " (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8019 | name, (FBytes|FUInt64|FInt64) ->
8020 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
8021 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8022 | name, (FUInt32|FInt32) ->
8023 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
8024 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8025 | name, FOptPercent ->
8026 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
8027 pr " (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
8029 pr " fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
8030 pr " (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8032 pr " (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
8034 pr " guestfs_free_%s_list (r);\n" typ;
8037 and generate_haskell_hs () =
8038 generate_header HaskellStyle LGPLv2;
8040 (* XXX We only know how to generate partial FFI for Haskell
8041 * at the moment. Please help out!
8043 let can_generate style =
8047 | RInt64 _, _ -> true
8050 | RConstOptString _, _
8056 | RBufferOut _, _ -> false in
8059 {-# INCLUDE <guestfs.h> #-}
8060 {-# LANGUAGE ForeignFunctionInterface #-}
8065 (* List out the names of the actions we want to export. *)
8067 fun (name, style, _, _, _, _, _) ->
8068 if can_generate style then pr ",\n %s" name
8075 import Foreign.C.Types
8077 import Control.Exception
8078 import Data.Typeable
8080 data GuestfsS = GuestfsS -- represents the opaque C struct
8081 type GuestfsP = Ptr GuestfsS -- guestfs_h *
8082 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
8084 -- XXX define properly later XXX
8088 data IntBool = IntBool
8090 data StatVFS = StatVFS
8091 data Hashtable = Hashtable
8093 foreign import ccall unsafe \"guestfs_create\" c_create
8095 foreign import ccall unsafe \"&guestfs_close\" c_close
8096 :: FunPtr (GuestfsP -> IO ())
8097 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
8098 :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
8100 create :: IO GuestfsH
8103 c_set_error_handler p nullPtr nullPtr
8104 h <- newForeignPtr c_close p
8107 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
8108 :: GuestfsP -> IO CString
8110 -- last_error :: GuestfsH -> IO (Maybe String)
8111 -- last_error h = do
8112 -- str <- withForeignPtr h (\\p -> c_last_error p)
8113 -- maybePeek peekCString str
8115 last_error :: GuestfsH -> IO (String)
8117 str <- withForeignPtr h (\\p -> c_last_error p)
8119 then return \"no error\"
8120 else peekCString str
8124 (* Generate wrappers for each foreign function. *)
8126 fun (name, style, _, _, _, _, _) ->
8127 if can_generate style then (
8128 pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
8130 generate_haskell_prototype ~handle:"GuestfsP" style;
8134 generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
8136 pr "%s %s = do\n" name
8137 (String.concat " " ("h" :: List.map name_of_argt (snd style)));
8139 (* Convert pointer arguments using with* functions. *)
8144 | String n -> pr "withCString %s $ \\%s -> " n n
8145 | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
8146 | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
8147 | Bool _ | Int _ -> ()
8149 (* Convert integer arguments. *)
8153 | Bool n -> sprintf "(fromBool %s)" n
8154 | Int n -> sprintf "(fromIntegral %s)" n
8155 | FileIn n | FileOut n | String n | OptString n | StringList n -> n
8157 pr "withForeignPtr h (\\p -> c_%s %s)\n" name
8158 (String.concat " " ("p" :: args));
8159 (match fst style with
8160 | RErr | RInt _ | RInt64 _ | RBool _ ->
8161 pr " if (r == -1)\n";
8163 pr " err <- last_error h\n";
8165 | RConstString _ | RConstOptString _ | RString _
8166 | RStringList _ | RStruct _
8167 | RStructList _ | RHashtable _ | RBufferOut _ ->
8168 pr " if (r == nullPtr)\n";
8170 pr " err <- last_error h\n";
8173 (match fst style with
8175 pr " else return ()\n"
8177 pr " else return (fromIntegral r)\n"
8179 pr " else return (fromIntegral r)\n"
8181 pr " else return (toBool r)\n"
8190 pr " else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
8196 and generate_haskell_prototype ~handle ?(hs = false) style =
8198 let string = if hs then "String" else "CString" in
8199 let int = if hs then "Int" else "CInt" in
8200 let bool = if hs then "Bool" else "CInt" in
8201 let int64 = if hs then "Integer" else "Int64" in
8205 | String _ -> pr "%s" string
8206 | OptString _ -> if hs then pr "Maybe String" else pr "CString"
8207 | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
8208 | Bool _ -> pr "%s" bool
8209 | Int _ -> pr "%s" int
8210 | FileIn _ -> pr "%s" string
8211 | FileOut _ -> pr "%s" string
8216 (match fst style with
8217 | RErr -> if not hs then pr "CInt"
8218 | RInt _ -> pr "%s" int
8219 | RInt64 _ -> pr "%s" int64
8220 | RBool _ -> pr "%s" bool
8221 | RConstString _ -> pr "%s" string
8222 | RConstOptString _ -> pr "Maybe %s" string
8223 | RString _ -> pr "%s" string
8224 | RStringList _ -> pr "[%s]" string
8225 | RStruct (_, typ) ->
8226 let name = java_name_of_struct typ in
8228 | RStructList (_, typ) ->
8229 let name = java_name_of_struct typ in
8231 | RHashtable _ -> pr "Hashtable"
8232 | RBufferOut _ -> pr "%s" string
8236 and generate_bindtests () =
8237 generate_header CStyle LGPLv2;
8242 #include <inttypes.h>
8245 #include \"guestfs.h\"
8246 #include \"guestfs_protocol.h\"
8248 #define error guestfs_error
8249 #define safe_calloc guestfs_safe_calloc
8250 #define safe_malloc guestfs_safe_malloc
8253 print_strings (char * const* const argv)
8258 for (argc = 0; argv[argc] != NULL; ++argc) {
8259 if (argc > 0) printf (\", \");
8260 printf (\"\\\"%%s\\\"\", argv[argc]);
8265 /* The test0 function prints its parameters to stdout. */
8269 match test_functions with
8270 | [] -> assert false
8271 | test0 :: tests -> test0, tests in
8274 let (name, style, _, _, _, _, _) = test0 in
8275 generate_prototype ~extern:false ~semicolon:false ~newline:true
8276 ~handle:"g" ~prefix:"guestfs_" name style;
8282 | FileOut n -> pr " printf (\"%%s\\n\", %s);\n" n
8283 | OptString n -> pr " printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
8284 | StringList n -> pr " print_strings (%s);\n" n
8285 | Bool n -> pr " printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
8286 | Int n -> pr " printf (\"%%d\\n\", %s);\n" n
8288 pr " /* Java changes stdout line buffering so we need this: */\n";
8289 pr " fflush (stdout);\n";
8295 fun (name, style, _, _, _, _, _) ->
8296 if String.sub name (String.length name - 3) 3 <> "err" then (
8297 pr "/* Test normal return. */\n";
8298 generate_prototype ~extern:false ~semicolon:false ~newline:true
8299 ~handle:"g" ~prefix:"guestfs_" name style;
8301 (match fst style with
8306 pr " sscanf (val, \"%%d\", &r);\n";
8310 pr " sscanf (val, \"%%\" SCNi64, &r);\n";
8313 pr " return strcmp (val, \"true\") == 0;\n"
8315 | RConstOptString _ ->
8316 (* Can't return the input string here. Return a static
8317 * string so we ensure we get a segfault if the caller
8320 pr " return \"static string\";\n"
8322 pr " return strdup (val);\n"
8324 pr " char **strs;\n";
8326 pr " sscanf (val, \"%%d\", &n);\n";
8327 pr " strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
8328 pr " for (i = 0; i < n; ++i) {\n";
8329 pr " strs[i] = safe_malloc (g, 16);\n";
8330 pr " snprintf (strs[i], 16, \"%%d\", i);\n";
8332 pr " strs[n] = NULL;\n";
8333 pr " return strs;\n"
8334 | RStruct (_, typ) ->
8335 pr " struct guestfs_%s *r;\n" typ;
8336 pr " r = safe_calloc (g, sizeof *r, 1);\n";
8338 | RStructList (_, typ) ->
8339 pr " struct guestfs_%s_list *r;\n" typ;
8340 pr " r = safe_calloc (g, sizeof *r, 1);\n";
8341 pr " sscanf (val, \"%%d\", &r->len);\n";
8342 pr " r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
8345 pr " char **strs;\n";
8347 pr " sscanf (val, \"%%d\", &n);\n";
8348 pr " strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
8349 pr " for (i = 0; i < n; ++i) {\n";
8350 pr " strs[i*2] = safe_malloc (g, 16);\n";
8351 pr " strs[i*2+1] = safe_malloc (g, 16);\n";
8352 pr " snprintf (strs[i*2], 16, \"%%d\", i);\n";
8353 pr " snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
8355 pr " strs[n*2] = NULL;\n";
8356 pr " return strs;\n"
8358 pr " return strdup (val);\n"
8363 pr "/* Test error return. */\n";
8364 generate_prototype ~extern:false ~semicolon:false ~newline:true
8365 ~handle:"g" ~prefix:"guestfs_" name style;
8367 pr " error (g, \"error\");\n";
8368 (match fst style with
8369 | RErr | RInt _ | RInt64 _ | RBool _ ->
8371 | RConstString _ | RConstOptString _
8372 | RString _ | RStringList _ | RStruct _
8376 pr " return NULL;\n"
8383 and generate_ocaml_bindtests () =
8384 generate_header OCamlStyle GPLv2;
8388 let g = Guestfs.create () in
8395 | CallString s -> "\"" ^ s ^ "\""
8396 | CallOptString None -> "None"
8397 | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
8398 | CallStringList xs ->
8399 "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
8400 | CallInt i when i >= 0 -> string_of_int i
8401 | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
8402 | CallBool b -> string_of_bool b
8407 generate_lang_bindtests (
8408 fun f args -> pr " Guestfs.%s g %s;\n" f (mkargs args)
8411 pr "print_endline \"EOF\"\n"
8413 and generate_perl_bindtests () =
8414 pr "#!/usr/bin/perl -w\n";
8415 generate_header HashStyle GPLv2;
8422 my $g = Sys::Guestfs->new ();
8426 String.concat ", " (
8429 | CallString s -> "\"" ^ s ^ "\""
8430 | CallOptString None -> "undef"
8431 | CallOptString (Some s) -> sprintf "\"%s\"" s
8432 | CallStringList xs ->
8433 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8434 | CallInt i -> string_of_int i
8435 | CallBool b -> if b then "1" else "0"
8440 generate_lang_bindtests (
8441 fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
8444 pr "print \"EOF\\n\"\n"
8446 and generate_python_bindtests () =
8447 generate_header HashStyle GPLv2;
8452 g = guestfs.GuestFS ()
8456 String.concat ", " (
8459 | CallString s -> "\"" ^ s ^ "\""
8460 | CallOptString None -> "None"
8461 | CallOptString (Some s) -> sprintf "\"%s\"" s
8462 | CallStringList xs ->
8463 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8464 | CallInt i -> string_of_int i
8465 | CallBool b -> if b then "1" else "0"
8470 generate_lang_bindtests (
8471 fun f args -> pr "g.%s (%s)\n" f (mkargs args)
8474 pr "print \"EOF\"\n"
8476 and generate_ruby_bindtests () =
8477 generate_header HashStyle GPLv2;
8482 g = Guestfs::create()
8486 String.concat ", " (
8489 | CallString s -> "\"" ^ s ^ "\""
8490 | CallOptString None -> "nil"
8491 | CallOptString (Some s) -> sprintf "\"%s\"" s
8492 | CallStringList xs ->
8493 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8494 | CallInt i -> string_of_int i
8495 | CallBool b -> string_of_bool b
8500 generate_lang_bindtests (
8501 fun f args -> pr "g.%s(%s)\n" f (mkargs args)
8504 pr "print \"EOF\\n\"\n"
8506 and generate_java_bindtests () =
8507 generate_header CStyle GPLv2;
8510 import com.redhat.et.libguestfs.*;
8512 public class Bindtests {
8513 public static void main (String[] argv)
8516 GuestFS g = new GuestFS ();
8520 String.concat ", " (
8523 | CallString s -> "\"" ^ s ^ "\""
8524 | CallOptString None -> "null"
8525 | CallOptString (Some s) -> sprintf "\"%s\"" s
8526 | CallStringList xs ->
8528 String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
8529 | CallInt i -> string_of_int i
8530 | CallBool b -> string_of_bool b
8535 generate_lang_bindtests (
8536 fun f args -> pr " g.%s (%s);\n" f (mkargs args)
8540 System.out.println (\"EOF\");
8542 catch (Exception exn) {
8543 System.err.println (exn);
8550 and generate_haskell_bindtests () =
8551 generate_header HaskellStyle GPLv2;
8554 module Bindtests where
8555 import qualified Guestfs
8565 | CallString s -> "\"" ^ s ^ "\""
8566 | CallOptString None -> "Nothing"
8567 | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
8568 | CallStringList xs ->
8569 "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8570 | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
8571 | CallInt i -> string_of_int i
8572 | CallBool true -> "True"
8573 | CallBool false -> "False"
8578 generate_lang_bindtests (
8579 fun f args -> pr " Guestfs.%s g %s\n" f (mkargs args)
8582 pr " putStrLn \"EOF\"\n"
8584 (* Language-independent bindings tests - we do it this way to
8585 * ensure there is parity in testing bindings across all languages.
8587 and generate_lang_bindtests call =
8588 call "test0" [CallString "abc"; CallOptString (Some "def");
8589 CallStringList []; CallBool false;
8590 CallInt 0; CallString "123"; CallString "456"];
8591 call "test0" [CallString "abc"; CallOptString None;
8592 CallStringList []; CallBool false;
8593 CallInt 0; CallString "123"; CallString "456"];
8594 call "test0" [CallString ""; CallOptString (Some "def");
8595 CallStringList []; CallBool false;
8596 CallInt 0; CallString "123"; CallString "456"];
8597 call "test0" [CallString ""; CallOptString (Some "");
8598 CallStringList []; CallBool false;
8599 CallInt 0; CallString "123"; CallString "456"];
8600 call "test0" [CallString "abc"; CallOptString (Some "def");
8601 CallStringList ["1"]; CallBool false;
8602 CallInt 0; CallString "123"; CallString "456"];
8603 call "test0" [CallString "abc"; CallOptString (Some "def");
8604 CallStringList ["1"; "2"]; CallBool false;
8605 CallInt 0; CallString "123"; CallString "456"];
8606 call "test0" [CallString "abc"; CallOptString (Some "def");
8607 CallStringList ["1"]; CallBool true;
8608 CallInt 0; CallString "123"; CallString "456"];
8609 call "test0" [CallString "abc"; CallOptString (Some "def");
8610 CallStringList ["1"]; CallBool false;
8611 CallInt (-1); CallString "123"; CallString "456"];
8612 call "test0" [CallString "abc"; CallOptString (Some "def");
8613 CallStringList ["1"]; CallBool false;
8614 CallInt (-2); CallString "123"; CallString "456"];
8615 call "test0" [CallString "abc"; CallOptString (Some "def");
8616 CallStringList ["1"]; CallBool false;
8617 CallInt 1; CallString "123"; CallString "456"];
8618 call "test0" [CallString "abc"; CallOptString (Some "def");
8619 CallStringList ["1"]; CallBool false;
8620 CallInt 2; CallString "123"; CallString "456"];
8621 call "test0" [CallString "abc"; CallOptString (Some "def");
8622 CallStringList ["1"]; CallBool false;
8623 CallInt 4095; CallString "123"; CallString "456"];
8624 call "test0" [CallString "abc"; CallOptString (Some "def");
8625 CallStringList ["1"]; CallBool false;
8626 CallInt 0; CallString ""; CallString ""]
8628 (* XXX Add here tests of the return and error functions. *)
8630 (* This is used to generate the src/MAX_PROC_NR file which
8631 * contains the maximum procedure number, a surrogate for the
8632 * ABI version number. See src/Makefile.am for the details.
8634 and generate_max_proc_nr () =
8635 let proc_nrs = List.map (
8636 fun (_, _, proc_nr, _, _, _, _) -> proc_nr
8637 ) daemon_functions in
8639 let max_proc_nr = List.fold_left max 0 proc_nrs in
8641 pr "%d\n" max_proc_nr
8643 let output_to filename =
8644 let filename_new = filename ^ ".new" in
8645 chan := open_out filename_new;
8650 (* Is the new file different from the current file? *)
8651 if Sys.file_exists filename && files_equal filename filename_new then
8652 Unix.unlink filename_new (* same, so skip it *)
8654 (* different, overwrite old one *)
8655 (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
8656 Unix.rename filename_new filename;
8657 Unix.chmod filename 0o444;
8658 printf "written %s\n%!" filename;
8667 if not (Sys.file_exists "HACKING") then (
8669 You are probably running this from the wrong directory.
8670 Run it from the top source directory using the command
8676 let close = output_to "src/guestfs_protocol.x" in
8680 let close = output_to "src/guestfs-structs.h" in
8681 generate_structs_h ();
8684 let close = output_to "src/guestfs-actions.h" in
8685 generate_actions_h ();
8688 let close = output_to "src/guestfs-actions.c" in
8689 generate_client_actions ();
8692 let close = output_to "daemon/actions.h" in
8693 generate_daemon_actions_h ();
8696 let close = output_to "daemon/stubs.c" in
8697 generate_daemon_actions ();
8700 let close = output_to "daemon/names.c" in
8701 generate_daemon_names ();
8704 let close = output_to "capitests/tests.c" in
8708 let close = output_to "src/guestfs-bindtests.c" in
8709 generate_bindtests ();
8712 let close = output_to "fish/cmds.c" in
8713 generate_fish_cmds ();
8716 let close = output_to "fish/completion.c" in
8717 generate_fish_completion ();
8720 let close = output_to "guestfs-structs.pod" in
8721 generate_structs_pod ();
8724 let close = output_to "guestfs-actions.pod" in
8725 generate_actions_pod ();
8728 let close = output_to "guestfish-actions.pod" in
8729 generate_fish_actions_pod ();
8732 let close = output_to "ocaml/guestfs.mli" in
8733 generate_ocaml_mli ();
8736 let close = output_to "ocaml/guestfs.ml" in
8737 generate_ocaml_ml ();
8740 let close = output_to "ocaml/guestfs_c_actions.c" in
8741 generate_ocaml_c ();
8744 let close = output_to "ocaml/bindtests.ml" in
8745 generate_ocaml_bindtests ();
8748 let close = output_to "perl/Guestfs.xs" in
8749 generate_perl_xs ();
8752 let close = output_to "perl/lib/Sys/Guestfs.pm" in
8753 generate_perl_pm ();
8756 let close = output_to "perl/bindtests.pl" in
8757 generate_perl_bindtests ();
8760 let close = output_to "python/guestfs-py.c" in
8761 generate_python_c ();
8764 let close = output_to "python/guestfs.py" in
8765 generate_python_py ();
8768 let close = output_to "python/bindtests.py" in
8769 generate_python_bindtests ();
8772 let close = output_to "ruby/ext/guestfs/_guestfs.c" in
8776 let close = output_to "ruby/bindtests.rb" in
8777 generate_ruby_bindtests ();
8780 let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
8781 generate_java_java ();
8786 let cols = cols_of_struct typ in
8787 let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
8788 let close = output_to filename in
8789 generate_java_struct jtyp cols;
8793 let close = output_to "java/Makefile.inc" in
8794 pr "java_built_sources =";
8797 pr " com/redhat/et/libguestfs/%s.java" jtyp;
8799 pr " com/redhat/et/libguestfs/GuestFS.java\n";
8802 let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
8806 let close = output_to "java/Bindtests.java" in
8807 generate_java_bindtests ();
8810 let close = output_to "haskell/Guestfs.hs" in
8811 generate_haskell_hs ();
8814 let close = output_to "haskell/Bindtests.hs" in
8815 generate_haskell_bindtests ();
8818 let close = output_to "src/MAX_PROC_NR" in
8819 generate_max_proc_nr ();
8822 (* Always generate this file last, and unconditionally. It's used
8823 * by the Makefile to know when we must re-run the generator.
8825 let chan = open_out "src/stamp-generator" in