Implement progress messages in the daemon and library.
[libguestfs.git] / src / generator.ml
1 #!/usr/bin/env ocaml
2 (* libguestfs
3  * Copyright (C) 2009-2010 Red Hat Inc.
4  *
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.
9  *
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.
14  *
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
18  *)
19
20 (* This script generates a large amount of code and documentation for
21  * all the daemon actions.
22  *
23  * To add a new action there are only two files you need to change,
24  * this one to describe the interface (see the big table of
25  * 'daemon_functions' below), and daemon/<somefile>.c to write the
26  * implementation.
27  *
28  * After editing this file, run it (./src/generator.ml) to regenerate
29  * all the output files.  'make' will rerun this automatically when
30  * necessary.  Note that if you are using a separate build directory
31  * you must run generator.ml from the _source_ directory.
32  *
33  * IMPORTANT: This script should NOT print any warnings.  If it prints
34  * warnings, you should treat them as errors.
35  *
36  * OCaml tips:
37  * (1) In emacs, install tuareg-mode to display and format OCaml code
38  * correctly.  'vim' comes with a good OCaml editing mode by default.
39  * (2) Read the resources at http://ocaml-tutorial.org/
40  *)
41
42 #load "unix.cma";;
43 #load "str.cma";;
44 #directory "+xml-light";;
45 #directory "+../pkg-lib/xml-light";; (* for GODI users *)
46 #load "xml-light.cma";;
47
48 open Unix
49 open Printf
50
51 type style = ret * args
52 and ret =
53     (* "RErr" as a return value means an int used as a simple error
54      * indication, ie. 0 or -1.
55      *)
56   | RErr
57
58     (* "RInt" as a return value means an int which is -1 for error
59      * or any value >= 0 on success.  Only use this for smallish
60      * positive ints (0 <= i < 2^30).
61      *)
62   | RInt of string
63
64     (* "RInt64" is the same as RInt, but is guaranteed to be able
65      * to return a full 64 bit value, _except_ that -1 means error
66      * (so -1 cannot be a valid, non-error return value).
67      *)
68   | RInt64 of string
69
70     (* "RBool" is a bool return value which can be true/false or
71      * -1 for error.
72      *)
73   | RBool of string
74
75     (* "RConstString" is a string that refers to a constant value.
76      * The return value must NOT be NULL (since NULL indicates
77      * an error).
78      *
79      * Try to avoid using this.  In particular you cannot use this
80      * for values returned from the daemon, because there is no
81      * thread-safe way to return them in the C API.
82      *)
83   | RConstString of string
84
85     (* "RConstOptString" is an even more broken version of
86      * "RConstString".  The returned string may be NULL and there
87      * is no way to return an error indication.  Avoid using this!
88      *)
89   | RConstOptString of string
90
91     (* "RString" is a returned string.  It must NOT be NULL, since
92      * a NULL return indicates an error.  The caller frees this.
93      *)
94   | RString of string
95
96     (* "RStringList" is a list of strings.  No string in the list
97      * can be NULL.  The caller frees the strings and the array.
98      *)
99   | RStringList of string
100
101     (* "RStruct" is a function which returns a single named structure
102      * or an error indication (in C, a struct, and in other languages
103      * with varying representations, but usually very efficient).  See
104      * after the function list below for the structures.
105      *)
106   | RStruct of string * string          (* name of retval, name of struct *)
107
108     (* "RStructList" is a function which returns either a list/array
109      * of structures (could be zero-length), or an error indication.
110      *)
111   | RStructList of string * string      (* name of retval, name of struct *)
112
113     (* Key-value pairs of untyped strings.  Turns into a hashtable or
114      * dictionary in languages which support it.  DON'T use this as a
115      * general "bucket" for results.  Prefer a stronger typed return
116      * value if one is available, or write a custom struct.  Don't use
117      * this if the list could potentially be very long, since it is
118      * inefficient.  Keys should be unique.  NULLs are not permitted.
119      *)
120   | RHashtable of string
121
122     (* "RBufferOut" is handled almost exactly like RString, but
123      * it allows the string to contain arbitrary 8 bit data including
124      * ASCII NUL.  In the C API this causes an implicit extra parameter
125      * to be added of type <size_t *size_r>.  The extra parameter
126      * returns the actual size of the return buffer in bytes.
127      *
128      * Other programming languages support strings with arbitrary 8 bit
129      * data.
130      *
131      * At the RPC layer we have to use the opaque<> type instead of
132      * string<>.  Returned data is still limited to the max message
133      * size (ie. ~ 2 MB).
134      *)
135   | RBufferOut of string
136
137 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
138
139     (* Note in future we should allow a "variable args" parameter as
140      * the final parameter, to allow commands like
141      *   chmod mode file [file(s)...]
142      * This is not implemented yet, but many commands (such as chmod)
143      * are currently defined with the argument order keeping this future
144      * possibility in mind.
145      *)
146 and argt =
147   | String of string    (* const char *name, cannot be NULL *)
148   | Device of string    (* /dev device name, cannot be NULL *)
149   | Pathname of string  (* file name, cannot be NULL *)
150   | Dev_or_Path of string (* /dev device name or Pathname, cannot be NULL *)
151   | OptString of string (* const char *name, may be NULL *)
152   | StringList of string(* list of strings (each string cannot be NULL) *)
153   | DeviceList of string(* list of Device names (each cannot be NULL) *)
154   | Bool of string      (* boolean *)
155   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
156   | Int64 of string     (* any 64 bit int *)
157     (* These are treated as filenames (simple string parameters) in
158      * the C API and bindings.  But in the RPC protocol, we transfer
159      * the actual file content up to or down from the daemon.
160      * FileIn: local machine -> daemon (in request)
161      * FileOut: daemon -> local machine (in reply)
162      * In guestfish (only), the special name "-" means read from
163      * stdin or write to stdout.
164      *)
165   | FileIn of string
166   | FileOut of string
167     (* Opaque buffer which can contain arbitrary 8 bit data.
168      * In the C API, this is expressed as <const char *, size_t> pair.
169      * Most other languages have a string type which can contain
170      * ASCII NUL.  We use whatever type is appropriate for each
171      * language.
172      * Buffers are limited by the total message size.  To transfer
173      * large blocks of data, use FileIn/FileOut parameters instead.
174      * To return an arbitrary buffer, use RBufferOut.
175      *)
176   | BufferIn of string
177     (* Key material / passphrase.  Eventually we should treat this
178      * as sensitive and mlock it into physical RAM.  However this
179      * is highly complex because of all the places that XDR-encoded
180      * strings can end up.  So currently the only difference from
181      * 'String' is the way that guestfish requests these parameters
182      * from the user.
183      *)
184   | Key of string
185
186 type flags =
187   | ProtocolLimitWarning  (* display warning about protocol size limits *)
188   | DangerWillRobinson    (* flags particularly dangerous commands *)
189   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
190   | FishOutput of fish_output_t (* how to display output in guestfish *)
191   | NotInFish             (* do not export via guestfish *)
192   | NotInDocs             (* do not add this function to documentation *)
193   | DeprecatedBy of string (* function is deprecated, use .. instead *)
194   | Optional of string    (* function is part of an optional group *)
195
196 and fish_output_t =
197   | FishOutputOctal       (* for int return, print in octal *)
198   | FishOutputHexadecimal (* for int return, print in hex *)
199
200 (* You can supply zero or as many tests as you want per API call.
201  *
202  * Note that the test environment has 3 block devices, of size 500MB,
203  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
204  * a fourth ISO block device with some known files on it (/dev/sdd).
205  *
206  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
207  * Number of cylinders was 63 for IDE emulated disks with precisely
208  * the same size.  How exactly this is calculated is a mystery.
209  *
210  * The ISO block device (/dev/sdd) comes from images/test.iso.
211  *
212  * To be able to run the tests in a reasonable amount of time,
213  * the virtual machine and block devices are reused between tests.
214  * So don't try testing kill_subprocess :-x
215  *
216  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
217  *
218  * Don't assume anything about the previous contents of the block
219  * devices.  Use 'Init*' to create some initial scenarios.
220  *
221  * You can add a prerequisite clause to any individual test.  This
222  * is a run-time check, which, if it fails, causes the test to be
223  * skipped.  Useful if testing a command which might not work on
224  * all variations of libguestfs builds.  A test that has prerequisite
225  * of 'Always' is run unconditionally.
226  *
227  * In addition, packagers can skip individual tests by setting the
228  * environment variables:     eg:
229  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
230  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
231  *)
232 type tests = (test_init * test_prereq * test) list
233 and test =
234     (* Run the command sequence and just expect nothing to fail. *)
235   | TestRun of seq
236
237     (* Run the command sequence and expect the output of the final
238      * command to be the string.
239      *)
240   | TestOutput of seq * string
241
242     (* Run the command sequence and expect the output of the final
243      * command to be the list of strings.
244      *)
245   | TestOutputList of seq * string list
246
247     (* Run the command sequence and expect the output of the final
248      * command to be the list of block devices (could be either
249      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
250      * character of each string).
251      *)
252   | TestOutputListOfDevices of seq * string list
253
254     (* Run the command sequence and expect the output of the final
255      * command to be the integer.
256      *)
257   | TestOutputInt of seq * int
258
259     (* Run the command sequence and expect the output of the final
260      * command to be <op> <int>, eg. ">=", "1".
261      *)
262   | TestOutputIntOp of seq * string * int
263
264     (* Run the command sequence and expect the output of the final
265      * command to be a true value (!= 0 or != NULL).
266      *)
267   | TestOutputTrue of seq
268
269     (* Run the command sequence and expect the output of the final
270      * command to be a false value (== 0 or == NULL, but not an error).
271      *)
272   | TestOutputFalse of seq
273
274     (* Run the command sequence and expect the output of the final
275      * command to be a list of the given length (but don't care about
276      * content).
277      *)
278   | TestOutputLength of seq * int
279
280     (* Run the command sequence and expect the output of the final
281      * command to be a buffer (RBufferOut), ie. string + size.
282      *)
283   | TestOutputBuffer of seq * string
284
285     (* Run the command sequence and expect the output of the final
286      * command to be a structure.
287      *)
288   | TestOutputStruct of seq * test_field_compare list
289
290     (* Run the command sequence and expect the final command (only)
291      * to fail.
292      *)
293   | TestLastFail of seq
294
295 and test_field_compare =
296   | CompareWithInt of string * int
297   | CompareWithIntOp of string * string * int
298   | CompareWithString of string * string
299   | CompareFieldsIntEq of string * string
300   | CompareFieldsStrEq of string * string
301
302 (* Test prerequisites. *)
303 and test_prereq =
304     (* Test always runs. *)
305   | Always
306
307     (* Test is currently disabled - eg. it fails, or it tests some
308      * unimplemented feature.
309      *)
310   | Disabled
311
312     (* 'string' is some C code (a function body) that should return
313      * true or false.  The test will run if the code returns true.
314      *)
315   | If of string
316
317     (* As for 'If' but the test runs _unless_ the code returns true. *)
318   | Unless of string
319
320     (* Run the test only if 'string' is available in the daemon. *)
321   | IfAvailable of string
322
323 (* Some initial scenarios for testing. *)
324 and test_init =
325     (* Do nothing, block devices could contain random stuff including
326      * LVM PVs, and some filesystems might be mounted.  This is usually
327      * a bad idea.
328      *)
329   | InitNone
330
331     (* Block devices are empty and no filesystems are mounted. *)
332   | InitEmpty
333
334     (* /dev/sda contains a single partition /dev/sda1, with random
335      * content.  /dev/sdb and /dev/sdc may have random content.
336      * No LVM.
337      *)
338   | InitPartition
339
340     (* /dev/sda contains a single partition /dev/sda1, which is formatted
341      * as ext2, empty [except for lost+found] and mounted on /.
342      * /dev/sdb and /dev/sdc may have random content.
343      * No LVM.
344      *)
345   | InitBasicFS
346
347     (* /dev/sda:
348      *   /dev/sda1 (is a PV):
349      *     /dev/VG/LV (size 8MB):
350      *       formatted as ext2, empty [except for lost+found], mounted on /
351      * /dev/sdb and /dev/sdc may have random content.
352      *)
353   | InitBasicFSonLVM
354
355     (* /dev/sdd (the ISO, see images/ directory in source)
356      * is mounted on /
357      *)
358   | InitISOFS
359
360 (* Sequence of commands for testing. *)
361 and seq = cmd list
362 and cmd = string list
363
364 (* Note about long descriptions: When referring to another
365  * action, use the format C<guestfs_other> (ie. the full name of
366  * the C function).  This will be replaced as appropriate in other
367  * language bindings.
368  *
369  * Apart from that, long descriptions are just perldoc paragraphs.
370  *)
371
372 (* Generate a random UUID (used in tests). *)
373 let uuidgen () =
374   let chan = open_process_in "uuidgen" in
375   let uuid = input_line chan in
376   (match close_process_in chan with
377    | WEXITED 0 -> ()
378    | WEXITED _ ->
379        failwith "uuidgen: process exited with non-zero status"
380    | WSIGNALED _ | WSTOPPED _ ->
381        failwith "uuidgen: process signalled or stopped by signal"
382   );
383   uuid
384
385 (* These test functions are used in the language binding tests. *)
386
387 let test_all_args = [
388   String "str";
389   OptString "optstr";
390   StringList "strlist";
391   Bool "b";
392   Int "integer";
393   Int64 "integer64";
394   FileIn "filein";
395   FileOut "fileout";
396   BufferIn "bufferin";
397 ]
398
399 let test_all_rets = [
400   (* except for RErr, which is tested thoroughly elsewhere *)
401   "test0rint",         RInt "valout";
402   "test0rint64",       RInt64 "valout";
403   "test0rbool",        RBool "valout";
404   "test0rconststring", RConstString "valout";
405   "test0rconstoptstring", RConstOptString "valout";
406   "test0rstring",      RString "valout";
407   "test0rstringlist",  RStringList "valout";
408   "test0rstruct",      RStruct ("valout", "lvm_pv");
409   "test0rstructlist",  RStructList ("valout", "lvm_pv");
410   "test0rhashtable",   RHashtable "valout";
411 ]
412
413 let test_functions = [
414   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
415    [],
416    "internal test function - do not use",
417    "\
418 This is an internal test function which is used to test whether
419 the automatically generated bindings can handle every possible
420 parameter type correctly.
421
422 It echos the contents of each parameter to stdout.
423
424 You probably don't want to call this function.");
425 ] @ List.flatten (
426   List.map (
427     fun (name, ret) ->
428       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
429         [],
430         "internal test function - do not use",
431         "\
432 This is an internal test function which is used to test whether
433 the automatically generated bindings can handle every possible
434 return type correctly.
435
436 It converts string C<val> to the return type.
437
438 You probably don't want to call this function.");
439        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
440         [],
441         "internal test function - do not use",
442         "\
443 This is an internal test function which is used to test whether
444 the automatically generated bindings can handle every possible
445 return type correctly.
446
447 This function always returns an error.
448
449 You probably don't want to call this function.")]
450   ) test_all_rets
451 )
452
453 (* non_daemon_functions are any functions which don't get processed
454  * in the daemon, eg. functions for setting and getting local
455  * configuration values.
456  *)
457
458 let non_daemon_functions = test_functions @ [
459   ("launch", (RErr, []), -1, [FishAlias "run"],
460    [],
461    "launch the qemu subprocess",
462    "\
463 Internally libguestfs is implemented by running a virtual machine
464 using L<qemu(1)>.
465
466 You should call this after configuring the handle
467 (eg. adding drives) but before performing any actions.");
468
469   ("wait_ready", (RErr, []), -1, [NotInFish],
470    [],
471    "wait until the qemu subprocess launches (no op)",
472    "\
473 This function is a no op.
474
475 In versions of the API E<lt> 1.0.71 you had to call this function
476 just after calling C<guestfs_launch> to wait for the launch
477 to complete.  However this is no longer necessary because
478 C<guestfs_launch> now does the waiting.
479
480 If you see any calls to this function in code then you can just
481 remove them, unless you want to retain compatibility with older
482 versions of the API.");
483
484   ("kill_subprocess", (RErr, []), -1, [],
485    [],
486    "kill the qemu subprocess",
487    "\
488 This kills the qemu subprocess.  You should never need to call this.");
489
490   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
491    [],
492    "add an image to examine or modify",
493    "\
494 This function adds a virtual machine disk image C<filename> to the
495 guest.  The first time you call this function, the disk appears as IDE
496 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
497 so on.
498
499 You don't necessarily need to be root when using libguestfs.  However
500 you obviously do need sufficient permissions to access the filename
501 for whatever operations you want to perform (ie. read access if you
502 just want to read the image or write access if you want to modify the
503 image).
504
505 This is equivalent to the qemu parameter
506 C<-drive file=filename,cache=off,if=...>.
507
508 C<cache=off> is omitted in cases where it is not supported by
509 the underlying filesystem.
510
511 C<if=...> is set at compile time by the configuration option
512 C<./configure --with-drive-if=...>.  In the rare case where you
513 might need to change this at run time, use C<guestfs_add_drive_with_if>
514 or C<guestfs_add_drive_ro_with_if>.
515
516 Note that this call checks for the existence of C<filename>.  This
517 stops you from specifying other types of drive which are supported
518 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
519 the general C<guestfs_config> call instead.");
520
521   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
522    [],
523    "add a CD-ROM disk image to examine",
524    "\
525 This function adds a virtual CD-ROM disk image to the guest.
526
527 This is equivalent to the qemu parameter C<-cdrom filename>.
528
529 Notes:
530
531 =over 4
532
533 =item *
534
535 This call checks for the existence of C<filename>.  This
536 stops you from specifying other types of drive which are supported
537 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
538 the general C<guestfs_config> call instead.
539
540 =item *
541
542 If you just want to add an ISO file (often you use this as an
543 efficient way to transfer large files into the guest), then you
544 should probably use C<guestfs_add_drive_ro> instead.
545
546 =back");
547
548   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
549    [],
550    "add a drive in snapshot mode (read-only)",
551    "\
552 This adds a drive in snapshot mode, making it effectively
553 read-only.
554
555 Note that writes to the device are allowed, and will be seen for
556 the duration of the guestfs handle, but they are written
557 to a temporary file which is discarded as soon as the guestfs
558 handle is closed.  We don't currently have any method to enable
559 changes to be committed, although qemu can support this.
560
561 This is equivalent to the qemu parameter
562 C<-drive file=filename,snapshot=on,if=...>.
563
564 C<if=...> is set at compile time by the configuration option
565 C<./configure --with-drive-if=...>.  In the rare case where you
566 might need to change this at run time, use C<guestfs_add_drive_with_if>
567 or C<guestfs_add_drive_ro_with_if>.
568
569 Note that this call checks for the existence of C<filename>.  This
570 stops you from specifying other types of drive which are supported
571 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
572 the general C<guestfs_config> call instead.");
573
574   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
575    [],
576    "add qemu parameters",
577    "\
578 This can be used to add arbitrary qemu command line parameters
579 of the form C<-param value>.  Actually it's not quite arbitrary - we
580 prevent you from setting some parameters which would interfere with
581 parameters that we use.
582
583 The first character of C<param> string must be a C<-> (dash).
584
585 C<value> can be NULL.");
586
587   ("set_qemu", (RErr, [OptString "qemu"]), -1, [FishAlias "qemu"],
588    [],
589    "set the qemu binary",
590    "\
591 Set the qemu binary that we will use.
592
593 The default is chosen when the library was compiled by the
594 configure script.
595
596 You can also override this by setting the C<LIBGUESTFS_QEMU>
597 environment variable.
598
599 Setting C<qemu> to C<NULL> restores the default qemu binary.
600
601 Note that you should call this function as early as possible
602 after creating the handle.  This is because some pre-launch
603 operations depend on testing qemu features (by running C<qemu -help>).
604 If the qemu binary changes, we don't retest features, and
605 so you might see inconsistent results.  Using the environment
606 variable C<LIBGUESTFS_QEMU> is safest of all since that picks
607 the qemu binary at the same time as the handle is created.");
608
609   ("get_qemu", (RConstString "qemu", []), -1, [],
610    [InitNone, Always, TestRun (
611       [["get_qemu"]])],
612    "get the qemu binary",
613    "\
614 Return the current qemu binary.
615
616 This is always non-NULL.  If it wasn't set already, then this will
617 return the default qemu binary name.");
618
619   ("set_path", (RErr, [OptString "searchpath"]), -1, [FishAlias "path"],
620    [],
621    "set the search path",
622    "\
623 Set the path that libguestfs searches for kernel and initrd.img.
624
625 The default is C<$libdir/guestfs> unless overridden by setting
626 C<LIBGUESTFS_PATH> environment variable.
627
628 Setting C<path> to C<NULL> restores the default path.");
629
630   ("get_path", (RConstString "path", []), -1, [],
631    [InitNone, Always, TestRun (
632       [["get_path"]])],
633    "get the search path",
634    "\
635 Return the current search path.
636
637 This is always non-NULL.  If it wasn't set already, then this will
638 return the default path.");
639
640   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
641    [],
642    "add options to kernel command line",
643    "\
644 This function is used to add additional options to the
645 guest kernel command line.
646
647 The default is C<NULL> unless overridden by setting
648 C<LIBGUESTFS_APPEND> environment variable.
649
650 Setting C<append> to C<NULL> means I<no> additional options
651 are passed (libguestfs always adds a few of its own).");
652
653   ("get_append", (RConstOptString "append", []), -1, [],
654    (* This cannot be tested with the current framework.  The
655     * function can return NULL in normal operations, which the
656     * test framework interprets as an error.
657     *)
658    [],
659    "get the additional kernel options",
660    "\
661 Return the additional kernel options which are added to the
662 guest kernel command line.
663
664 If C<NULL> then no options are added.");
665
666   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
667    [],
668    "set autosync mode",
669    "\
670 If C<autosync> is true, this enables autosync.  Libguestfs will make a
671 best effort attempt to run C<guestfs_umount_all> followed by
672 C<guestfs_sync> when the handle is closed
673 (also if the program exits without closing handles).
674
675 This is disabled by default (except in guestfish where it is
676 enabled by default).");
677
678   ("get_autosync", (RBool "autosync", []), -1, [],
679    [InitNone, Always, TestRun (
680       [["get_autosync"]])],
681    "get autosync mode",
682    "\
683 Get the autosync flag.");
684
685   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
686    [],
687    "set verbose mode",
688    "\
689 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
690
691 Verbose messages are disabled unless the environment variable
692 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
693
694   ("get_verbose", (RBool "verbose", []), -1, [],
695    [],
696    "get verbose mode",
697    "\
698 This returns the verbose messages flag.");
699
700   ("is_ready", (RBool "ready", []), -1, [],
701    [InitNone, Always, TestOutputTrue (
702       [["is_ready"]])],
703    "is ready to accept commands",
704    "\
705 This returns true iff this handle is ready to accept commands
706 (in the C<READY> state).
707
708 For more information on states, see L<guestfs(3)>.");
709
710   ("is_config", (RBool "config", []), -1, [],
711    [InitNone, Always, TestOutputFalse (
712       [["is_config"]])],
713    "is in configuration state",
714    "\
715 This returns true iff this handle is being configured
716 (in the C<CONFIG> state).
717
718 For more information on states, see L<guestfs(3)>.");
719
720   ("is_launching", (RBool "launching", []), -1, [],
721    [InitNone, Always, TestOutputFalse (
722       [["is_launching"]])],
723    "is launching subprocess",
724    "\
725 This returns true iff this handle is launching the subprocess
726 (in the C<LAUNCHING> state).
727
728 For more information on states, see L<guestfs(3)>.");
729
730   ("is_busy", (RBool "busy", []), -1, [],
731    [InitNone, Always, TestOutputFalse (
732       [["is_busy"]])],
733    "is busy processing a command",
734    "\
735 This returns true iff this handle is busy processing a command
736 (in the C<BUSY> state).
737
738 For more information on states, see L<guestfs(3)>.");
739
740   ("get_state", (RInt "state", []), -1, [],
741    [],
742    "get the current state",
743    "\
744 This returns the current state as an opaque integer.  This is
745 only useful for printing debug and internal error messages.
746
747 For more information on states, see L<guestfs(3)>.");
748
749   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
750    [InitNone, Always, TestOutputInt (
751       [["set_memsize"; "500"];
752        ["get_memsize"]], 500)],
753    "set memory allocated to the qemu subprocess",
754    "\
755 This sets the memory size in megabytes allocated to the
756 qemu subprocess.  This only has any effect if called before
757 C<guestfs_launch>.
758
759 You can also change this by setting the environment
760 variable C<LIBGUESTFS_MEMSIZE> before the handle is
761 created.
762
763 For more information on the architecture of libguestfs,
764 see L<guestfs(3)>.");
765
766   ("get_memsize", (RInt "memsize", []), -1, [],
767    [InitNone, Always, TestOutputIntOp (
768       [["get_memsize"]], ">=", 256)],
769    "get memory allocated to the qemu subprocess",
770    "\
771 This gets the memory size in megabytes allocated to the
772 qemu subprocess.
773
774 If C<guestfs_set_memsize> was not called
775 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
776 then this returns the compiled-in default value for memsize.
777
778 For more information on the architecture of libguestfs,
779 see L<guestfs(3)>.");
780
781   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
782    [InitNone, Always, TestOutputIntOp (
783       [["get_pid"]], ">=", 1)],
784    "get PID of qemu subprocess",
785    "\
786 Return the process ID of the qemu subprocess.  If there is no
787 qemu subprocess, then this will return an error.
788
789 This is an internal call used for debugging and testing.");
790
791   ("version", (RStruct ("version", "version"), []), -1, [],
792    [InitNone, Always, TestOutputStruct (
793       [["version"]], [CompareWithInt ("major", 1)])],
794    "get the library version number",
795    "\
796 Return the libguestfs version number that the program is linked
797 against.
798
799 Note that because of dynamic linking this is not necessarily
800 the version of libguestfs that you compiled against.  You can
801 compile the program, and then at runtime dynamically link
802 against a completely different C<libguestfs.so> library.
803
804 This call was added in version C<1.0.58>.  In previous
805 versions of libguestfs there was no way to get the version
806 number.  From C code you can use dynamic linker functions
807 to find out if this symbol exists (if it doesn't, then
808 it's an earlier version).
809
810 The call returns a structure with four elements.  The first
811 three (C<major>, C<minor> and C<release>) are numbers and
812 correspond to the usual version triplet.  The fourth element
813 (C<extra>) is a string and is normally empty, but may be
814 used for distro-specific information.
815
816 To construct the original version string:
817 C<$major.$minor.$release$extra>
818
819 See also: L<guestfs(3)/LIBGUESTFS VERSION NUMBERS>.
820
821 I<Note:> Don't use this call to test for availability
822 of features.  In enterprise distributions we backport
823 features from later versions into earlier versions,
824 making this an unreliable way to test for features.
825 Use C<guestfs_available> instead.");
826
827   ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
828    [InitNone, Always, TestOutputTrue (
829       [["set_selinux"; "true"];
830        ["get_selinux"]])],
831    "set SELinux enabled or disabled at appliance boot",
832    "\
833 This sets the selinux flag that is passed to the appliance
834 at boot time.  The default is C<selinux=0> (disabled).
835
836 Note that if SELinux is enabled, it is always in
837 Permissive mode (C<enforcing=0>).
838
839 For more information on the architecture of libguestfs,
840 see L<guestfs(3)>.");
841
842   ("get_selinux", (RBool "selinux", []), -1, [],
843    [],
844    "get SELinux enabled flag",
845    "\
846 This returns the current setting of the selinux flag which
847 is passed to the appliance at boot time.  See C<guestfs_set_selinux>.
848
849 For more information on the architecture of libguestfs,
850 see L<guestfs(3)>.");
851
852   ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
853    [InitNone, Always, TestOutputFalse (
854       [["set_trace"; "false"];
855        ["get_trace"]])],
856    "enable or disable command traces",
857    "\
858 If the command trace flag is set to 1, then commands are
859 printed on stderr before they are executed in a format
860 which is very similar to the one used by guestfish.  In
861 other words, you can run a program with this enabled, and
862 you will get out a script which you can feed to guestfish
863 to perform the same set of actions.
864
865 If you want to trace C API calls into libguestfs (and
866 other libraries) then possibly a better way is to use
867 the external ltrace(1) command.
868
869 Command traces are disabled unless the environment variable
870 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
871
872   ("get_trace", (RBool "trace", []), -1, [],
873    [],
874    "get command trace enabled flag",
875    "\
876 Return the command trace flag.");
877
878   ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
879    [InitNone, Always, TestOutputFalse (
880       [["set_direct"; "false"];
881        ["get_direct"]])],
882    "enable or disable direct appliance mode",
883    "\
884 If the direct appliance mode flag is enabled, then stdin and
885 stdout are passed directly through to the appliance once it
886 is launched.
887
888 One consequence of this is that log messages aren't caught
889 by the library and handled by C<guestfs_set_log_message_callback>,
890 but go straight to stdout.
891
892 You probably don't want to use this unless you know what you
893 are doing.
894
895 The default is disabled.");
896
897   ("get_direct", (RBool "direct", []), -1, [],
898    [],
899    "get direct appliance mode flag",
900    "\
901 Return the direct appliance mode flag.");
902
903   ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
904    [InitNone, Always, TestOutputTrue (
905       [["set_recovery_proc"; "true"];
906        ["get_recovery_proc"]])],
907    "enable or disable the recovery process",
908    "\
909 If this is called with the parameter C<false> then
910 C<guestfs_launch> does not create a recovery process.  The
911 purpose of the recovery process is to stop runaway qemu
912 processes in the case where the main program aborts abruptly.
913
914 This only has any effect if called before C<guestfs_launch>,
915 and the default is true.
916
917 About the only time when you would want to disable this is
918 if the main process will fork itself into the background
919 (\"daemonize\" itself).  In this case the recovery process
920 thinks that the main program has disappeared and so kills
921 qemu, which is not very helpful.");
922
923   ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
924    [],
925    "get recovery process enabled flag",
926    "\
927 Return the recovery process enabled flag.");
928
929   ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
930    [],
931    "add a drive specifying the QEMU block emulation to use",
932    "\
933 This is the same as C<guestfs_add_drive> but it allows you
934 to specify the QEMU interface emulation to use at run time.");
935
936   ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
937    [],
938    "add a drive read-only specifying the QEMU block emulation to use",
939    "\
940 This is the same as C<guestfs_add_drive_ro> but it allows you
941 to specify the QEMU interface emulation to use at run time.");
942
943   ("file_architecture", (RString "arch", [Pathname "filename"]), -1, [],
944    [InitISOFS, Always, TestOutput (
945       [["file_architecture"; "/bin-i586-dynamic"]], "i386");
946     InitISOFS, Always, TestOutput (
947       [["file_architecture"; "/bin-sparc-dynamic"]], "sparc");
948     InitISOFS, Always, TestOutput (
949       [["file_architecture"; "/bin-win32.exe"]], "i386");
950     InitISOFS, Always, TestOutput (
951       [["file_architecture"; "/bin-win64.exe"]], "x86_64");
952     InitISOFS, Always, TestOutput (
953       [["file_architecture"; "/bin-x86_64-dynamic"]], "x86_64");
954     InitISOFS, Always, TestOutput (
955       [["file_architecture"; "/lib-i586.so"]], "i386");
956     InitISOFS, Always, TestOutput (
957       [["file_architecture"; "/lib-sparc.so"]], "sparc");
958     InitISOFS, Always, TestOutput (
959       [["file_architecture"; "/lib-win32.dll"]], "i386");
960     InitISOFS, Always, TestOutput (
961       [["file_architecture"; "/lib-win64.dll"]], "x86_64");
962     InitISOFS, Always, TestOutput (
963       [["file_architecture"; "/lib-x86_64.so"]], "x86_64");
964     InitISOFS, Always, TestOutput (
965       [["file_architecture"; "/initrd-x86_64.img"]], "x86_64");
966     InitISOFS, Always, TestOutput (
967       [["file_architecture"; "/initrd-x86_64.img.gz"]], "x86_64");],
968    "detect the architecture of a binary file",
969    "\
970 This detects the architecture of the binary C<filename>,
971 and returns it if known.
972
973 Currently defined architectures are:
974
975 =over 4
976
977 =item \"i386\"
978
979 This string is returned for all 32 bit i386, i486, i586, i686 binaries
980 irrespective of the precise processor requirements of the binary.
981
982 =item \"x86_64\"
983
984 64 bit x86-64.
985
986 =item \"sparc\"
987
988 32 bit SPARC.
989
990 =item \"sparc64\"
991
992 64 bit SPARC V9 and above.
993
994 =item \"ia64\"
995
996 Intel Itanium.
997
998 =item \"ppc\"
999
1000 32 bit Power PC.
1001
1002 =item \"ppc64\"
1003
1004 64 bit Power PC.
1005
1006 =back
1007
1008 Libguestfs may return other architecture strings in future.
1009
1010 The function works on at least the following types of files:
1011
1012 =over 4
1013
1014 =item *
1015
1016 many types of Un*x and Linux binary
1017
1018 =item *
1019
1020 many types of Un*x and Linux shared library
1021
1022 =item *
1023
1024 Windows Win32 and Win64 binaries
1025
1026 =item *
1027
1028 Windows Win32 and Win64 DLLs
1029
1030 Win32 binaries and DLLs return C<i386>.
1031
1032 Win64 binaries and DLLs return C<x86_64>.
1033
1034 =item *
1035
1036 Linux kernel modules
1037
1038 =item *
1039
1040 Linux new-style initrd images
1041
1042 =item *
1043
1044 some non-x86 Linux vmlinuz kernels
1045
1046 =back
1047
1048 What it can't do currently:
1049
1050 =over 4
1051
1052 =item *
1053
1054 static libraries (libfoo.a)
1055
1056 =item *
1057
1058 Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
1059
1060 =item *
1061
1062 x86 Linux vmlinuz kernels
1063
1064 x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and
1065 compressed code, and are horribly hard to unpack.  If you want to find
1066 the architecture of a kernel, use the architecture of the associated
1067 initrd or kernel module(s) instead.
1068
1069 =back");
1070
1071   ("inspect_os", (RStringList "roots", []), -1, [],
1072    [],
1073    "inspect disk and return list of operating systems found",
1074    "\
1075 This function uses other libguestfs functions and certain
1076 heuristics to inspect the disk(s) (usually disks belonging to
1077 a virtual machine), looking for operating systems.
1078
1079 The list returned is empty if no operating systems were found.
1080
1081 If one operating system was found, then this returns a list with
1082 a single element, which is the name of the root filesystem of
1083 this operating system.  It is also possible for this function
1084 to return a list containing more than one element, indicating
1085 a dual-boot or multi-boot virtual machine, with each element being
1086 the root filesystem of one of the operating systems.
1087
1088 You can pass the root string(s) returned to other
1089 C<guestfs_inspect_get_*> functions in order to query further
1090 information about each operating system, such as the name
1091 and version.
1092
1093 This function uses other libguestfs features such as
1094 C<guestfs_mount_ro> and C<guestfs_umount_all> in order to mount
1095 and unmount filesystems and look at the contents.  This should
1096 be called with no disks currently mounted.  The function may also
1097 use Augeas, so any existing Augeas handle will be closed.
1098
1099 This function cannot decrypt encrypted disks.  The caller
1100 must do that first (supplying the necessary keys) if the
1101 disk is encrypted.
1102
1103 Please read L<guestfs(3)/INSPECTION> for more details.");
1104
1105   ("inspect_get_type", (RString "name", [Device "root"]), -1, [],
1106    [],
1107    "get type of inspected operating system",
1108    "\
1109 This function should only be called with a root device string
1110 as returned by C<guestfs_inspect_os>.
1111
1112 This returns the type of the inspected operating system.
1113 Currently defined types are:
1114
1115 =over 4
1116
1117 =item \"linux\"
1118
1119 Any Linux-based operating system.
1120
1121 =item \"windows\"
1122
1123 Any Microsoft Windows operating system.
1124
1125 =item \"unknown\"
1126
1127 The operating system type could not be determined.
1128
1129 =back
1130
1131 Future versions of libguestfs may return other strings here.
1132 The caller should be prepared to handle any string.
1133
1134 Please read L<guestfs(3)/INSPECTION> for more details.");
1135
1136   ("inspect_get_arch", (RString "arch", [Device "root"]), -1, [],
1137    [],
1138    "get architecture of inspected operating system",
1139    "\
1140 This function should only be called with a root device string
1141 as returned by C<guestfs_inspect_os>.
1142
1143 This returns the architecture of the inspected operating system.
1144 The possible return values are listed under
1145 C<guestfs_file_architecture>.
1146
1147 If the architecture could not be determined, then the
1148 string C<unknown> is returned.
1149
1150 Please read L<guestfs(3)/INSPECTION> for more details.");
1151
1152   ("inspect_get_distro", (RString "distro", [Device "root"]), -1, [],
1153    [],
1154    "get distro of inspected operating system",
1155    "\
1156 This function should only be called with a root device string
1157 as returned by C<guestfs_inspect_os>.
1158
1159 This returns the distro (distribution) of the inspected operating
1160 system.
1161
1162 Currently defined distros are:
1163
1164 =over 4
1165
1166 =item \"debian\"
1167
1168 Debian or a Debian-derived distro such as Ubuntu.
1169
1170 =item \"fedora\"
1171
1172 Fedora.
1173
1174 =item \"redhat-based\"
1175
1176 Some Red Hat-derived distro.
1177
1178 =item \"rhel\"
1179
1180 Red Hat Enterprise Linux and some derivatives.
1181
1182 =item \"windows\"
1183
1184 Windows does not have distributions.  This string is
1185 returned if the OS type is Windows.
1186
1187 =item \"unknown\"
1188
1189 The distro could not be determined.
1190
1191 =back
1192
1193 Future versions of libguestfs may return other strings here.
1194 The caller should be prepared to handle any string.
1195
1196 Please read L<guestfs(3)/INSPECTION> for more details.");
1197
1198   ("inspect_get_major_version", (RInt "major", [Device "root"]), -1, [],
1199    [],
1200    "get major version of inspected operating system",
1201    "\
1202 This function should only be called with a root device string
1203 as returned by C<guestfs_inspect_os>.
1204
1205 This returns the major version number of the inspected operating
1206 system.
1207
1208 Windows uses a consistent versioning scheme which is I<not>
1209 reflected in the popular public names used by the operating system.
1210 Notably the operating system known as \"Windows 7\" is really
1211 version 6.1 (ie. major = 6, minor = 1).  You can find out the
1212 real versions corresponding to releases of Windows by consulting
1213 Wikipedia or MSDN.
1214
1215 If the version could not be determined, then C<0> is returned.
1216
1217 Please read L<guestfs(3)/INSPECTION> for more details.");
1218
1219   ("inspect_get_minor_version", (RInt "minor", [Device "root"]), -1, [],
1220    [],
1221    "get minor version of inspected operating system",
1222    "\
1223 This function should only be called with a root device string
1224 as returned by C<guestfs_inspect_os>.
1225
1226 This returns the minor version number of the inspected operating
1227 system.
1228
1229 If the version could not be determined, then C<0> is returned.
1230
1231 Please read L<guestfs(3)/INSPECTION> for more details.
1232 See also C<guestfs_inspect_get_major_version>.");
1233
1234   ("inspect_get_product_name", (RString "product", [Device "root"]), -1, [],
1235    [],
1236    "get product name of inspected operating system",
1237    "\
1238 This function should only be called with a root device string
1239 as returned by C<guestfs_inspect_os>.
1240
1241 This returns the product name of the inspected operating
1242 system.  The product name is generally some freeform string
1243 which can be displayed to the user, but should not be
1244 parsed by programs.
1245
1246 If the product name could not be determined, then the
1247 string C<unknown> is returned.
1248
1249 Please read L<guestfs(3)/INSPECTION> for more details.");
1250
1251   ("inspect_get_mountpoints", (RHashtable "mountpoints", [Device "root"]), -1, [],
1252    [],
1253    "get mountpoints of inspected operating system",
1254    "\
1255 This function should only be called with a root device string
1256 as returned by C<guestfs_inspect_os>.
1257
1258 This returns a hash of where we think the filesystems
1259 associated with this operating system should be mounted.
1260 Callers should note that this is at best an educated guess
1261 made by reading configuration files such as C</etc/fstab>.
1262
1263 Each element in the returned hashtable has a key which
1264 is the path of the mountpoint (eg. C</boot>) and a value
1265 which is the filesystem that would be mounted there
1266 (eg. C</dev/sda1>).
1267
1268 Non-mounted devices such as swap devices are I<not>
1269 returned in this list.
1270
1271 Please read L<guestfs(3)/INSPECTION> for more details.
1272 See also C<guestfs_inspect_get_filesystems>.");
1273
1274   ("inspect_get_filesystems", (RStringList "filesystems", [Device "root"]), -1, [],
1275    [],
1276    "get filesystems associated with inspected operating system",
1277    "\
1278 This function should only be called with a root device string
1279 as returned by C<guestfs_inspect_os>.
1280
1281 This returns a list of all the filesystems that we think
1282 are associated with this operating system.  This includes
1283 the root filesystem, other ordinary filesystems, and
1284 non-mounted devices like swap partitions.
1285
1286 In the case of a multi-boot virtual machine, it is possible
1287 for a filesystem to be shared between operating systems.
1288
1289 Please read L<guestfs(3)/INSPECTION> for more details.
1290 See also C<guestfs_inspect_get_mountpoints>.");
1291
1292   ("set_network", (RErr, [Bool "network"]), -1, [FishAlias "network"],
1293    [],
1294    "set enable network flag",
1295    "\
1296 If C<network> is true, then the network is enabled in the
1297 libguestfs appliance.  The default is false.
1298
1299 This affects whether commands are able to access the network
1300 (see L<guestfs(3)/RUNNING COMMANDS>).
1301
1302 You must call this before calling C<guestfs_launch>, otherwise
1303 it has no effect.");
1304
1305   ("get_network", (RBool "network", []), -1, [],
1306    [],
1307    "get enable network flag",
1308    "\
1309 This returns the enable network flag.");
1310
1311 ]
1312
1313 (* daemon_functions are any functions which cause some action
1314  * to take place in the daemon.
1315  *)
1316
1317 let daemon_functions = [
1318   ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
1319    [InitEmpty, Always, TestOutput (
1320       [["part_disk"; "/dev/sda"; "mbr"];
1321        ["mkfs"; "ext2"; "/dev/sda1"];
1322        ["mount"; "/dev/sda1"; "/"];
1323        ["write"; "/new"; "new file contents"];
1324        ["cat"; "/new"]], "new file contents")],
1325    "mount a guest disk at a position in the filesystem",
1326    "\
1327 Mount a guest disk at a position in the filesystem.  Block devices
1328 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
1329 the guest.  If those block devices contain partitions, they will have
1330 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
1331 names can be used.
1332
1333 The rules are the same as for L<mount(2)>:  A filesystem must
1334 first be mounted on C</> before others can be mounted.  Other
1335 filesystems can only be mounted on directories which already
1336 exist.
1337
1338 The mounted filesystem is writable, if we have sufficient permissions
1339 on the underlying device.
1340
1341 B<Important note:>
1342 When you use this call, the filesystem options C<sync> and C<noatime>
1343 are set implicitly.  This was originally done because we thought it
1344 would improve reliability, but it turns out that I<-o sync> has a
1345 very large negative performance impact and negligible effect on
1346 reliability.  Therefore we recommend that you avoid using
1347 C<guestfs_mount> in any code that needs performance, and instead
1348 use C<guestfs_mount_options> (use an empty string for the first
1349 parameter if you don't want any options).");
1350
1351   ("sync", (RErr, []), 2, [],
1352    [ InitEmpty, Always, TestRun [["sync"]]],
1353    "sync disks, writes are flushed through to the disk image",
1354    "\
1355 This syncs the disk, so that any writes are flushed through to the
1356 underlying disk image.
1357
1358 You should always call this if you have modified a disk image, before
1359 closing the handle.");
1360
1361   ("touch", (RErr, [Pathname "path"]), 3, [],
1362    [InitBasicFS, Always, TestOutputTrue (
1363       [["touch"; "/new"];
1364        ["exists"; "/new"]])],
1365    "update file timestamps or create a new file",
1366    "\
1367 Touch acts like the L<touch(1)> command.  It can be used to
1368 update the timestamps on a file, or, if the file does not exist,
1369 to create a new zero-length file.
1370
1371 This command only works on regular files, and will fail on other
1372 file types such as directories, symbolic links, block special etc.");
1373
1374   ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
1375    [InitISOFS, Always, TestOutput (
1376       [["cat"; "/known-2"]], "abcdef\n")],
1377    "list the contents of a file",
1378    "\
1379 Return the contents of the file named C<path>.
1380
1381 Note that this function cannot correctly handle binary files
1382 (specifically, files containing C<\\0> character which is treated
1383 as end of string).  For those you need to use the C<guestfs_read_file>
1384 or C<guestfs_download> functions which have a more complex interface.");
1385
1386   ("ll", (RString "listing", [Pathname "directory"]), 5, [],
1387    [], (* XXX Tricky to test because it depends on the exact format
1388         * of the 'ls -l' command, which changes between F10 and F11.
1389         *)
1390    "list the files in a directory (long format)",
1391    "\
1392 List the files in C<directory> (relative to the root directory,
1393 there is no cwd) in the format of 'ls -la'.
1394
1395 This command is mostly useful for interactive sessions.  It
1396 is I<not> intended that you try to parse the output string.");
1397
1398   ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
1399    [InitBasicFS, Always, TestOutputList (
1400       [["touch"; "/new"];
1401        ["touch"; "/newer"];
1402        ["touch"; "/newest"];
1403        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
1404    "list the files in a directory",
1405    "\
1406 List the files in C<directory> (relative to the root directory,
1407 there is no cwd).  The '.' and '..' entries are not returned, but
1408 hidden files are shown.
1409
1410 This command is mostly useful for interactive sessions.  Programs
1411 should probably use C<guestfs_readdir> instead.");
1412
1413   ("list_devices", (RStringList "devices", []), 7, [],
1414    [InitEmpty, Always, TestOutputListOfDevices (
1415       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1416    "list the block devices",
1417    "\
1418 List all the block devices.
1419
1420 The full block device names are returned, eg. C</dev/sda>");
1421
1422   ("list_partitions", (RStringList "partitions", []), 8, [],
1423    [InitBasicFS, Always, TestOutputListOfDevices (
1424       [["list_partitions"]], ["/dev/sda1"]);
1425     InitEmpty, Always, TestOutputListOfDevices (
1426       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1427        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1428    "list the partitions",
1429    "\
1430 List all the partitions detected on all block devices.
1431
1432 The full partition device names are returned, eg. C</dev/sda1>
1433
1434 This does not return logical volumes.  For that you will need to
1435 call C<guestfs_lvs>.");
1436
1437   ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1438    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1439       [["pvs"]], ["/dev/sda1"]);
1440     InitEmpty, Always, TestOutputListOfDevices (
1441       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1442        ["pvcreate"; "/dev/sda1"];
1443        ["pvcreate"; "/dev/sda2"];
1444        ["pvcreate"; "/dev/sda3"];
1445        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1446    "list the LVM physical volumes (PVs)",
1447    "\
1448 List all the physical volumes detected.  This is the equivalent
1449 of the L<pvs(8)> command.
1450
1451 This returns a list of just the device names that contain
1452 PVs (eg. C</dev/sda2>).
1453
1454 See also C<guestfs_pvs_full>.");
1455
1456   ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1457    [InitBasicFSonLVM, Always, TestOutputList (
1458       [["vgs"]], ["VG"]);
1459     InitEmpty, Always, TestOutputList (
1460       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1461        ["pvcreate"; "/dev/sda1"];
1462        ["pvcreate"; "/dev/sda2"];
1463        ["pvcreate"; "/dev/sda3"];
1464        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1465        ["vgcreate"; "VG2"; "/dev/sda3"];
1466        ["vgs"]], ["VG1"; "VG2"])],
1467    "list the LVM volume groups (VGs)",
1468    "\
1469 List all the volumes groups detected.  This is the equivalent
1470 of the L<vgs(8)> command.
1471
1472 This returns a list of just the volume group names that were
1473 detected (eg. C<VolGroup00>).
1474
1475 See also C<guestfs_vgs_full>.");
1476
1477   ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1478    [InitBasicFSonLVM, Always, TestOutputList (
1479       [["lvs"]], ["/dev/VG/LV"]);
1480     InitEmpty, Always, TestOutputList (
1481       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1482        ["pvcreate"; "/dev/sda1"];
1483        ["pvcreate"; "/dev/sda2"];
1484        ["pvcreate"; "/dev/sda3"];
1485        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1486        ["vgcreate"; "VG2"; "/dev/sda3"];
1487        ["lvcreate"; "LV1"; "VG1"; "50"];
1488        ["lvcreate"; "LV2"; "VG1"; "50"];
1489        ["lvcreate"; "LV3"; "VG2"; "50"];
1490        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1491    "list the LVM logical volumes (LVs)",
1492    "\
1493 List all the logical volumes detected.  This is the equivalent
1494 of the L<lvs(8)> command.
1495
1496 This returns a list of the logical volume device names
1497 (eg. C</dev/VolGroup00/LogVol00>).
1498
1499 See also C<guestfs_lvs_full>.");
1500
1501   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1502    [], (* XXX how to test? *)
1503    "list the LVM physical volumes (PVs)",
1504    "\
1505 List all the physical volumes detected.  This is the equivalent
1506 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
1507
1508   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1509    [], (* XXX how to test? *)
1510    "list the LVM volume groups (VGs)",
1511    "\
1512 List all the volumes groups detected.  This is the equivalent
1513 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
1514
1515   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1516    [], (* XXX how to test? *)
1517    "list the LVM logical volumes (LVs)",
1518    "\
1519 List all the logical volumes detected.  This is the equivalent
1520 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
1521
1522   ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1523    [InitISOFS, Always, TestOutputList (
1524       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1525     InitISOFS, Always, TestOutputList (
1526       [["read_lines"; "/empty"]], [])],
1527    "read file as lines",
1528    "\
1529 Return the contents of the file named C<path>.
1530
1531 The file contents are returned as a list of lines.  Trailing
1532 C<LF> and C<CRLF> character sequences are I<not> returned.
1533
1534 Note that this function cannot correctly handle binary files
1535 (specifically, files containing C<\\0> character which is treated
1536 as end of line).  For those you need to use the C<guestfs_read_file>
1537 function which has a more complex interface.");
1538
1539   ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1540    [], (* XXX Augeas code needs tests. *)
1541    "create a new Augeas handle",
1542    "\
1543 Create a new Augeas handle for editing configuration files.
1544 If there was any previous Augeas handle associated with this
1545 guestfs session, then it is closed.
1546
1547 You must call this before using any other C<guestfs_aug_*>
1548 commands.
1549
1550 C<root> is the filesystem root.  C<root> must not be NULL,
1551 use C</> instead.
1552
1553 The flags are the same as the flags defined in
1554 E<lt>augeas.hE<gt>, the logical I<or> of the following
1555 integers:
1556
1557 =over 4
1558
1559 =item C<AUG_SAVE_BACKUP> = 1
1560
1561 Keep the original file with a C<.augsave> extension.
1562
1563 =item C<AUG_SAVE_NEWFILE> = 2
1564
1565 Save changes into a file with extension C<.augnew>, and
1566 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
1567
1568 =item C<AUG_TYPE_CHECK> = 4
1569
1570 Typecheck lenses (can be expensive).
1571
1572 =item C<AUG_NO_STDINC> = 8
1573
1574 Do not use standard load path for modules.
1575
1576 =item C<AUG_SAVE_NOOP> = 16
1577
1578 Make save a no-op, just record what would have been changed.
1579
1580 =item C<AUG_NO_LOAD> = 32
1581
1582 Do not load the tree in C<guestfs_aug_init>.
1583
1584 =back
1585
1586 To close the handle, you can call C<guestfs_aug_close>.
1587
1588 To find out more about Augeas, see L<http://augeas.net/>.");
1589
1590   ("aug_close", (RErr, []), 26, [Optional "augeas"],
1591    [], (* XXX Augeas code needs tests. *)
1592    "close the current Augeas handle",
1593    "\
1594 Close the current Augeas handle and free up any resources
1595 used by it.  After calling this, you have to call
1596 C<guestfs_aug_init> again before you can use any other
1597 Augeas functions.");
1598
1599   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1600    [], (* XXX Augeas code needs tests. *)
1601    "define an Augeas variable",
1602    "\
1603 Defines an Augeas variable C<name> whose value is the result
1604 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1605 undefined.
1606
1607 On success this returns the number of nodes in C<expr>, or
1608 C<0> if C<expr> evaluates to something which is not a nodeset.");
1609
1610   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1611    [], (* XXX Augeas code needs tests. *)
1612    "define an Augeas node",
1613    "\
1614 Defines a variable C<name> whose value is the result of
1615 evaluating C<expr>.
1616
1617 If C<expr> evaluates to an empty nodeset, a node is created,
1618 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1619 C<name> will be the nodeset containing that single node.
1620
1621 On success this returns a pair containing the
1622 number of nodes in the nodeset, and a boolean flag
1623 if a node was created.");
1624
1625   ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1626    [], (* XXX Augeas code needs tests. *)
1627    "look up the value of an Augeas path",
1628    "\
1629 Look up the value associated with C<path>.  If C<path>
1630 matches exactly one node, the C<value> is returned.");
1631
1632   ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1633    [], (* XXX Augeas code needs tests. *)
1634    "set Augeas path to value",
1635    "\
1636 Set the value associated with C<path> to C<val>.
1637
1638 In the Augeas API, it is possible to clear a node by setting
1639 the value to NULL.  Due to an oversight in the libguestfs API
1640 you cannot do that with this call.  Instead you must use the
1641 C<guestfs_aug_clear> call.");
1642
1643   ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1644    [], (* XXX Augeas code needs tests. *)
1645    "insert a sibling Augeas node",
1646    "\
1647 Create a new sibling C<label> for C<path>, inserting it into
1648 the tree before or after C<path> (depending on the boolean
1649 flag C<before>).
1650
1651 C<path> must match exactly one existing node in the tree, and
1652 C<label> must be a label, ie. not contain C</>, C<*> or end
1653 with a bracketed index C<[N]>.");
1654
1655   ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1656    [], (* XXX Augeas code needs tests. *)
1657    "remove an Augeas path",
1658    "\
1659 Remove C<path> and all of its children.
1660
1661 On success this returns the number of entries which were removed.");
1662
1663   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1664    [], (* XXX Augeas code needs tests. *)
1665    "move Augeas node",
1666    "\
1667 Move the node C<src> to C<dest>.  C<src> must match exactly
1668 one node.  C<dest> is overwritten if it exists.");
1669
1670   ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1671    [], (* XXX Augeas code needs tests. *)
1672    "return Augeas nodes which match augpath",
1673    "\
1674 Returns a list of paths which match the path expression C<path>.
1675 The returned paths are sufficiently qualified so that they match
1676 exactly one node in the current tree.");
1677
1678   ("aug_save", (RErr, []), 25, [Optional "augeas"],
1679    [], (* XXX Augeas code needs tests. *)
1680    "write all pending Augeas changes to disk",
1681    "\
1682 This writes all pending changes to disk.
1683
1684 The flags which were passed to C<guestfs_aug_init> affect exactly
1685 how files are saved.");
1686
1687   ("aug_load", (RErr, []), 27, [Optional "augeas"],
1688    [], (* XXX Augeas code needs tests. *)
1689    "load files into the tree",
1690    "\
1691 Load files into the tree.
1692
1693 See C<aug_load> in the Augeas documentation for the full gory
1694 details.");
1695
1696   ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1697    [], (* XXX Augeas code needs tests. *)
1698    "list Augeas nodes under augpath",
1699    "\
1700 This is just a shortcut for listing C<guestfs_aug_match>
1701 C<path/*> and sorting the resulting nodes into alphabetical order.");
1702
1703   ("rm", (RErr, [Pathname "path"]), 29, [],
1704    [InitBasicFS, Always, TestRun
1705       [["touch"; "/new"];
1706        ["rm"; "/new"]];
1707     InitBasicFS, Always, TestLastFail
1708       [["rm"; "/new"]];
1709     InitBasicFS, Always, TestLastFail
1710       [["mkdir"; "/new"];
1711        ["rm"; "/new"]]],
1712    "remove a file",
1713    "\
1714 Remove the single file C<path>.");
1715
1716   ("rmdir", (RErr, [Pathname "path"]), 30, [],
1717    [InitBasicFS, Always, TestRun
1718       [["mkdir"; "/new"];
1719        ["rmdir"; "/new"]];
1720     InitBasicFS, Always, TestLastFail
1721       [["rmdir"; "/new"]];
1722     InitBasicFS, Always, TestLastFail
1723       [["touch"; "/new"];
1724        ["rmdir"; "/new"]]],
1725    "remove a directory",
1726    "\
1727 Remove the single directory C<path>.");
1728
1729   ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1730    [InitBasicFS, Always, TestOutputFalse
1731       [["mkdir"; "/new"];
1732        ["mkdir"; "/new/foo"];
1733        ["touch"; "/new/foo/bar"];
1734        ["rm_rf"; "/new"];
1735        ["exists"; "/new"]]],
1736    "remove a file or directory recursively",
1737    "\
1738 Remove the file or directory C<path>, recursively removing the
1739 contents if its a directory.  This is like the C<rm -rf> shell
1740 command.");
1741
1742   ("mkdir", (RErr, [Pathname "path"]), 32, [],
1743    [InitBasicFS, Always, TestOutputTrue
1744       [["mkdir"; "/new"];
1745        ["is_dir"; "/new"]];
1746     InitBasicFS, Always, TestLastFail
1747       [["mkdir"; "/new/foo/bar"]]],
1748    "create a directory",
1749    "\
1750 Create a directory named C<path>.");
1751
1752   ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1753    [InitBasicFS, Always, TestOutputTrue
1754       [["mkdir_p"; "/new/foo/bar"];
1755        ["is_dir"; "/new/foo/bar"]];
1756     InitBasicFS, Always, TestOutputTrue
1757       [["mkdir_p"; "/new/foo/bar"];
1758        ["is_dir"; "/new/foo"]];
1759     InitBasicFS, Always, TestOutputTrue
1760       [["mkdir_p"; "/new/foo/bar"];
1761        ["is_dir"; "/new"]];
1762     (* Regression tests for RHBZ#503133: *)
1763     InitBasicFS, Always, TestRun
1764       [["mkdir"; "/new"];
1765        ["mkdir_p"; "/new"]];
1766     InitBasicFS, Always, TestLastFail
1767       [["touch"; "/new"];
1768        ["mkdir_p"; "/new"]]],
1769    "create a directory and parents",
1770    "\
1771 Create a directory named C<path>, creating any parent directories
1772 as necessary.  This is like the C<mkdir -p> shell command.");
1773
1774   ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1775    [], (* XXX Need stat command to test *)
1776    "change file mode",
1777    "\
1778 Change the mode (permissions) of C<path> to C<mode>.  Only
1779 numeric modes are supported.
1780
1781 I<Note>: When using this command from guestfish, C<mode>
1782 by default would be decimal, unless you prefix it with
1783 C<0> to get octal, ie. use C<0700> not C<700>.
1784
1785 The mode actually set is affected by the umask.");
1786
1787   ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1788    [], (* XXX Need stat command to test *)
1789    "change file owner and group",
1790    "\
1791 Change the file owner to C<owner> and group to C<group>.
1792
1793 Only numeric uid and gid are supported.  If you want to use
1794 names, you will need to locate and parse the password file
1795 yourself (Augeas support makes this relatively easy).");
1796
1797   ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1798    [InitISOFS, Always, TestOutputTrue (
1799       [["exists"; "/empty"]]);
1800     InitISOFS, Always, TestOutputTrue (
1801       [["exists"; "/directory"]])],
1802    "test if file or directory exists",
1803    "\
1804 This returns C<true> if and only if there is a file, directory
1805 (or anything) with the given C<path> name.
1806
1807 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1808
1809   ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1810    [InitISOFS, Always, TestOutputTrue (
1811       [["is_file"; "/known-1"]]);
1812     InitISOFS, Always, TestOutputFalse (
1813       [["is_file"; "/directory"]])],
1814    "test if file exists",
1815    "\
1816 This returns C<true> if and only if there is a file
1817 with the given C<path> name.  Note that it returns false for
1818 other objects like directories.
1819
1820 See also C<guestfs_stat>.");
1821
1822   ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1823    [InitISOFS, Always, TestOutputFalse (
1824       [["is_dir"; "/known-3"]]);
1825     InitISOFS, Always, TestOutputTrue (
1826       [["is_dir"; "/directory"]])],
1827    "test if file exists",
1828    "\
1829 This returns C<true> if and only if there is a directory
1830 with the given C<path> name.  Note that it returns false for
1831 other objects like files.
1832
1833 See also C<guestfs_stat>.");
1834
1835   ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1836    [InitEmpty, Always, TestOutputListOfDevices (
1837       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1838        ["pvcreate"; "/dev/sda1"];
1839        ["pvcreate"; "/dev/sda2"];
1840        ["pvcreate"; "/dev/sda3"];
1841        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1842    "create an LVM physical volume",
1843    "\
1844 This creates an LVM physical volume on the named C<device>,
1845 where C<device> should usually be a partition name such
1846 as C</dev/sda1>.");
1847
1848   ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1849    [InitEmpty, Always, TestOutputList (
1850       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1851        ["pvcreate"; "/dev/sda1"];
1852        ["pvcreate"; "/dev/sda2"];
1853        ["pvcreate"; "/dev/sda3"];
1854        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1855        ["vgcreate"; "VG2"; "/dev/sda3"];
1856        ["vgs"]], ["VG1"; "VG2"])],
1857    "create an LVM volume group",
1858    "\
1859 This creates an LVM volume group called C<volgroup>
1860 from the non-empty list of physical volumes C<physvols>.");
1861
1862   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1863    [InitEmpty, Always, TestOutputList (
1864       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1865        ["pvcreate"; "/dev/sda1"];
1866        ["pvcreate"; "/dev/sda2"];
1867        ["pvcreate"; "/dev/sda3"];
1868        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1869        ["vgcreate"; "VG2"; "/dev/sda3"];
1870        ["lvcreate"; "LV1"; "VG1"; "50"];
1871        ["lvcreate"; "LV2"; "VG1"; "50"];
1872        ["lvcreate"; "LV3"; "VG2"; "50"];
1873        ["lvcreate"; "LV4"; "VG2"; "50"];
1874        ["lvcreate"; "LV5"; "VG2"; "50"];
1875        ["lvs"]],
1876       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1877        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1878    "create an LVM logical volume",
1879    "\
1880 This creates an LVM logical volume called C<logvol>
1881 on the volume group C<volgroup>, with C<size> megabytes.");
1882
1883   ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1884    [InitEmpty, Always, TestOutput (
1885       [["part_disk"; "/dev/sda"; "mbr"];
1886        ["mkfs"; "ext2"; "/dev/sda1"];
1887        ["mount_options"; ""; "/dev/sda1"; "/"];
1888        ["write"; "/new"; "new file contents"];
1889        ["cat"; "/new"]], "new file contents")],
1890    "make a filesystem",
1891    "\
1892 This creates a filesystem on C<device> (usually a partition
1893 or LVM logical volume).  The filesystem type is C<fstype>, for
1894 example C<ext3>.");
1895
1896   ("sfdisk", (RErr, [Device "device";
1897                      Int "cyls"; Int "heads"; Int "sectors";
1898                      StringList "lines"]), 43, [DangerWillRobinson],
1899    [],
1900    "create partitions on a block device",
1901    "\
1902 This is a direct interface to the L<sfdisk(8)> program for creating
1903 partitions on block devices.
1904
1905 C<device> should be a block device, for example C</dev/sda>.
1906
1907 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1908 and sectors on the device, which are passed directly to sfdisk as
1909 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1910 of these, then the corresponding parameter is omitted.  Usually for
1911 'large' disks, you can just pass C<0> for these, but for small
1912 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1913 out the right geometry and you will need to tell it.
1914
1915 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1916 information refer to the L<sfdisk(8)> manpage.
1917
1918 To create a single partition occupying the whole disk, you would
1919 pass C<lines> as a single element list, when the single element being
1920 the string C<,> (comma).
1921
1922 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1923 C<guestfs_part_init>");
1924
1925   ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning; DeprecatedBy "write"],
1926    (* Regression test for RHBZ#597135. *)
1927    [InitBasicFS, Always, TestLastFail
1928       [["write_file"; "/new"; "abc"; "10000"]]],
1929    "create a file",
1930    "\
1931 This call creates a file called C<path>.  The contents of the
1932 file is the string C<content> (which can contain any 8 bit data),
1933 with length C<size>.
1934
1935 As a special case, if C<size> is C<0>
1936 then the length is calculated using C<strlen> (so in this case
1937 the content cannot contain embedded ASCII NULs).
1938
1939 I<NB.> Owing to a bug, writing content containing ASCII NUL
1940 characters does I<not> work, even if the length is specified.");
1941
1942   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1943    [InitEmpty, Always, TestOutputListOfDevices (
1944       [["part_disk"; "/dev/sda"; "mbr"];
1945        ["mkfs"; "ext2"; "/dev/sda1"];
1946        ["mount_options"; ""; "/dev/sda1"; "/"];
1947        ["mounts"]], ["/dev/sda1"]);
1948     InitEmpty, Always, TestOutputList (
1949       [["part_disk"; "/dev/sda"; "mbr"];
1950        ["mkfs"; "ext2"; "/dev/sda1"];
1951        ["mount_options"; ""; "/dev/sda1"; "/"];
1952        ["umount"; "/"];
1953        ["mounts"]], [])],
1954    "unmount a filesystem",
1955    "\
1956 This unmounts the given filesystem.  The filesystem may be
1957 specified either by its mountpoint (path) or the device which
1958 contains the filesystem.");
1959
1960   ("mounts", (RStringList "devices", []), 46, [],
1961    [InitBasicFS, Always, TestOutputListOfDevices (
1962       [["mounts"]], ["/dev/sda1"])],
1963    "show mounted filesystems",
1964    "\
1965 This returns the list of currently mounted filesystems.  It returns
1966 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1967
1968 Some internal mounts are not shown.
1969
1970 See also: C<guestfs_mountpoints>");
1971
1972   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1973    [InitBasicFS, Always, TestOutputList (
1974       [["umount_all"];
1975        ["mounts"]], []);
1976     (* check that umount_all can unmount nested mounts correctly: *)
1977     InitEmpty, Always, TestOutputList (
1978       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1979        ["mkfs"; "ext2"; "/dev/sda1"];
1980        ["mkfs"; "ext2"; "/dev/sda2"];
1981        ["mkfs"; "ext2"; "/dev/sda3"];
1982        ["mount_options"; ""; "/dev/sda1"; "/"];
1983        ["mkdir"; "/mp1"];
1984        ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1985        ["mkdir"; "/mp1/mp2"];
1986        ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1987        ["mkdir"; "/mp1/mp2/mp3"];
1988        ["umount_all"];
1989        ["mounts"]], [])],
1990    "unmount all filesystems",
1991    "\
1992 This unmounts all mounted filesystems.
1993
1994 Some internal mounts are not unmounted by this call.");
1995
1996   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1997    [],
1998    "remove all LVM LVs, VGs and PVs",
1999    "\
2000 This command removes all LVM logical volumes, volume groups
2001 and physical volumes.");
2002
2003   ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
2004    [InitISOFS, Always, TestOutput (
2005       [["file"; "/empty"]], "empty");
2006     InitISOFS, Always, TestOutput (
2007       [["file"; "/known-1"]], "ASCII text");
2008     InitISOFS, Always, TestLastFail (
2009       [["file"; "/notexists"]]);
2010     InitISOFS, Always, TestOutput (
2011       [["file"; "/abssymlink"]], "symbolic link");
2012     InitISOFS, Always, TestOutput (
2013       [["file"; "/directory"]], "directory")],
2014    "determine file type",
2015    "\
2016 This call uses the standard L<file(1)> command to determine
2017 the type or contents of the file.
2018
2019 This call will also transparently look inside various types
2020 of compressed file.
2021
2022 The exact command which runs is C<file -zb path>.  Note in
2023 particular that the filename is not prepended to the output
2024 (the C<-b> option).
2025
2026 This command can also be used on C</dev/> devices
2027 (and partitions, LV names).  You can for example use this
2028 to determine if a device contains a filesystem, although
2029 it's usually better to use C<guestfs_vfs_type>.
2030
2031 If the C<path> does not begin with C</dev/> then
2032 this command only works for the content of regular files.
2033 For other file types (directory, symbolic link etc) it
2034 will just return the string C<directory> etc.");
2035
2036   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
2037    [InitBasicFS, Always, TestOutput (
2038       [["upload"; "test-command"; "/test-command"];
2039        ["chmod"; "0o755"; "/test-command"];
2040        ["command"; "/test-command 1"]], "Result1");
2041     InitBasicFS, Always, TestOutput (
2042       [["upload"; "test-command"; "/test-command"];
2043        ["chmod"; "0o755"; "/test-command"];
2044        ["command"; "/test-command 2"]], "Result2\n");
2045     InitBasicFS, Always, TestOutput (
2046       [["upload"; "test-command"; "/test-command"];
2047        ["chmod"; "0o755"; "/test-command"];
2048        ["command"; "/test-command 3"]], "\nResult3");
2049     InitBasicFS, Always, TestOutput (
2050       [["upload"; "test-command"; "/test-command"];
2051        ["chmod"; "0o755"; "/test-command"];
2052        ["command"; "/test-command 4"]], "\nResult4\n");
2053     InitBasicFS, Always, TestOutput (
2054       [["upload"; "test-command"; "/test-command"];
2055        ["chmod"; "0o755"; "/test-command"];
2056        ["command"; "/test-command 5"]], "\nResult5\n\n");
2057     InitBasicFS, Always, TestOutput (
2058       [["upload"; "test-command"; "/test-command"];
2059        ["chmod"; "0o755"; "/test-command"];
2060        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
2061     InitBasicFS, Always, TestOutput (
2062       [["upload"; "test-command"; "/test-command"];
2063        ["chmod"; "0o755"; "/test-command"];
2064        ["command"; "/test-command 7"]], "");
2065     InitBasicFS, Always, TestOutput (
2066       [["upload"; "test-command"; "/test-command"];
2067        ["chmod"; "0o755"; "/test-command"];
2068        ["command"; "/test-command 8"]], "\n");
2069     InitBasicFS, Always, TestOutput (
2070       [["upload"; "test-command"; "/test-command"];
2071        ["chmod"; "0o755"; "/test-command"];
2072        ["command"; "/test-command 9"]], "\n\n");
2073     InitBasicFS, Always, TestOutput (
2074       [["upload"; "test-command"; "/test-command"];
2075        ["chmod"; "0o755"; "/test-command"];
2076        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
2077     InitBasicFS, Always, TestOutput (
2078       [["upload"; "test-command"; "/test-command"];
2079        ["chmod"; "0o755"; "/test-command"];
2080        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
2081     InitBasicFS, Always, TestLastFail (
2082       [["upload"; "test-command"; "/test-command"];
2083        ["chmod"; "0o755"; "/test-command"];
2084        ["command"; "/test-command"]])],
2085    "run a command from the guest filesystem",
2086    "\
2087 This call runs a command from the guest filesystem.  The
2088 filesystem must be mounted, and must contain a compatible
2089 operating system (ie. something Linux, with the same
2090 or compatible processor architecture).
2091
2092 The single parameter is an argv-style list of arguments.
2093 The first element is the name of the program to run.
2094 Subsequent elements are parameters.  The list must be
2095 non-empty (ie. must contain a program name).  Note that
2096 the command runs directly, and is I<not> invoked via
2097 the shell (see C<guestfs_sh>).
2098
2099 The return value is anything printed to I<stdout> by
2100 the command.
2101
2102 If the command returns a non-zero exit status, then
2103 this function returns an error message.  The error message
2104 string is the content of I<stderr> from the command.
2105
2106 The C<$PATH> environment variable will contain at least
2107 C</usr/bin> and C</bin>.  If you require a program from
2108 another location, you should provide the full path in the
2109 first parameter.
2110
2111 Shared libraries and data files required by the program
2112 must be available on filesystems which are mounted in the
2113 correct places.  It is the caller's responsibility to ensure
2114 all filesystems that are needed are mounted at the right
2115 locations.");
2116
2117   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
2118    [InitBasicFS, Always, TestOutputList (
2119       [["upload"; "test-command"; "/test-command"];
2120        ["chmod"; "0o755"; "/test-command"];
2121        ["command_lines"; "/test-command 1"]], ["Result1"]);
2122     InitBasicFS, Always, TestOutputList (
2123       [["upload"; "test-command"; "/test-command"];
2124        ["chmod"; "0o755"; "/test-command"];
2125        ["command_lines"; "/test-command 2"]], ["Result2"]);
2126     InitBasicFS, Always, TestOutputList (
2127       [["upload"; "test-command"; "/test-command"];
2128        ["chmod"; "0o755"; "/test-command"];
2129        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
2130     InitBasicFS, Always, TestOutputList (
2131       [["upload"; "test-command"; "/test-command"];
2132        ["chmod"; "0o755"; "/test-command"];
2133        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
2134     InitBasicFS, Always, TestOutputList (
2135       [["upload"; "test-command"; "/test-command"];
2136        ["chmod"; "0o755"; "/test-command"];
2137        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
2138     InitBasicFS, Always, TestOutputList (
2139       [["upload"; "test-command"; "/test-command"];
2140        ["chmod"; "0o755"; "/test-command"];
2141        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
2142     InitBasicFS, Always, TestOutputList (
2143       [["upload"; "test-command"; "/test-command"];
2144        ["chmod"; "0o755"; "/test-command"];
2145        ["command_lines"; "/test-command 7"]], []);
2146     InitBasicFS, Always, TestOutputList (
2147       [["upload"; "test-command"; "/test-command"];
2148        ["chmod"; "0o755"; "/test-command"];
2149        ["command_lines"; "/test-command 8"]], [""]);
2150     InitBasicFS, Always, TestOutputList (
2151       [["upload"; "test-command"; "/test-command"];
2152        ["chmod"; "0o755"; "/test-command"];
2153        ["command_lines"; "/test-command 9"]], ["";""]);
2154     InitBasicFS, Always, TestOutputList (
2155       [["upload"; "test-command"; "/test-command"];
2156        ["chmod"; "0o755"; "/test-command"];
2157        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
2158     InitBasicFS, Always, TestOutputList (
2159       [["upload"; "test-command"; "/test-command"];
2160        ["chmod"; "0o755"; "/test-command"];
2161        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
2162    "run a command, returning lines",
2163    "\
2164 This is the same as C<guestfs_command>, but splits the
2165 result into a list of lines.
2166
2167 See also: C<guestfs_sh_lines>");
2168
2169   ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
2170    [InitISOFS, Always, TestOutputStruct (
2171       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
2172    "get file information",
2173    "\
2174 Returns file information for the given C<path>.
2175
2176 This is the same as the C<stat(2)> system call.");
2177
2178   ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
2179    [InitISOFS, Always, TestOutputStruct (
2180       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
2181    "get file information for a symbolic link",
2182    "\
2183 Returns file information for the given C<path>.
2184
2185 This is the same as C<guestfs_stat> except that if C<path>
2186 is a symbolic link, then the link is stat-ed, not the file it
2187 refers to.
2188
2189 This is the same as the C<lstat(2)> system call.");
2190
2191   ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
2192    [InitISOFS, Always, TestOutputStruct (
2193       [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
2194    "get file system statistics",
2195    "\
2196 Returns file system statistics for any mounted file system.
2197 C<path> should be a file or directory in the mounted file system
2198 (typically it is the mount point itself, but it doesn't need to be).
2199
2200 This is the same as the C<statvfs(2)> system call.");
2201
2202   ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
2203    [], (* XXX test *)
2204    "get ext2/ext3/ext4 superblock details",
2205    "\
2206 This returns the contents of the ext2, ext3 or ext4 filesystem
2207 superblock on C<device>.
2208
2209 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
2210 manpage for more details.  The list of fields returned isn't
2211 clearly defined, and depends on both the version of C<tune2fs>
2212 that libguestfs was built against, and the filesystem itself.");
2213
2214   ("blockdev_setro", (RErr, [Device "device"]), 56, [],
2215    [InitEmpty, Always, TestOutputTrue (
2216       [["blockdev_setro"; "/dev/sda"];
2217        ["blockdev_getro"; "/dev/sda"]])],
2218    "set block device to read-only",
2219    "\
2220 Sets the block device named C<device> to read-only.
2221
2222 This uses the L<blockdev(8)> command.");
2223
2224   ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
2225    [InitEmpty, Always, TestOutputFalse (
2226       [["blockdev_setrw"; "/dev/sda"];
2227        ["blockdev_getro"; "/dev/sda"]])],
2228    "set block device to read-write",
2229    "\
2230 Sets the block device named C<device> to read-write.
2231
2232 This uses the L<blockdev(8)> command.");
2233
2234   ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
2235    [InitEmpty, Always, TestOutputTrue (
2236       [["blockdev_setro"; "/dev/sda"];
2237        ["blockdev_getro"; "/dev/sda"]])],
2238    "is block device set to read-only",
2239    "\
2240 Returns a boolean indicating if the block device is read-only
2241 (true if read-only, false if not).
2242
2243 This uses the L<blockdev(8)> command.");
2244
2245   ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
2246    [InitEmpty, Always, TestOutputInt (
2247       [["blockdev_getss"; "/dev/sda"]], 512)],
2248    "get sectorsize of block device",
2249    "\
2250 This returns the size of sectors on a block device.
2251 Usually 512, but can be larger for modern devices.
2252
2253 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
2254 for that).
2255
2256 This uses the L<blockdev(8)> command.");
2257
2258   ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
2259    [InitEmpty, Always, TestOutputInt (
2260       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
2261    "get blocksize of block device",
2262    "\
2263 This returns the block size of a device.
2264
2265 (Note this is different from both I<size in blocks> and
2266 I<filesystem block size>).
2267
2268 This uses the L<blockdev(8)> command.");
2269
2270   ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
2271    [], (* XXX test *)
2272    "set blocksize of block device",
2273    "\
2274 This sets the block size of a device.
2275
2276 (Note this is different from both I<size in blocks> and
2277 I<filesystem block size>).
2278
2279 This uses the L<blockdev(8)> command.");
2280
2281   ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
2282    [InitEmpty, Always, TestOutputInt (
2283       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
2284    "get total size of device in 512-byte sectors",
2285    "\
2286 This returns the size of the device in units of 512-byte sectors
2287 (even if the sectorsize isn't 512 bytes ... weird).
2288
2289 See also C<guestfs_blockdev_getss> for the real sector size of
2290 the device, and C<guestfs_blockdev_getsize64> for the more
2291 useful I<size in bytes>.
2292
2293 This uses the L<blockdev(8)> command.");
2294
2295   ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
2296    [InitEmpty, Always, TestOutputInt (
2297       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
2298    "get total size of device in bytes",
2299    "\
2300 This returns the size of the device in bytes.
2301
2302 See also C<guestfs_blockdev_getsz>.
2303
2304 This uses the L<blockdev(8)> command.");
2305
2306   ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
2307    [InitEmpty, Always, TestRun
2308       [["blockdev_flushbufs"; "/dev/sda"]]],
2309    "flush device buffers",
2310    "\
2311 This tells the kernel to flush internal buffers associated
2312 with C<device>.
2313
2314 This uses the L<blockdev(8)> command.");
2315
2316   ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
2317    [InitEmpty, Always, TestRun
2318       [["blockdev_rereadpt"; "/dev/sda"]]],
2319    "reread partition table",
2320    "\
2321 Reread the partition table on C<device>.
2322
2323 This uses the L<blockdev(8)> command.");
2324
2325   ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
2326    [InitBasicFS, Always, TestOutput (
2327       (* Pick a file from cwd which isn't likely to change. *)
2328       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2329        ["checksum"; "md5"; "/COPYING.LIB"]],
2330       Digest.to_hex (Digest.file "COPYING.LIB"))],
2331    "upload a file from the local machine",
2332    "\
2333 Upload local file C<filename> to C<remotefilename> on the
2334 filesystem.
2335
2336 C<filename> can also be a named pipe.
2337
2338 See also C<guestfs_download>.");
2339
2340   ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [],
2341    [InitBasicFS, Always, TestOutput (
2342       (* Pick a file from cwd which isn't likely to change. *)
2343       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2344        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
2345        ["upload"; "testdownload.tmp"; "/upload"];
2346        ["checksum"; "md5"; "/upload"]],
2347       Digest.to_hex (Digest.file "COPYING.LIB"))],
2348    "download a file to the local machine",
2349    "\
2350 Download file C<remotefilename> and save it as C<filename>
2351 on the local machine.
2352
2353 C<filename> can also be a named pipe.
2354
2355 See also C<guestfs_upload>, C<guestfs_cat>.");
2356
2357   ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
2358    [InitISOFS, Always, TestOutput (
2359       [["checksum"; "crc"; "/known-3"]], "2891671662");
2360     InitISOFS, Always, TestLastFail (
2361       [["checksum"; "crc"; "/notexists"]]);
2362     InitISOFS, Always, TestOutput (
2363       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
2364     InitISOFS, Always, TestOutput (
2365       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
2366     InitISOFS, Always, TestOutput (
2367       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
2368     InitISOFS, Always, TestOutput (
2369       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
2370     InitISOFS, Always, TestOutput (
2371       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
2372     InitISOFS, Always, TestOutput (
2373       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6");
2374     (* Test for RHBZ#579608, absolute symbolic links. *)
2375     InitISOFS, Always, TestOutput (
2376       [["checksum"; "sha512"; "/abssymlink"]], "5f57d0639bc95081c53afc63a449403883818edc64da48930ad6b1a4fb49be90404686877743fbcd7c99811f3def7df7bc22635c885c6a8cf79c806b43451c1a")],
2377    "compute MD5, SHAx or CRC checksum of file",
2378    "\
2379 This call computes the MD5, SHAx or CRC checksum of the
2380 file named C<path>.
2381
2382 The type of checksum to compute is given by the C<csumtype>
2383 parameter which must have one of the following values:
2384
2385 =over 4
2386
2387 =item C<crc>
2388
2389 Compute the cyclic redundancy check (CRC) specified by POSIX
2390 for the C<cksum> command.
2391
2392 =item C<md5>
2393
2394 Compute the MD5 hash (using the C<md5sum> program).
2395
2396 =item C<sha1>
2397
2398 Compute the SHA1 hash (using the C<sha1sum> program).
2399
2400 =item C<sha224>
2401
2402 Compute the SHA224 hash (using the C<sha224sum> program).
2403
2404 =item C<sha256>
2405
2406 Compute the SHA256 hash (using the C<sha256sum> program).
2407
2408 =item C<sha384>
2409
2410 Compute the SHA384 hash (using the C<sha384sum> program).
2411
2412 =item C<sha512>
2413
2414 Compute the SHA512 hash (using the C<sha512sum> program).
2415
2416 =back
2417
2418 The checksum is returned as a printable string.
2419
2420 To get the checksum for a device, use C<guestfs_checksum_device>.
2421
2422 To get the checksums for many files, use C<guestfs_checksums_out>.");
2423
2424   ("tar_in", (RErr, [FileIn "tarfile"; Pathname "directory"]), 69, [],
2425    [InitBasicFS, Always, TestOutput (
2426       [["tar_in"; "../images/helloworld.tar"; "/"];
2427        ["cat"; "/hello"]], "hello\n")],
2428    "unpack tarfile to directory",
2429    "\
2430 This command uploads and unpacks local file C<tarfile> (an
2431 I<uncompressed> tar file) into C<directory>.
2432
2433 To upload a compressed tarball, use C<guestfs_tgz_in>
2434 or C<guestfs_txz_in>.");
2435
2436   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2437    [],
2438    "pack directory into tarfile",
2439    "\
2440 This command packs the contents of C<directory> and downloads
2441 it to local file C<tarfile>.
2442
2443 To download a compressed tarball, use C<guestfs_tgz_out>
2444 or C<guestfs_txz_out>.");
2445
2446   ("tgz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 71, [],
2447    [InitBasicFS, Always, TestOutput (
2448       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2449        ["cat"; "/hello"]], "hello\n")],
2450    "unpack compressed tarball to directory",
2451    "\
2452 This command uploads and unpacks local file C<tarball> (a
2453 I<gzip compressed> tar file) into C<directory>.
2454
2455 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2456
2457   ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2458    [],
2459    "pack directory into compressed tarball",
2460    "\
2461 This command packs the contents of C<directory> and downloads
2462 it to local file C<tarball>.
2463
2464 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2465
2466   ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2467    [InitBasicFS, Always, TestLastFail (
2468       [["umount"; "/"];
2469        ["mount_ro"; "/dev/sda1"; "/"];
2470        ["touch"; "/new"]]);
2471     InitBasicFS, Always, TestOutput (
2472       [["write"; "/new"; "data"];
2473        ["umount"; "/"];
2474        ["mount_ro"; "/dev/sda1"; "/"];
2475        ["cat"; "/new"]], "data")],
2476    "mount a guest disk, read-only",
2477    "\
2478 This is the same as the C<guestfs_mount> command, but it
2479 mounts the filesystem with the read-only (I<-o ro>) flag.");
2480
2481   ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2482    [],
2483    "mount a guest disk with mount options",
2484    "\
2485 This is the same as the C<guestfs_mount> command, but it
2486 allows you to set the mount options as for the
2487 L<mount(8)> I<-o> flag.
2488
2489 If the C<options> parameter is an empty string, then
2490 no options are passed (all options default to whatever
2491 the filesystem uses).");
2492
2493   ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2494    [],
2495    "mount a guest disk with mount options and vfstype",
2496    "\
2497 This is the same as the C<guestfs_mount> command, but it
2498 allows you to set both the mount options and the vfstype
2499 as for the L<mount(8)> I<-o> and I<-t> flags.");
2500
2501   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2502    [],
2503    "debugging and internals",
2504    "\
2505 The C<guestfs_debug> command exposes some internals of
2506 C<guestfsd> (the guestfs daemon) that runs inside the
2507 qemu subprocess.
2508
2509 There is no comprehensive help for this command.  You have
2510 to look at the file C<daemon/debug.c> in the libguestfs source
2511 to find out what you can do.");
2512
2513   ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2514    [InitEmpty, Always, TestOutputList (
2515       [["part_disk"; "/dev/sda"; "mbr"];
2516        ["pvcreate"; "/dev/sda1"];
2517        ["vgcreate"; "VG"; "/dev/sda1"];
2518        ["lvcreate"; "LV1"; "VG"; "50"];
2519        ["lvcreate"; "LV2"; "VG"; "50"];
2520        ["lvremove"; "/dev/VG/LV1"];
2521        ["lvs"]], ["/dev/VG/LV2"]);
2522     InitEmpty, Always, TestOutputList (
2523       [["part_disk"; "/dev/sda"; "mbr"];
2524        ["pvcreate"; "/dev/sda1"];
2525        ["vgcreate"; "VG"; "/dev/sda1"];
2526        ["lvcreate"; "LV1"; "VG"; "50"];
2527        ["lvcreate"; "LV2"; "VG"; "50"];
2528        ["lvremove"; "/dev/VG"];
2529        ["lvs"]], []);
2530     InitEmpty, Always, TestOutputList (
2531       [["part_disk"; "/dev/sda"; "mbr"];
2532        ["pvcreate"; "/dev/sda1"];
2533        ["vgcreate"; "VG"; "/dev/sda1"];
2534        ["lvcreate"; "LV1"; "VG"; "50"];
2535        ["lvcreate"; "LV2"; "VG"; "50"];
2536        ["lvremove"; "/dev/VG"];
2537        ["vgs"]], ["VG"])],
2538    "remove an LVM logical volume",
2539    "\
2540 Remove an LVM logical volume C<device>, where C<device> is
2541 the path to the LV, such as C</dev/VG/LV>.
2542
2543 You can also remove all LVs in a volume group by specifying
2544 the VG name, C</dev/VG>.");
2545
2546   ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2547    [InitEmpty, Always, TestOutputList (
2548       [["part_disk"; "/dev/sda"; "mbr"];
2549        ["pvcreate"; "/dev/sda1"];
2550        ["vgcreate"; "VG"; "/dev/sda1"];
2551        ["lvcreate"; "LV1"; "VG"; "50"];
2552        ["lvcreate"; "LV2"; "VG"; "50"];
2553        ["vgremove"; "VG"];
2554        ["lvs"]], []);
2555     InitEmpty, Always, TestOutputList (
2556       [["part_disk"; "/dev/sda"; "mbr"];
2557        ["pvcreate"; "/dev/sda1"];
2558        ["vgcreate"; "VG"; "/dev/sda1"];
2559        ["lvcreate"; "LV1"; "VG"; "50"];
2560        ["lvcreate"; "LV2"; "VG"; "50"];
2561        ["vgremove"; "VG"];
2562        ["vgs"]], [])],
2563    "remove an LVM volume group",
2564    "\
2565 Remove an LVM volume group C<vgname>, (for example C<VG>).
2566
2567 This also forcibly removes all logical volumes in the volume
2568 group (if any).");
2569
2570   ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2571    [InitEmpty, Always, TestOutputListOfDevices (
2572       [["part_disk"; "/dev/sda"; "mbr"];
2573        ["pvcreate"; "/dev/sda1"];
2574        ["vgcreate"; "VG"; "/dev/sda1"];
2575        ["lvcreate"; "LV1"; "VG"; "50"];
2576        ["lvcreate"; "LV2"; "VG"; "50"];
2577        ["vgremove"; "VG"];
2578        ["pvremove"; "/dev/sda1"];
2579        ["lvs"]], []);
2580     InitEmpty, Always, TestOutputListOfDevices (
2581       [["part_disk"; "/dev/sda"; "mbr"];
2582        ["pvcreate"; "/dev/sda1"];
2583        ["vgcreate"; "VG"; "/dev/sda1"];
2584        ["lvcreate"; "LV1"; "VG"; "50"];
2585        ["lvcreate"; "LV2"; "VG"; "50"];
2586        ["vgremove"; "VG"];
2587        ["pvremove"; "/dev/sda1"];
2588        ["vgs"]], []);
2589     InitEmpty, Always, TestOutputListOfDevices (
2590       [["part_disk"; "/dev/sda"; "mbr"];
2591        ["pvcreate"; "/dev/sda1"];
2592        ["vgcreate"; "VG"; "/dev/sda1"];
2593        ["lvcreate"; "LV1"; "VG"; "50"];
2594        ["lvcreate"; "LV2"; "VG"; "50"];
2595        ["vgremove"; "VG"];
2596        ["pvremove"; "/dev/sda1"];
2597        ["pvs"]], [])],
2598    "remove an LVM physical volume",
2599    "\
2600 This wipes a physical volume C<device> so that LVM will no longer
2601 recognise it.
2602
2603 The implementation uses the C<pvremove> command which refuses to
2604 wipe physical volumes that contain any volume groups, so you have
2605 to remove those first.");
2606
2607   ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2608    [InitBasicFS, Always, TestOutput (
2609       [["set_e2label"; "/dev/sda1"; "testlabel"];
2610        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2611    "set the ext2/3/4 filesystem label",
2612    "\
2613 This sets the ext2/3/4 filesystem label of the filesystem on
2614 C<device> to C<label>.  Filesystem labels are limited to
2615 16 characters.
2616
2617 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2618 to return the existing label on a filesystem.");
2619
2620   ("get_e2label", (RString "label", [Device "device"]), 81, [DeprecatedBy "vfs_label"],
2621    [],
2622    "get the ext2/3/4 filesystem label",
2623    "\
2624 This returns the ext2/3/4 filesystem label of the filesystem on
2625 C<device>.");
2626
2627   ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2628    (let uuid = uuidgen () in
2629     [InitBasicFS, Always, TestOutput (
2630        [["set_e2uuid"; "/dev/sda1"; uuid];
2631         ["get_e2uuid"; "/dev/sda1"]], uuid);
2632      InitBasicFS, Always, TestOutput (
2633        [["set_e2uuid"; "/dev/sda1"; "clear"];
2634         ["get_e2uuid"; "/dev/sda1"]], "");
2635      (* We can't predict what UUIDs will be, so just check the commands run. *)
2636      InitBasicFS, Always, TestRun (
2637        [["set_e2uuid"; "/dev/sda1"; "random"]]);
2638      InitBasicFS, Always, TestRun (
2639        [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2640    "set the ext2/3/4 filesystem UUID",
2641    "\
2642 This sets the ext2/3/4 filesystem UUID of the filesystem on
2643 C<device> to C<uuid>.  The format of the UUID and alternatives
2644 such as C<clear>, C<random> and C<time> are described in the
2645 L<tune2fs(8)> manpage.
2646
2647 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2648 to return the existing UUID of a filesystem.");
2649
2650   ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [DeprecatedBy "vfs_uuid"],
2651    (* Regression test for RHBZ#597112. *)
2652    (let uuid = uuidgen () in
2653     [InitBasicFS, Always, TestOutput (
2654        [["mke2journal"; "1024"; "/dev/sdb"];
2655         ["set_e2uuid"; "/dev/sdb"; uuid];
2656         ["get_e2uuid"; "/dev/sdb"]], uuid)]),
2657    "get the ext2/3/4 filesystem UUID",
2658    "\
2659 This returns the ext2/3/4 filesystem UUID of the filesystem on
2660 C<device>.");
2661
2662   ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [FishOutput FishOutputHexadecimal],
2663    [InitBasicFS, Always, TestOutputInt (
2664       [["umount"; "/dev/sda1"];
2665        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2666     InitBasicFS, Always, TestOutputInt (
2667       [["umount"; "/dev/sda1"];
2668        ["zero"; "/dev/sda1"];
2669        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2670    "run the filesystem checker",
2671    "\
2672 This runs the filesystem checker (fsck) on C<device> which
2673 should have filesystem type C<fstype>.
2674
2675 The returned integer is the status.  See L<fsck(8)> for the
2676 list of status codes from C<fsck>.
2677
2678 Notes:
2679
2680 =over 4
2681
2682 =item *
2683
2684 Multiple status codes can be summed together.
2685
2686 =item *
2687
2688 A non-zero return code can mean \"success\", for example if
2689 errors have been corrected on the filesystem.
2690
2691 =item *
2692
2693 Checking or repairing NTFS volumes is not supported
2694 (by linux-ntfs).
2695
2696 =back
2697
2698 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2699
2700   ("zero", (RErr, [Device "device"]), 85, [],
2701    [InitBasicFS, Always, TestOutput (
2702       [["umount"; "/dev/sda1"];
2703        ["zero"; "/dev/sda1"];
2704        ["file"; "/dev/sda1"]], "data")],
2705    "write zeroes to the device",
2706    "\
2707 This command writes zeroes over the first few blocks of C<device>.
2708
2709 How many blocks are zeroed isn't specified (but it's I<not> enough
2710 to securely wipe the device).  It should be sufficient to remove
2711 any partition tables, filesystem superblocks and so on.
2712
2713 See also: C<guestfs_zero_device>, C<guestfs_scrub_device>.");
2714
2715   ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2716    (* See:
2717     * https://bugzilla.redhat.com/show_bug.cgi?id=484986
2718     * https://bugzilla.redhat.com/show_bug.cgi?id=479760
2719     *)
2720    [InitBasicFS, Always, TestOutputTrue (
2721       [["mkdir_p"; "/boot/grub"];
2722        ["write"; "/boot/grub/device.map"; "(hd0) /dev/vda"];
2723        ["grub_install"; "/"; "/dev/vda"];
2724        ["is_dir"; "/boot"]])],
2725    "install GRUB",
2726    "\
2727 This command installs GRUB (the Grand Unified Bootloader) on
2728 C<device>, with the root directory being C<root>.
2729
2730 Note: If grub-install reports the error
2731 \"No suitable drive was found in the generated device map.\"
2732 it may be that you need to create a C</boot/grub/device.map>
2733 file first that contains the mapping between grub device names
2734 and Linux device names.  It is usually sufficient to create
2735 a file containing:
2736
2737  (hd0) /dev/vda
2738
2739 replacing C</dev/vda> with the name of the installation device.");
2740
2741   ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2742    [InitBasicFS, Always, TestOutput (
2743       [["write"; "/old"; "file content"];
2744        ["cp"; "/old"; "/new"];
2745        ["cat"; "/new"]], "file content");
2746     InitBasicFS, Always, TestOutputTrue (
2747       [["write"; "/old"; "file content"];
2748        ["cp"; "/old"; "/new"];
2749        ["is_file"; "/old"]]);
2750     InitBasicFS, Always, TestOutput (
2751       [["write"; "/old"; "file content"];
2752        ["mkdir"; "/dir"];
2753        ["cp"; "/old"; "/dir/new"];
2754        ["cat"; "/dir/new"]], "file content")],
2755    "copy a file",
2756    "\
2757 This copies a file from C<src> to C<dest> where C<dest> is
2758 either a destination filename or destination directory.");
2759
2760   ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2761    [InitBasicFS, Always, TestOutput (
2762       [["mkdir"; "/olddir"];
2763        ["mkdir"; "/newdir"];
2764        ["write"; "/olddir/file"; "file content"];
2765        ["cp_a"; "/olddir"; "/newdir"];
2766        ["cat"; "/newdir/olddir/file"]], "file content")],
2767    "copy a file or directory recursively",
2768    "\
2769 This copies a file or directory from C<src> to C<dest>
2770 recursively using the C<cp -a> command.");
2771
2772   ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2773    [InitBasicFS, Always, TestOutput (
2774       [["write"; "/old"; "file content"];
2775        ["mv"; "/old"; "/new"];
2776        ["cat"; "/new"]], "file content");
2777     InitBasicFS, Always, TestOutputFalse (
2778       [["write"; "/old"; "file content"];
2779        ["mv"; "/old"; "/new"];
2780        ["is_file"; "/old"]])],
2781    "move a file",
2782    "\
2783 This moves a file from C<src> to C<dest> where C<dest> is
2784 either a destination filename or destination directory.");
2785
2786   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2787    [InitEmpty, Always, TestRun (
2788       [["drop_caches"; "3"]])],
2789    "drop kernel page cache, dentries and inodes",
2790    "\
2791 This instructs the guest kernel to drop its page cache,
2792 and/or dentries and inode caches.  The parameter C<whattodrop>
2793 tells the kernel what precisely to drop, see
2794 L<http://linux-mm.org/Drop_Caches>
2795
2796 Setting C<whattodrop> to 3 should drop everything.
2797
2798 This automatically calls L<sync(2)> before the operation,
2799 so that the maximum guest memory is freed.");
2800
2801   ("dmesg", (RString "kmsgs", []), 91, [],
2802    [InitEmpty, Always, TestRun (
2803       [["dmesg"]])],
2804    "return kernel messages",
2805    "\
2806 This returns the kernel messages (C<dmesg> output) from
2807 the guest kernel.  This is sometimes useful for extended
2808 debugging of problems.
2809
2810 Another way to get the same information is to enable
2811 verbose messages with C<guestfs_set_verbose> or by setting
2812 the environment variable C<LIBGUESTFS_DEBUG=1> before
2813 running the program.");
2814
2815   ("ping_daemon", (RErr, []), 92, [],
2816    [InitEmpty, Always, TestRun (
2817       [["ping_daemon"]])],
2818    "ping the guest daemon",
2819    "\
2820 This is a test probe into the guestfs daemon running inside
2821 the qemu subprocess.  Calling this function checks that the
2822 daemon responds to the ping message, without affecting the daemon
2823 or attached block device(s) in any other way.");
2824
2825   ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2826    [InitBasicFS, Always, TestOutputTrue (
2827       [["write"; "/file1"; "contents of a file"];
2828        ["cp"; "/file1"; "/file2"];
2829        ["equal"; "/file1"; "/file2"]]);
2830     InitBasicFS, Always, TestOutputFalse (
2831       [["write"; "/file1"; "contents of a file"];
2832        ["write"; "/file2"; "contents of another file"];
2833        ["equal"; "/file1"; "/file2"]]);
2834     InitBasicFS, Always, TestLastFail (
2835       [["equal"; "/file1"; "/file2"]])],
2836    "test if two files have equal contents",
2837    "\
2838 This compares the two files C<file1> and C<file2> and returns
2839 true if their content is exactly equal, or false otherwise.
2840
2841 The external L<cmp(1)> program is used for the comparison.");
2842
2843   ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2844    [InitISOFS, Always, TestOutputList (
2845       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2846     InitISOFS, Always, TestOutputList (
2847       [["strings"; "/empty"]], []);
2848     (* Test for RHBZ#579608, absolute symbolic links. *)
2849     InitISOFS, Always, TestRun (
2850       [["strings"; "/abssymlink"]])],
2851    "print the printable strings in a file",
2852    "\
2853 This runs the L<strings(1)> command on a file and returns
2854 the list of printable strings found.");
2855
2856   ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2857    [InitISOFS, Always, TestOutputList (
2858       [["strings_e"; "b"; "/known-5"]], []);
2859     InitBasicFS, Always, TestOutputList (
2860       [["write"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"];
2861        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2862    "print the printable strings in a file",
2863    "\
2864 This is like the C<guestfs_strings> command, but allows you to
2865 specify the encoding of strings that are looked for in
2866 the source file C<path>.
2867
2868 Allowed encodings are:
2869
2870 =over 4
2871
2872 =item s
2873
2874 Single 7-bit-byte characters like ASCII and the ASCII-compatible
2875 parts of ISO-8859-X (this is what C<guestfs_strings> uses).
2876
2877 =item S
2878
2879 Single 8-bit-byte characters.
2880
2881 =item b
2882
2883 16-bit big endian strings such as those encoded in
2884 UTF-16BE or UCS-2BE.
2885
2886 =item l (lower case letter L)
2887
2888 16-bit little endian such as UTF-16LE and UCS-2LE.
2889 This is useful for examining binaries in Windows guests.
2890
2891 =item B
2892
2893 32-bit big endian such as UCS-4BE.
2894
2895 =item L
2896
2897 32-bit little endian such as UCS-4LE.
2898
2899 =back
2900
2901 The returned strings are transcoded to UTF-8.");
2902
2903   ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2904    [InitISOFS, Always, TestOutput (
2905       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2906     (* Test for RHBZ#501888c2 regression which caused large hexdump
2907      * commands to segfault.
2908      *)
2909     InitISOFS, Always, TestRun (
2910       [["hexdump"; "/100krandom"]]);
2911     (* Test for RHBZ#579608, absolute symbolic links. *)
2912     InitISOFS, Always, TestRun (
2913       [["hexdump"; "/abssymlink"]])],
2914    "dump a file in hexadecimal",
2915    "\
2916 This runs C<hexdump -C> on the given C<path>.  The result is
2917 the human-readable, canonical hex dump of the file.");
2918
2919   ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2920    [InitNone, Always, TestOutput (
2921       [["part_disk"; "/dev/sda"; "mbr"];
2922        ["mkfs"; "ext3"; "/dev/sda1"];
2923        ["mount_options"; ""; "/dev/sda1"; "/"];
2924        ["write"; "/new"; "test file"];
2925        ["umount"; "/dev/sda1"];
2926        ["zerofree"; "/dev/sda1"];
2927        ["mount_options"; ""; "/dev/sda1"; "/"];
2928        ["cat"; "/new"]], "test file")],
2929    "zero unused inodes and disk blocks on ext2/3 filesystem",
2930    "\
2931 This runs the I<zerofree> program on C<device>.  This program
2932 claims to zero unused inodes and disk blocks on an ext2/3
2933 filesystem, thus making it possible to compress the filesystem
2934 more effectively.
2935
2936 You should B<not> run this program if the filesystem is
2937 mounted.
2938
2939 It is possible that using this program can damage the filesystem
2940 or data on the filesystem.");
2941
2942   ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2943    [],
2944    "resize an LVM physical volume",
2945    "\
2946 This resizes (expands or shrinks) an existing LVM physical
2947 volume to match the new size of the underlying device.");
2948
2949   ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2950                        Int "cyls"; Int "heads"; Int "sectors";
2951                        String "line"]), 99, [DangerWillRobinson],
2952    [],
2953    "modify a single partition on a block device",
2954    "\
2955 This runs L<sfdisk(8)> option to modify just the single
2956 partition C<n> (note: C<n> counts from 1).
2957
2958 For other parameters, see C<guestfs_sfdisk>.  You should usually
2959 pass C<0> for the cyls/heads/sectors parameters.
2960
2961 See also: C<guestfs_part_add>");
2962
2963   ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2964    [],
2965    "display the partition table",
2966    "\
2967 This displays the partition table on C<device>, in the
2968 human-readable output of the L<sfdisk(8)> command.  It is
2969 not intended to be parsed.
2970
2971 See also: C<guestfs_part_list>");
2972
2973   ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2974    [],
2975    "display the kernel geometry",
2976    "\
2977 This displays the kernel's idea of the geometry of C<device>.
2978
2979 The result is in human-readable format, and not designed to
2980 be parsed.");
2981
2982   ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2983    [],
2984    "display the disk geometry from the partition table",
2985    "\
2986 This displays the disk geometry of C<device> read from the
2987 partition table.  Especially in the case where the underlying
2988 block device has been resized, this can be different from the
2989 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2990
2991 The result is in human-readable format, and not designed to
2992 be parsed.");
2993
2994   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2995    [],
2996    "activate or deactivate all volume groups",
2997    "\
2998 This command activates or (if C<activate> is false) deactivates
2999 all logical volumes in all volume groups.
3000 If activated, then they are made known to the
3001 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3002 then those devices disappear.
3003
3004 This command is the same as running C<vgchange -a y|n>");
3005
3006   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
3007    [],
3008    "activate or deactivate some volume groups",
3009    "\
3010 This command activates or (if C<activate> is false) deactivates
3011 all logical volumes in the listed volume groups C<volgroups>.
3012 If activated, then they are made known to the
3013 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3014 then those devices disappear.
3015
3016 This command is the same as running C<vgchange -a y|n volgroups...>
3017
3018 Note that if C<volgroups> is an empty list then B<all> volume groups
3019 are activated or deactivated.");
3020
3021   ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
3022    [InitNone, Always, TestOutput (
3023       [["part_disk"; "/dev/sda"; "mbr"];
3024        ["pvcreate"; "/dev/sda1"];
3025        ["vgcreate"; "VG"; "/dev/sda1"];
3026        ["lvcreate"; "LV"; "VG"; "10"];
3027        ["mkfs"; "ext2"; "/dev/VG/LV"];
3028        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3029        ["write"; "/new"; "test content"];
3030        ["umount"; "/"];
3031        ["lvresize"; "/dev/VG/LV"; "20"];
3032        ["e2fsck_f"; "/dev/VG/LV"];
3033        ["resize2fs"; "/dev/VG/LV"];
3034        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3035        ["cat"; "/new"]], "test content");
3036     InitNone, Always, TestRun (
3037       (* Make an LV smaller to test RHBZ#587484. *)
3038       [["part_disk"; "/dev/sda"; "mbr"];
3039        ["pvcreate"; "/dev/sda1"];
3040        ["vgcreate"; "VG"; "/dev/sda1"];
3041        ["lvcreate"; "LV"; "VG"; "20"];
3042        ["lvresize"; "/dev/VG/LV"; "10"]])],
3043    "resize an LVM logical volume",
3044    "\
3045 This resizes (expands or shrinks) an existing LVM logical
3046 volume to C<mbytes>.  When reducing, data in the reduced part
3047 is lost.");
3048
3049   ("resize2fs", (RErr, [Device "device"]), 106, [],
3050    [], (* lvresize tests this *)
3051    "resize an ext2, ext3 or ext4 filesystem",
3052    "\
3053 This resizes an ext2, ext3 or ext4 filesystem to match the size of
3054 the underlying device.
3055
3056 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
3057 on the C<device> before calling this command.  For unknown reasons
3058 C<resize2fs> sometimes gives an error about this and sometimes not.
3059 In any case, it is always safe to call C<guestfs_e2fsck_f> before
3060 calling this function.");
3061
3062   ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
3063    [InitBasicFS, Always, TestOutputList (
3064       [["find"; "/"]], ["lost+found"]);
3065     InitBasicFS, Always, TestOutputList (
3066       [["touch"; "/a"];
3067        ["mkdir"; "/b"];
3068        ["touch"; "/b/c"];
3069        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
3070     InitBasicFS, Always, TestOutputList (
3071       [["mkdir_p"; "/a/b/c"];
3072        ["touch"; "/a/b/c/d"];
3073        ["find"; "/a/b/"]], ["c"; "c/d"])],
3074    "find all files and directories",
3075    "\
3076 This command lists out all files and directories, recursively,
3077 starting at C<directory>.  It is essentially equivalent to
3078 running the shell command C<find directory -print> but some
3079 post-processing happens on the output, described below.
3080
3081 This returns a list of strings I<without any prefix>.  Thus
3082 if the directory structure was:
3083
3084  /tmp/a
3085  /tmp/b
3086  /tmp/c/d
3087
3088 then the returned list from C<guestfs_find> C</tmp> would be
3089 4 elements:
3090
3091  a
3092  b
3093  c
3094  c/d
3095
3096 If C<directory> is not a directory, then this command returns
3097 an error.
3098
3099 The returned list is sorted.
3100
3101 See also C<guestfs_find0>.");
3102
3103   ("e2fsck_f", (RErr, [Device "device"]), 108, [],
3104    [], (* lvresize tests this *)
3105    "check an ext2/ext3 filesystem",
3106    "\
3107 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
3108 filesystem checker on C<device>, noninteractively (C<-p>),
3109 even if the filesystem appears to be clean (C<-f>).
3110
3111 This command is only needed because of C<guestfs_resize2fs>
3112 (q.v.).  Normally you should use C<guestfs_fsck>.");
3113
3114   ("sleep", (RErr, [Int "secs"]), 109, [],
3115    [InitNone, Always, TestRun (
3116       [["sleep"; "1"]])],
3117    "sleep for some seconds",
3118    "\
3119 Sleep for C<secs> seconds.");
3120
3121   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
3122    [InitNone, Always, TestOutputInt (
3123       [["part_disk"; "/dev/sda"; "mbr"];
3124        ["mkfs"; "ntfs"; "/dev/sda1"];
3125        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
3126     InitNone, Always, TestOutputInt (
3127       [["part_disk"; "/dev/sda"; "mbr"];
3128        ["mkfs"; "ext2"; "/dev/sda1"];
3129        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
3130    "probe NTFS volume",
3131    "\
3132 This command runs the L<ntfs-3g.probe(8)> command which probes
3133 an NTFS C<device> for mountability.  (Not all NTFS volumes can
3134 be mounted read-write, and some cannot be mounted at all).
3135
3136 C<rw> is a boolean flag.  Set it to true if you want to test
3137 if the volume can be mounted read-write.  Set it to false if
3138 you want to test if the volume can be mounted read-only.
3139
3140 The return value is an integer which C<0> if the operation
3141 would succeed, or some non-zero value documented in the
3142 L<ntfs-3g.probe(8)> manual page.");
3143
3144   ("sh", (RString "output", [String "command"]), 111, [],
3145    [], (* XXX needs tests *)
3146    "run a command via the shell",
3147    "\
3148 This call runs a command from the guest filesystem via the
3149 guest's C</bin/sh>.
3150
3151 This is like C<guestfs_command>, but passes the command to:
3152
3153  /bin/sh -c \"command\"
3154
3155 Depending on the guest's shell, this usually results in
3156 wildcards being expanded, shell expressions being interpolated
3157 and so on.
3158
3159 All the provisos about C<guestfs_command> apply to this call.");
3160
3161   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
3162    [], (* XXX needs tests *)
3163    "run a command via the shell returning lines",
3164    "\
3165 This is the same as C<guestfs_sh>, but splits the result
3166 into a list of lines.
3167
3168 See also: C<guestfs_command_lines>");
3169
3170   ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
3171    (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
3172     * code in stubs.c, since all valid glob patterns must start with "/".
3173     * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
3174     *)
3175    [InitBasicFS, Always, TestOutputList (
3176       [["mkdir_p"; "/a/b/c"];
3177        ["touch"; "/a/b/c/d"];
3178        ["touch"; "/a/b/c/e"];
3179        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3180     InitBasicFS, Always, TestOutputList (
3181       [["mkdir_p"; "/a/b/c"];
3182        ["touch"; "/a/b/c/d"];
3183        ["touch"; "/a/b/c/e"];
3184        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3185     InitBasicFS, Always, TestOutputList (
3186       [["mkdir_p"; "/a/b/c"];
3187        ["touch"; "/a/b/c/d"];
3188        ["touch"; "/a/b/c/e"];
3189        ["glob_expand"; "/a/*/x/*"]], [])],
3190    "expand a wildcard path",
3191    "\
3192 This command searches for all the pathnames matching
3193 C<pattern> according to the wildcard expansion rules
3194 used by the shell.
3195
3196 If no paths match, then this returns an empty list
3197 (note: not an error).
3198
3199 It is just a wrapper around the C L<glob(3)> function
3200 with flags C<GLOB_MARK|GLOB_BRACE>.
3201 See that manual page for more details.");
3202
3203   ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
3204    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
3205       [["scrub_device"; "/dev/sdc"]])],
3206    "scrub (securely wipe) a device",
3207    "\
3208 This command writes patterns over C<device> to make data retrieval
3209 more difficult.
3210
3211 It is an interface to the L<scrub(1)> program.  See that
3212 manual page for more details.");
3213
3214   ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
3215    [InitBasicFS, Always, TestRun (
3216       [["write"; "/file"; "content"];
3217        ["scrub_file"; "/file"]])],
3218    "scrub (securely wipe) a file",
3219    "\
3220 This command writes patterns over a file to make data retrieval
3221 more difficult.
3222
3223 The file is I<removed> after scrubbing.
3224
3225 It is an interface to the L<scrub(1)> program.  See that
3226 manual page for more details.");
3227
3228   ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
3229    [], (* XXX needs testing *)
3230    "scrub (securely wipe) free space",
3231    "\
3232 This command creates the directory C<dir> and then fills it
3233 with files until the filesystem is full, and scrubs the files
3234 as for C<guestfs_scrub_file>, and deletes them.
3235 The intention is to scrub any free space on the partition
3236 containing C<dir>.
3237
3238 It is an interface to the L<scrub(1)> program.  See that
3239 manual page for more details.");
3240
3241   ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
3242    [InitBasicFS, Always, TestRun (
3243       [["mkdir"; "/tmp"];
3244        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
3245    "create a temporary directory",
3246    "\
3247 This command creates a temporary directory.  The
3248 C<template> parameter should be a full pathname for the
3249 temporary directory name with the final six characters being
3250 \"XXXXXX\".
3251
3252 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
3253 the second one being suitable for Windows filesystems.
3254
3255 The name of the temporary directory that was created
3256 is returned.
3257
3258 The temporary directory is created with mode 0700
3259 and is owned by root.
3260
3261 The caller is responsible for deleting the temporary
3262 directory and its contents after use.
3263
3264 See also: L<mkdtemp(3)>");
3265
3266   ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
3267    [InitISOFS, Always, TestOutputInt (
3268       [["wc_l"; "/10klines"]], 10000);
3269     (* Test for RHBZ#579608, absolute symbolic links. *)
3270     InitISOFS, Always, TestOutputInt (
3271       [["wc_l"; "/abssymlink"]], 10000)],
3272    "count lines in a file",
3273    "\
3274 This command counts the lines in a file, using the
3275 C<wc -l> external command.");
3276
3277   ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
3278    [InitISOFS, Always, TestOutputInt (
3279       [["wc_w"; "/10klines"]], 10000)],
3280    "count words in a file",
3281    "\
3282 This command counts the words in a file, using the
3283 C<wc -w> external command.");
3284
3285   ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
3286    [InitISOFS, Always, TestOutputInt (
3287       [["wc_c"; "/100kallspaces"]], 102400)],
3288    "count characters in a file",
3289    "\
3290 This command counts the characters in a file, using the
3291 C<wc -c> external command.");
3292
3293   ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
3294    [InitISOFS, Always, TestOutputList (
3295       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"]);
3296     (* Test for RHBZ#579608, absolute symbolic links. *)
3297     InitISOFS, Always, TestOutputList (
3298       [["head"; "/abssymlink"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
3299    "return first 10 lines of a file",
3300    "\
3301 This command returns up to the first 10 lines of a file as
3302 a list of strings.");
3303
3304   ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
3305    [InitISOFS, Always, TestOutputList (
3306       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3307     InitISOFS, Always, TestOutputList (
3308       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3309     InitISOFS, Always, TestOutputList (
3310       [["head_n"; "0"; "/10klines"]], [])],
3311    "return first N lines of a file",
3312    "\
3313 If the parameter C<nrlines> is a positive number, this returns the first
3314 C<nrlines> lines of the file C<path>.
3315
3316 If the parameter C<nrlines> is a negative number, this returns lines
3317 from the file C<path>, excluding the last C<nrlines> lines.
3318
3319 If the parameter C<nrlines> is zero, this returns an empty list.");
3320
3321   ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
3322    [InitISOFS, Always, TestOutputList (
3323       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
3324    "return last 10 lines of a file",
3325    "\
3326 This command returns up to the last 10 lines of a file as
3327 a list of strings.");
3328
3329   ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
3330    [InitISOFS, Always, TestOutputList (
3331       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3332     InitISOFS, Always, TestOutputList (
3333       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3334     InitISOFS, Always, TestOutputList (
3335       [["tail_n"; "0"; "/10klines"]], [])],
3336    "return last N lines of a file",
3337    "\
3338 If the parameter C<nrlines> is a positive number, this returns the last
3339 C<nrlines> lines of the file C<path>.
3340
3341 If the parameter C<nrlines> is a negative number, this returns lines
3342 from the file C<path>, starting with the C<-nrlines>th line.
3343
3344 If the parameter C<nrlines> is zero, this returns an empty list.");
3345
3346   ("df", (RString "output", []), 125, [],
3347    [], (* XXX Tricky to test because it depends on the exact format
3348         * of the 'df' command and other imponderables.
3349         *)
3350    "report file system disk space usage",
3351    "\
3352 This command runs the C<df> command to report disk space used.
3353
3354 This command is mostly useful for interactive sessions.  It
3355 is I<not> intended that you try to parse the output string.
3356 Use C<statvfs> from programs.");
3357
3358   ("df_h", (RString "output", []), 126, [],
3359    [], (* XXX Tricky to test because it depends on the exact format
3360         * of the 'df' command and other imponderables.
3361         *)
3362    "report file system disk space usage (human readable)",
3363    "\
3364 This command runs the C<df -h> command to report disk space used
3365 in human-readable format.
3366
3367 This command is mostly useful for interactive sessions.  It
3368 is I<not> intended that you try to parse the output string.
3369 Use C<statvfs> from programs.");
3370
3371   ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
3372    [InitISOFS, Always, TestOutputInt (
3373       [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
3374    "estimate file space usage",
3375    "\
3376 This command runs the C<du -s> command to estimate file space
3377 usage for C<path>.
3378
3379 C<path> can be a file or a directory.  If C<path> is a directory
3380 then the estimate includes the contents of the directory and all
3381 subdirectories (recursively).
3382
3383 The result is the estimated size in I<kilobytes>
3384 (ie. units of 1024 bytes).");
3385
3386   ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
3387    [InitISOFS, Always, TestOutputList (
3388       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
3389    "list files in an initrd",
3390    "\
3391 This command lists out files contained in an initrd.
3392
3393 The files are listed without any initial C</> character.  The
3394 files are listed in the order they appear (not necessarily
3395 alphabetical).  Directory names are listed as separate items.
3396
3397 Old Linux kernels (2.4 and earlier) used a compressed ext2
3398 filesystem as initrd.  We I<only> support the newer initramfs
3399 format (compressed cpio files).");
3400
3401   ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
3402    [],
3403    "mount a file using the loop device",
3404    "\
3405 This command lets you mount C<file> (a filesystem image
3406 in a file) on a mount point.  It is entirely equivalent to
3407 the command C<mount -o loop file mountpoint>.");
3408
3409   ("mkswap", (RErr, [Device "device"]), 130, [],
3410    [InitEmpty, Always, TestRun (
3411       [["part_disk"; "/dev/sda"; "mbr"];
3412        ["mkswap"; "/dev/sda1"]])],
3413    "create a swap partition",
3414    "\
3415 Create a swap partition on C<device>.");
3416
3417   ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
3418    [InitEmpty, Always, TestRun (
3419       [["part_disk"; "/dev/sda"; "mbr"];
3420        ["mkswap_L"; "hello"; "/dev/sda1"]])],
3421    "create a swap partition with a label",
3422    "\
3423 Create a swap partition on C<device> with label C<label>.
3424
3425 Note that you cannot attach a swap label to a block device
3426 (eg. C</dev/sda>), just to a partition.  This appears to be
3427 a limitation of the kernel or swap tools.");
3428
3429   ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
3430    (let uuid = uuidgen () in
3431     [InitEmpty, Always, TestRun (
3432        [["part_disk"; "/dev/sda"; "mbr"];
3433         ["mkswap_U"; uuid; "/dev/sda1"]])]),
3434    "create a swap partition with an explicit UUID",
3435    "\
3436 Create a swap partition on C<device> with UUID C<uuid>.");
3437
3438   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
3439    [InitBasicFS, Always, TestOutputStruct (
3440       [["mknod"; "0o10777"; "0"; "0"; "/node"];
3441        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
3442        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
3443     InitBasicFS, Always, TestOutputStruct (
3444       [["mknod"; "0o60777"; "66"; "99"; "/node"];
3445        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3446    "make block, character or FIFO devices",
3447    "\
3448 This call creates block or character special devices, or
3449 named pipes (FIFOs).
3450
3451 The C<mode> parameter should be the mode, using the standard
3452 constants.  C<devmajor> and C<devminor> are the
3453 device major and minor numbers, only used when creating block
3454 and character special devices.
3455
3456 Note that, just like L<mknod(2)>, the mode must be bitwise
3457 OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
3458 just creates a regular file).  These constants are
3459 available in the standard Linux header files, or you can use
3460 C<guestfs_mknod_b>, C<guestfs_mknod_c> or C<guestfs_mkfifo>
3461 which are wrappers around this command which bitwise OR
3462 in the appropriate constant for you.
3463
3464 The mode actually set is affected by the umask.");
3465
3466   ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
3467    [InitBasicFS, Always, TestOutputStruct (
3468       [["mkfifo"; "0o777"; "/node"];
3469        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
3470    "make FIFO (named pipe)",
3471    "\
3472 This call creates a FIFO (named pipe) called C<path> with
3473 mode C<mode>.  It is just a convenient wrapper around
3474 C<guestfs_mknod>.
3475
3476 The mode actually set is affected by the umask.");
3477
3478   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
3479    [InitBasicFS, Always, TestOutputStruct (
3480       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
3481        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3482    "make block device node",
3483    "\
3484 This call creates a block device node called C<path> with
3485 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3486 It is just a convenient wrapper around C<guestfs_mknod>.
3487
3488 The mode actually set is affected by the umask.");
3489
3490   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
3491    [InitBasicFS, Always, TestOutputStruct (
3492       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
3493        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
3494    "make char device node",
3495    "\
3496 This call creates a char device node called C<path> with
3497 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3498 It is just a convenient wrapper around C<guestfs_mknod>.
3499
3500 The mode actually set is affected by the umask.");
3501
3502   ("umask", (RInt "oldmask", [Int "mask"]), 137, [FishOutput FishOutputOctal],
3503    [InitEmpty, Always, TestOutputInt (
3504       [["umask"; "0o22"]], 0o22)],
3505    "set file mode creation mask (umask)",
3506    "\
3507 This function sets the mask used for creating new files and
3508 device nodes to C<mask & 0777>.
3509
3510 Typical umask values would be C<022> which creates new files
3511 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3512 C<002> which creates new files with permissions like
3513 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3514
3515 The default umask is C<022>.  This is important because it
3516 means that directories and device nodes will be created with
3517 C<0644> or C<0755> mode even if you specify C<0777>.
3518
3519 See also C<guestfs_get_umask>,
3520 L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3521
3522 This call returns the previous umask.");
3523
3524   ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3525    [],
3526    "read directories entries",
3527    "\
3528 This returns the list of directory entries in directory C<dir>.
3529
3530 All entries in the directory are returned, including C<.> and
3531 C<..>.  The entries are I<not> sorted, but returned in the same
3532 order as the underlying filesystem.
3533
3534 Also this call returns basic file type information about each
3535 file.  The C<ftyp> field will contain one of the following characters:
3536
3537 =over 4
3538
3539 =item 'b'
3540
3541 Block special
3542
3543 =item 'c'
3544
3545 Char special
3546
3547 =item 'd'
3548
3549 Directory
3550
3551 =item 'f'
3552
3553 FIFO (named pipe)
3554
3555 =item 'l'
3556
3557 Symbolic link
3558
3559 =item 'r'
3560
3561 Regular file
3562
3563 =item 's'
3564
3565 Socket
3566
3567 =item 'u'
3568
3569 Unknown file type
3570
3571 =item '?'
3572
3573 The L<readdir(3)> call returned a C<d_type> field with an
3574 unexpected value
3575
3576 =back
3577
3578 This function is primarily intended for use by programs.  To
3579 get a simple list of names, use C<guestfs_ls>.  To get a printable
3580 directory for human consumption, use C<guestfs_ll>.");
3581
3582   ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3583    [],
3584    "create partitions on a block device",
3585    "\
3586 This is a simplified interface to the C<guestfs_sfdisk>
3587 command, where partition sizes are specified in megabytes
3588 only (rounded to the nearest cylinder) and you don't need
3589 to specify the cyls, heads and sectors parameters which
3590 were rarely if ever used anyway.
3591
3592 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3593 and C<guestfs_part_disk>");
3594
3595   ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3596    [],
3597    "determine file type inside a compressed file",
3598    "\
3599 This command runs C<file> after first decompressing C<path>
3600 using C<method>.
3601
3602 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3603
3604 Since 1.0.63, use C<guestfs_file> instead which can now
3605 process compressed files.");
3606
3607   ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3608    [],
3609    "list extended attributes of a file or directory",
3610    "\
3611 This call lists the extended attributes of the file or directory
3612 C<path>.
3613
3614 At the system call level, this is a combination of the
3615 L<listxattr(2)> and L<getxattr(2)> calls.
3616
3617 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3618
3619   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3620    [],
3621    "list extended attributes of a file or directory",
3622    "\
3623 This is the same as C<guestfs_getxattrs>, but if C<path>
3624 is a symbolic link, then it returns the extended attributes
3625 of the link itself.");
3626
3627   ("setxattr", (RErr, [String "xattr";
3628                        String "val"; Int "vallen"; (* will be BufferIn *)
3629                        Pathname "path"]), 143, [Optional "linuxxattrs"],
3630    [],
3631    "set extended attribute of a file or directory",
3632    "\
3633 This call sets the extended attribute named C<xattr>
3634 of the file C<path> to the value C<val> (of length C<vallen>).
3635 The value is arbitrary 8 bit data.
3636
3637 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3638
3639   ("lsetxattr", (RErr, [String "xattr";
3640                         String "val"; Int "vallen"; (* will be BufferIn *)
3641                         Pathname "path"]), 144, [Optional "linuxxattrs"],
3642    [],
3643    "set extended attribute of a file or directory",
3644    "\
3645 This is the same as C<guestfs_setxattr>, but if C<path>
3646 is a symbolic link, then it sets an extended attribute
3647 of the link itself.");
3648
3649   ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3650    [],
3651    "remove extended attribute of a file or directory",
3652    "\
3653 This call removes the extended attribute named C<xattr>
3654 of the file C<path>.
3655
3656 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3657
3658   ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3659    [],
3660    "remove extended attribute of a file or directory",
3661    "\
3662 This is the same as C<guestfs_removexattr>, but if C<path>
3663 is a symbolic link, then it removes an extended attribute
3664 of the link itself.");
3665
3666   ("mountpoints", (RHashtable "mps", []), 147, [],
3667    [],
3668    "show mountpoints",
3669    "\
3670 This call is similar to C<guestfs_mounts>.  That call returns
3671 a list of devices.  This one returns a hash table (map) of
3672 device name to directory where the device is mounted.");
3673
3674   ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3675    (* This is a special case: while you would expect a parameter
3676     * of type "Pathname", that doesn't work, because it implies
3677     * NEED_ROOT in the generated calling code in stubs.c, and
3678     * this function cannot use NEED_ROOT.
3679     *)
3680    [],
3681    "create a mountpoint",
3682    "\
3683 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3684 specialized calls that can be used to create extra mountpoints
3685 before mounting the first filesystem.
3686
3687 These calls are I<only> necessary in some very limited circumstances,
3688 mainly the case where you want to mount a mix of unrelated and/or
3689 read-only filesystems together.
3690
3691 For example, live CDs often contain a \"Russian doll\" nest of
3692 filesystems, an ISO outer layer, with a squashfs image inside, with
3693 an ext2/3 image inside that.  You can unpack this as follows
3694 in guestfish:
3695
3696  add-ro Fedora-11-i686-Live.iso
3697  run
3698  mkmountpoint /cd
3699  mkmountpoint /squash
3700  mkmountpoint /ext3
3701  mount /dev/sda /cd
3702  mount-loop /cd/LiveOS/squashfs.img /squash
3703  mount-loop /squash/LiveOS/ext3fs.img /ext3
3704
3705 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3706
3707   ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3708    [],
3709    "remove a mountpoint",
3710    "\
3711 This calls removes a mountpoint that was previously created
3712 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3713 for full details.");
3714
3715   ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3716    [InitISOFS, Always, TestOutputBuffer (
3717       [["read_file"; "/known-4"]], "abc\ndef\nghi");
3718     (* Test various near large, large and too large files (RHBZ#589039). *)
3719     InitBasicFS, Always, TestLastFail (
3720       [["touch"; "/a"];
3721        ["truncate_size"; "/a"; "4194303"]; (* GUESTFS_MESSAGE_MAX - 1 *)
3722        ["read_file"; "/a"]]);
3723     InitBasicFS, Always, TestLastFail (
3724       [["touch"; "/a"];
3725        ["truncate_size"; "/a"; "4194304"]; (* GUESTFS_MESSAGE_MAX *)
3726        ["read_file"; "/a"]]);
3727     InitBasicFS, Always, TestLastFail (
3728       [["touch"; "/a"];
3729        ["truncate_size"; "/a"; "41943040"]; (* GUESTFS_MESSAGE_MAX * 10 *)
3730        ["read_file"; "/a"]])],
3731    "read a file",
3732    "\
3733 This calls returns the contents of the file C<path> as a
3734 buffer.
3735
3736 Unlike C<guestfs_cat>, this function can correctly
3737 handle files that contain embedded ASCII NUL characters.
3738 However unlike C<guestfs_download>, this function is limited
3739 in the total size of file that can be handled.");
3740
3741   ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3742    [InitISOFS, Always, TestOutputList (
3743       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3744     InitISOFS, Always, TestOutputList (
3745       [["grep"; "nomatch"; "/test-grep.txt"]], []);
3746     (* Test for RHBZ#579608, absolute symbolic links. *)
3747     InitISOFS, Always, TestOutputList (
3748       [["grep"; "nomatch"; "/abssymlink"]], [])],
3749    "return lines matching a pattern",
3750    "\
3751 This calls the external C<grep> program and returns the
3752 matching lines.");
3753
3754   ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3755    [InitISOFS, Always, TestOutputList (
3756       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3757    "return lines matching a pattern",
3758    "\
3759 This calls the external C<egrep> program and returns the
3760 matching lines.");
3761
3762   ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3763    [InitISOFS, Always, TestOutputList (
3764       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3765    "return lines matching a pattern",
3766    "\
3767 This calls the external C<fgrep> program and returns the
3768 matching lines.");
3769
3770   ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3771    [InitISOFS, Always, TestOutputList (
3772       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3773    "return lines matching a pattern",
3774    "\
3775 This calls the external C<grep -i> program and returns the
3776 matching lines.");
3777
3778   ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3779    [InitISOFS, Always, TestOutputList (
3780       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3781    "return lines matching a pattern",
3782    "\
3783 This calls the external C<egrep -i> program and returns the
3784 matching lines.");
3785
3786   ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3787    [InitISOFS, Always, TestOutputList (
3788       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3789    "return lines matching a pattern",
3790    "\
3791 This calls the external C<fgrep -i> program and returns the
3792 matching lines.");
3793
3794   ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3795    [InitISOFS, Always, TestOutputList (
3796       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3797    "return lines matching a pattern",
3798    "\
3799 This calls the external C<zgrep> program and returns the
3800 matching lines.");
3801
3802   ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3803    [InitISOFS, Always, TestOutputList (
3804       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3805    "return lines matching a pattern",
3806    "\
3807 This calls the external C<zegrep> program and returns the
3808 matching lines.");
3809
3810   ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3811    [InitISOFS, Always, TestOutputList (
3812       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3813    "return lines matching a pattern",
3814    "\
3815 This calls the external C<zfgrep> program and returns the
3816 matching lines.");
3817
3818   ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3819    [InitISOFS, Always, TestOutputList (
3820       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3821    "return lines matching a pattern",
3822    "\
3823 This calls the external C<zgrep -i> program and returns the
3824 matching lines.");
3825
3826   ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3827    [InitISOFS, Always, TestOutputList (
3828       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3829    "return lines matching a pattern",
3830    "\
3831 This calls the external C<zegrep -i> program and returns the
3832 matching lines.");
3833
3834   ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3835    [InitISOFS, Always, TestOutputList (
3836       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3837    "return lines matching a pattern",
3838    "\
3839 This calls the external C<zfgrep -i> program and returns the
3840 matching lines.");
3841
3842   ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3843    [InitISOFS, Always, TestOutput (
3844       [["realpath"; "/../directory"]], "/directory")],
3845    "canonicalized absolute pathname",
3846    "\
3847 Return the canonicalized absolute pathname of C<path>.  The
3848 returned path has no C<.>, C<..> or symbolic link path elements.");
3849
3850   ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3851    [InitBasicFS, Always, TestOutputStruct (
3852       [["touch"; "/a"];
3853        ["ln"; "/a"; "/b"];
3854        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3855    "create a hard link",
3856    "\
3857 This command creates a hard link using the C<ln> command.");
3858
3859   ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3860    [InitBasicFS, Always, TestOutputStruct (
3861       [["touch"; "/a"];
3862        ["touch"; "/b"];
3863        ["ln_f"; "/a"; "/b"];
3864        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3865    "create a hard link",
3866    "\
3867 This command creates a hard link using the C<ln -f> command.
3868 The C<-f> option removes the link (C<linkname>) if it exists already.");
3869
3870   ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3871    [InitBasicFS, Always, TestOutputStruct (
3872       [["touch"; "/a"];
3873        ["ln_s"; "a"; "/b"];
3874        ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3875    "create a symbolic link",
3876    "\
3877 This command creates a symbolic link using the C<ln -s> command.");
3878
3879   ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3880    [InitBasicFS, Always, TestOutput (
3881       [["mkdir_p"; "/a/b"];
3882        ["touch"; "/a/b/c"];
3883        ["ln_sf"; "../d"; "/a/b/c"];
3884        ["readlink"; "/a/b/c"]], "../d")],
3885    "create a symbolic link",
3886    "\
3887 This command creates a symbolic link using the C<ln -sf> command,
3888 The C<-f> option removes the link (C<linkname>) if it exists already.");
3889
3890   ("readlink", (RString "link", [Pathname "path"]), 168, [],
3891    [] (* XXX tested above *),
3892    "read the target of a symbolic link",
3893    "\
3894 This command reads the target of a symbolic link.");
3895
3896   ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [DeprecatedBy "fallocate64"],
3897    [InitBasicFS, Always, TestOutputStruct (
3898       [["fallocate"; "/a"; "1000000"];
3899        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3900    "preallocate a file in the guest filesystem",
3901    "\
3902 This command preallocates a file (containing zero bytes) named
3903 C<path> of size C<len> bytes.  If the file exists already, it
3904 is overwritten.
3905
3906 Do not confuse this with the guestfish-specific
3907 C<alloc> command which allocates a file in the host and
3908 attaches it as a device.");
3909
3910   ("swapon_device", (RErr, [Device "device"]), 170, [],
3911    [InitPartition, Always, TestRun (
3912       [["mkswap"; "/dev/sda1"];
3913        ["swapon_device"; "/dev/sda1"];
3914        ["swapoff_device"; "/dev/sda1"]])],
3915    "enable swap on device",
3916    "\
3917 This command enables the libguestfs appliance to use the
3918 swap device or partition named C<device>.  The increased
3919 memory is made available for all commands, for example
3920 those run using C<guestfs_command> or C<guestfs_sh>.
3921
3922 Note that you should not swap to existing guest swap
3923 partitions unless you know what you are doing.  They may
3924 contain hibernation information, or other information that
3925 the guest doesn't want you to trash.  You also risk leaking
3926 information about the host to the guest this way.  Instead,
3927 attach a new host device to the guest and swap on that.");
3928
3929   ("swapoff_device", (RErr, [Device "device"]), 171, [],
3930    [], (* XXX tested by swapon_device *)
3931    "disable swap on device",
3932    "\
3933 This command disables the libguestfs appliance swap
3934 device or partition named C<device>.
3935 See C<guestfs_swapon_device>.");
3936
3937   ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3938    [InitBasicFS, Always, TestRun (
3939       [["fallocate"; "/swap"; "8388608"];
3940        ["mkswap_file"; "/swap"];
3941        ["swapon_file"; "/swap"];
3942        ["swapoff_file"; "/swap"]])],
3943    "enable swap on file",
3944    "\
3945 This command enables swap to a file.
3946 See C<guestfs_swapon_device> for other notes.");
3947
3948   ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3949    [], (* XXX tested by swapon_file *)
3950    "disable swap on file",
3951    "\
3952 This command disables the libguestfs appliance swap on file.");
3953
3954   ("swapon_label", (RErr, [String "label"]), 174, [],
3955    [InitEmpty, Always, TestRun (
3956       [["part_disk"; "/dev/sdb"; "mbr"];
3957        ["mkswap_L"; "swapit"; "/dev/sdb1"];
3958        ["swapon_label"; "swapit"];
3959        ["swapoff_label"; "swapit"];
3960        ["zero"; "/dev/sdb"];
3961        ["blockdev_rereadpt"; "/dev/sdb"]])],
3962    "enable swap on labeled swap partition",
3963    "\
3964 This command enables swap to a labeled swap partition.
3965 See C<guestfs_swapon_device> for other notes.");
3966
3967   ("swapoff_label", (RErr, [String "label"]), 175, [],
3968    [], (* XXX tested by swapon_label *)
3969    "disable swap on labeled swap partition",
3970    "\
3971 This command disables the libguestfs appliance swap on
3972 labeled swap partition.");
3973
3974   ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3975    (let uuid = uuidgen () in
3976     [InitEmpty, Always, TestRun (
3977        [["mkswap_U"; uuid; "/dev/sdb"];
3978         ["swapon_uuid"; uuid];
3979         ["swapoff_uuid"; uuid]])]),
3980    "enable swap on swap partition by UUID",
3981    "\
3982 This command enables swap to a swap partition with the given UUID.
3983 See C<guestfs_swapon_device> for other notes.");
3984
3985   ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3986    [], (* XXX tested by swapon_uuid *)
3987    "disable swap on swap partition by UUID",
3988    "\
3989 This command disables the libguestfs appliance swap partition
3990 with the given UUID.");
3991
3992   ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3993    [InitBasicFS, Always, TestRun (
3994       [["fallocate"; "/swap"; "8388608"];
3995        ["mkswap_file"; "/swap"]])],
3996    "create a swap file",
3997    "\
3998 Create a swap file.
3999
4000 This command just writes a swap file signature to an existing
4001 file.  To create the file itself, use something like C<guestfs_fallocate>.");
4002
4003   ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
4004    [InitISOFS, Always, TestRun (
4005       [["inotify_init"; "0"]])],
4006    "create an inotify handle",
4007    "\
4008 This command creates a new inotify handle.
4009 The inotify subsystem can be used to notify events which happen to
4010 objects in the guest filesystem.
4011
4012 C<maxevents> is the maximum number of events which will be
4013 queued up between calls to C<guestfs_inotify_read> or
4014 C<guestfs_inotify_files>.
4015 If this is passed as C<0>, then the kernel (or previously set)
4016 default is used.  For Linux 2.6.29 the default was 16384 events.
4017 Beyond this limit, the kernel throws away events, but records
4018 the fact that it threw them away by setting a flag
4019 C<IN_Q_OVERFLOW> in the returned structure list (see
4020 C<guestfs_inotify_read>).
4021
4022 Before any events are generated, you have to add some
4023 watches to the internal watch list.  See:
4024 C<guestfs_inotify_add_watch>,
4025 C<guestfs_inotify_rm_watch> and
4026 C<guestfs_inotify_watch_all>.
4027
4028 Queued up events should be read periodically by calling
4029 C<guestfs_inotify_read>
4030 (or C<guestfs_inotify_files> which is just a helpful
4031 wrapper around C<guestfs_inotify_read>).  If you don't
4032 read the events out often enough then you risk the internal
4033 queue overflowing.
4034
4035 The handle should be closed after use by calling
4036 C<guestfs_inotify_close>.  This also removes any
4037 watches automatically.
4038
4039 See also L<inotify(7)> for an overview of the inotify interface
4040 as exposed by the Linux kernel, which is roughly what we expose
4041 via libguestfs.  Note that there is one global inotify handle
4042 per libguestfs instance.");
4043
4044   ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
4045    [InitBasicFS, Always, TestOutputList (
4046       [["inotify_init"; "0"];
4047        ["inotify_add_watch"; "/"; "1073741823"];
4048        ["touch"; "/a"];
4049        ["touch"; "/b"];
4050        ["inotify_files"]], ["a"; "b"])],
4051    "add an inotify watch",
4052    "\
4053 Watch C<path> for the events listed in C<mask>.
4054
4055 Note that if C<path> is a directory then events within that
4056 directory are watched, but this does I<not> happen recursively
4057 (in subdirectories).
4058
4059 Note for non-C or non-Linux callers: the inotify events are
4060 defined by the Linux kernel ABI and are listed in
4061 C</usr/include/sys/inotify.h>.");
4062
4063   ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
4064    [],
4065    "remove an inotify watch",
4066    "\
4067 Remove a previously defined inotify watch.
4068 See C<guestfs_inotify_add_watch>.");
4069
4070   ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
4071    [],
4072    "return list of inotify events",
4073    "\
4074 Return the complete queue of events that have happened
4075 since the previous read call.
4076
4077 If no events have happened, this returns an empty list.
4078
4079 I<Note>: In order to make sure that all events have been
4080 read, you must call this function repeatedly until it
4081 returns an empty list.  The reason is that the call will
4082 read events up to the maximum appliance-to-host message
4083 size and leave remaining events in the queue.");
4084
4085   ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
4086    [],
4087    "return list of watched files that had events",
4088    "\
4089 This function is a helpful wrapper around C<guestfs_inotify_read>
4090 which just returns a list of pathnames of objects that were
4091 touched.  The returned pathnames are sorted and deduplicated.");
4092
4093   ("inotify_close", (RErr, []), 184, [Optional "inotify"],
4094    [],
4095    "close the inotify handle",
4096    "\
4097 This closes the inotify handle which was previously
4098 opened by inotify_init.  It removes all watches, throws
4099 away any pending events, and deallocates all resources.");
4100
4101   ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
4102    [],
4103    "set SELinux security context",
4104    "\
4105 This sets the SELinux security context of the daemon
4106 to the string C<context>.
4107
4108 See the documentation about SELINUX in L<guestfs(3)>.");
4109
4110   ("getcon", (RString "context", []), 186, [Optional "selinux"],
4111    [],
4112    "get SELinux security context",
4113    "\
4114 This gets the SELinux security context of the daemon.
4115
4116 See the documentation about SELINUX in L<guestfs(3)>,
4117 and C<guestfs_setcon>");
4118
4119   ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
4120    [InitEmpty, Always, TestOutput (
4121       [["part_disk"; "/dev/sda"; "mbr"];
4122        ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
4123        ["mount_options"; ""; "/dev/sda1"; "/"];
4124        ["write"; "/new"; "new file contents"];
4125        ["cat"; "/new"]], "new file contents");
4126     InitEmpty, Always, TestRun (
4127       [["part_disk"; "/dev/sda"; "mbr"];
4128        ["mkfs_b"; "vfat"; "32768"; "/dev/sda1"]]);
4129     InitEmpty, Always, TestLastFail (
4130       [["part_disk"; "/dev/sda"; "mbr"];
4131        ["mkfs_b"; "vfat"; "32769"; "/dev/sda1"]]);
4132     InitEmpty, Always, TestLastFail (
4133       [["part_disk"; "/dev/sda"; "mbr"];
4134        ["mkfs_b"; "vfat"; "33280"; "/dev/sda1"]]);
4135     InitEmpty, IfAvailable "ntfsprogs", TestRun (
4136       [["part_disk"; "/dev/sda"; "mbr"];
4137        ["mkfs_b"; "ntfs"; "32768"; "/dev/sda1"]])],
4138    "make a filesystem with block size",
4139    "\
4140 This call is similar to C<guestfs_mkfs>, but it allows you to
4141 control the block size of the resulting filesystem.  Supported
4142 block sizes depend on the filesystem type, but typically they
4143 are C<1024>, C<2048> or C<4096> only.
4144
4145 For VFAT and NTFS the C<blocksize> parameter is treated as
4146 the requested cluster size.");
4147
4148   ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
4149    [InitEmpty, Always, TestOutput (
4150       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4151        ["mke2journal"; "4096"; "/dev/sda1"];
4152        ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
4153        ["mount_options"; ""; "/dev/sda2"; "/"];
4154        ["write"; "/new"; "new file contents"];
4155        ["cat"; "/new"]], "new file contents")],
4156    "make ext2/3/4 external journal",
4157    "\
4158 This creates an ext2 external journal on C<device>.  It is equivalent
4159 to the command:
4160
4161  mke2fs -O journal_dev -b blocksize device");
4162
4163   ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
4164    [InitEmpty, Always, TestOutput (
4165       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4166        ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
4167        ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
4168        ["mount_options"; ""; "/dev/sda2"; "/"];
4169        ["write"; "/new"; "new file contents"];
4170        ["cat"; "/new"]], "new file contents")],
4171    "make ext2/3/4 external journal with label",
4172    "\
4173 This creates an ext2 external journal on C<device> with label C<label>.");
4174
4175   ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
4176    (let uuid = uuidgen () in
4177     [InitEmpty, Always, TestOutput (
4178        [["sfdiskM"; "/dev/sda"; ",100 ,"];
4179         ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
4180         ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
4181         ["mount_options"; ""; "/dev/sda2"; "/"];
4182         ["write"; "/new"; "new file contents"];
4183         ["cat"; "/new"]], "new file contents")]),
4184    "make ext2/3/4 external journal with UUID",
4185    "\
4186 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
4187
4188   ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
4189    [],
4190    "make ext2/3/4 filesystem with external journal",
4191    "\
4192 This creates an ext2/3/4 filesystem on C<device> with
4193 an external journal on C<journal>.  It is equivalent
4194 to the command:
4195
4196  mke2fs -t fstype -b blocksize -J device=<journal> <device>
4197
4198 See also C<guestfs_mke2journal>.");
4199
4200   ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
4201    [],
4202    "make ext2/3/4 filesystem with external journal",
4203    "\
4204 This creates an ext2/3/4 filesystem on C<device> with
4205 an external journal on the journal labeled C<label>.
4206
4207 See also C<guestfs_mke2journal_L>.");
4208
4209   ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
4210    [],
4211    "make ext2/3/4 filesystem with external journal",
4212    "\
4213 This creates an ext2/3/4 filesystem on C<device> with
4214 an external journal on the journal with UUID C<uuid>.
4215
4216 See also C<guestfs_mke2journal_U>.");
4217
4218   ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
4219    [InitNone, Always, TestRun [["modprobe"; "fat"]]],
4220    "load a kernel module",
4221    "\
4222 This loads a kernel module in the appliance.
4223
4224 The kernel module must have been whitelisted when libguestfs
4225 was built (see C<appliance/kmod.whitelist.in> in the source).");
4226
4227   ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
4228    [InitNone, Always, TestOutput (
4229       [["echo_daemon"; "This is a test"]], "This is a test"
4230     )],
4231    "echo arguments back to the client",
4232    "\
4233 This command concatenates the list of C<words> passed with single spaces
4234 between them and returns the resulting string.
4235
4236 You can use this command to test the connection through to the daemon.
4237
4238 See also C<guestfs_ping_daemon>.");
4239
4240   ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
4241    [], (* There is a regression test for this. *)
4242    "find all files and directories, returning NUL-separated list",
4243    "\
4244 This command lists out all files and directories, recursively,
4245 starting at C<directory>, placing the resulting list in the
4246 external file called C<files>.
4247
4248 This command works the same way as C<guestfs_find> with the
4249 following exceptions:
4250
4251 =over 4
4252
4253 =item *
4254
4255 The resulting list is written to an external file.
4256
4257 =item *
4258
4259 Items (filenames) in the result are separated
4260 by C<\\0> characters.  See L<find(1)> option I<-print0>.
4261
4262 =item *
4263
4264 This command is not limited in the number of names that it
4265 can return.
4266
4267 =item *
4268
4269 The result list is not sorted.
4270
4271 =back");
4272
4273   ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
4274    [InitISOFS, Always, TestOutput (
4275       [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
4276     InitISOFS, Always, TestOutput (
4277       [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
4278     InitISOFS, Always, TestOutput (
4279       [["case_sensitive_path"; "/Known-1"]], "/known-1");
4280     InitISOFS, Always, TestLastFail (
4281       [["case_sensitive_path"; "/Known-1/"]]);
4282     InitBasicFS, Always, TestOutput (
4283       [["mkdir"; "/a"];
4284        ["mkdir"; "/a/bbb"];
4285        ["touch"; "/a/bbb/c"];
4286        ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
4287     InitBasicFS, Always, TestOutput (
4288       [["mkdir"; "/a"];
4289        ["mkdir"; "/a/bbb"];
4290        ["touch"; "/a/bbb/c"];
4291        ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
4292     InitBasicFS, Always, TestLastFail (
4293       [["mkdir"; "/a"];
4294        ["mkdir"; "/a/bbb"];
4295        ["touch"; "/a/bbb/c"];
4296        ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
4297    "return true path on case-insensitive filesystem",
4298    "\
4299 This can be used to resolve case insensitive paths on
4300 a filesystem which is case sensitive.  The use case is
4301 to resolve paths which you have read from Windows configuration
4302 files or the Windows Registry, to the true path.
4303
4304 The command handles a peculiarity of the Linux ntfs-3g
4305 filesystem driver (and probably others), which is that although
4306 the underlying filesystem is case-insensitive, the driver
4307 exports the filesystem to Linux as case-sensitive.
4308
4309 One consequence of this is that special directories such
4310 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
4311 (or other things) depending on the precise details of how
4312 they were created.  In Windows itself this would not be
4313 a problem.
4314
4315 Bug or feature?  You decide:
4316 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
4317
4318 This function resolves the true case of each element in the
4319 path and returns the case-sensitive path.
4320
4321 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
4322 might return C<\"/WINDOWS/system32\"> (the exact return value
4323 would depend on details of how the directories were originally
4324 created under Windows).
4325
4326 I<Note>:
4327 This function does not handle drive names, backslashes etc.
4328
4329 See also C<guestfs_realpath>.");
4330
4331   ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
4332    [InitBasicFS, Always, TestOutput (
4333       [["vfs_type"; "/dev/sda1"]], "ext2")],
4334    "get the Linux VFS type corresponding to a mounted device",
4335    "\
4336 This command gets the filesystem type corresponding to
4337 the filesystem on C<device>.
4338
4339 For most filesystems, the result is the name of the Linux
4340 VFS module which would be used to mount this filesystem
4341 if you mounted it without specifying the filesystem type.
4342 For example a string such as C<ext3> or C<ntfs>.");
4343
4344   ("truncate", (RErr, [Pathname "path"]), 199, [],
4345    [InitBasicFS, Always, TestOutputStruct (
4346       [["write"; "/test"; "some stuff so size is not zero"];
4347        ["truncate"; "/test"];
4348        ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
4349    "truncate a file to zero size",
4350    "\
4351 This command truncates C<path> to a zero-length file.  The
4352 file must exist already.");
4353
4354   ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
4355    [InitBasicFS, Always, TestOutputStruct (
4356       [["touch"; "/test"];
4357        ["truncate_size"; "/test"; "1000"];
4358        ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
4359    "truncate a file to a particular size",
4360    "\
4361 This command truncates C<path> to size C<size> bytes.  The file
4362 must exist already.
4363
4364 If the current file size is less than C<size> then
4365 the file is extended to the required size with zero bytes.
4366 This creates a sparse file (ie. disk blocks are not allocated
4367 for the file until you write to it).  To create a non-sparse
4368 file of zeroes, use C<guestfs_fallocate64> instead.");
4369
4370   ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
4371    [InitBasicFS, Always, TestOutputStruct (
4372       [["touch"; "/test"];
4373        ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
4374        ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
4375    "set timestamp of a file with nanosecond precision",
4376    "\
4377 This command sets the timestamps of a file with nanosecond
4378 precision.
4379
4380 C<atsecs, atnsecs> are the last access time (atime) in secs and
4381 nanoseconds from the epoch.
4382
4383 C<mtsecs, mtnsecs> are the last modification time (mtime) in
4384 secs and nanoseconds from the epoch.
4385
4386 If the C<*nsecs> field contains the special value C<-1> then
4387 the corresponding timestamp is set to the current time.  (The
4388 C<*secs> field is ignored in this case).
4389
4390 If the C<*nsecs> field contains the special value C<-2> then
4391 the corresponding timestamp is left unchanged.  (The
4392 C<*secs> field is ignored in this case).");
4393
4394   ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
4395    [InitBasicFS, Always, TestOutputStruct (
4396       [["mkdir_mode"; "/test"; "0o111"];
4397        ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
4398    "create a directory with a particular mode",
4399    "\
4400 This command creates a directory, setting the initial permissions
4401 of the directory to C<mode>.
4402
4403 For common Linux filesystems, the actual mode which is set will
4404 be C<mode & ~umask & 01777>.  Non-native-Linux filesystems may
4405 interpret the mode in other ways.
4406
4407 See also C<guestfs_mkdir>, C<guestfs_umask>");
4408
4409   ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
4410    [], (* XXX *)
4411    "change file owner and group",
4412    "\
4413 Change the file owner to C<owner> and group to C<group>.
4414 This is like C<guestfs_chown> but if C<path> is a symlink then
4415 the link itself is changed, not the target.
4416
4417 Only numeric uid and gid are supported.  If you want to use
4418 names, you will need to locate and parse the password file
4419 yourself (Augeas support makes this relatively easy).");
4420
4421   ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
4422    [], (* XXX *)
4423    "lstat on multiple files",
4424    "\
4425 This call allows you to perform the C<guestfs_lstat> operation
4426 on multiple files, where all files are in the directory C<path>.
4427 C<names> is the list of files from this directory.
4428
4429 On return you get a list of stat structs, with a one-to-one
4430 correspondence to the C<names> list.  If any name did not exist
4431 or could not be lstat'd, then the C<ino> field of that structure
4432 is set to C<-1>.
4433
4434 This call is intended for programs that want to efficiently
4435 list a directory contents without making many round-trips.
4436 See also C<guestfs_lxattrlist> for a similarly efficient call
4437 for getting extended attributes.  Very long directory listings
4438 might cause the protocol message size to be exceeded, causing
4439 this call to fail.  The caller must split up such requests
4440 into smaller groups of names.");
4441
4442   ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
4443    [], (* XXX *)
4444    "lgetxattr on multiple files",
4445    "\
4446 This call allows you to get the extended attributes
4447 of multiple files, where all files are in the directory C<path>.
4448 C<names> is the list of files from this directory.
4449
4450 On return you get a flat list of xattr structs which must be
4451 interpreted sequentially.  The first xattr struct always has a zero-length
4452 C<attrname>.  C<attrval> in this struct is zero-length
4453 to indicate there was an error doing C<lgetxattr> for this
4454 file, I<or> is a C string which is a decimal number
4455 (the number of following attributes for this file, which could
4456 be C<\"0\">).  Then after the first xattr struct are the
4457 zero or more attributes for the first named file.
4458 This repeats for the second and subsequent files.
4459
4460 This call is intended for programs that want to efficiently
4461 list a directory contents without making many round-trips.
4462 See also C<guestfs_lstatlist> for a similarly efficient call
4463 for getting standard stats.  Very long directory listings
4464 might cause the protocol message size to be exceeded, causing
4465 this call to fail.  The caller must split up such requests
4466 into smaller groups of names.");
4467
4468   ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
4469    [], (* XXX *)
4470    "readlink on multiple files",
4471    "\
4472 This call allows you to do a C<readlink> operation
4473 on multiple files, where all files are in the directory C<path>.
4474 C<names> is the list of files from this directory.
4475
4476 On return you get a list of strings, with a one-to-one
4477 correspondence to the C<names> list.  Each string is the
4478 value of the symbolic link.
4479
4480 If the C<readlink(2)> operation fails on any name, then
4481 the corresponding result string is the empty string C<\"\">.
4482 However the whole operation is completed even if there
4483 were C<readlink(2)> errors, and so you can call this
4484 function with names where you don't know if they are
4485 symbolic links already (albeit slightly less efficient).
4486
4487 This call is intended for programs that want to efficiently
4488 list a directory contents without making many round-trips.
4489 Very long directory listings might cause the protocol
4490 message size to be exceeded, causing
4491 this call to fail.  The caller must split up such requests
4492 into smaller groups of names.");
4493
4494   ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
4495    [InitISOFS, Always, TestOutputBuffer (
4496       [["pread"; "/known-4"; "1"; "3"]], "\n");
4497     InitISOFS, Always, TestOutputBuffer (
4498       [["pread"; "/empty"; "0"; "100"]], "")],
4499    "read part of a file",
4500    "\
4501 This command lets you read part of a file.  It reads C<count>
4502 bytes of the file, starting at C<offset>, from file C<path>.
4503
4504 This may read fewer bytes than requested.  For further details
4505 see the L<pread(2)> system call.
4506
4507 See also C<guestfs_pwrite>.");
4508
4509   ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
4510    [InitEmpty, Always, TestRun (
4511       [["part_init"; "/dev/sda"; "gpt"]])],
4512    "create an empty partition table",
4513    "\
4514 This creates an empty partition table on C<device> of one of the
4515 partition types listed below.  Usually C<parttype> should be
4516 either C<msdos> or C<gpt> (for large disks).
4517
4518 Initially there are no partitions.  Following this, you should
4519 call C<guestfs_part_add> for each partition required.
4520
4521 Possible values for C<parttype> are:
4522
4523 =over 4
4524
4525 =item B<efi> | B<gpt>
4526
4527 Intel EFI / GPT partition table.
4528
4529 This is recommended for >= 2 TB partitions that will be accessed
4530 from Linux and Intel-based Mac OS X.  It also has limited backwards
4531 compatibility with the C<mbr> format.
4532
4533 =item B<mbr> | B<msdos>
4534
4535 The standard PC \"Master Boot Record\" (MBR) format used
4536 by MS-DOS and Windows.  This partition type will B<only> work
4537 for device sizes up to 2 TB.  For large disks we recommend
4538 using C<gpt>.
4539
4540 =back
4541
4542 Other partition table types that may work but are not
4543 supported include:
4544
4545 =over 4
4546
4547 =item B<aix>
4548
4549 AIX disk labels.
4550
4551 =item B<amiga> | B<rdb>
4552
4553 Amiga \"Rigid Disk Block\" format.
4554
4555 =item B<bsd>
4556
4557 BSD disk labels.
4558
4559 =item B<dasd>
4560
4561 DASD, used on IBM mainframes.
4562
4563 =item B<dvh>
4564
4565 MIPS/SGI volumes.
4566
4567 =item B<mac>
4568
4569 Old Mac partition format.  Modern Macs use C<gpt>.
4570
4571 =item B<pc98>
4572
4573 NEC PC-98 format, common in Japan apparently.
4574
4575 =item B<sun>
4576
4577 Sun disk labels.
4578
4579 =back");
4580
4581   ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4582    [InitEmpty, Always, TestRun (
4583       [["part_init"; "/dev/sda"; "mbr"];
4584        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4585     InitEmpty, Always, TestRun (
4586       [["part_init"; "/dev/sda"; "gpt"];
4587        ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4588        ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4589     InitEmpty, Always, TestRun (
4590       [["part_init"; "/dev/sda"; "mbr"];
4591        ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4592        ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4593        ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4594        ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4595    "add a partition to the device",
4596    "\
4597 This command adds a partition to C<device>.  If there is no partition
4598 table on the device, call C<guestfs_part_init> first.
4599
4600 The C<prlogex> parameter is the type of partition.  Normally you
4601 should pass C<p> or C<primary> here, but MBR partition tables also
4602 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4603 types.
4604
4605 C<startsect> and C<endsect> are the start and end of the partition
4606 in I<sectors>.  C<endsect> may be negative, which means it counts
4607 backwards from the end of the disk (C<-1> is the last sector).
4608
4609 Creating a partition which covers the whole disk is not so easy.
4610 Use C<guestfs_part_disk> to do that.");
4611
4612   ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4613    [InitEmpty, Always, TestRun (
4614       [["part_disk"; "/dev/sda"; "mbr"]]);
4615     InitEmpty, Always, TestRun (
4616       [["part_disk"; "/dev/sda"; "gpt"]])],
4617    "partition whole disk with a single primary partition",
4618    "\
4619 This command is simply a combination of C<guestfs_part_init>
4620 followed by C<guestfs_part_add> to create a single primary partition
4621 covering the whole disk.
4622
4623 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4624 but other possible values are described in C<guestfs_part_init>.");
4625
4626   ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4627    [InitEmpty, Always, TestRun (
4628       [["part_disk"; "/dev/sda"; "mbr"];
4629        ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4630    "make a partition bootable",
4631    "\
4632 This sets the bootable flag on partition numbered C<partnum> on
4633 device C<device>.  Note that partitions are numbered from 1.
4634
4635 The bootable flag is used by some operating systems (notably
4636 Windows) to determine which partition to boot from.  It is by
4637 no means universally recognized.");
4638
4639   ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4640    [InitEmpty, Always, TestRun (
4641       [["part_disk"; "/dev/sda"; "gpt"];
4642        ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4643    "set partition name",
4644    "\
4645 This sets the partition name on partition numbered C<partnum> on
4646 device C<device>.  Note that partitions are numbered from 1.
4647
4648 The partition name can only be set on certain types of partition
4649 table.  This works on C<gpt> but not on C<mbr> partitions.");
4650
4651   ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4652    [], (* XXX Add a regression test for this. *)
4653    "list partitions on a device",
4654    "\
4655 This command parses the partition table on C<device> and
4656 returns the list of partitions found.
4657
4658 The fields in the returned structure are:
4659
4660 =over 4
4661
4662 =item B<part_num>
4663
4664 Partition number, counting from 1.
4665
4666 =item B<part_start>
4667
4668 Start of the partition I<in bytes>.  To get sectors you have to
4669 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4670
4671 =item B<part_end>
4672
4673 End of the partition in bytes.
4674
4675 =item B<part_size>
4676
4677 Size of the partition in bytes.
4678
4679 =back");
4680
4681   ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4682    [InitEmpty, Always, TestOutput (
4683       [["part_disk"; "/dev/sda"; "gpt"];
4684        ["part_get_parttype"; "/dev/sda"]], "gpt")],
4685    "get the partition table type",
4686    "\
4687 This command examines the partition table on C<device> and
4688 returns the partition table type (format) being used.
4689
4690 Common return values include: C<msdos> (a DOS/Windows style MBR
4691 partition table), C<gpt> (a GPT/EFI-style partition table).  Other
4692 values are possible, although unusual.  See C<guestfs_part_init>
4693 for a full list.");
4694
4695   ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [],
4696    [InitBasicFS, Always, TestOutputBuffer (
4697       [["fill"; "0x63"; "10"; "/test"];
4698        ["read_file"; "/test"]], "cccccccccc")],
4699    "fill a file with octets",
4700    "\
4701 This command creates a new file called C<path>.  The initial
4702 content of the file is C<len> octets of C<c>, where C<c>
4703 must be a number in the range C<[0..255]>.
4704
4705 To fill a file with zero bytes (sparsely), it is
4706 much more efficient to use C<guestfs_truncate_size>.
4707 To create a file with a pattern of repeating bytes
4708 use C<guestfs_fill_pattern>.");
4709
4710   ("available", (RErr, [StringList "groups"]), 216, [],
4711    [InitNone, Always, TestRun [["available"; ""]]],
4712    "test availability of some parts of the API",
4713    "\
4714 This command is used to check the availability of some
4715 groups of functionality in the appliance, which not all builds of
4716 the libguestfs appliance will be able to provide.
4717
4718 The libguestfs groups, and the functions that those
4719 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4720 You can also fetch this list at runtime by calling
4721 C<guestfs_available_all_groups>.
4722
4723 The argument C<groups> is a list of group names, eg:
4724 C<[\"inotify\", \"augeas\"]> would check for the availability of
4725 the Linux inotify functions and Augeas (configuration file
4726 editing) functions.
4727
4728 The command returns no error if I<all> requested groups are available.
4729
4730 It fails with an error if one or more of the requested
4731 groups is unavailable in the appliance.
4732
4733 If an unknown group name is included in the
4734 list of groups then an error is always returned.
4735
4736 I<Notes:>
4737
4738 =over 4
4739
4740 =item *
4741
4742 You must call C<guestfs_launch> before calling this function.
4743
4744 The reason is because we don't know what groups are
4745 supported by the appliance/daemon until it is running and can
4746 be queried.
4747
4748 =item *
4749
4750 If a group of functions is available, this does not necessarily
4751 mean that they will work.  You still have to check for errors
4752 when calling individual API functions even if they are
4753 available.
4754
4755 =item *
4756
4757 It is usually the job of distro packagers to build
4758 complete functionality into the libguestfs appliance.
4759 Upstream libguestfs, if built from source with all
4760 requirements satisfied, will support everything.
4761
4762 =item *
4763
4764 This call was added in version C<1.0.80>.  In previous
4765 versions of libguestfs all you could do would be to speculatively
4766 execute a command to find out if the daemon implemented it.
4767 See also C<guestfs_version>.
4768
4769 =back");
4770
4771   ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4772    [InitBasicFS, Always, TestOutputBuffer (
4773       [["write"; "/src"; "hello, world"];
4774        ["dd"; "/src"; "/dest"];
4775        ["read_file"; "/dest"]], "hello, world")],
4776    "copy from source to destination using dd",
4777    "\
4778 This command copies from one source device or file C<src>
4779 to another destination device or file C<dest>.  Normally you
4780 would use this to copy to or from a device or partition, for
4781 example to duplicate a filesystem.
4782
4783 If the destination is a device, it must be as large or larger
4784 than the source file or device, otherwise the copy will fail.
4785 This command cannot do partial copies (see C<guestfs_copy_size>).");
4786
4787   ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4788    [InitBasicFS, Always, TestOutputInt (
4789       [["write"; "/file"; "hello, world"];
4790        ["filesize"; "/file"]], 12)],
4791    "return the size of the file in bytes",
4792    "\
4793 This command returns the size of C<file> in bytes.
4794
4795 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4796 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4797 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4798
4799   ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4800    [InitBasicFSonLVM, Always, TestOutputList (
4801       [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4802        ["lvs"]], ["/dev/VG/LV2"])],
4803    "rename an LVM logical volume",
4804    "\
4805 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4806
4807   ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4808    [InitBasicFSonLVM, Always, TestOutputList (
4809       [["umount"; "/"];
4810        ["vg_activate"; "false"; "VG"];
4811        ["vgrename"; "VG"; "VG2"];
4812        ["vg_activate"; "true"; "VG2"];
4813        ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4814        ["vgs"]], ["VG2"])],
4815    "rename an LVM volume group",
4816    "\
4817 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4818
4819   ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4820    [InitISOFS, Always, TestOutputBuffer (
4821       [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4822    "list the contents of a single file in an initrd",
4823    "\
4824 This command unpacks the file C<filename> from the initrd file
4825 called C<initrdpath>.  The filename must be given I<without> the
4826 initial C</> character.
4827
4828 For example, in guestfish you could use the following command
4829 to examine the boot script (usually called C</init>)
4830 contained in a Linux initrd or initramfs image:
4831
4832  initrd-cat /boot/initrd-<version>.img init
4833
4834 See also C<guestfs_initrd_list>.");
4835
4836   ("pvuuid", (RString "uuid", [Device "device"]), 222, [],
4837    [],
4838    "get the UUID of a physical volume",
4839    "\
4840 This command returns the UUID of the LVM PV C<device>.");
4841
4842   ("vguuid", (RString "uuid", [String "vgname"]), 223, [],
4843    [],
4844    "get the UUID of a volume group",
4845    "\
4846 This command returns the UUID of the LVM VG named C<vgname>.");
4847
4848   ("lvuuid", (RString "uuid", [Device "device"]), 224, [],
4849    [],
4850    "get the UUID of a logical volume",
4851    "\
4852 This command returns the UUID of the LVM LV C<device>.");
4853
4854   ("vgpvuuids", (RStringList "uuids", [String "vgname"]), 225, [],
4855    [],
4856    "get the PV UUIDs containing the volume group",
4857    "\
4858 Given a VG called C<vgname>, this returns the UUIDs of all
4859 the physical volumes that this volume group resides on.
4860
4861 You can use this along with C<guestfs_pvs> and C<guestfs_pvuuid>
4862 calls to associate physical volumes and volume groups.
4863
4864 See also C<guestfs_vglvuuids>.");
4865
4866   ("vglvuuids", (RStringList "uuids", [String "vgname"]), 226, [],
4867    [],
4868    "get the LV UUIDs of all LVs in the volume group",
4869    "\
4870 Given a VG called C<vgname>, this returns the UUIDs of all
4871 the logical volumes created in this volume group.
4872
4873 You can use this along with C<guestfs_lvs> and C<guestfs_lvuuid>
4874 calls to associate logical volumes and volume groups.
4875
4876 See also C<guestfs_vgpvuuids>.");
4877
4878   ("copy_size", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"; Int64 "size"]), 227, [],
4879    [InitBasicFS, Always, TestOutputBuffer (
4880       [["write"; "/src"; "hello, world"];
4881        ["copy_size"; "/src"; "/dest"; "5"];
4882        ["read_file"; "/dest"]], "hello")],
4883    "copy size bytes from source to destination using dd",
4884    "\
4885 This command copies exactly C<size> bytes from one source device
4886 or file C<src> to another destination device or file C<dest>.
4887
4888 Note this will fail if the source is too short or if the destination
4889 is not large enough.");
4890
4891   ("zero_device", (RErr, [Device "device"]), 228, [DangerWillRobinson],
4892    [InitBasicFSonLVM, Always, TestRun (
4893       [["zero_device"; "/dev/VG/LV"]])],
4894    "write zeroes to an entire device",
4895    "\
4896 This command writes zeroes over the entire C<device>.  Compare
4897 with C<guestfs_zero> which just zeroes the first few blocks of
4898 a device.");
4899
4900   ("txz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 229, [Optional "xz"],
4901    [InitBasicFS, Always, TestOutput (
4902       [["txz_in"; "../images/helloworld.tar.xz"; "/"];
4903        ["cat"; "/hello"]], "hello\n")],
4904    "unpack compressed tarball to directory",
4905    "\
4906 This command uploads and unpacks local file C<tarball> (an
4907 I<xz compressed> tar file) into C<directory>.");
4908
4909   ("txz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 230, [Optional "xz"],
4910    [],
4911    "pack directory into compressed tarball",
4912    "\
4913 This command packs the contents of C<directory> and downloads
4914 it to local file C<tarball> (as an xz compressed tar archive).");
4915
4916   ("ntfsresize", (RErr, [Device "device"]), 231, [Optional "ntfsprogs"],
4917    [],
4918    "resize an NTFS filesystem",
4919    "\
4920 This command resizes an NTFS filesystem, expanding or
4921 shrinking it to the size of the underlying device.
4922 See also L<ntfsresize(8)>.");
4923
4924   ("vgscan", (RErr, []), 232, [],
4925    [InitEmpty, Always, TestRun (
4926       [["vgscan"]])],
4927    "rescan for LVM physical volumes, volume groups and logical volumes",
4928    "\
4929 This rescans all block devices and rebuilds the list of LVM
4930 physical volumes, volume groups and logical volumes.");
4931
4932   ("part_del", (RErr, [Device "device"; Int "partnum"]), 233, [],
4933    [InitEmpty, Always, TestRun (
4934       [["part_init"; "/dev/sda"; "mbr"];
4935        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4936        ["part_del"; "/dev/sda"; "1"]])],
4937    "delete a partition",
4938    "\
4939 This command deletes the partition numbered C<partnum> on C<device>.
4940
4941 Note that in the case of MBR partitioning, deleting an
4942 extended partition also deletes any logical partitions
4943 it contains.");
4944
4945   ("part_get_bootable", (RBool "bootable", [Device "device"; Int "partnum"]), 234, [],
4946    [InitEmpty, Always, TestOutputTrue (
4947       [["part_init"; "/dev/sda"; "mbr"];
4948        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4949        ["part_set_bootable"; "/dev/sda"; "1"; "true"];
4950        ["part_get_bootable"; "/dev/sda"; "1"]])],
4951    "return true if a partition is bootable",
4952    "\
4953 This command returns true if the partition C<partnum> on
4954 C<device> has the bootable flag set.
4955
4956 See also C<guestfs_part_set_bootable>.");
4957
4958   ("part_get_mbr_id", (RInt "idbyte", [Device "device"; Int "partnum"]), 235, [FishOutput FishOutputHexadecimal],
4959    [InitEmpty, Always, TestOutputInt (
4960       [["part_init"; "/dev/sda"; "mbr"];
4961        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4962        ["part_set_mbr_id"; "/dev/sda"; "1"; "0x7f"];
4963        ["part_get_mbr_id"; "/dev/sda"; "1"]], 0x7f)],
4964    "get the MBR type byte (ID byte) from a partition",
4965    "\
4966 Returns the MBR type byte (also known as the ID byte) from
4967 the numbered partition C<partnum>.
4968
4969 Note that only MBR (old DOS-style) partitions have type bytes.
4970 You will get undefined results for other partition table
4971 types (see C<guestfs_part_get_parttype>).");
4972
4973   ("part_set_mbr_id", (RErr, [Device "device"; Int "partnum"; Int "idbyte"]), 236, [],
4974    [], (* tested by part_get_mbr_id *)
4975    "set the MBR type byte (ID byte) of a partition",
4976    "\
4977 Sets the MBR type byte (also known as the ID byte) of
4978 the numbered partition C<partnum> to C<idbyte>.  Note
4979 that the type bytes quoted in most documentation are
4980 in fact hexadecimal numbers, but usually documented
4981 without any leading \"0x\" which might be confusing.
4982
4983 Note that only MBR (old DOS-style) partitions have type bytes.
4984 You will get undefined results for other partition table
4985 types (see C<guestfs_part_get_parttype>).");
4986
4987   ("checksum_device", (RString "checksum", [String "csumtype"; Device "device"]), 237, [],
4988    [InitISOFS, Always, TestOutput (
4989       [["checksum_device"; "md5"; "/dev/sdd"]],
4990       (Digest.to_hex (Digest.file "images/test.iso")))],
4991    "compute MD5, SHAx or CRC checksum of the contents of a device",
4992    "\
4993 This call computes the MD5, SHAx or CRC checksum of the
4994 contents of the device named C<device>.  For the types of
4995 checksums supported see the C<guestfs_checksum> command.");
4996
4997   ("lvresize_free", (RErr, [Device "lv"; Int "percent"]), 238, [Optional "lvm2"],
4998    [InitNone, Always, TestRun (
4999       [["part_disk"; "/dev/sda"; "mbr"];
5000        ["pvcreate"; "/dev/sda1"];
5001        ["vgcreate"; "VG"; "/dev/sda1"];
5002        ["lvcreate"; "LV"; "VG"; "10"];
5003        ["lvresize_free"; "/dev/VG/LV"; "100"]])],
5004    "expand an LV to fill free space",
5005    "\
5006 This expands an existing logical volume C<lv> so that it fills
5007 C<pc>% of the remaining free space in the volume group.  Commonly
5008 you would call this with pc = 100 which expands the logical volume
5009 as much as possible, using all remaining free space in the volume
5010 group.");
5011
5012   ("aug_clear", (RErr, [String "augpath"]), 239, [Optional "augeas"],
5013    [], (* XXX Augeas code needs tests. *)
5014    "clear Augeas path",
5015    "\
5016 Set the value associated with C<path> to C<NULL>.  This
5017 is the same as the L<augtool(1)> C<clear> command.");
5018
5019   ("get_umask", (RInt "mask", []), 240, [FishOutput FishOutputOctal],
5020    [InitEmpty, Always, TestOutputInt (
5021       [["get_umask"]], 0o22)],
5022    "get the current umask",
5023    "\
5024 Return the current umask.  By default the umask is C<022>
5025 unless it has been set by calling C<guestfs_umask>.");
5026
5027   ("debug_upload", (RErr, [FileIn "filename"; String "tmpname"; Int "mode"]), 241, [],
5028    [],
5029    "upload a file to the appliance (internal use only)",
5030    "\
5031 The C<guestfs_debug_upload> command uploads a file to
5032 the libguestfs appliance.
5033
5034 There is no comprehensive help for this command.  You have
5035 to look at the file C<daemon/debug.c> in the libguestfs source
5036 to find out what it is for.");
5037
5038   ("base64_in", (RErr, [FileIn "base64file"; Pathname "filename"]), 242, [],
5039    [InitBasicFS, Always, TestOutput (
5040       [["base64_in"; "../images/hello.b64"; "/hello"];
5041        ["cat"; "/hello"]], "hello\n")],
5042    "upload base64-encoded data to file",
5043    "\
5044 This command uploads base64-encoded data from C<base64file>
5045 to C<filename>.");
5046
5047   ("base64_out", (RErr, [Pathname "filename"; FileOut "base64file"]), 243, [],
5048    [],
5049    "download file and encode as base64",
5050    "\
5051 This command downloads the contents of C<filename>, writing
5052 it out to local file C<base64file> encoded as base64.");
5053
5054   ("checksums_out", (RErr, [String "csumtype"; Pathname "directory"; FileOut "sumsfile"]), 244, [],
5055    [],
5056    "compute MD5, SHAx or CRC checksum of files in a directory",
5057    "\
5058 This command computes the checksums of all regular files in
5059 C<directory> and then emits a list of those checksums to
5060 the local output file C<sumsfile>.
5061
5062 This can be used for verifying the integrity of a virtual
5063 machine.  However to be properly secure you should pay
5064 attention to the output of the checksum command (it uses
5065 the ones from GNU coreutils).  In particular when the
5066 filename is not printable, coreutils uses a special
5067 backslash syntax.  For more information, see the GNU
5068 coreutils info file.");
5069
5070   ("fill_pattern", (RErr, [String "pattern"; Int "len"; Pathname "path"]), 245, [],
5071    [InitBasicFS, Always, TestOutputBuffer (
5072       [["fill_pattern"; "abcdefghijklmnopqrstuvwxyz"; "28"; "/test"];
5073        ["read_file"; "/test"]], "abcdefghijklmnopqrstuvwxyzab")],
5074    "fill a file with a repeating pattern of bytes",
5075    "\
5076 This function is like C<guestfs_fill> except that it creates
5077 a new file of length C<len> containing the repeating pattern
5078 of bytes in C<pattern>.  The pattern is truncated if necessary
5079 to ensure the length of the file is exactly C<len> bytes.");
5080
5081   ("write", (RErr, [Pathname "path"; BufferIn "content"]), 246, [ProtocolLimitWarning],
5082    [InitBasicFS, Always, TestOutput (
5083       [["write"; "/new"; "new file contents"];
5084        ["cat"; "/new"]], "new file contents");
5085     InitBasicFS, Always, TestOutput (
5086       [["write"; "/new"; "\nnew file contents\n"];
5087        ["cat"; "/new"]], "\nnew file contents\n");
5088     InitBasicFS, Always, TestOutput (
5089       [["write"; "/new"; "\n\n"];
5090        ["cat"; "/new"]], "\n\n");
5091     InitBasicFS, Always, TestOutput (
5092       [["write"; "/new"; ""];
5093        ["cat"; "/new"]], "");
5094     InitBasicFS, Always, TestOutput (
5095       [["write"; "/new"; "\n\n\n"];
5096        ["cat"; "/new"]], "\n\n\n");
5097     InitBasicFS, Always, TestOutput (
5098       [["write"; "/new"; "\n"];
5099        ["cat"; "/new"]], "\n")],
5100    "create a new file",
5101    "\
5102 This call creates a file called C<path>.  The content of the
5103 file is the string C<content> (which can contain any 8 bit data).");
5104
5105   ("pwrite", (RInt "nbytes", [Pathname "path"; BufferIn "content"; Int64 "offset"]), 247, [ProtocolLimitWarning],
5106    [InitBasicFS, Always, TestOutput (
5107       [["write"; "/new"; "new file contents"];
5108        ["pwrite"; "/new"; "data"; "4"];
5109        ["cat"; "/new"]], "new data contents");
5110     InitBasicFS, Always, TestOutput (
5111       [["write"; "/new"; "new file contents"];
5112        ["pwrite"; "/new"; "is extended"; "9"];
5113        ["cat"; "/new"]], "new file is extended");
5114     InitBasicFS, Always, TestOutput (
5115       [["write"; "/new"; "new file contents"];
5116        ["pwrite"; "/new"; ""; "4"];
5117        ["cat"; "/new"]], "new file contents")],
5118    "write to part of a file",
5119    "\
5120 This command writes to part of a file.  It writes the data
5121 buffer C<content> to the file C<path> starting at offset C<offset>.
5122
5123 This command implements the L<pwrite(2)> system call, and like
5124 that system call it may not write the full data requested.  The
5125 return value is the number of bytes that were actually written
5126 to the file.  This could even be 0, although short writes are
5127 unlikely for regular files in ordinary circumstances.
5128
5129 See also C<guestfs_pread>.");
5130
5131   ("resize2fs_size", (RErr, [Device "device"; Int64 "size"]), 248, [],
5132    [],
5133    "resize an ext2, ext3 or ext4 filesystem (with size)",
5134    "\
5135 This command is the same as C<guestfs_resize2fs> except that it
5136 allows you to specify the new size (in bytes) explicitly.");
5137
5138   ("pvresize_size", (RErr, [Device "device"; Int64 "size"]), 249, [Optional "lvm2"],
5139    [],
5140    "resize an LVM physical volume (with size)",
5141    "\
5142 This command is the same as C<guestfs_pvresize> except that it
5143 allows you to specify the new size (in bytes) explicitly.");
5144
5145   ("ntfsresize_size", (RErr, [Device "device"; Int64 "size"]), 250, [Optional "ntfsprogs"],
5146    [],
5147    "resize an NTFS filesystem (with size)",
5148    "\
5149 This command is the same as C<guestfs_ntfsresize> except that it
5150 allows you to specify the new size (in bytes) explicitly.");
5151
5152   ("available_all_groups", (RStringList "groups", []), 251, [],
5153    [InitNone, Always, TestRun [["available_all_groups"]]],
5154    "return a list of all optional groups",
5155    "\
5156 This command returns a list of all optional groups that this
5157 daemon knows about.  Note this returns both supported and unsupported
5158 groups.  To find out which ones the daemon can actually support
5159 you have to call C<guestfs_available> on each member of the
5160 returned list.
5161
5162 See also C<guestfs_available> and L<guestfs(3)/AVAILABILITY>.");
5163
5164   ("fallocate64", (RErr, [Pathname "path"; Int64 "len"]), 252, [],
5165    [InitBasicFS, Always, TestOutputStruct (
5166       [["fallocate64"; "/a"; "1000000"];
5167        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
5168    "preallocate a file in the guest filesystem",
5169    "\
5170 This command preallocates a file (containing zero bytes) named
5171 C<path> of size C<len> bytes.  If the file exists already, it
5172 is overwritten.
5173
5174 Note that this call allocates disk blocks for the file.
5175 To create a sparse file use C<guestfs_truncate_size> instead.
5176
5177 The deprecated call C<guestfs_fallocate> does the same,
5178 but owing to an oversight it only allowed 30 bit lengths
5179 to be specified, effectively limiting the maximum size
5180 of files created through that call to 1GB.
5181
5182 Do not confuse this with the guestfish-specific
5183 C<alloc> and C<sparse> commands which create
5184 a file in the host and attach it as a device.");
5185
5186   ("vfs_label", (RString "label", [Device "device"]), 253, [],
5187    [InitBasicFS, Always, TestOutput (
5188        [["set_e2label"; "/dev/sda1"; "LTEST"];
5189         ["vfs_label"; "/dev/sda1"]], "LTEST")],
5190    "get the filesystem label",
5191    "\
5192 This returns the filesystem label of the filesystem on
5193 C<device>.
5194
5195 If the filesystem is unlabeled, this returns the empty string.
5196
5197 To find a filesystem from the label, use C<guestfs_findfs_label>.");
5198
5199   ("vfs_uuid", (RString "uuid", [Device "device"]), 254, [],
5200    (let uuid = uuidgen () in
5201     [InitBasicFS, Always, TestOutput (
5202        [["set_e2uuid"; "/dev/sda1"; uuid];
5203         ["vfs_uuid"; "/dev/sda1"]], uuid)]),
5204    "get the filesystem UUID",
5205    "\
5206 This returns the filesystem UUID of the filesystem on
5207 C<device>.
5208
5209 If the filesystem does not have a UUID, this returns the empty string.
5210
5211 To find a filesystem from the UUID, use C<guestfs_findfs_uuid>.");
5212
5213   ("lvm_set_filter", (RErr, [DeviceList "devices"]), 255, [Optional "lvm2"],
5214    (* Can't be tested with the current framework because
5215     * the VG is being used by the mounted filesystem, so
5216     * the vgchange -an command we do first will fail.
5217     *)
5218     [],
5219    "set LVM device filter",
5220    "\
5221 This sets the LVM device filter so that LVM will only be
5222 able to \"see\" the block devices in the list C<devices>,
5223 and will ignore all other attached block devices.
5224
5225 Where disk image(s) contain duplicate PVs or VGs, this
5226 command is useful to get LVM to ignore the duplicates, otherwise
5227 LVM can get confused.  Note also there are two types
5228 of duplication possible: either cloned PVs/VGs which have
5229 identical UUIDs; or VGs that are not cloned but just happen
5230 to have the same name.  In normal operation you cannot
5231 create this situation, but you can do it outside LVM, eg.
5232 by cloning disk images or by bit twiddling inside the LVM
5233 metadata.
5234
5235 This command also clears the LVM cache and performs a volume
5236 group scan.
5237
5238 You can filter whole block devices or individual partitions.
5239
5240 You cannot use this if any VG is currently in use (eg.
5241 contains a mounted filesystem), even if you are not
5242 filtering out that VG.");
5243
5244   ("lvm_clear_filter", (RErr, []), 256, [],
5245    [], (* see note on lvm_set_filter *)
5246    "clear LVM device filter",
5247    "\
5248 This undoes the effect of C<guestfs_lvm_set_filter>.  LVM
5249 will be able to see every block device.
5250
5251 This command also clears the LVM cache and performs a volume
5252 group scan.");
5253
5254   ("luks_open", (RErr, [Device "device"; Key "key"; String "mapname"]), 257, [Optional "luks"],
5255    [],
5256    "open a LUKS-encrypted block device",
5257    "\
5258 This command opens a block device which has been encrypted
5259 according to the Linux Unified Key Setup (LUKS) standard.
5260
5261 C<device> is the encrypted block device or partition.
5262
5263 The caller must supply one of the keys associated with the
5264 LUKS block device, in the C<key> parameter.
5265
5266 This creates a new block device called C</dev/mapper/mapname>.
5267 Reads and writes to this block device are decrypted from and
5268 encrypted to the underlying C<device> respectively.
5269
5270 If this block device contains LVM volume groups, then
5271 calling C<guestfs_vgscan> followed by C<guestfs_vg_activate_all>
5272 will make them visible.");
5273
5274   ("luks_open_ro", (RErr, [Device "device"; Key "key"; String "mapname"]), 258, [Optional "luks"],
5275    [],
5276    "open a LUKS-encrypted block device read-only",
5277    "\
5278 This is the same as C<guestfs_luks_open> except that a read-only
5279 mapping is created.");
5280
5281   ("luks_close", (RErr, [Device "device"]), 259, [Optional "luks"],
5282    [],
5283    "close a LUKS device",
5284    "\
5285 This closes a LUKS device that was created earlier by
5286 C<guestfs_luks_open> or C<guestfs_luks_open_ro>.  The
5287 C<device> parameter must be the name of the LUKS mapping
5288 device (ie. C</dev/mapper/mapname>) and I<not> the name
5289 of the underlying block device.");
5290
5291   ("luks_format", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 260, [Optional "luks"; DangerWillRobinson],
5292    [],
5293    "format a block device as a LUKS encrypted device",
5294    "\
5295 This command erases existing data on C<device> and formats
5296 the device as a LUKS encrypted device.  C<key> is the
5297 initial key, which is added to key slot C<slot>.  (LUKS
5298 supports 8 key slots, numbered 0-7).");
5299
5300   ("luks_format_cipher", (RErr, [Device "device"; Key "key"; Int "keyslot"; String "cipher"]), 261, [Optional "luks"; DangerWillRobinson],
5301    [],
5302    "format a block device as a LUKS encrypted device",
5303    "\
5304 This command is the same as C<guestfs_luks_format> but
5305 it also allows you to set the C<cipher> used.");
5306
5307   ("luks_add_key", (RErr, [Device "device"; Key "key"; Key "newkey"; Int "keyslot"]), 262, [Optional "luks"],
5308    [],
5309    "add a key on a LUKS encrypted device",
5310    "\
5311 This command adds a new key on LUKS device C<device>.
5312 C<key> is any existing key, and is used to access the device.
5313 C<newkey> is the new key to add.  C<keyslot> is the key slot
5314 that will be replaced.
5315
5316 Note that if C<keyslot> already contains a key, then this
5317 command will fail.  You have to use C<guestfs_luks_kill_slot>
5318 first to remove that key.");
5319
5320   ("luks_kill_slot", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 263, [Optional "luks"],
5321    [],
5322    "remove a key from a LUKS encrypted device",
5323    "\
5324 This command deletes the key in key slot C<keyslot> from the
5325 encrypted LUKS device C<device>.  C<key> must be one of the
5326 I<other> keys.");
5327
5328   ("is_lv", (RBool "lvflag", [Device "device"]), 264, [Optional "lvm2"],
5329    [InitBasicFSonLVM, IfAvailable "lvm2", TestOutputTrue (
5330       [["is_lv"; "/dev/VG/LV"]]);
5331     InitBasicFSonLVM, IfAvailable "lvm2", TestOutputFalse (
5332       [["is_lv"; "/dev/sda1"]])],
5333    "test if device is a logical volume",
5334    "\
5335 This command tests whether C<device> is a logical volume, and
5336 returns true iff this is the case.");
5337
5338   ("findfs_uuid", (RString "device", [String "uuid"]), 265, [],
5339    [],
5340    "find a filesystem by UUID",
5341    "\
5342 This command searches the filesystems and returns the one
5343 which has the given UUID.  An error is returned if no such
5344 filesystem can be found.
5345
5346 To find the UUID of a filesystem, use C<guestfs_vfs_uuid>.");
5347
5348   ("findfs_label", (RString "device", [String "label"]), 266, [],
5349    [],
5350    "find a filesystem by label",
5351    "\
5352 This command searches the filesystems and returns the one
5353 which has the given label.  An error is returned if no such
5354 filesystem can be found.
5355
5356 To find the label of a filesystem, use C<guestfs_vfs_label>.");
5357
5358 ]
5359
5360 let all_functions = non_daemon_functions @ daemon_functions
5361
5362 (* In some places we want the functions to be displayed sorted
5363  * alphabetically, so this is useful:
5364  *)
5365 let all_functions_sorted =
5366   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
5367                compare n1 n2) all_functions
5368
5369 (* This is used to generate the src/MAX_PROC_NR file which
5370  * contains the maximum procedure number, a surrogate for the
5371  * ABI version number.  See src/Makefile.am for the details.
5372  *)
5373 let max_proc_nr =
5374   let proc_nrs = List.map (
5375     fun (_, _, proc_nr, _, _, _, _) -> proc_nr
5376   ) daemon_functions in
5377   List.fold_left max 0 proc_nrs
5378
5379 (* Field types for structures. *)
5380 type field =
5381   | FChar                       (* C 'char' (really, a 7 bit byte). *)
5382   | FString                     (* nul-terminated ASCII string, NOT NULL. *)
5383   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
5384   | FUInt32
5385   | FInt32
5386   | FUInt64
5387   | FInt64
5388   | FBytes                      (* Any int measure that counts bytes. *)
5389   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
5390   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
5391
5392 (* Because we generate extra parsing code for LVM command line tools,
5393  * we have to pull out the LVM columns separately here.
5394  *)
5395 let lvm_pv_cols = [
5396   "pv_name", FString;
5397   "pv_uuid", FUUID;
5398   "pv_fmt", FString;
5399   "pv_size", FBytes;
5400   "dev_size", FBytes;
5401   "pv_free", FBytes;
5402   "pv_used", FBytes;
5403   "pv_attr", FString (* XXX *);
5404   "pv_pe_count", FInt64;
5405   "pv_pe_alloc_count", FInt64;
5406   "pv_tags", FString;
5407   "pe_start", FBytes;
5408   "pv_mda_count", FInt64;
5409   "pv_mda_free", FBytes;
5410   (* Not in Fedora 10:
5411      "pv_mda_size", FBytes;
5412   *)
5413 ]
5414 let lvm_vg_cols = [
5415   "vg_name", FString;
5416   "vg_uuid", FUUID;
5417   "vg_fmt", FString;
5418   "vg_attr", FString (* XXX *);
5419   "vg_size", FBytes;
5420   "vg_free", FBytes;
5421   "vg_sysid", FString;
5422   "vg_extent_size", FBytes;
5423   "vg_extent_count", FInt64;
5424   "vg_free_count", FInt64;
5425   "max_lv", FInt64;
5426   "max_pv", FInt64;
5427   "pv_count", FInt64;
5428   "lv_count", FInt64;
5429   "snap_count", FInt64;
5430   "vg_seqno", FInt64;
5431   "vg_tags", FString;
5432   "vg_mda_count", FInt64;
5433   "vg_mda_free", FBytes;
5434   (* Not in Fedora 10:
5435      "vg_mda_size", FBytes;
5436   *)
5437 ]
5438 let lvm_lv_cols = [
5439   "lv_name", FString;
5440   "lv_uuid", FUUID;
5441   "lv_attr", FString (* XXX *);
5442   "lv_major", FInt64;
5443   "lv_minor", FInt64;
5444   "lv_kernel_major", FInt64;
5445   "lv_kernel_minor", FInt64;
5446   "lv_size", FBytes;
5447   "seg_count", FInt64;
5448   "origin", FString;
5449   "snap_percent", FOptPercent;
5450   "copy_percent", FOptPercent;
5451   "move_pv", FString;
5452   "lv_tags", FString;
5453   "mirror_log", FString;
5454   "modules", FString;
5455 ]
5456
5457 (* Names and fields in all structures (in RStruct and RStructList)
5458  * that we support.
5459  *)
5460 let structs = [
5461   (* The old RIntBool return type, only ever used for aug_defnode.  Do
5462    * not use this struct in any new code.
5463    *)
5464   "int_bool", [
5465     "i", FInt32;                (* for historical compatibility *)
5466     "b", FInt32;                (* for historical compatibility *)
5467   ];
5468
5469   (* LVM PVs, VGs, LVs. *)
5470   "lvm_pv", lvm_pv_cols;
5471   "lvm_vg", lvm_vg_cols;
5472   "lvm_lv", lvm_lv_cols;
5473
5474   (* Column names and types from stat structures.
5475    * NB. Can't use things like 'st_atime' because glibc header files
5476    * define some of these as macros.  Ugh.
5477    *)
5478   "stat", [
5479     "dev", FInt64;
5480     "ino", FInt64;
5481     "mode", FInt64;
5482     "nlink", FInt64;
5483     "uid", FInt64;
5484     "gid", FInt64;
5485     "rdev", FInt64;
5486     "size", FInt64;
5487     "blksize", FInt64;
5488     "blocks", FInt64;
5489     "atime", FInt64;
5490     "mtime", FInt64;
5491     "ctime", FInt64;
5492   ];
5493   "statvfs", [
5494     "bsize", FInt64;
5495     "frsize", FInt64;
5496     "blocks", FInt64;
5497     "bfree", FInt64;
5498     "bavail", FInt64;
5499     "files", FInt64;
5500     "ffree", FInt64;
5501     "favail", FInt64;
5502     "fsid", FInt64;
5503     "flag", FInt64;
5504     "namemax", FInt64;
5505   ];
5506
5507   (* Column names in dirent structure. *)
5508   "dirent", [
5509     "ino", FInt64;
5510     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
5511     "ftyp", FChar;
5512     "name", FString;
5513   ];
5514
5515   (* Version numbers. *)
5516   "version", [
5517     "major", FInt64;
5518     "minor", FInt64;
5519     "release", FInt64;
5520     "extra", FString;
5521   ];
5522
5523   (* Extended attribute. *)
5524   "xattr", [
5525     "attrname", FString;
5526     "attrval", FBuffer;
5527   ];
5528
5529   (* Inotify events. *)
5530   "inotify_event", [
5531     "in_wd", FInt64;
5532     "in_mask", FUInt32;
5533     "in_cookie", FUInt32;
5534     "in_name", FString;
5535   ];
5536
5537   (* Partition table entry. *)
5538   "partition", [
5539     "part_num", FInt32;
5540     "part_start", FBytes;
5541     "part_end", FBytes;
5542     "part_size", FBytes;
5543   ];
5544 ] (* end of structs *)
5545
5546 (* Ugh, Java has to be different ..
5547  * These names are also used by the Haskell bindings.
5548  *)
5549 let java_structs = [
5550   "int_bool", "IntBool";
5551   "lvm_pv", "PV";
5552   "lvm_vg", "VG";
5553   "lvm_lv", "LV";
5554   "stat", "Stat";
5555   "statvfs", "StatVFS";
5556   "dirent", "Dirent";
5557   "version", "Version";
5558   "xattr", "XAttr";
5559   "inotify_event", "INotifyEvent";
5560   "partition", "Partition";
5561 ]
5562
5563 (* What structs are actually returned. *)
5564 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
5565
5566 (* Returns a list of RStruct/RStructList structs that are returned
5567  * by any function.  Each element of returned list is a pair:
5568  *
5569  * (structname, RStructOnly)
5570  *    == there exists function which returns RStruct (_, structname)
5571  * (structname, RStructListOnly)
5572  *    == there exists function which returns RStructList (_, structname)
5573  * (structname, RStructAndList)
5574  *    == there are functions returning both RStruct (_, structname)
5575  *                                      and RStructList (_, structname)
5576  *)
5577 let rstructs_used_by functions =
5578   (* ||| is a "logical OR" for rstructs_used_t *)
5579   let (|||) a b =
5580     match a, b with
5581     | RStructAndList, _
5582     | _, RStructAndList -> RStructAndList
5583     | RStructOnly, RStructListOnly
5584     | RStructListOnly, RStructOnly -> RStructAndList
5585     | RStructOnly, RStructOnly -> RStructOnly
5586     | RStructListOnly, RStructListOnly -> RStructListOnly
5587   in
5588
5589   let h = Hashtbl.create 13 in
5590
5591   (* if elem->oldv exists, update entry using ||| operator,
5592    * else just add elem->newv to the hash
5593    *)
5594   let update elem newv =
5595     try  let oldv = Hashtbl.find h elem in
5596          Hashtbl.replace h elem (newv ||| oldv)
5597     with Not_found -> Hashtbl.add h elem newv
5598   in
5599
5600   List.iter (
5601     fun (_, style, _, _, _, _, _) ->
5602       match fst style with
5603       | RStruct (_, structname) -> update structname RStructOnly
5604       | RStructList (_, structname) -> update structname RStructListOnly
5605       | _ -> ()
5606   ) functions;
5607
5608   (* return key->values as a list of (key,value) *)
5609   Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
5610
5611 (* Used for testing language bindings. *)
5612 type callt =
5613   | CallString of string
5614   | CallOptString of string option
5615   | CallStringList of string list
5616   | CallInt of int
5617   | CallInt64 of int64
5618   | CallBool of bool
5619   | CallBuffer of string
5620
5621 (* Used to memoize the result of pod2text. *)
5622 let pod2text_memo_filename = "src/.pod2text.data"
5623 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
5624   try
5625     let chan = open_in pod2text_memo_filename in
5626     let v = input_value chan in
5627     close_in chan;
5628     v
5629   with
5630     _ -> Hashtbl.create 13
5631 let pod2text_memo_updated () =
5632   let chan = open_out pod2text_memo_filename in
5633   output_value chan pod2text_memo;
5634   close_out chan
5635
5636 (* Useful functions.
5637  * Note we don't want to use any external OCaml libraries which
5638  * makes this a bit harder than it should be.
5639  *)
5640 module StringMap = Map.Make (String)
5641
5642 let failwithf fs = ksprintf failwith fs
5643
5644 let unique = let i = ref 0 in fun () -> incr i; !i
5645
5646 let replace_char s c1 c2 =
5647   let s2 = String.copy s in
5648   let r = ref false in
5649   for i = 0 to String.length s2 - 1 do
5650     if String.unsafe_get s2 i = c1 then (
5651       String.unsafe_set s2 i c2;
5652       r := true
5653     )
5654   done;
5655   if not !r then s else s2
5656
5657 let isspace c =
5658   c = ' '
5659   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
5660
5661 let triml ?(test = isspace) str =
5662   let i = ref 0 in
5663   let n = ref (String.length str) in
5664   while !n > 0 && test str.[!i]; do
5665     decr n;
5666     incr i
5667   done;
5668   if !i = 0 then str
5669   else String.sub str !i !n
5670
5671 let trimr ?(test = isspace) str =
5672   let n = ref (String.length str) in
5673   while !n > 0 && test str.[!n-1]; do
5674     decr n
5675   done;
5676   if !n = String.length str then str
5677   else String.sub str 0 !n
5678
5679 let trim ?(test = isspace) str =
5680   trimr ~test (triml ~test str)
5681
5682 let rec find s sub =
5683   let len = String.length s in
5684   let sublen = String.length sub in
5685   let rec loop i =
5686     if i <= len-sublen then (
5687       let rec loop2 j =
5688         if j < sublen then (
5689           if s.[i+j] = sub.[j] then loop2 (j+1)
5690           else -1
5691         ) else
5692           i (* found *)
5693       in
5694       let r = loop2 0 in
5695       if r = -1 then loop (i+1) else r
5696     ) else
5697       -1 (* not found *)
5698   in
5699   loop 0
5700
5701 let rec replace_str s s1 s2 =
5702   let len = String.length s in
5703   let sublen = String.length s1 in
5704   let i = find s s1 in
5705   if i = -1 then s
5706   else (
5707     let s' = String.sub s 0 i in
5708     let s'' = String.sub s (i+sublen) (len-i-sublen) in
5709     s' ^ s2 ^ replace_str s'' s1 s2
5710   )
5711
5712 let rec string_split sep str =
5713   let len = String.length str in
5714   let seplen = String.length sep in
5715   let i = find str sep in
5716   if i = -1 then [str]
5717   else (
5718     let s' = String.sub str 0 i in
5719     let s'' = String.sub str (i+seplen) (len-i-seplen) in
5720     s' :: string_split sep s''
5721   )
5722
5723 let files_equal n1 n2 =
5724   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
5725   match Sys.command cmd with
5726   | 0 -> true
5727   | 1 -> false
5728   | i -> failwithf "%s: failed with error code %d" cmd i
5729
5730 let rec filter_map f = function
5731   | [] -> []
5732   | x :: xs ->
5733       match f x with
5734       | Some y -> y :: filter_map f xs
5735       | None -> filter_map f xs
5736
5737 let rec find_map f = function
5738   | [] -> raise Not_found
5739   | x :: xs ->
5740       match f x with
5741       | Some y -> y
5742       | None -> find_map f xs
5743
5744 let iteri f xs =
5745   let rec loop i = function
5746     | [] -> ()
5747     | x :: xs -> f i x; loop (i+1) xs
5748   in
5749   loop 0 xs
5750
5751 let mapi f xs =
5752   let rec loop i = function
5753     | [] -> []
5754     | x :: xs -> let r = f i x in r :: loop (i+1) xs
5755   in
5756   loop 0 xs
5757
5758 let count_chars c str =
5759   let count = ref 0 in
5760   for i = 0 to String.length str - 1 do
5761     if c = String.unsafe_get str i then incr count
5762   done;
5763   !count
5764
5765 let explode str =
5766   let r = ref [] in
5767   for i = 0 to String.length str - 1 do
5768     let c = String.unsafe_get str i in
5769     r := c :: !r;
5770   done;
5771   List.rev !r
5772
5773 let map_chars f str =
5774   List.map f (explode str)
5775
5776 let name_of_argt = function
5777   | Pathname n | Device n | Dev_or_Path n | String n | OptString n
5778   | StringList n | DeviceList n | Bool n | Int n | Int64 n
5779   | FileIn n | FileOut n | BufferIn n | Key n -> n
5780
5781 let java_name_of_struct typ =
5782   try List.assoc typ java_structs
5783   with Not_found ->
5784     failwithf
5785       "java_name_of_struct: no java_structs entry corresponding to %s" typ
5786
5787 let cols_of_struct typ =
5788   try List.assoc typ structs
5789   with Not_found ->
5790     failwithf "cols_of_struct: unknown struct %s" typ
5791
5792 let seq_of_test = function
5793   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
5794   | TestOutputListOfDevices (s, _)
5795   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
5796   | TestOutputTrue s | TestOutputFalse s
5797   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
5798   | TestOutputStruct (s, _)
5799   | TestLastFail s -> s
5800
5801 (* Handling for function flags. *)
5802 let protocol_limit_warning =
5803   "Because of the message protocol, there is a transfer limit
5804 of somewhere between 2MB and 4MB.  See L<guestfs(3)/PROTOCOL LIMITS>."
5805
5806 let danger_will_robinson =
5807   "B<This command is dangerous.  Without careful use you
5808 can easily destroy all your data>."
5809
5810 let deprecation_notice flags =
5811   try
5812     let alt =
5813       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
5814     let txt =
5815       sprintf "This function is deprecated.
5816 In new code, use the C<%s> call instead.
5817
5818 Deprecated functions will not be removed from the API, but the
5819 fact that they are deprecated indicates that there are problems
5820 with correct use of these functions." alt in
5821     Some txt
5822   with
5823     Not_found -> None
5824
5825 (* Create list of optional groups. *)
5826 let optgroups =
5827   let h = Hashtbl.create 13 in
5828   List.iter (
5829     fun (name, _, _, flags, _, _, _) ->
5830       List.iter (
5831         function
5832         | Optional group ->
5833             let names = try Hashtbl.find h group with Not_found -> [] in
5834             Hashtbl.replace h group (name :: names)
5835         | _ -> ()
5836       ) flags
5837   ) daemon_functions;
5838   let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
5839   let groups =
5840     List.map (
5841       fun group -> group, List.sort compare (Hashtbl.find h group)
5842     ) groups in
5843   List.sort (fun x y -> compare (fst x) (fst y)) groups
5844
5845 (* Check function names etc. for consistency. *)
5846 let check_functions () =
5847   let contains_uppercase str =
5848     let len = String.length str in
5849     let rec loop i =
5850       if i >= len then false
5851       else (
5852         let c = str.[i] in
5853         if c >= 'A' && c <= 'Z' then true
5854         else loop (i+1)
5855       )
5856     in
5857     loop 0
5858   in
5859
5860   (* Check function names. *)
5861   List.iter (
5862     fun (name, _, _, _, _, _, _) ->
5863       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
5864         failwithf "function name %s does not need 'guestfs' prefix" name;
5865       if name = "" then
5866         failwithf "function name is empty";
5867       if name.[0] < 'a' || name.[0] > 'z' then
5868         failwithf "function name %s must start with lowercase a-z" name;
5869       if String.contains name '-' then
5870         failwithf "function name %s should not contain '-', use '_' instead."
5871           name
5872   ) all_functions;
5873
5874   (* Check function parameter/return names. *)
5875   List.iter (
5876     fun (name, style, _, _, _, _, _) ->
5877       let check_arg_ret_name n =
5878         if contains_uppercase n then
5879           failwithf "%s param/ret %s should not contain uppercase chars"
5880             name n;
5881         if String.contains n '-' || String.contains n '_' then
5882           failwithf "%s param/ret %s should not contain '-' or '_'"
5883             name n;
5884         if n = "value" then
5885           failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
5886         if n = "int" || n = "char" || n = "short" || n = "long" then
5887           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
5888         if n = "i" || n = "n" then
5889           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
5890         if n = "argv" || n = "args" then
5891           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
5892
5893         (* List Haskell, OCaml and C keywords here.
5894          * http://www.haskell.org/haskellwiki/Keywords
5895          * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
5896          * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
5897          * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
5898          *   |perl -pe 's/(.+)/"$1";/'|fmt -70
5899          * Omitting _-containing words, since they're handled above.
5900          * Omitting the OCaml reserved word, "val", is ok,
5901          * and saves us from renaming several parameters.
5902          *)
5903         let reserved = [
5904           "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
5905           "char"; "class"; "const"; "constraint"; "continue"; "data";
5906           "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
5907           "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
5908           "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
5909           "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
5910           "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
5911           "interface";
5912           "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
5913           "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
5914           "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
5915           "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
5916           "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
5917           "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
5918           "volatile"; "when"; "where"; "while";
5919           ] in
5920         if List.mem n reserved then
5921           failwithf "%s has param/ret using reserved word %s" name n;
5922       in
5923
5924       (match fst style with
5925        | RErr -> ()
5926        | RInt n | RInt64 n | RBool n
5927        | RConstString n | RConstOptString n | RString n
5928        | RStringList n | RStruct (n, _) | RStructList (n, _)
5929        | RHashtable n | RBufferOut n ->
5930            check_arg_ret_name n
5931       );
5932       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
5933   ) all_functions;
5934
5935   (* Check short descriptions. *)
5936   List.iter (
5937     fun (name, _, _, _, _, shortdesc, _) ->
5938       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
5939         failwithf "short description of %s should begin with lowercase." name;
5940       let c = shortdesc.[String.length shortdesc-1] in
5941       if c = '\n' || c = '.' then
5942         failwithf "short description of %s should not end with . or \\n." name
5943   ) all_functions;
5944
5945   (* Check long descriptions. *)
5946   List.iter (
5947     fun (name, _, _, _, _, _, longdesc) ->
5948       if longdesc.[String.length longdesc-1] = '\n' then
5949         failwithf "long description of %s should not end with \\n." name
5950   ) all_functions;
5951
5952   (* Check proc_nrs. *)
5953   List.iter (
5954     fun (name, _, proc_nr, _, _, _, _) ->
5955       if proc_nr <= 0 then
5956         failwithf "daemon function %s should have proc_nr > 0" name
5957   ) daemon_functions;
5958
5959   List.iter (
5960     fun (name, _, proc_nr, _, _, _, _) ->
5961       if proc_nr <> -1 then
5962         failwithf "non-daemon function %s should have proc_nr -1" name
5963   ) non_daemon_functions;
5964
5965   let proc_nrs =
5966     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
5967       daemon_functions in
5968   let proc_nrs =
5969     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
5970   let rec loop = function
5971     | [] -> ()
5972     | [_] -> ()
5973     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
5974         loop rest
5975     | (name1,nr1) :: (name2,nr2) :: _ ->
5976         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
5977           name1 name2 nr1 nr2
5978   in
5979   loop proc_nrs;
5980
5981   (* Check tests. *)
5982   List.iter (
5983     function
5984       (* Ignore functions that have no tests.  We generate a
5985        * warning when the user does 'make check' instead.
5986        *)
5987     | name, _, _, _, [], _, _ -> ()
5988     | name, _, _, _, tests, _, _ ->
5989         let funcs =
5990           List.map (
5991             fun (_, _, test) ->
5992               match seq_of_test test with
5993               | [] ->
5994                   failwithf "%s has a test containing an empty sequence" name
5995               | cmds -> List.map List.hd cmds
5996           ) tests in
5997         let funcs = List.flatten funcs in
5998
5999         let tested = List.mem name funcs in
6000
6001         if not tested then
6002           failwithf "function %s has tests but does not test itself" name
6003   ) all_functions
6004
6005 (* 'pr' prints to the current output file. *)
6006 let chan = ref Pervasives.stdout
6007 let lines = ref 0
6008 let pr fs =
6009   ksprintf
6010     (fun str ->
6011        let i = count_chars '\n' str in
6012        lines := !lines + i;
6013        output_string !chan str
6014     ) fs
6015
6016 let copyright_years =
6017   let this_year = 1900 + (localtime (time ())).tm_year in
6018   if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
6019
6020 (* Generate a header block in a number of standard styles. *)
6021 type comment_style =
6022     CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
6023 type license = GPLv2plus | LGPLv2plus
6024
6025 let generate_header ?(extra_inputs = []) comment license =
6026   let inputs = "src/generator.ml" :: extra_inputs in
6027   let c = match comment with
6028     | CStyle ->         pr "/* "; " *"
6029     | CPlusPlusStyle -> pr "// "; "//"
6030     | HashStyle ->      pr "# ";  "#"
6031     | OCamlStyle ->     pr "(* "; " *"
6032     | HaskellStyle ->   pr "{- "; "  " in
6033   pr "libguestfs generated file\n";
6034   pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
6035   List.iter (pr "%s   %s\n" c) inputs;
6036   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
6037   pr "%s\n" c;
6038   pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
6039   pr "%s\n" c;
6040   (match license with
6041    | GPLv2plus ->
6042        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
6043        pr "%s it under the terms of the GNU General Public License as published by\n" c;
6044        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
6045        pr "%s (at your option) any later version.\n" c;
6046        pr "%s\n" c;
6047        pr "%s This program is distributed in the hope that it will be useful,\n" c;
6048        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6049        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
6050        pr "%s GNU General Public License for more details.\n" c;
6051        pr "%s\n" c;
6052        pr "%s You should have received a copy of the GNU General Public License along\n" c;
6053        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
6054        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
6055
6056    | LGPLv2plus ->
6057        pr "%s This library is free software; you can redistribute it and/or\n" c;
6058        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
6059        pr "%s License as published by the Free Software Foundation; either\n" c;
6060        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
6061        pr "%s\n" c;
6062        pr "%s This library is distributed in the hope that it will be useful,\n" c;
6063        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6064        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
6065        pr "%s Lesser General Public License for more details.\n" c;
6066        pr "%s\n" c;
6067        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
6068        pr "%s License along with this library; if not, write to the Free Software\n" c;
6069        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
6070   );
6071   (match comment with
6072    | CStyle -> pr " */\n"
6073    | CPlusPlusStyle
6074    | HashStyle -> ()
6075    | OCamlStyle -> pr " *)\n"
6076    | HaskellStyle -> pr "-}\n"
6077   );
6078   pr "\n"
6079
6080 (* Start of main code generation functions below this line. *)
6081
6082 (* Generate the pod documentation for the C API. *)
6083 let rec generate_actions_pod () =
6084   List.iter (
6085     fun (shortname, style, _, flags, _, _, longdesc) ->
6086       if not (List.mem NotInDocs flags) then (
6087         let name = "guestfs_" ^ shortname in
6088         pr "=head2 %s\n\n" name;
6089         pr " ";
6090         generate_prototype ~extern:false ~handle:"g" name style;
6091         pr "\n\n";
6092         pr "%s\n\n" longdesc;
6093         (match fst style with
6094          | RErr ->
6095              pr "This function returns 0 on success or -1 on error.\n\n"
6096          | RInt _ ->
6097              pr "On error this function returns -1.\n\n"
6098          | RInt64 _ ->
6099              pr "On error this function returns -1.\n\n"
6100          | RBool _ ->
6101              pr "This function returns a C truth value on success or -1 on error.\n\n"
6102          | RConstString _ ->
6103              pr "This function returns a string, or NULL on error.
6104 The string is owned by the guest handle and must I<not> be freed.\n\n"
6105          | RConstOptString _ ->
6106              pr "This function returns a string which may be NULL.
6107 There is no way to return an error from this function.
6108 The string is owned by the guest handle and must I<not> be freed.\n\n"
6109          | RString _ ->
6110              pr "This function returns a string, or NULL on error.
6111 I<The caller must free the returned string after use>.\n\n"
6112          | RStringList _ ->
6113              pr "This function returns a NULL-terminated array of strings
6114 (like L<environ(3)>), or NULL if there was an error.
6115 I<The caller must free the strings and the array after use>.\n\n"
6116          | RStruct (_, typ) ->
6117              pr "This function returns a C<struct guestfs_%s *>,
6118 or NULL if there was an error.
6119 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
6120          | RStructList (_, typ) ->
6121              pr "This function returns a C<struct guestfs_%s_list *>
6122 (see E<lt>guestfs-structs.hE<gt>),
6123 or NULL if there was an error.
6124 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
6125          | RHashtable _ ->
6126              pr "This function returns a NULL-terminated array of
6127 strings, or NULL if there was an error.
6128 The array of strings will always have length C<2n+1>, where
6129 C<n> keys and values alternate, followed by the trailing NULL entry.
6130 I<The caller must free the strings and the array after use>.\n\n"
6131          | RBufferOut _ ->
6132              pr "This function returns a buffer, or NULL on error.
6133 The size of the returned buffer is written to C<*size_r>.
6134 I<The caller must free the returned buffer after use>.\n\n"
6135         );
6136         if List.mem ProtocolLimitWarning flags then
6137           pr "%s\n\n" protocol_limit_warning;
6138         if List.mem DangerWillRobinson flags then
6139           pr "%s\n\n" danger_will_robinson;
6140         if List.exists (function Key _ -> true | _ -> false) (snd style) then
6141           pr "This function takes a key or passphrase parameter which
6142 could contain sensitive material.  Read the section
6143 L</KEYS AND PASSPHRASES> for more information.\n\n";
6144         match deprecation_notice flags with
6145         | None -> ()
6146         | Some txt -> pr "%s\n\n" txt
6147       )
6148   ) all_functions_sorted
6149
6150 and generate_structs_pod () =
6151   (* Structs documentation. *)
6152   List.iter (
6153     fun (typ, cols) ->
6154       pr "=head2 guestfs_%s\n" typ;
6155       pr "\n";
6156       pr " struct guestfs_%s {\n" typ;
6157       List.iter (
6158         function
6159         | name, FChar -> pr "   char %s;\n" name
6160         | name, FUInt32 -> pr "   uint32_t %s;\n" name
6161         | name, FInt32 -> pr "   int32_t %s;\n" name
6162         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
6163         | name, FInt64 -> pr "   int64_t %s;\n" name
6164         | name, FString -> pr "   char *%s;\n" name
6165         | name, FBuffer ->
6166             pr "   /* The next two fields describe a byte array. */\n";
6167             pr "   uint32_t %s_len;\n" name;
6168             pr "   char *%s;\n" name
6169         | name, FUUID ->
6170             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
6171             pr "   char %s[32];\n" name
6172         | name, FOptPercent ->
6173             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
6174             pr "   float %s;\n" name
6175       ) cols;
6176       pr " };\n";
6177       pr " \n";
6178       pr " struct guestfs_%s_list {\n" typ;
6179       pr "   uint32_t len; /* Number of elements in list. */\n";
6180       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
6181       pr " };\n";
6182       pr " \n";
6183       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
6184       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
6185         typ typ;
6186       pr "\n"
6187   ) structs
6188
6189 and generate_availability_pod () =
6190   (* Availability documentation. *)
6191   pr "=over 4\n";
6192   pr "\n";
6193   List.iter (
6194     fun (group, functions) ->
6195       pr "=item B<%s>\n" group;
6196       pr "\n";
6197       pr "The following functions:\n";
6198       List.iter (pr "L</guestfs_%s>\n") functions;
6199       pr "\n"
6200   ) optgroups;
6201   pr "=back\n";
6202   pr "\n"
6203
6204 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
6205  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
6206  *
6207  * We have to use an underscore instead of a dash because otherwise
6208  * rpcgen generates incorrect code.
6209  *
6210  * This header is NOT exported to clients, but see also generate_structs_h.
6211  *)
6212 and generate_xdr () =
6213   generate_header CStyle LGPLv2plus;
6214
6215   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
6216   pr "typedef string guestfs_str<>;\n";
6217   pr "\n";
6218
6219   (* Internal structures. *)
6220   List.iter (
6221     function
6222     | typ, cols ->
6223         pr "struct guestfs_int_%s {\n" typ;
6224         List.iter (function
6225                    | name, FChar -> pr "  char %s;\n" name
6226                    | name, FString -> pr "  string %s<>;\n" name
6227                    | name, FBuffer -> pr "  opaque %s<>;\n" name
6228                    | name, FUUID -> pr "  opaque %s[32];\n" name
6229                    | name, (FInt32|FUInt32) -> pr "  int %s;\n" name
6230                    | name, (FInt64|FUInt64|FBytes) -> pr "  hyper %s;\n" name
6231                    | name, FOptPercent -> pr "  float %s;\n" name
6232                   ) cols;
6233         pr "};\n";
6234         pr "\n";
6235         pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
6236         pr "\n";
6237   ) structs;
6238
6239   List.iter (
6240     fun (shortname, style, _, _, _, _, _) ->
6241       let name = "guestfs_" ^ shortname in
6242
6243       (match snd style with
6244        | [] -> ()
6245        | args ->
6246            pr "struct %s_args {\n" name;
6247            List.iter (
6248              function
6249              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6250                  pr "  string %s<>;\n" n
6251              | OptString n -> pr "  guestfs_str *%s;\n" n
6252              | StringList n | DeviceList n -> pr "  guestfs_str %s<>;\n" n
6253              | Bool n -> pr "  bool %s;\n" n
6254              | Int n -> pr "  int %s;\n" n
6255              | Int64 n -> pr "  hyper %s;\n" n
6256              | BufferIn n ->
6257                  pr "  opaque %s<>;\n" n
6258              | FileIn _ | FileOut _ -> ()
6259            ) args;
6260            pr "};\n\n"
6261       );
6262       (match fst style with
6263        | RErr -> ()
6264        | RInt n ->
6265            pr "struct %s_ret {\n" name;
6266            pr "  int %s;\n" n;
6267            pr "};\n\n"
6268        | RInt64 n ->
6269            pr "struct %s_ret {\n" name;
6270            pr "  hyper %s;\n" n;
6271            pr "};\n\n"
6272        | RBool n ->
6273            pr "struct %s_ret {\n" name;
6274            pr "  bool %s;\n" n;
6275            pr "};\n\n"
6276        | RConstString _ | RConstOptString _ ->
6277            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6278        | RString n ->
6279            pr "struct %s_ret {\n" name;
6280            pr "  string %s<>;\n" n;
6281            pr "};\n\n"
6282        | RStringList n ->
6283            pr "struct %s_ret {\n" name;
6284            pr "  guestfs_str %s<>;\n" n;
6285            pr "};\n\n"
6286        | RStruct (n, typ) ->
6287            pr "struct %s_ret {\n" name;
6288            pr "  guestfs_int_%s %s;\n" typ n;
6289            pr "};\n\n"
6290        | RStructList (n, typ) ->
6291            pr "struct %s_ret {\n" name;
6292            pr "  guestfs_int_%s_list %s;\n" typ n;
6293            pr "};\n\n"
6294        | RHashtable n ->
6295            pr "struct %s_ret {\n" name;
6296            pr "  guestfs_str %s<>;\n" n;
6297            pr "};\n\n"
6298        | RBufferOut n ->
6299            pr "struct %s_ret {\n" name;
6300            pr "  opaque %s<>;\n" n;
6301            pr "};\n\n"
6302       );
6303   ) daemon_functions;
6304
6305   (* Table of procedure numbers. *)
6306   pr "enum guestfs_procedure {\n";
6307   List.iter (
6308     fun (shortname, _, proc_nr, _, _, _, _) ->
6309       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
6310   ) daemon_functions;
6311   pr "  GUESTFS_PROC_NR_PROCS\n";
6312   pr "};\n";
6313   pr "\n";
6314
6315   (* Having to choose a maximum message size is annoying for several
6316    * reasons (it limits what we can do in the API), but it (a) makes
6317    * the protocol a lot simpler, and (b) provides a bound on the size
6318    * of the daemon which operates in limited memory space.
6319    *)
6320   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
6321   pr "\n";
6322
6323   (* Message header, etc. *)
6324   pr "\
6325 /* The communication protocol is now documented in the guestfs(3)
6326  * manpage.
6327  */
6328
6329 const GUESTFS_PROGRAM = 0x2000F5F5;
6330 const GUESTFS_PROTOCOL_VERSION = 2;
6331
6332 /* These constants must be larger than any possible message length. */
6333 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
6334 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
6335 const GUESTFS_PROGRESS_FLAG = 0xffff5555;
6336
6337 enum guestfs_message_direction {
6338   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
6339   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
6340 };
6341
6342 enum guestfs_message_status {
6343   GUESTFS_STATUS_OK = 0,
6344   GUESTFS_STATUS_ERROR = 1
6345 };
6346
6347 ";
6348
6349   pr "const GUESTFS_ERROR_LEN = %d;\n" (64 * 1024);
6350   pr "\n";
6351
6352   pr "\
6353 struct guestfs_message_error {
6354   int linux_errno;                   /* Linux errno if available. */
6355   string error_message<GUESTFS_ERROR_LEN>;
6356 };
6357
6358 struct guestfs_message_header {
6359   unsigned prog;                     /* GUESTFS_PROGRAM */
6360   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
6361   guestfs_procedure proc;            /* GUESTFS_PROC_x */
6362   guestfs_message_direction direction;
6363   unsigned serial;                   /* message serial number */
6364   guestfs_message_status status;
6365 };
6366
6367 const GUESTFS_MAX_CHUNK_SIZE = 8192;
6368
6369 struct guestfs_chunk {
6370   int cancel;                        /* if non-zero, transfer is cancelled */
6371   /* data size is 0 bytes if the transfer has finished successfully */
6372   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
6373 };
6374
6375 /* Progress notifications.  Daemon self-limits these messages to
6376  * at most one per second.  The daemon can send these messages
6377  * at any time, and the caller should discard unexpected messages.
6378  * 'position' and 'total' have undefined units; however they may
6379  * have meaning for some calls.
6380  *
6381  * NB. guestfs___recv_from_daemon assumes the XDR-encoded
6382  * structure is 24 bytes long.
6383  */
6384 struct guestfs_progress {
6385   guestfs_procedure proc;            /* @0:  GUESTFS_PROC_x */
6386   unsigned serial;                   /* @4:  message serial number */
6387   unsigned hyper position;           /* @8:  0 <= position <= total */
6388   unsigned hyper total;              /* @16: total size of operation */
6389                                      /* @24: size of structure */
6390 };
6391 "
6392
6393 (* Generate the guestfs-structs.h file. *)
6394 and generate_structs_h () =
6395   generate_header CStyle LGPLv2plus;
6396
6397   (* This is a public exported header file containing various
6398    * structures.  The structures are carefully written to have
6399    * exactly the same in-memory format as the XDR structures that
6400    * we use on the wire to the daemon.  The reason for creating
6401    * copies of these structures here is just so we don't have to
6402    * export the whole of guestfs_protocol.h (which includes much
6403    * unrelated and XDR-dependent stuff that we don't want to be
6404    * public, or required by clients).
6405    *
6406    * To reiterate, we will pass these structures to and from the
6407    * client with a simple assignment or memcpy, so the format
6408    * must be identical to what rpcgen / the RFC defines.
6409    *)
6410
6411   (* Public structures. *)
6412   List.iter (
6413     fun (typ, cols) ->
6414       pr "struct guestfs_%s {\n" typ;
6415       List.iter (
6416         function
6417         | name, FChar -> pr "  char %s;\n" name
6418         | name, FString -> pr "  char *%s;\n" name
6419         | name, FBuffer ->
6420             pr "  uint32_t %s_len;\n" name;
6421             pr "  char *%s;\n" name
6422         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
6423         | name, FUInt32 -> pr "  uint32_t %s;\n" name
6424         | name, FInt32 -> pr "  int32_t %s;\n" name
6425         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
6426         | name, FInt64 -> pr "  int64_t %s;\n" name
6427         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
6428       ) cols;
6429       pr "};\n";
6430       pr "\n";
6431       pr "struct guestfs_%s_list {\n" typ;
6432       pr "  uint32_t len;\n";
6433       pr "  struct guestfs_%s *val;\n" typ;
6434       pr "};\n";
6435       pr "\n";
6436       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
6437       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
6438       pr "\n"
6439   ) structs
6440
6441 (* Generate the guestfs-actions.h file. *)
6442 and generate_actions_h () =
6443   generate_header CStyle LGPLv2plus;
6444   List.iter (
6445     fun (shortname, style, _, _, _, _, _) ->
6446       let name = "guestfs_" ^ shortname in
6447       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6448         name style
6449   ) all_functions
6450
6451 (* Generate the guestfs-internal-actions.h file. *)
6452 and generate_internal_actions_h () =
6453   generate_header CStyle LGPLv2plus;
6454   List.iter (
6455     fun (shortname, style, _, _, _, _, _) ->
6456       let name = "guestfs__" ^ shortname in
6457       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6458         name style
6459   ) non_daemon_functions
6460
6461 (* Generate the client-side dispatch stubs. *)
6462 and generate_client_actions () =
6463   generate_header CStyle LGPLv2plus;
6464
6465   pr "\
6466 #include <stdio.h>
6467 #include <stdlib.h>
6468 #include <stdint.h>
6469 #include <string.h>
6470 #include <inttypes.h>
6471
6472 #include \"guestfs.h\"
6473 #include \"guestfs-internal.h\"
6474 #include \"guestfs-internal-actions.h\"
6475 #include \"guestfs_protocol.h\"
6476
6477 /* Check the return message from a call for validity. */
6478 static int
6479 check_reply_header (guestfs_h *g,
6480                     const struct guestfs_message_header *hdr,
6481                     unsigned int proc_nr, unsigned int serial)
6482 {
6483   if (hdr->prog != GUESTFS_PROGRAM) {
6484     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
6485     return -1;
6486   }
6487   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
6488     error (g, \"wrong protocol version (%%d/%%d)\",
6489            hdr->vers, GUESTFS_PROTOCOL_VERSION);
6490     return -1;
6491   }
6492   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
6493     error (g, \"unexpected message direction (%%d/%%d)\",
6494            hdr->direction, GUESTFS_DIRECTION_REPLY);
6495     return -1;
6496   }
6497   if (hdr->proc != proc_nr) {
6498     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
6499     return -1;
6500   }
6501   if (hdr->serial != serial) {
6502     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
6503     return -1;
6504   }
6505
6506   return 0;
6507 }
6508
6509 /* Check we are in the right state to run a high-level action. */
6510 static int
6511 check_state (guestfs_h *g, const char *caller)
6512 {
6513   if (!guestfs__is_ready (g)) {
6514     if (guestfs__is_config (g) || guestfs__is_launching (g))
6515       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
6516         caller);
6517     else
6518       error (g, \"%%s called from the wrong state, %%d != READY\",
6519         caller, guestfs__get_state (g));
6520     return -1;
6521   }
6522   return 0;
6523 }
6524
6525 ";
6526
6527   let error_code_of = function
6528     | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
6529     | RConstString _ | RConstOptString _
6530     | RString _ | RStringList _
6531     | RStruct _ | RStructList _
6532     | RHashtable _ | RBufferOut _ -> "NULL"
6533   in
6534
6535   (* Generate code to check String-like parameters are not passed in
6536    * as NULL (returning an error if they are).
6537    *)
6538   let check_null_strings shortname style =
6539     let pr_newline = ref false in
6540     List.iter (
6541       function
6542       (* parameters which should not be NULL *)
6543       | String n
6544       | Device n
6545       | Pathname n
6546       | Dev_or_Path n
6547       | FileIn n
6548       | FileOut n
6549       | BufferIn n
6550       | StringList n
6551       | DeviceList n
6552       | Key n ->
6553           pr "  if (%s == NULL) {\n" n;
6554           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
6555           pr "           \"%s\", \"%s\");\n" shortname n;
6556           pr "    return %s;\n" (error_code_of (fst style));
6557           pr "  }\n";
6558           pr_newline := true
6559
6560       (* can be NULL *)
6561       | OptString _
6562
6563       (* not applicable *)
6564       | Bool _
6565       | Int _
6566       | Int64 _ -> ()
6567     ) (snd style);
6568
6569     if !pr_newline then pr "\n";
6570   in
6571
6572   (* Generate code to generate guestfish call traces. *)
6573   let trace_call shortname style =
6574     pr "  if (guestfs__get_trace (g)) {\n";
6575
6576     let needs_i =
6577       List.exists (function
6578                    | StringList _ | DeviceList _ -> true
6579                    | _ -> false) (snd style) in
6580     if needs_i then (
6581       pr "    size_t i;\n";
6582       pr "\n"
6583     );
6584
6585     pr "    fprintf (stderr, \"%s\");\n" shortname;
6586     List.iter (
6587       function
6588       | String n                        (* strings *)
6589       | Device n
6590       | Pathname n
6591       | Dev_or_Path n
6592       | FileIn n
6593       | FileOut n
6594       | BufferIn n
6595       | Key n ->
6596           (* guestfish doesn't support string escaping, so neither do we *)
6597           pr "    fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
6598       | OptString n ->                  (* string option *)
6599           pr "    if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
6600           pr "    else fprintf (stderr, \" null\");\n"
6601       | StringList n
6602       | DeviceList n ->                 (* string list *)
6603           pr "    fputc (' ', stderr);\n";
6604           pr "    fputc ('\"', stderr);\n";
6605           pr "    for (i = 0; %s[i]; ++i) {\n" n;
6606           pr "      if (i > 0) fputc (' ', stderr);\n";
6607           pr "      fputs (%s[i], stderr);\n" n;
6608           pr "    }\n";
6609           pr "    fputc ('\"', stderr);\n";
6610       | Bool n ->                       (* boolean *)
6611           pr "    fputs (%s ? \" true\" : \" false\", stderr);\n" n
6612       | Int n ->                        (* int *)
6613           pr "    fprintf (stderr, \" %%d\", %s);\n" n
6614       | Int64 n ->
6615           pr "    fprintf (stderr, \" %%\" PRIi64, %s);\n" n
6616     ) (snd style);
6617     pr "    fputc ('\\n', stderr);\n";
6618     pr "  }\n";
6619     pr "\n";
6620   in
6621
6622   (* For non-daemon functions, generate a wrapper around each function. *)
6623   List.iter (
6624     fun (shortname, style, _, _, _, _, _) ->
6625       let name = "guestfs_" ^ shortname in
6626
6627       generate_prototype ~extern:false ~semicolon:false ~newline:true
6628         ~handle:"g" name style;
6629       pr "{\n";
6630       check_null_strings shortname style;
6631       trace_call shortname style;
6632       pr "  return guestfs__%s " shortname;
6633       generate_c_call_args ~handle:"g" style;
6634       pr ";\n";
6635       pr "}\n";
6636       pr "\n"
6637   ) non_daemon_functions;
6638
6639   (* Client-side stubs for each function. *)
6640   List.iter (
6641     fun (shortname, style, _, _, _, _, _) ->
6642       let name = "guestfs_" ^ shortname in
6643       let error_code = error_code_of (fst style) in
6644
6645       (* Generate the action stub. *)
6646       generate_prototype ~extern:false ~semicolon:false ~newline:true
6647         ~handle:"g" name style;
6648
6649       pr "{\n";
6650
6651       (match snd style with
6652        | [] -> ()
6653        | _ -> pr "  struct %s_args args;\n" name
6654       );
6655
6656       pr "  guestfs_message_header hdr;\n";
6657       pr "  guestfs_message_error err;\n";
6658       let has_ret =
6659         match fst style with
6660         | RErr -> false
6661         | RConstString _ | RConstOptString _ ->
6662             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6663         | RInt _ | RInt64 _
6664         | RBool _ | RString _ | RStringList _
6665         | RStruct _ | RStructList _
6666         | RHashtable _ | RBufferOut _ ->
6667             pr "  struct %s_ret ret;\n" name;
6668             true in
6669
6670       pr "  int serial;\n";
6671       pr "  int r;\n";
6672       pr "\n";
6673       check_null_strings shortname style;
6674       trace_call shortname style;
6675       pr "  if (check_state (g, \"%s\") == -1) return %s;\n"
6676         shortname error_code;
6677       pr "  guestfs___set_busy (g);\n";
6678       pr "\n";
6679
6680       (* Send the main header and arguments. *)
6681       (match snd style with
6682        | [] ->
6683            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
6684              (String.uppercase shortname)
6685        | args ->
6686            List.iter (
6687              function
6688              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6689                  pr "  args.%s = (char *) %s;\n" n n
6690              | OptString n ->
6691                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
6692              | StringList n | DeviceList n ->
6693                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
6694                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
6695              | Bool n ->
6696                  pr "  args.%s = %s;\n" n n
6697              | Int n ->
6698                  pr "  args.%s = %s;\n" n n
6699              | Int64 n ->
6700                  pr "  args.%s = %s;\n" n n
6701              | FileIn _ | FileOut _ -> ()
6702              | BufferIn n ->
6703                  pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
6704                  pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
6705                  pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
6706                    shortname;
6707                  pr "    guestfs___end_busy (g);\n";
6708                  pr "    return %s;\n" error_code;
6709                  pr "  }\n";
6710                  pr "  args.%s.%s_val = (char *) %s;\n" n n n;
6711                  pr "  args.%s.%s_len = %s_size;\n" n n n
6712            ) args;
6713            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
6714              (String.uppercase shortname);
6715            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
6716              name;
6717       );
6718       pr "  if (serial == -1) {\n";
6719       pr "    guestfs___end_busy (g);\n";
6720       pr "    return %s;\n" error_code;
6721       pr "  }\n";
6722       pr "\n";
6723
6724       (* Send any additional files (FileIn) requested. *)
6725       let need_read_reply_label = ref false in
6726       List.iter (
6727         function
6728         | FileIn n ->
6729             pr "  r = guestfs___send_file (g, %s);\n" n;
6730             pr "  if (r == -1) {\n";
6731             pr "    guestfs___end_busy (g);\n";
6732             pr "    return %s;\n" error_code;
6733             pr "  }\n";
6734             pr "  if (r == -2) /* daemon cancelled */\n";
6735             pr "    goto read_reply;\n";
6736             need_read_reply_label := true;
6737             pr "\n";
6738         | _ -> ()
6739       ) (snd style);
6740
6741       (* Wait for the reply from the remote end. *)
6742       if !need_read_reply_label then pr " read_reply:\n";
6743       pr "  memset (&hdr, 0, sizeof hdr);\n";
6744       pr "  memset (&err, 0, sizeof err);\n";
6745       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
6746       pr "\n";
6747       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
6748       if not has_ret then
6749         pr "NULL, NULL"
6750       else
6751         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
6752       pr ");\n";
6753
6754       pr "  if (r == -1) {\n";
6755       pr "    guestfs___end_busy (g);\n";
6756       pr "    return %s;\n" error_code;
6757       pr "  }\n";
6758       pr "\n";
6759
6760       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
6761         (String.uppercase shortname);
6762       pr "    guestfs___end_busy (g);\n";
6763       pr "    return %s;\n" error_code;
6764       pr "  }\n";
6765       pr "\n";
6766
6767       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
6768       pr "    error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
6769       pr "    free (err.error_message);\n";
6770       pr "    guestfs___end_busy (g);\n";
6771       pr "    return %s;\n" error_code;
6772       pr "  }\n";
6773       pr "\n";
6774
6775       (* Expecting to receive further files (FileOut)? *)
6776       List.iter (
6777         function
6778         | FileOut n ->
6779             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
6780             pr "    guestfs___end_busy (g);\n";
6781             pr "    return %s;\n" error_code;
6782             pr "  }\n";
6783             pr "\n";
6784         | _ -> ()
6785       ) (snd style);
6786
6787       pr "  guestfs___end_busy (g);\n";
6788
6789       (match fst style with
6790        | RErr -> pr "  return 0;\n"
6791        | RInt n | RInt64 n | RBool n ->
6792            pr "  return ret.%s;\n" n
6793        | RConstString _ | RConstOptString _ ->
6794            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6795        | RString n ->
6796            pr "  return ret.%s; /* caller will free */\n" n
6797        | RStringList n | RHashtable n ->
6798            pr "  /* caller will free this, but we need to add a NULL entry */\n";
6799            pr "  ret.%s.%s_val =\n" n n;
6800            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
6801            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
6802              n n;
6803            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
6804            pr "  return ret.%s.%s_val;\n" n n
6805        | RStruct (n, _) ->
6806            pr "  /* caller will free this */\n";
6807            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6808        | RStructList (n, _) ->
6809            pr "  /* caller will free this */\n";
6810            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6811        | RBufferOut n ->
6812            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
6813            pr "   * _val might be NULL here.  To make the API saner for\n";
6814            pr "   * callers, we turn this case into a unique pointer (using\n";
6815            pr "   * malloc(1)).\n";
6816            pr "   */\n";
6817            pr "  if (ret.%s.%s_len > 0) {\n" n n;
6818            pr "    *size_r = ret.%s.%s_len;\n" n n;
6819            pr "    return ret.%s.%s_val; /* caller will free */\n" n n;
6820            pr "  } else {\n";
6821            pr "    free (ret.%s.%s_val);\n" n n;
6822            pr "    char *p = safe_malloc (g, 1);\n";
6823            pr "    *size_r = ret.%s.%s_len;\n" n n;
6824            pr "    return p;\n";
6825            pr "  }\n";
6826       );
6827
6828       pr "}\n\n"
6829   ) daemon_functions;
6830
6831   (* Functions to free structures. *)
6832   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
6833   pr " * structure format is identical to the XDR format.  See note in\n";
6834   pr " * generator.ml.\n";
6835   pr " */\n";
6836   pr "\n";
6837
6838   List.iter (
6839     fun (typ, _) ->
6840       pr "void\n";
6841       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
6842       pr "{\n";
6843       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
6844       pr "  free (x);\n";
6845       pr "}\n";
6846       pr "\n";
6847
6848       pr "void\n";
6849       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
6850       pr "{\n";
6851       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
6852       pr "  free (x);\n";
6853       pr "}\n";
6854       pr "\n";
6855
6856   ) structs;
6857
6858 (* Generate daemon/actions.h. *)
6859 and generate_daemon_actions_h () =
6860   generate_header CStyle GPLv2plus;
6861
6862   pr "#include \"../src/guestfs_protocol.h\"\n";
6863   pr "\n";
6864
6865   List.iter (
6866     fun (name, style, _, _, _, _, _) ->
6867       generate_prototype
6868         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
6869         name style;
6870   ) daemon_functions
6871
6872 (* Generate the linker script which controls the visibility of
6873  * symbols in the public ABI and ensures no other symbols get
6874  * exported accidentally.
6875  *)
6876 and generate_linker_script () =
6877   generate_header HashStyle GPLv2plus;
6878
6879   let globals = [
6880     "guestfs_create";
6881     "guestfs_close";
6882     "guestfs_get_error_handler";
6883     "guestfs_get_out_of_memory_handler";
6884     "guestfs_last_error";
6885     "guestfs_set_close_callback";
6886     "guestfs_set_error_handler";
6887     "guestfs_set_launch_done_callback";
6888     "guestfs_set_log_message_callback";
6889     "guestfs_set_out_of_memory_handler";
6890     "guestfs_set_progress_callback";
6891     "guestfs_set_subprocess_quit_callback";
6892
6893     (* Unofficial parts of the API: the bindings code use these
6894      * functions, so it is useful to export them.
6895      *)
6896     "guestfs_safe_calloc";
6897     "guestfs_safe_malloc";
6898     "guestfs_safe_strdup";
6899     "guestfs_safe_memdup";
6900   ] in
6901   let functions =
6902     List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
6903       all_functions in
6904   let structs =
6905     List.concat (
6906       List.map (fun (typ, _) ->
6907                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
6908         structs
6909     ) in
6910   let globals = List.sort compare (globals @ functions @ structs) in
6911
6912   pr "{\n";
6913   pr "    global:\n";
6914   List.iter (pr "        %s;\n") globals;
6915   pr "\n";
6916
6917   pr "    local:\n";
6918   pr "        *;\n";
6919   pr "};\n"
6920
6921 (* Generate the server-side stubs. *)
6922 and generate_daemon_actions () =
6923   generate_header CStyle GPLv2plus;
6924
6925   pr "#include <config.h>\n";
6926   pr "\n";
6927   pr "#include <stdio.h>\n";
6928   pr "#include <stdlib.h>\n";
6929   pr "#include <string.h>\n";
6930   pr "#include <inttypes.h>\n";
6931   pr "#include <rpc/types.h>\n";
6932   pr "#include <rpc/xdr.h>\n";
6933   pr "\n";
6934   pr "#include \"daemon.h\"\n";
6935   pr "#include \"c-ctype.h\"\n";
6936   pr "#include \"../src/guestfs_protocol.h\"\n";
6937   pr "#include \"actions.h\"\n";
6938   pr "\n";
6939
6940   List.iter (
6941     fun (name, style, _, _, _, _, _) ->
6942       (* Generate server-side stubs. *)
6943       pr "static void %s_stub (XDR *xdr_in)\n" name;
6944       pr "{\n";
6945       let error_code =
6946         match fst style with
6947         | RErr | RInt _ -> pr "  int r;\n"; "-1"
6948         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
6949         | RBool _ -> pr "  int r;\n"; "-1"
6950         | RConstString _ | RConstOptString _ ->
6951             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6952         | RString _ -> pr "  char *r;\n"; "NULL"
6953         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
6954         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
6955         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
6956         | RBufferOut _ ->
6957             pr "  size_t size = 1;\n";
6958             pr "  char *r;\n";
6959             "NULL" in
6960
6961       (match snd style with
6962        | [] -> ()
6963        | args ->
6964            pr "  struct guestfs_%s_args args;\n" name;
6965            List.iter (
6966              function
6967              | Device n | Dev_or_Path n
6968              | Pathname n
6969              | String n
6970              | Key n -> ()
6971              | OptString n -> pr "  char *%s;\n" n
6972              | StringList n | DeviceList n -> pr "  char **%s;\n" n
6973              | Bool n -> pr "  int %s;\n" n
6974              | Int n -> pr "  int %s;\n" n
6975              | Int64 n -> pr "  int64_t %s;\n" n
6976              | FileIn _ | FileOut _ -> ()
6977              | BufferIn n ->
6978                  pr "  const char *%s;\n" n;
6979                  pr "  size_t %s_size;\n" n
6980            ) args
6981       );
6982       pr "\n";
6983
6984       let is_filein =
6985         List.exists (function FileIn _ -> true | _ -> false) (snd style) in
6986
6987       (match snd style with
6988        | [] -> ()
6989        | args ->
6990            pr "  memset (&args, 0, sizeof args);\n";
6991            pr "\n";
6992            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
6993            if is_filein then
6994              pr "    if (cancel_receive () != -2)\n";
6995            pr "      reply_with_error (\"daemon failed to decode procedure arguments\");\n";
6996            pr "    goto done;\n";
6997            pr "  }\n";
6998            let pr_args n =
6999              pr "  char *%s = args.%s;\n" n n
7000            in
7001            let pr_list_handling_code n =
7002              pr "  %s = realloc (args.%s.%s_val,\n" n n n;
7003              pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
7004              pr "  if (%s == NULL) {\n" n;
7005              if is_filein then
7006                pr "    if (cancel_receive () != -2)\n";
7007              pr "      reply_with_perror (\"realloc\");\n";
7008              pr "    goto done;\n";
7009              pr "  }\n";
7010              pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
7011              pr "  args.%s.%s_val = %s;\n" n n n;
7012            in
7013            List.iter (
7014              function
7015              | Pathname n ->
7016                  pr_args n;
7017                  pr "  ABS_PATH (%s, %s, goto done);\n"
7018                    n (if is_filein then "cancel_receive ()" else "0");
7019              | Device n ->
7020                  pr_args n;
7021                  pr "  RESOLVE_DEVICE (%s, %s, goto done);\n"
7022                    n (if is_filein then "cancel_receive ()" else "0");
7023              | Dev_or_Path n ->
7024                  pr_args n;
7025                  pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
7026                    n (if is_filein then "cancel_receive ()" else "0");
7027              | String n | Key n -> pr_args n
7028              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
7029              | StringList n ->
7030                  pr_list_handling_code n;
7031              | DeviceList n ->
7032                  pr_list_handling_code n;
7033                  pr "  /* Ensure that each is a device,\n";
7034                  pr "   * and perform device name translation.\n";
7035                  pr "   */\n";
7036                  pr "  {\n";
7037                  pr "    size_t i;\n";
7038                  pr "    for (i = 0; %s[i] != NULL; ++i)\n" n;
7039                  pr "      RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
7040                    (if is_filein then "cancel_receive ()" else "0");
7041                  pr "  }\n";
7042              | Bool n -> pr "  %s = args.%s;\n" n n
7043              | Int n -> pr "  %s = args.%s;\n" n n
7044              | Int64 n -> pr "  %s = args.%s;\n" n n
7045              | FileIn _ | FileOut _ -> ()
7046              | BufferIn n ->
7047                  pr "  %s = args.%s.%s_val;\n" n n n;
7048                  pr "  %s_size = args.%s.%s_len;\n" n n n
7049            ) args;
7050            pr "\n"
7051       );
7052
7053       (* this is used at least for do_equal *)
7054       if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
7055         (* Emit NEED_ROOT just once, even when there are two or
7056            more Pathname args *)
7057         pr "  NEED_ROOT (%s, goto done);\n"
7058           (if is_filein then "cancel_receive ()" else "0");
7059       );
7060
7061       (* Don't want to call the impl with any FileIn or FileOut
7062        * parameters, since these go "outside" the RPC protocol.
7063        *)
7064       let args' =
7065         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
7066           (snd style) in
7067       pr "  r = do_%s " name;
7068       generate_c_call_args (fst style, args');
7069       pr ";\n";
7070
7071       (match fst style with
7072        | RErr | RInt _ | RInt64 _ | RBool _
7073        | RConstString _ | RConstOptString _
7074        | RString _ | RStringList _ | RHashtable _
7075        | RStruct (_, _) | RStructList (_, _) ->
7076            pr "  if (r == %s)\n" error_code;
7077            pr "    /* do_%s has already called reply_with_error */\n" name;
7078            pr "    goto done;\n";
7079            pr "\n"
7080        | RBufferOut _ ->
7081            pr "  /* size == 0 && r == NULL could be a non-error case (just\n";
7082            pr "   * an ordinary zero-length buffer), so be careful ...\n";
7083            pr "   */\n";
7084            pr "  if (size == 1 && r == %s)\n" error_code;
7085            pr "    /* do_%s has already called reply_with_error */\n" name;
7086            pr "    goto done;\n";
7087            pr "\n"
7088       );
7089
7090       (* If there are any FileOut parameters, then the impl must
7091        * send its own reply.
7092        *)
7093       let no_reply =
7094         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
7095       if no_reply then
7096         pr "  /* do_%s has already sent a reply */\n" name
7097       else (
7098         match fst style with
7099         | RErr -> pr "  reply (NULL, NULL);\n"
7100         | RInt n | RInt64 n | RBool n ->
7101             pr "  struct guestfs_%s_ret ret;\n" name;
7102             pr "  ret.%s = r;\n" n;
7103             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7104               name
7105         | RConstString _ | RConstOptString _ ->
7106             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7107         | RString n ->
7108             pr "  struct guestfs_%s_ret ret;\n" name;
7109             pr "  ret.%s = r;\n" n;
7110             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7111               name;
7112             pr "  free (r);\n"
7113         | RStringList n | RHashtable n ->
7114             pr "  struct guestfs_%s_ret ret;\n" name;
7115             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
7116             pr "  ret.%s.%s_val = r;\n" n n;
7117             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7118               name;
7119             pr "  free_strings (r);\n"
7120         | RStruct (n, _) ->
7121             pr "  struct guestfs_%s_ret ret;\n" name;
7122             pr "  ret.%s = *r;\n" n;
7123             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7124               name;
7125             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7126               name
7127         | RStructList (n, _) ->
7128             pr "  struct guestfs_%s_ret ret;\n" name;
7129             pr "  ret.%s = *r;\n" n;
7130             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7131               name;
7132             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7133               name
7134         | RBufferOut n ->
7135             pr "  struct guestfs_%s_ret ret;\n" name;
7136             pr "  ret.%s.%s_val = r;\n" n n;
7137             pr "  ret.%s.%s_len = size;\n" n n;
7138             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7139               name;
7140             pr "  free (r);\n"
7141       );
7142
7143       (* Free the args. *)
7144       pr "done:\n";
7145       (match snd style with
7146        | [] -> ()
7147        | _ ->
7148            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
7149              name
7150       );
7151       pr "  return;\n";
7152       pr "}\n\n";
7153   ) daemon_functions;
7154
7155   (* Dispatch function. *)
7156   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
7157   pr "{\n";
7158   pr "  switch (proc_nr) {\n";
7159
7160   List.iter (
7161     fun (name, style, _, _, _, _, _) ->
7162       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
7163       pr "      %s_stub (xdr_in);\n" name;
7164       pr "      break;\n"
7165   ) daemon_functions;
7166
7167   pr "    default:\n";
7168   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";
7169   pr "  }\n";
7170   pr "}\n";
7171   pr "\n";
7172
7173   (* LVM columns and tokenization functions. *)
7174   (* XXX This generates crap code.  We should rethink how we
7175    * do this parsing.
7176    *)
7177   List.iter (
7178     function
7179     | typ, cols ->
7180         pr "static const char *lvm_%s_cols = \"%s\";\n"
7181           typ (String.concat "," (List.map fst cols));
7182         pr "\n";
7183
7184         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
7185         pr "{\n";
7186         pr "  char *tok, *p, *next;\n";
7187         pr "  size_t i, j;\n";
7188         pr "\n";
7189         (*
7190           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
7191           pr "\n";
7192         *)
7193         pr "  if (!str) {\n";
7194         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
7195         pr "    return -1;\n";
7196         pr "  }\n";
7197         pr "  if (!*str || c_isspace (*str)) {\n";
7198         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
7199         pr "    return -1;\n";
7200         pr "  }\n";
7201         pr "  tok = str;\n";
7202         List.iter (
7203           fun (name, coltype) ->
7204             pr "  if (!tok) {\n";
7205             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
7206             pr "    return -1;\n";
7207             pr "  }\n";
7208             pr "  p = strchrnul (tok, ',');\n";
7209             pr "  if (*p) next = p+1; else next = NULL;\n";
7210             pr "  *p = '\\0';\n";
7211             (match coltype with
7212              | FString ->
7213                  pr "  r->%s = strdup (tok);\n" name;
7214                  pr "  if (r->%s == NULL) {\n" name;
7215                  pr "    perror (\"strdup\");\n";
7216                  pr "    return -1;\n";
7217                  pr "  }\n"
7218              | FUUID ->
7219                  pr "  for (i = j = 0; i < 32; ++j) {\n";
7220                  pr "    if (tok[j] == '\\0') {\n";
7221                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
7222                  pr "      return -1;\n";
7223                  pr "    } else if (tok[j] != '-')\n";
7224                  pr "      r->%s[i++] = tok[j];\n" name;
7225                  pr "  }\n";
7226              | FBytes ->
7227                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
7228                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7229                  pr "    return -1;\n";
7230                  pr "  }\n";
7231              | FInt64 ->
7232                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
7233                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7234                  pr "    return -1;\n";
7235                  pr "  }\n";
7236              | FOptPercent ->
7237                  pr "  if (tok[0] == '\\0')\n";
7238                  pr "    r->%s = -1;\n" name;
7239                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
7240                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7241                  pr "    return -1;\n";
7242                  pr "  }\n";
7243              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
7244                  assert false (* can never be an LVM column *)
7245             );
7246             pr "  tok = next;\n";
7247         ) cols;
7248
7249         pr "  if (tok != NULL) {\n";
7250         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
7251         pr "    return -1;\n";
7252         pr "  }\n";
7253         pr "  return 0;\n";
7254         pr "}\n";
7255         pr "\n";
7256
7257         pr "guestfs_int_lvm_%s_list *\n" typ;
7258         pr "parse_command_line_%ss (void)\n" typ;
7259         pr "{\n";
7260         pr "  char *out, *err;\n";
7261         pr "  char *p, *pend;\n";
7262         pr "  int r, i;\n";
7263         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
7264         pr "  void *newp;\n";
7265         pr "\n";
7266         pr "  ret = malloc (sizeof *ret);\n";
7267         pr "  if (!ret) {\n";
7268         pr "    reply_with_perror (\"malloc\");\n";
7269         pr "    return NULL;\n";
7270         pr "  }\n";
7271         pr "\n";
7272         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
7273         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
7274         pr "\n";
7275         pr "  r = command (&out, &err,\n";
7276         pr "           \"lvm\", \"%ss\",\n" typ;
7277         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
7278         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
7279         pr "  if (r == -1) {\n";
7280         pr "    reply_with_error (\"%%s\", err);\n";
7281         pr "    free (out);\n";
7282         pr "    free (err);\n";
7283         pr "    free (ret);\n";
7284         pr "    return NULL;\n";
7285         pr "  }\n";
7286         pr "\n";
7287         pr "  free (err);\n";
7288         pr "\n";
7289         pr "  /* Tokenize each line of the output. */\n";
7290         pr "  p = out;\n";
7291         pr "  i = 0;\n";
7292         pr "  while (p) {\n";
7293         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
7294         pr "    if (pend) {\n";
7295         pr "      *pend = '\\0';\n";
7296         pr "      pend++;\n";
7297         pr "    }\n";
7298         pr "\n";
7299         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
7300         pr "      p++;\n";
7301         pr "\n";
7302         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
7303         pr "      p = pend;\n";
7304         pr "      continue;\n";
7305         pr "    }\n";
7306         pr "\n";
7307         pr "    /* Allocate some space to store this next entry. */\n";
7308         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
7309         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
7310         pr "    if (newp == NULL) {\n";
7311         pr "      reply_with_perror (\"realloc\");\n";
7312         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7313         pr "      free (ret);\n";
7314         pr "      free (out);\n";
7315         pr "      return NULL;\n";
7316         pr "    }\n";
7317         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
7318         pr "\n";
7319         pr "    /* Tokenize the next entry. */\n";
7320         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
7321         pr "    if (r == -1) {\n";
7322         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
7323         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7324         pr "      free (ret);\n";
7325         pr "      free (out);\n";
7326         pr "      return NULL;\n";
7327         pr "    }\n";
7328         pr "\n";
7329         pr "    ++i;\n";
7330         pr "    p = pend;\n";
7331         pr "  }\n";
7332         pr "\n";
7333         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
7334         pr "\n";
7335         pr "  free (out);\n";
7336         pr "  return ret;\n";
7337         pr "}\n"
7338
7339   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
7340
7341 (* Generate a list of function names, for debugging in the daemon.. *)
7342 and generate_daemon_names () =
7343   generate_header CStyle GPLv2plus;
7344
7345   pr "#include <config.h>\n";
7346   pr "\n";
7347   pr "#include \"daemon.h\"\n";
7348   pr "\n";
7349
7350   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
7351   pr "const char *function_names[] = {\n";
7352   List.iter (
7353     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
7354   ) daemon_functions;
7355   pr "};\n";
7356
7357 (* Generate the optional groups for the daemon to implement
7358  * guestfs_available.
7359  *)
7360 and generate_daemon_optgroups_c () =
7361   generate_header CStyle GPLv2plus;
7362
7363   pr "#include <config.h>\n";
7364   pr "\n";
7365   pr "#include \"daemon.h\"\n";
7366   pr "#include \"optgroups.h\"\n";
7367   pr "\n";
7368
7369   pr "struct optgroup optgroups[] = {\n";
7370   List.iter (
7371     fun (group, _) ->
7372       pr "  { \"%s\", optgroup_%s_available },\n" group group
7373   ) optgroups;
7374   pr "  { NULL, NULL }\n";
7375   pr "};\n"
7376
7377 and generate_daemon_optgroups_h () =
7378   generate_header CStyle GPLv2plus;
7379
7380   List.iter (
7381     fun (group, _) ->
7382       pr "extern int optgroup_%s_available (void);\n" group
7383   ) optgroups
7384
7385 (* Generate the tests. *)
7386 and generate_tests () =
7387   generate_header CStyle GPLv2plus;
7388
7389   pr "\
7390 #include <stdio.h>
7391 #include <stdlib.h>
7392 #include <string.h>
7393 #include <unistd.h>
7394 #include <sys/types.h>
7395 #include <fcntl.h>
7396
7397 #include \"guestfs.h\"
7398 #include \"guestfs-internal.h\"
7399
7400 static guestfs_h *g;
7401 static int suppress_error = 0;
7402
7403 static void print_error (guestfs_h *g, void *data, const char *msg)
7404 {
7405   if (!suppress_error)
7406     fprintf (stderr, \"%%s\\n\", msg);
7407 }
7408
7409 /* FIXME: nearly identical code appears in fish.c */
7410 static void print_strings (char *const *argv)
7411 {
7412   size_t argc;
7413
7414   for (argc = 0; argv[argc] != NULL; ++argc)
7415     printf (\"\\t%%s\\n\", argv[argc]);
7416 }
7417
7418 /*
7419 static void print_table (char const *const *argv)
7420 {
7421   size_t i;
7422
7423   for (i = 0; argv[i] != NULL; i += 2)
7424     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
7425 }
7426 */
7427
7428 static int
7429 is_available (const char *group)
7430 {
7431   const char *groups[] = { group, NULL };
7432   int r;
7433
7434   suppress_error = 1;
7435   r = guestfs_available (g, (char **) groups);
7436   suppress_error = 0;
7437
7438   return r == 0;
7439 }
7440
7441 static void
7442 incr (guestfs_h *g, void *iv)
7443 {
7444   int *i = (int *) iv;
7445   (*i)++;
7446 }
7447
7448 ";
7449
7450   (* Generate a list of commands which are not tested anywhere. *)
7451   pr "static void no_test_warnings (void)\n";
7452   pr "{\n";
7453
7454   let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
7455   List.iter (
7456     fun (_, _, _, _, tests, _, _) ->
7457       let tests = filter_map (
7458         function
7459         | (_, (Always|If _|Unless _|IfAvailable _), test) -> Some test
7460         | (_, Disabled, _) -> None
7461       ) tests in
7462       let seq = List.concat (List.map seq_of_test tests) in
7463       let cmds_tested = List.map List.hd seq in
7464       List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
7465   ) all_functions;
7466
7467   List.iter (
7468     fun (name, _, _, _, _, _, _) ->
7469       if not (Hashtbl.mem hash name) then
7470         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
7471   ) all_functions;
7472
7473   pr "}\n";
7474   pr "\n";
7475
7476   (* Generate the actual tests.  Note that we generate the tests
7477    * in reverse order, deliberately, so that (in general) the
7478    * newest tests run first.  This makes it quicker and easier to
7479    * debug them.
7480    *)
7481   let test_names =
7482     List.map (
7483       fun (name, _, _, flags, tests, _, _) ->
7484         mapi (generate_one_test name flags) tests
7485     ) (List.rev all_functions) in
7486   let test_names = List.concat test_names in
7487   let nr_tests = List.length test_names in
7488
7489   pr "\
7490 int main (int argc, char *argv[])
7491 {
7492   char c = 0;
7493   unsigned long int n_failed = 0;
7494   const char *filename;
7495   int fd;
7496   int nr_tests, test_num = 0;
7497
7498   setbuf (stdout, NULL);
7499
7500   no_test_warnings ();
7501
7502   g = guestfs_create ();
7503   if (g == NULL) {
7504     printf (\"guestfs_create FAILED\\n\");
7505     exit (EXIT_FAILURE);
7506   }
7507
7508   guestfs_set_error_handler (g, print_error, NULL);
7509
7510   guestfs_set_path (g, \"../appliance\");
7511
7512   filename = \"test1.img\";
7513   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7514   if (fd == -1) {
7515     perror (filename);
7516     exit (EXIT_FAILURE);
7517   }
7518   if (lseek (fd, %d, SEEK_SET) == -1) {
7519     perror (\"lseek\");
7520     close (fd);
7521     unlink (filename);
7522     exit (EXIT_FAILURE);
7523   }
7524   if (write (fd, &c, 1) == -1) {
7525     perror (\"write\");
7526     close (fd);
7527     unlink (filename);
7528     exit (EXIT_FAILURE);
7529   }
7530   if (close (fd) == -1) {
7531     perror (filename);
7532     unlink (filename);
7533     exit (EXIT_FAILURE);
7534   }
7535   if (guestfs_add_drive (g, filename) == -1) {
7536     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7537     exit (EXIT_FAILURE);
7538   }
7539
7540   filename = \"test2.img\";
7541   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7542   if (fd == -1) {
7543     perror (filename);
7544     exit (EXIT_FAILURE);
7545   }
7546   if (lseek (fd, %d, SEEK_SET) == -1) {
7547     perror (\"lseek\");
7548     close (fd);
7549     unlink (filename);
7550     exit (EXIT_FAILURE);
7551   }
7552   if (write (fd, &c, 1) == -1) {
7553     perror (\"write\");
7554     close (fd);
7555     unlink (filename);
7556     exit (EXIT_FAILURE);
7557   }
7558   if (close (fd) == -1) {
7559     perror (filename);
7560     unlink (filename);
7561     exit (EXIT_FAILURE);
7562   }
7563   if (guestfs_add_drive (g, filename) == -1) {
7564     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7565     exit (EXIT_FAILURE);
7566   }
7567
7568   filename = \"test3.img\";
7569   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7570   if (fd == -1) {
7571     perror (filename);
7572     exit (EXIT_FAILURE);
7573   }
7574   if (lseek (fd, %d, SEEK_SET) == -1) {
7575     perror (\"lseek\");
7576     close (fd);
7577     unlink (filename);
7578     exit (EXIT_FAILURE);
7579   }
7580   if (write (fd, &c, 1) == -1) {
7581     perror (\"write\");
7582     close (fd);
7583     unlink (filename);
7584     exit (EXIT_FAILURE);
7585   }
7586   if (close (fd) == -1) {
7587     perror (filename);
7588     unlink (filename);
7589     exit (EXIT_FAILURE);
7590   }
7591   if (guestfs_add_drive (g, filename) == -1) {
7592     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7593     exit (EXIT_FAILURE);
7594   }
7595
7596   if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
7597     printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
7598     exit (EXIT_FAILURE);
7599   }
7600
7601   /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
7602   alarm (600);
7603
7604   if (guestfs_launch (g) == -1) {
7605     printf (\"guestfs_launch FAILED\\n\");
7606     exit (EXIT_FAILURE);
7607   }
7608
7609   /* Cancel previous alarm. */
7610   alarm (0);
7611
7612   nr_tests = %d;
7613
7614 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
7615
7616   iteri (
7617     fun i test_name ->
7618       pr "  test_num++;\n";
7619       pr "  if (guestfs_get_verbose (g))\n";
7620       pr "    printf (\"-------------------------------------------------------------------------------\\n\");\n";
7621       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
7622       pr "  if (%s () == -1) {\n" test_name;
7623       pr "    printf (\"%s FAILED\\n\");\n" test_name;
7624       pr "    n_failed++;\n";
7625       pr "  }\n";
7626   ) test_names;
7627   pr "\n";
7628
7629   pr "  /* Check close callback is called. */
7630   int close_sentinel = 1;
7631   guestfs_set_close_callback (g, incr, &close_sentinel);
7632
7633   guestfs_close (g);
7634
7635   if (close_sentinel != 2) {
7636     fprintf (stderr, \"close callback was not called\\n\");
7637     exit (EXIT_FAILURE);
7638   }
7639
7640   unlink (\"test1.img\");
7641   unlink (\"test2.img\");
7642   unlink (\"test3.img\");
7643
7644 ";
7645
7646   pr "  if (n_failed > 0) {\n";
7647   pr "    printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
7648   pr "    exit (EXIT_FAILURE);\n";
7649   pr "  }\n";
7650   pr "\n";
7651
7652   pr "  exit (EXIT_SUCCESS);\n";
7653   pr "}\n"
7654
7655 and generate_one_test name flags i (init, prereq, test) =
7656   let test_name = sprintf "test_%s_%d" name i in
7657
7658   pr "\
7659 static int %s_skip (void)
7660 {
7661   const char *str;
7662
7663   str = getenv (\"TEST_ONLY\");
7664   if (str)
7665     return strstr (str, \"%s\") == NULL;
7666   str = getenv (\"SKIP_%s\");
7667   if (str && STREQ (str, \"1\")) return 1;
7668   str = getenv (\"SKIP_TEST_%s\");
7669   if (str && STREQ (str, \"1\")) return 1;
7670   return 0;
7671 }
7672
7673 " test_name name (String.uppercase test_name) (String.uppercase name);
7674
7675   (match prereq with
7676    | Disabled | Always | IfAvailable _ -> ()
7677    | If code | Unless code ->
7678        pr "static int %s_prereq (void)\n" test_name;
7679        pr "{\n";
7680        pr "  %s\n" code;
7681        pr "}\n";
7682        pr "\n";
7683   );
7684
7685   pr "\
7686 static int %s (void)
7687 {
7688   if (%s_skip ()) {
7689     printf (\"        %%s skipped (reason: environment variable set)\\n\", \"%s\");
7690     return 0;
7691   }
7692
7693 " test_name test_name test_name;
7694
7695   (* Optional functions should only be tested if the relevant
7696    * support is available in the daemon.
7697    *)
7698   List.iter (
7699     function
7700     | Optional group ->
7701         pr "  if (!is_available (\"%s\")) {\n" group;
7702         pr "    printf (\"        %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", \"%s\");\n" test_name group;
7703         pr "    return 0;\n";
7704         pr "  }\n";
7705     | _ -> ()
7706   ) flags;
7707
7708   (match prereq with
7709    | Disabled ->
7710        pr "  printf (\"        %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
7711    | If _ ->
7712        pr "  if (! %s_prereq ()) {\n" test_name;
7713        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7714        pr "    return 0;\n";
7715        pr "  }\n";
7716        pr "\n";
7717        generate_one_test_body name i test_name init test;
7718    | Unless _ ->
7719        pr "  if (%s_prereq ()) {\n" test_name;
7720        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7721        pr "    return 0;\n";
7722        pr "  }\n";
7723        pr "\n";
7724        generate_one_test_body name i test_name init test;
7725    | IfAvailable group ->
7726        pr "  if (!is_available (\"%s\")) {\n" group;
7727        pr "    printf (\"        %%s skipped (reason: %%s not available)\\n\", \"%s\", \"%s\");\n" test_name group;
7728        pr "    return 0;\n";
7729        pr "  }\n";
7730        pr "\n";
7731        generate_one_test_body name i test_name init test;
7732    | Always ->
7733        generate_one_test_body name i test_name init test
7734   );
7735
7736   pr "  return 0;\n";
7737   pr "}\n";
7738   pr "\n";
7739   test_name
7740
7741 and generate_one_test_body name i test_name init test =
7742   (match init with
7743    | InitNone (* XXX at some point, InitNone and InitEmpty became
7744                * folded together as the same thing.  Really we should
7745                * make InitNone do nothing at all, but the tests may
7746                * need to be checked to make sure this is OK.
7747                *)
7748    | InitEmpty ->
7749        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
7750        List.iter (generate_test_command_call test_name)
7751          [["blockdev_setrw"; "/dev/sda"];
7752           ["umount_all"];
7753           ["lvm_remove_all"]]
7754    | InitPartition ->
7755        pr "  /* InitPartition for %s: create /dev/sda1 */\n" test_name;
7756        List.iter (generate_test_command_call test_name)
7757          [["blockdev_setrw"; "/dev/sda"];
7758           ["umount_all"];
7759           ["lvm_remove_all"];
7760           ["part_disk"; "/dev/sda"; "mbr"]]
7761    | InitBasicFS ->
7762        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
7763        List.iter (generate_test_command_call test_name)
7764          [["blockdev_setrw"; "/dev/sda"];
7765           ["umount_all"];
7766           ["lvm_remove_all"];
7767           ["part_disk"; "/dev/sda"; "mbr"];
7768           ["mkfs"; "ext2"; "/dev/sda1"];
7769           ["mount_options"; ""; "/dev/sda1"; "/"]]
7770    | InitBasicFSonLVM ->
7771        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
7772          test_name;
7773        List.iter (generate_test_command_call test_name)
7774          [["blockdev_setrw"; "/dev/sda"];
7775           ["umount_all"];
7776           ["lvm_remove_all"];
7777           ["part_disk"; "/dev/sda"; "mbr"];
7778           ["pvcreate"; "/dev/sda1"];
7779           ["vgcreate"; "VG"; "/dev/sda1"];
7780           ["lvcreate"; "LV"; "VG"; "8"];
7781           ["mkfs"; "ext2"; "/dev/VG/LV"];
7782           ["mount_options"; ""; "/dev/VG/LV"; "/"]]
7783    | InitISOFS ->
7784        pr "  /* InitISOFS for %s */\n" test_name;
7785        List.iter (generate_test_command_call test_name)
7786          [["blockdev_setrw"; "/dev/sda"];
7787           ["umount_all"];
7788           ["lvm_remove_all"];
7789           ["mount_ro"; "/dev/sdd"; "/"]]
7790   );
7791
7792   let get_seq_last = function
7793     | [] ->
7794         failwithf "%s: you cannot use [] (empty list) when expecting a command"
7795           test_name
7796     | seq ->
7797         let seq = List.rev seq in
7798         List.rev (List.tl seq), List.hd seq
7799   in
7800
7801   match test with
7802   | TestRun seq ->
7803       pr "  /* TestRun for %s (%d) */\n" name i;
7804       List.iter (generate_test_command_call test_name) seq
7805   | TestOutput (seq, expected) ->
7806       pr "  /* TestOutput for %s (%d) */\n" name i;
7807       pr "  const char *expected = \"%s\";\n" (c_quote expected);
7808       let seq, last = get_seq_last seq in
7809       let test () =
7810         pr "    if (STRNEQ (r, expected)) {\n";
7811         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7812         pr "      return -1;\n";
7813         pr "    }\n"
7814       in
7815       List.iter (generate_test_command_call test_name) seq;
7816       generate_test_command_call ~test test_name last
7817   | TestOutputList (seq, expected) ->
7818       pr "  /* TestOutputList for %s (%d) */\n" name i;
7819       let seq, last = get_seq_last seq in
7820       let test () =
7821         iteri (
7822           fun i str ->
7823             pr "    if (!r[%d]) {\n" i;
7824             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7825             pr "      print_strings (r);\n";
7826             pr "      return -1;\n";
7827             pr "    }\n";
7828             pr "    {\n";
7829             pr "      const char *expected = \"%s\";\n" (c_quote str);
7830             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7831             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7832             pr "        return -1;\n";
7833             pr "      }\n";
7834             pr "    }\n"
7835         ) expected;
7836         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7837         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7838           test_name;
7839         pr "      print_strings (r);\n";
7840         pr "      return -1;\n";
7841         pr "    }\n"
7842       in
7843       List.iter (generate_test_command_call test_name) seq;
7844       generate_test_command_call ~test test_name last
7845   | TestOutputListOfDevices (seq, expected) ->
7846       pr "  /* TestOutputListOfDevices for %s (%d) */\n" name i;
7847       let seq, last = get_seq_last seq in
7848       let test () =
7849         iteri (
7850           fun i str ->
7851             pr "    if (!r[%d]) {\n" i;
7852             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7853             pr "      print_strings (r);\n";
7854             pr "      return -1;\n";
7855             pr "    }\n";
7856             pr "    {\n";
7857             pr "      const char *expected = \"%s\";\n" (c_quote str);
7858             pr "      r[%d][5] = 's';\n" i;
7859             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7860             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7861             pr "        return -1;\n";
7862             pr "      }\n";
7863             pr "    }\n"
7864         ) expected;
7865         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7866         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7867           test_name;
7868         pr "      print_strings (r);\n";
7869         pr "      return -1;\n";
7870         pr "    }\n"
7871       in
7872       List.iter (generate_test_command_call test_name) seq;
7873       generate_test_command_call ~test test_name last
7874   | TestOutputInt (seq, expected) ->
7875       pr "  /* TestOutputInt for %s (%d) */\n" name i;
7876       let seq, last = get_seq_last seq in
7877       let test () =
7878         pr "    if (r != %d) {\n" expected;
7879         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
7880           test_name expected;
7881         pr "               (int) r);\n";
7882         pr "      return -1;\n";
7883         pr "    }\n"
7884       in
7885       List.iter (generate_test_command_call test_name) seq;
7886       generate_test_command_call ~test test_name last
7887   | TestOutputIntOp (seq, op, expected) ->
7888       pr "  /* TestOutputIntOp for %s (%d) */\n" name i;
7889       let seq, last = get_seq_last seq in
7890       let test () =
7891         pr "    if (! (r %s %d)) {\n" op expected;
7892         pr "      fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
7893           test_name op expected;
7894         pr "               (int) r);\n";
7895         pr "      return -1;\n";
7896         pr "    }\n"
7897       in
7898       List.iter (generate_test_command_call test_name) seq;
7899       generate_test_command_call ~test test_name last
7900   | TestOutputTrue seq ->
7901       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
7902       let seq, last = get_seq_last seq in
7903       let test () =
7904         pr "    if (!r) {\n";
7905         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
7906           test_name;
7907         pr "      return -1;\n";
7908         pr "    }\n"
7909       in
7910       List.iter (generate_test_command_call test_name) seq;
7911       generate_test_command_call ~test test_name last
7912   | TestOutputFalse seq ->
7913       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
7914       let seq, last = get_seq_last seq in
7915       let test () =
7916         pr "    if (r) {\n";
7917         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
7918           test_name;
7919         pr "      return -1;\n";
7920         pr "    }\n"
7921       in
7922       List.iter (generate_test_command_call test_name) seq;
7923       generate_test_command_call ~test test_name last
7924   | TestOutputLength (seq, expected) ->
7925       pr "  /* TestOutputLength for %s (%d) */\n" name i;
7926       let seq, last = get_seq_last seq in
7927       let test () =
7928         pr "    int j;\n";
7929         pr "    for (j = 0; j < %d; ++j)\n" expected;
7930         pr "      if (r[j] == NULL) {\n";
7931         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
7932           test_name;
7933         pr "        print_strings (r);\n";
7934         pr "        return -1;\n";
7935         pr "      }\n";
7936         pr "    if (r[j] != NULL) {\n";
7937         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
7938           test_name;
7939         pr "      print_strings (r);\n";
7940         pr "      return -1;\n";
7941         pr "    }\n"
7942       in
7943       List.iter (generate_test_command_call test_name) seq;
7944       generate_test_command_call ~test test_name last
7945   | TestOutputBuffer (seq, expected) ->
7946       pr "  /* TestOutputBuffer for %s (%d) */\n" name i;
7947       pr "  const char *expected = \"%s\";\n" (c_quote expected);
7948       let seq, last = get_seq_last seq in
7949       let len = String.length expected in
7950       let test () =
7951         pr "    if (size != %d) {\n" len;
7952         pr "      fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
7953         pr "      return -1;\n";
7954         pr "    }\n";
7955         pr "    if (STRNEQLEN (r, expected, size)) {\n";
7956         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7957         pr "      return -1;\n";
7958         pr "    }\n"
7959       in
7960       List.iter (generate_test_command_call test_name) seq;
7961       generate_test_command_call ~test test_name last
7962   | TestOutputStruct (seq, checks) ->
7963       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
7964       let seq, last = get_seq_last seq in
7965       let test () =
7966         List.iter (
7967           function
7968           | CompareWithInt (field, expected) ->
7969               pr "    if (r->%s != %d) {\n" field expected;
7970               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
7971                 test_name field expected;
7972               pr "               (int) r->%s);\n" field;
7973               pr "      return -1;\n";
7974               pr "    }\n"
7975           | CompareWithIntOp (field, op, expected) ->
7976               pr "    if (!(r->%s %s %d)) {\n" field op expected;
7977               pr "      fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
7978                 test_name field op expected;
7979               pr "               (int) r->%s);\n" field;
7980               pr "      return -1;\n";
7981               pr "    }\n"
7982           | CompareWithString (field, expected) ->
7983               pr "    if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
7984               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
7985                 test_name field expected;
7986               pr "               r->%s);\n" field;
7987               pr "      return -1;\n";
7988               pr "    }\n"
7989           | CompareFieldsIntEq (field1, field2) ->
7990               pr "    if (r->%s != r->%s) {\n" field1 field2;
7991               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
7992                 test_name field1 field2;
7993               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
7994               pr "      return -1;\n";
7995               pr "    }\n"
7996           | CompareFieldsStrEq (field1, field2) ->
7997               pr "    if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
7998               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
7999                 test_name field1 field2;
8000               pr "               r->%s, r->%s);\n" field1 field2;
8001               pr "      return -1;\n";
8002               pr "    }\n"
8003         ) checks
8004       in
8005       List.iter (generate_test_command_call test_name) seq;
8006       generate_test_command_call ~test test_name last
8007   | TestLastFail seq ->
8008       pr "  /* TestLastFail for %s (%d) */\n" name i;
8009       let seq, last = get_seq_last seq in
8010       List.iter (generate_test_command_call test_name) seq;
8011       generate_test_command_call test_name ~expect_error:true last
8012
8013 (* Generate the code to run a command, leaving the result in 'r'.
8014  * If you expect to get an error then you should set expect_error:true.
8015  *)
8016 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
8017   match cmd with
8018   | [] -> assert false
8019   | name :: args ->
8020       (* Look up the command to find out what args/ret it has. *)
8021       let style =
8022         try
8023           let _, style, _, _, _, _, _ =
8024             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
8025           style
8026         with Not_found ->
8027           failwithf "%s: in test, command %s was not found" test_name name in
8028
8029       if List.length (snd style) <> List.length args then
8030         failwithf "%s: in test, wrong number of args given to %s"
8031           test_name name;
8032
8033       pr "  {\n";
8034
8035       List.iter (
8036         function
8037         | OptString n, "NULL" -> ()
8038         | Pathname n, arg
8039         | Device n, arg
8040         | Dev_or_Path n, arg
8041         | String n, arg
8042         | OptString n, arg
8043         | Key n, arg ->
8044             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8045         | BufferIn n, arg ->
8046             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8047             pr "    size_t %s_size = %d;\n" n (String.length arg)
8048         | Int _, _
8049         | Int64 _, _
8050         | Bool _, _
8051         | FileIn _, _ | FileOut _, _ -> ()
8052         | StringList n, "" | DeviceList n, "" ->
8053             pr "    const char *const %s[1] = { NULL };\n" n
8054         | StringList n, arg | DeviceList n, arg ->
8055             let strs = string_split " " arg in
8056             iteri (
8057               fun i str ->
8058                 pr "    const char *%s_%d = \"%s\";\n" n i (c_quote str);
8059             ) strs;
8060             pr "    const char *const %s[] = {\n" n;
8061             iteri (
8062               fun i _ -> pr "      %s_%d,\n" n i
8063             ) strs;
8064             pr "      NULL\n";
8065             pr "    };\n";
8066       ) (List.combine (snd style) args);
8067
8068       let error_code =
8069         match fst style with
8070         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
8071         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
8072         | RConstString _ | RConstOptString _ ->
8073             pr "    const char *r;\n"; "NULL"
8074         | RString _ -> pr "    char *r;\n"; "NULL"
8075         | RStringList _ | RHashtable _ ->
8076             pr "    char **r;\n";
8077             pr "    size_t i;\n";
8078             "NULL"
8079         | RStruct (_, typ) ->
8080             pr "    struct guestfs_%s *r;\n" typ; "NULL"
8081         | RStructList (_, typ) ->
8082             pr "    struct guestfs_%s_list *r;\n" typ; "NULL"
8083         | RBufferOut _ ->
8084             pr "    char *r;\n";
8085             pr "    size_t size;\n";
8086             "NULL" in
8087
8088       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
8089       pr "    r = guestfs_%s (g" name;
8090
8091       (* Generate the parameters. *)
8092       List.iter (
8093         function
8094         | OptString _, "NULL" -> pr ", NULL"
8095         | Pathname n, _
8096         | Device n, _ | Dev_or_Path n, _
8097         | String n, _
8098         | OptString n, _
8099         | Key n, _ ->
8100             pr ", %s" n
8101         | BufferIn n, _ ->
8102             pr ", %s, %s_size" n n
8103         | FileIn _, arg | FileOut _, arg ->
8104             pr ", \"%s\"" (c_quote arg)
8105         | StringList n, _ | DeviceList n, _ ->
8106             pr ", (char **) %s" n
8107         | Int _, arg ->
8108             let i =
8109               try int_of_string arg
8110               with Failure "int_of_string" ->
8111                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
8112             pr ", %d" i
8113         | Int64 _, arg ->
8114             let i =
8115               try Int64.of_string arg
8116               with Failure "int_of_string" ->
8117                 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
8118             pr ", %Ld" i
8119         | Bool _, arg ->
8120             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
8121       ) (List.combine (snd style) args);
8122
8123       (match fst style with
8124        | RBufferOut _ -> pr ", &size"
8125        | _ -> ()
8126       );
8127
8128       pr ");\n";
8129
8130       if not expect_error then
8131         pr "    if (r == %s)\n" error_code
8132       else
8133         pr "    if (r != %s)\n" error_code;
8134       pr "      return -1;\n";
8135
8136       (* Insert the test code. *)
8137       (match test with
8138        | None -> ()
8139        | Some f -> f ()
8140       );
8141
8142       (match fst style with
8143        | RErr | RInt _ | RInt64 _ | RBool _
8144        | RConstString _ | RConstOptString _ -> ()
8145        | RString _ | RBufferOut _ -> pr "    free (r);\n"
8146        | RStringList _ | RHashtable _ ->
8147            pr "    for (i = 0; r[i] != NULL; ++i)\n";
8148            pr "      free (r[i]);\n";
8149            pr "    free (r);\n"
8150        | RStruct (_, typ) ->
8151            pr "    guestfs_free_%s (r);\n" typ
8152        | RStructList (_, typ) ->
8153            pr "    guestfs_free_%s_list (r);\n" typ
8154       );
8155
8156       pr "  }\n"
8157
8158 and c_quote str =
8159   let str = replace_str str "\r" "\\r" in
8160   let str = replace_str str "\n" "\\n" in
8161   let str = replace_str str "\t" "\\t" in
8162   let str = replace_str str "\000" "\\0" in
8163   str
8164
8165 (* Generate a lot of different functions for guestfish. *)
8166 and generate_fish_cmds () =
8167   generate_header CStyle GPLv2plus;
8168
8169   let all_functions =
8170     List.filter (
8171       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8172     ) all_functions in
8173   let all_functions_sorted =
8174     List.filter (
8175       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8176     ) all_functions_sorted in
8177
8178   pr "#include <config.h>\n";
8179   pr "\n";
8180   pr "#include <stdio.h>\n";
8181   pr "#include <stdlib.h>\n";
8182   pr "#include <string.h>\n";
8183   pr "#include <inttypes.h>\n";
8184   pr "\n";
8185   pr "#include <guestfs.h>\n";
8186   pr "#include \"c-ctype.h\"\n";
8187   pr "#include \"full-write.h\"\n";
8188   pr "#include \"xstrtol.h\"\n";
8189   pr "#include \"fish.h\"\n";
8190   pr "\n";
8191   pr "/* Valid suffixes allowed for numbers.  See Gnulib xstrtol function. */\n";
8192   pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
8193   pr "\n";
8194
8195   (* list_commands function, which implements guestfish -h *)
8196   pr "void list_commands (void)\n";
8197   pr "{\n";
8198   pr "  printf (\"    %%-16s     %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
8199   pr "  list_builtin_commands ();\n";
8200   List.iter (
8201     fun (name, _, _, flags, _, shortdesc, _) ->
8202       let name = replace_char name '_' '-' in
8203       pr "  printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
8204         name shortdesc
8205   ) all_functions_sorted;
8206   pr "  printf (\"    %%s\\n\",";
8207   pr "          _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
8208   pr "}\n";
8209   pr "\n";
8210
8211   (* display_command function, which implements guestfish -h cmd *)
8212   pr "int display_command (const char *cmd)\n";
8213   pr "{\n";
8214   List.iter (
8215     fun (name, style, _, flags, _, shortdesc, longdesc) ->
8216       let name2 = replace_char name '_' '-' in
8217       let alias =
8218         try find_map (function FishAlias n -> Some n | _ -> None) flags
8219         with Not_found -> name in
8220       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
8221       let synopsis =
8222         match snd style with
8223         | [] -> name2
8224         | args ->
8225             let args = List.filter (function Key _ -> false | _ -> true) args in
8226             sprintf "%s %s"
8227               name2 (String.concat " " (List.map name_of_argt args)) in
8228
8229       let warnings =
8230         if List.exists (function Key _ -> true | _ -> false) (snd style) then
8231           "\n\nThis command has one or more key or passphrase parameters.
8232 Guestfish will prompt for these separately."
8233         else "" in
8234
8235       let warnings =
8236         warnings ^
8237           if List.mem ProtocolLimitWarning flags then
8238             ("\n\n" ^ protocol_limit_warning)
8239           else "" in
8240
8241       (* For DangerWillRobinson commands, we should probably have
8242        * guestfish prompt before allowing you to use them (especially
8243        * in interactive mode). XXX
8244        *)
8245       let warnings =
8246         warnings ^
8247           if List.mem DangerWillRobinson flags then
8248             ("\n\n" ^ danger_will_robinson)
8249           else "" in
8250
8251       let warnings =
8252         warnings ^
8253           match deprecation_notice flags with
8254           | None -> ""
8255           | Some txt -> "\n\n" ^ txt in
8256
8257       let describe_alias =
8258         if name <> alias then
8259           sprintf "\n\nYou can use '%s' as an alias for this command." alias
8260         else "" in
8261
8262       pr "  if (";
8263       pr "STRCASEEQ (cmd, \"%s\")" name;
8264       if name <> name2 then
8265         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8266       if name <> alias then
8267         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8268       pr ") {\n";
8269       pr "    pod2text (\"%s\", _(\"%s\"), %S);\n"
8270         name2 shortdesc
8271         ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
8272          "=head1 DESCRIPTION\n\n" ^
8273          longdesc ^ warnings ^ describe_alias);
8274       pr "    return 0;\n";
8275       pr "  }\n";
8276       pr "  else\n"
8277   ) all_functions;
8278   pr "    return display_builtin_command (cmd);\n";
8279   pr "}\n";
8280   pr "\n";
8281
8282   let emit_print_list_function typ =
8283     pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
8284       typ typ typ;
8285     pr "{\n";
8286     pr "  unsigned int i;\n";
8287     pr "\n";
8288     pr "  for (i = 0; i < %ss->len; ++i) {\n" typ;
8289     pr "    printf (\"[%%d] = {\\n\", i);\n";
8290     pr "    print_%s_indent (&%ss->val[i], \"  \");\n" typ typ;
8291     pr "    printf (\"}\\n\");\n";
8292     pr "  }\n";
8293     pr "}\n";
8294     pr "\n";
8295   in
8296
8297   (* print_* functions *)
8298   List.iter (
8299     fun (typ, cols) ->
8300       let needs_i =
8301         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
8302
8303       pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
8304       pr "{\n";
8305       if needs_i then (
8306         pr "  unsigned int i;\n";
8307         pr "\n"
8308       );
8309       List.iter (
8310         function
8311         | name, FString ->
8312             pr "  printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
8313         | name, FUUID ->
8314             pr "  printf (\"%%s%s: \", indent);\n" name;
8315             pr "  for (i = 0; i < 32; ++i)\n";
8316             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
8317             pr "  printf (\"\\n\");\n"
8318         | name, FBuffer ->
8319             pr "  printf (\"%%s%s: \", indent);\n" name;
8320             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
8321             pr "    if (c_isprint (%s->%s[i]))\n" typ name;
8322             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
8323             pr "    else\n";
8324             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
8325             pr "  printf (\"\\n\");\n"
8326         | name, (FUInt64|FBytes) ->
8327             pr "  printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
8328               name typ name
8329         | name, FInt64 ->
8330             pr "  printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
8331               name typ name
8332         | name, FUInt32 ->
8333             pr "  printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
8334               name typ name
8335         | name, FInt32 ->
8336             pr "  printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
8337               name typ name
8338         | name, FChar ->
8339             pr "  printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
8340               name typ name
8341         | name, FOptPercent ->
8342             pr "  if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
8343               typ name name typ name;
8344             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
8345       ) cols;
8346       pr "}\n";
8347       pr "\n";
8348   ) structs;
8349
8350   (* Emit a print_TYPE_list function definition only if that function is used. *)
8351   List.iter (
8352     function
8353     | typ, (RStructListOnly | RStructAndList) ->
8354         (* generate the function for typ *)
8355         emit_print_list_function typ
8356     | typ, _ -> () (* empty *)
8357   ) (rstructs_used_by all_functions);
8358
8359   (* Emit a print_TYPE function definition only if that function is used. *)
8360   List.iter (
8361     function
8362     | typ, (RStructOnly | RStructAndList) ->
8363         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
8364         pr "{\n";
8365         pr "  print_%s_indent (%s, \"\");\n" typ typ;
8366         pr "}\n";
8367         pr "\n";
8368     | typ, _ -> () (* empty *)
8369   ) (rstructs_used_by all_functions);
8370
8371   (* run_<action> actions *)
8372   List.iter (
8373     fun (name, style, _, flags, _, _, _) ->
8374       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
8375       pr "{\n";
8376       (match fst style with
8377        | RErr
8378        | RInt _
8379        | RBool _ -> pr "  int r;\n"
8380        | RInt64 _ -> pr "  int64_t r;\n"
8381        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
8382        | RString _ -> pr "  char *r;\n"
8383        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
8384        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
8385        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
8386        | RBufferOut _ ->
8387            pr "  char *r;\n";
8388            pr "  size_t size;\n";
8389       );
8390       List.iter (
8391         function
8392         | Device n
8393         | String n
8394         | OptString n -> pr "  const char *%s;\n" n
8395         | Pathname n
8396         | Dev_or_Path n
8397         | FileIn n
8398         | FileOut n
8399         | Key n -> pr "  char *%s;\n" n
8400         | BufferIn n ->
8401             pr "  const char *%s;\n" n;
8402             pr "  size_t %s_size;\n" n
8403         | StringList n | DeviceList n -> pr "  char **%s;\n" n
8404         | Bool n -> pr "  int %s;\n" n
8405         | Int n -> pr "  int %s;\n" n
8406         | Int64 n -> pr "  int64_t %s;\n" n
8407       ) (snd style);
8408
8409       (* Check and convert parameters. *)
8410       let argc_expected =
8411         let args_no_keys =
8412           List.filter (function Key _ -> false | _ -> true) (snd style) in
8413         List.length args_no_keys in
8414       pr "  if (argc != %d) {\n" argc_expected;
8415       pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
8416         argc_expected;
8417       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
8418       pr "    return -1;\n";
8419       pr "  }\n";
8420
8421       let parse_integer fn fntyp rtyp range name =
8422         pr "  {\n";
8423         pr "    strtol_error xerr;\n";
8424         pr "    %s r;\n" fntyp;
8425         pr "\n";
8426         pr "    xerr = %s (argv[i++], NULL, 0, &r, xstrtol_suffixes);\n" fn;
8427         pr "    if (xerr != LONGINT_OK) {\n";
8428         pr "      fprintf (stderr,\n";
8429         pr "               _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
8430         pr "               cmd, \"%s\", \"%s\", xerr);\n" name fn;
8431         pr "      return -1;\n";
8432         pr "    }\n";
8433         (match range with
8434          | None -> ()
8435          | Some (min, max, comment) ->
8436              pr "    /* %s */\n" comment;
8437              pr "    if (r < %s || r > %s) {\n" min max;
8438              pr "      fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
8439                name;
8440              pr "      return -1;\n";
8441              pr "    }\n";
8442              pr "    /* The check above should ensure this assignment does not overflow. */\n";
8443         );
8444         pr "    %s = r;\n" name;
8445         pr "  }\n";
8446       in
8447
8448       if snd style <> [] then
8449         pr "  size_t i = 0;\n";
8450
8451       List.iter (
8452         function
8453         | Device name
8454         | String name ->
8455             pr "  %s = argv[i++];\n" name
8456         | Pathname name
8457         | Dev_or_Path name ->
8458             pr "  %s = resolve_win_path (argv[i++]);\n" name;
8459             pr "  if (%s == NULL) return -1;\n" name
8460         | OptString name ->
8461             pr "  %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
8462             pr "  i++;\n"
8463         | BufferIn name ->
8464             pr "  %s = argv[i];\n" name;
8465             pr "  %s_size = strlen (argv[i]);\n" name;
8466             pr "  i++;\n"
8467         | FileIn name ->
8468             pr "  %s = file_in (argv[i++]);\n" name;
8469             pr "  if (%s == NULL) return -1;\n" name
8470         | FileOut name ->
8471             pr "  %s = file_out (argv[i++]);\n" name;
8472             pr "  if (%s == NULL) return -1;\n" name
8473         | StringList name | DeviceList name ->
8474             pr "  %s = parse_string_list (argv[i++]);\n" name;
8475             pr "  if (%s == NULL) return -1;\n" name
8476         | Key name ->
8477             pr "  %s = read_key (\"%s\");\n" name name;
8478             pr "  if (%s == NULL) return -1;\n" name
8479         | Bool name ->
8480             pr "  %s = is_true (argv[i++]) ? 1 : 0;\n" name
8481         | Int name ->
8482             let range =
8483               let min = "(-(2LL<<30))"
8484               and max = "((2LL<<30)-1)"
8485               and comment =
8486                 "The Int type in the generator is a signed 31 bit int." in
8487               Some (min, max, comment) in
8488             parse_integer "xstrtoll" "long long" "int" range name
8489         | Int64 name ->
8490             parse_integer "xstrtoll" "long long" "int64_t" None name
8491       ) (snd style);
8492
8493       (* Call C API function. *)
8494       pr "  r = guestfs_%s " name;
8495       generate_c_call_args ~handle:"g" style;
8496       pr ";\n";
8497
8498       List.iter (
8499         function
8500         | Device _ | String _
8501         | OptString _ | Bool _
8502         | Int _ | Int64 _
8503         | BufferIn _ -> ()
8504         | Pathname name | Dev_or_Path name | FileOut name
8505         | Key name ->
8506             pr "  free (%s);\n" name
8507         | FileIn name ->
8508             pr "  free_file_in (%s);\n" name
8509         | StringList name | DeviceList name ->
8510             pr "  free_strings (%s);\n" name
8511       ) (snd style);
8512
8513       (* Any output flags? *)
8514       let fish_output =
8515         let flags = filter_map (
8516           function FishOutput flag -> Some flag | _ -> None
8517         ) flags in
8518         match flags with
8519         | [] -> None
8520         | [f] -> Some f
8521         | _ ->
8522             failwithf "%s: more than one FishOutput flag is not allowed" name in
8523
8524       (* Check return value for errors and display command results. *)
8525       (match fst style with
8526        | RErr -> pr "  return r;\n"
8527        | RInt _ ->
8528            pr "  if (r == -1) return -1;\n";
8529            (match fish_output with
8530             | None ->
8531                 pr "  printf (\"%%d\\n\", r);\n";
8532             | Some FishOutputOctal ->
8533                 pr "  printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
8534             | Some FishOutputHexadecimal ->
8535                 pr "  printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8536            pr "  return 0;\n"
8537        | RInt64 _ ->
8538            pr "  if (r == -1) return -1;\n";
8539            (match fish_output with
8540             | None ->
8541                 pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
8542             | Some FishOutputOctal ->
8543                 pr "  printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
8544             | Some FishOutputHexadecimal ->
8545                 pr "  printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8546            pr "  return 0;\n"
8547        | RBool _ ->
8548            pr "  if (r == -1) return -1;\n";
8549            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
8550            pr "  return 0;\n"
8551        | RConstString _ ->
8552            pr "  if (r == NULL) return -1;\n";
8553            pr "  printf (\"%%s\\n\", r);\n";
8554            pr "  return 0;\n"
8555        | RConstOptString _ ->
8556            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
8557            pr "  return 0;\n"
8558        | RString _ ->
8559            pr "  if (r == NULL) return -1;\n";
8560            pr "  printf (\"%%s\\n\", r);\n";
8561            pr "  free (r);\n";
8562            pr "  return 0;\n"
8563        | RStringList _ ->
8564            pr "  if (r == NULL) return -1;\n";
8565            pr "  print_strings (r);\n";
8566            pr "  free_strings (r);\n";
8567            pr "  return 0;\n"
8568        | RStruct (_, typ) ->
8569            pr "  if (r == NULL) return -1;\n";
8570            pr "  print_%s (r);\n" typ;
8571            pr "  guestfs_free_%s (r);\n" typ;
8572            pr "  return 0;\n"
8573        | RStructList (_, typ) ->
8574            pr "  if (r == NULL) return -1;\n";
8575            pr "  print_%s_list (r);\n" typ;
8576            pr "  guestfs_free_%s_list (r);\n" typ;
8577            pr "  return 0;\n"
8578        | RHashtable _ ->
8579            pr "  if (r == NULL) return -1;\n";
8580            pr "  print_table (r);\n";
8581            pr "  free_strings (r);\n";
8582            pr "  return 0;\n"
8583        | RBufferOut _ ->
8584            pr "  if (r == NULL) return -1;\n";
8585            pr "  if (full_write (1, r, size) != size) {\n";
8586            pr "    perror (\"write\");\n";
8587            pr "    free (r);\n";
8588            pr "    return -1;\n";
8589            pr "  }\n";
8590            pr "  free (r);\n";
8591            pr "  return 0;\n"
8592       );
8593       pr "}\n";
8594       pr "\n"
8595   ) all_functions;
8596
8597   (* run_action function *)
8598   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
8599   pr "{\n";
8600   List.iter (
8601     fun (name, _, _, flags, _, _, _) ->
8602       let name2 = replace_char name '_' '-' in
8603       let alias =
8604         try find_map (function FishAlias n -> Some n | _ -> None) flags
8605         with Not_found -> name in
8606       pr "  if (";
8607       pr "STRCASEEQ (cmd, \"%s\")" name;
8608       if name <> name2 then
8609         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8610       if name <> alias then
8611         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8612       pr ")\n";
8613       pr "    return run_%s (cmd, argc, argv);\n" name;
8614       pr "  else\n";
8615   ) all_functions;
8616   pr "    {\n";
8617   pr "      fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
8618   pr "      if (command_num == 1)\n";
8619   pr "        extended_help_message ();\n";
8620   pr "      return -1;\n";
8621   pr "    }\n";
8622   pr "  return 0;\n";
8623   pr "}\n";
8624   pr "\n"
8625
8626 (* Readline completion for guestfish. *)
8627 and generate_fish_completion () =
8628   generate_header CStyle GPLv2plus;
8629
8630   let all_functions =
8631     List.filter (
8632       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8633     ) all_functions in
8634
8635   pr "\
8636 #include <config.h>
8637
8638 #include <stdio.h>
8639 #include <stdlib.h>
8640 #include <string.h>
8641
8642 #ifdef HAVE_LIBREADLINE
8643 #include <readline/readline.h>
8644 #endif
8645
8646 #include \"fish.h\"
8647
8648 #ifdef HAVE_LIBREADLINE
8649
8650 static const char *const commands[] = {
8651   BUILTIN_COMMANDS_FOR_COMPLETION,
8652 ";
8653
8654   (* Get the commands, including the aliases.  They don't need to be
8655    * sorted - the generator() function just does a dumb linear search.
8656    *)
8657   let commands =
8658     List.map (
8659       fun (name, _, _, flags, _, _, _) ->
8660         let name2 = replace_char name '_' '-' in
8661         let alias =
8662           try find_map (function FishAlias n -> Some n | _ -> None) flags
8663           with Not_found -> name in
8664
8665         if name <> alias then [name2; alias] else [name2]
8666     ) all_functions in
8667   let commands = List.flatten commands in
8668
8669   List.iter (pr "  \"%s\",\n") commands;
8670
8671   pr "  NULL
8672 };
8673
8674 static char *
8675 generator (const char *text, int state)
8676 {
8677   static size_t index, len;
8678   const char *name;
8679
8680   if (!state) {
8681     index = 0;
8682     len = strlen (text);
8683   }
8684
8685   rl_attempted_completion_over = 1;
8686
8687   while ((name = commands[index]) != NULL) {
8688     index++;
8689     if (STRCASEEQLEN (name, text, len))
8690       return strdup (name);
8691   }
8692
8693   return NULL;
8694 }
8695
8696 #endif /* HAVE_LIBREADLINE */
8697
8698 #ifdef HAVE_RL_COMPLETION_MATCHES
8699 #define RL_COMPLETION_MATCHES rl_completion_matches
8700 #else
8701 #ifdef HAVE_COMPLETION_MATCHES
8702 #define RL_COMPLETION_MATCHES completion_matches
8703 #endif
8704 #endif /* else just fail if we don't have either symbol */
8705
8706 char **
8707 do_completion (const char *text, int start, int end)
8708 {
8709   char **matches = NULL;
8710
8711 #ifdef HAVE_LIBREADLINE
8712   rl_completion_append_character = ' ';
8713
8714   if (start == 0)
8715     matches = RL_COMPLETION_MATCHES (text, generator);
8716   else if (complete_dest_paths)
8717     matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
8718 #endif
8719
8720   return matches;
8721 }
8722 ";
8723
8724 (* Generate the POD documentation for guestfish. *)
8725 and generate_fish_actions_pod () =
8726   let all_functions_sorted =
8727     List.filter (
8728       fun (_, _, _, flags, _, _, _) ->
8729         not (List.mem NotInFish flags || List.mem NotInDocs flags)
8730     ) all_functions_sorted in
8731
8732   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
8733
8734   List.iter (
8735     fun (name, style, _, flags, _, _, longdesc) ->
8736       let longdesc =
8737         Str.global_substitute rex (
8738           fun s ->
8739             let sub =
8740               try Str.matched_group 1 s
8741               with Not_found ->
8742                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
8743             "C<" ^ replace_char sub '_' '-' ^ ">"
8744         ) longdesc in
8745       let name = replace_char name '_' '-' in
8746       let alias =
8747         try find_map (function FishAlias n -> Some n | _ -> None) flags
8748         with Not_found -> name in
8749
8750       pr "=head2 %s" name;
8751       if name <> alias then
8752         pr " | %s" alias;
8753       pr "\n";
8754       pr "\n";
8755       pr " %s" name;
8756       List.iter (
8757         function
8758         | Pathname n | Device n | Dev_or_Path n | String n ->
8759             pr " %s" n
8760         | OptString n -> pr " %s" n
8761         | StringList n | DeviceList n -> pr " '%s ...'" n
8762         | Bool _ -> pr " true|false"
8763         | Int n -> pr " %s" n
8764         | Int64 n -> pr " %s" n
8765         | FileIn n | FileOut n -> pr " (%s|-)" n
8766         | BufferIn n -> pr " %s" n
8767         | Key _ -> () (* keys are entered at a prompt *)
8768       ) (snd style);
8769       pr "\n";
8770       pr "\n";
8771       pr "%s\n\n" longdesc;
8772
8773       if List.exists (function FileIn _ | FileOut _ -> true
8774                       | _ -> false) (snd style) then
8775         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
8776
8777       if List.exists (function Key _ -> true | _ -> false) (snd style) then
8778         pr "This command has one or more key or passphrase parameters.
8779 Guestfish will prompt for these separately.\n\n";
8780
8781       if List.mem ProtocolLimitWarning flags then
8782         pr "%s\n\n" protocol_limit_warning;
8783
8784       if List.mem DangerWillRobinson flags then
8785         pr "%s\n\n" danger_will_robinson;
8786
8787       match deprecation_notice flags with
8788       | None -> ()
8789       | Some txt -> pr "%s\n\n" txt
8790   ) all_functions_sorted
8791
8792 (* Generate a C function prototype. *)
8793 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
8794     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
8795     ?(prefix = "")
8796     ?handle name style =
8797   if extern then pr "extern ";
8798   if static then pr "static ";
8799   (match fst style with
8800    | RErr -> pr "int "
8801    | RInt _ -> pr "int "
8802    | RInt64 _ -> pr "int64_t "
8803    | RBool _ -> pr "int "
8804    | RConstString _ | RConstOptString _ -> pr "const char *"
8805    | RString _ | RBufferOut _ -> pr "char *"
8806    | RStringList _ | RHashtable _ -> pr "char **"
8807    | RStruct (_, typ) ->
8808        if not in_daemon then pr "struct guestfs_%s *" typ
8809        else pr "guestfs_int_%s *" typ
8810    | RStructList (_, typ) ->
8811        if not in_daemon then pr "struct guestfs_%s_list *" typ
8812        else pr "guestfs_int_%s_list *" typ
8813   );
8814   let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
8815   pr "%s%s (" prefix name;
8816   if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
8817     pr "void"
8818   else (
8819     let comma = ref false in
8820     (match handle with
8821      | None -> ()
8822      | Some handle -> pr "guestfs_h *%s" handle; comma := true
8823     );
8824     let next () =
8825       if !comma then (
8826         if single_line then pr ", " else pr ",\n\t\t"
8827       );
8828       comma := true
8829     in
8830     List.iter (
8831       function
8832       | Pathname n
8833       | Device n | Dev_or_Path n
8834       | String n
8835       | OptString n
8836       | Key n ->
8837           next ();
8838           pr "const char *%s" n
8839       | StringList n | DeviceList n ->
8840           next ();
8841           pr "char *const *%s" n
8842       | Bool n -> next (); pr "int %s" n
8843       | Int n -> next (); pr "int %s" n
8844       | Int64 n -> next (); pr "int64_t %s" n
8845       | FileIn n
8846       | FileOut n ->
8847           if not in_daemon then (next (); pr "const char *%s" n)
8848       | BufferIn n ->
8849           next ();
8850           pr "const char *%s" n;
8851           next ();
8852           pr "size_t %s_size" n
8853     ) (snd style);
8854     if is_RBufferOut then (next (); pr "size_t *size_r");
8855   );
8856   pr ")";
8857   if semicolon then pr ";";
8858   if newline then pr "\n"
8859
8860 (* Generate C call arguments, eg "(handle, foo, bar)" *)
8861 and generate_c_call_args ?handle ?(decl = false) style =
8862   pr "(";
8863   let comma = ref false in
8864   let next () =
8865     if !comma then pr ", ";
8866     comma := true
8867   in
8868   (match handle with
8869    | None -> ()
8870    | Some handle -> pr "%s" handle; comma := true
8871   );
8872   List.iter (
8873     function
8874     | BufferIn n ->
8875         next ();
8876         pr "%s, %s_size" n n
8877     | arg ->
8878         next ();
8879         pr "%s" (name_of_argt arg)
8880   ) (snd style);
8881   (* For RBufferOut calls, add implicit &size parameter. *)
8882   if not decl then (
8883     match fst style with
8884     | RBufferOut _ ->
8885         next ();
8886         pr "&size"
8887     | _ -> ()
8888   );
8889   pr ")"
8890
8891 (* Generate the OCaml bindings interface. *)
8892 and generate_ocaml_mli () =
8893   generate_header OCamlStyle LGPLv2plus;
8894
8895   pr "\
8896 (** For API documentation you should refer to the C API
8897     in the guestfs(3) manual page.  The OCaml API uses almost
8898     exactly the same calls. *)
8899
8900 type t
8901 (** A [guestfs_h] handle. *)
8902
8903 exception Error of string
8904 (** This exception is raised when there is an error. *)
8905
8906 exception Handle_closed of string
8907 (** This exception is raised if you use a {!Guestfs.t} handle
8908     after calling {!close} on it.  The string is the name of
8909     the function. *)
8910
8911 val create : unit -> t
8912 (** Create a {!Guestfs.t} handle. *)
8913
8914 val close : t -> unit
8915 (** Close the {!Guestfs.t} handle and free up all resources used
8916     by it immediately.
8917
8918     Handles are closed by the garbage collector when they become
8919     unreferenced, but callers can call this in order to provide
8920     predictable cleanup. *)
8921
8922 ";
8923   generate_ocaml_structure_decls ();
8924
8925   (* The actions. *)
8926   List.iter (
8927     fun (name, style, _, _, _, shortdesc, _) ->
8928       generate_ocaml_prototype name style;
8929       pr "(** %s *)\n" shortdesc;
8930       pr "\n"
8931   ) all_functions_sorted
8932
8933 (* Generate the OCaml bindings implementation. *)
8934 and generate_ocaml_ml () =
8935   generate_header OCamlStyle LGPLv2plus;
8936
8937   pr "\
8938 type t
8939
8940 exception Error of string
8941 exception Handle_closed of string
8942
8943 external create : unit -> t = \"ocaml_guestfs_create\"
8944 external close : t -> unit = \"ocaml_guestfs_close\"
8945
8946 (* Give the exceptions names, so they can be raised from the C code. *)
8947 let () =
8948   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
8949   Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
8950
8951 ";
8952
8953   generate_ocaml_structure_decls ();
8954
8955   (* The actions. *)
8956   List.iter (
8957     fun (name, style, _, _, _, shortdesc, _) ->
8958       generate_ocaml_prototype ~is_external:true name style;
8959   ) all_functions_sorted
8960
8961 (* Generate the OCaml bindings C implementation. *)
8962 and generate_ocaml_c () =
8963   generate_header CStyle LGPLv2plus;
8964
8965   pr "\
8966 #include <stdio.h>
8967 #include <stdlib.h>
8968 #include <string.h>
8969
8970 #include <caml/config.h>
8971 #include <caml/alloc.h>
8972 #include <caml/callback.h>
8973 #include <caml/fail.h>
8974 #include <caml/memory.h>
8975 #include <caml/mlvalues.h>
8976 #include <caml/signals.h>
8977
8978 #include \"guestfs.h\"
8979
8980 #include \"guestfs_c.h\"
8981
8982 /* Copy a hashtable of string pairs into an assoc-list.  We return
8983  * the list in reverse order, but hashtables aren't supposed to be
8984  * ordered anyway.
8985  */
8986 static CAMLprim value
8987 copy_table (char * const * argv)
8988 {
8989   CAMLparam0 ();
8990   CAMLlocal5 (rv, pairv, kv, vv, cons);
8991   size_t i;
8992
8993   rv = Val_int (0);
8994   for (i = 0; argv[i] != NULL; i += 2) {
8995     kv = caml_copy_string (argv[i]);
8996     vv = caml_copy_string (argv[i+1]);
8997     pairv = caml_alloc (2, 0);
8998     Store_field (pairv, 0, kv);
8999     Store_field (pairv, 1, vv);
9000     cons = caml_alloc (2, 0);
9001     Store_field (cons, 1, rv);
9002     rv = cons;
9003     Store_field (cons, 0, pairv);
9004   }
9005
9006   CAMLreturn (rv);
9007 }
9008
9009 ";
9010
9011   (* Struct copy functions. *)
9012
9013   let emit_ocaml_copy_list_function typ =
9014     pr "static CAMLprim value\n";
9015     pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
9016     pr "{\n";
9017     pr "  CAMLparam0 ();\n";
9018     pr "  CAMLlocal2 (rv, v);\n";
9019     pr "  unsigned int i;\n";
9020     pr "\n";
9021     pr "  if (%ss->len == 0)\n" typ;
9022     pr "    CAMLreturn (Atom (0));\n";
9023     pr "  else {\n";
9024     pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
9025     pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
9026     pr "      v = copy_%s (&%ss->val[i]);\n" typ typ;
9027     pr "      caml_modify (&Field (rv, i), v);\n";
9028     pr "    }\n";
9029     pr "    CAMLreturn (rv);\n";
9030     pr "  }\n";
9031     pr "}\n";
9032     pr "\n";
9033   in
9034
9035   List.iter (
9036     fun (typ, cols) ->
9037       let has_optpercent_col =
9038         List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
9039
9040       pr "static CAMLprim value\n";
9041       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
9042       pr "{\n";
9043       pr "  CAMLparam0 ();\n";
9044       if has_optpercent_col then
9045         pr "  CAMLlocal3 (rv, v, v2);\n"
9046       else
9047         pr "  CAMLlocal2 (rv, v);\n";
9048       pr "\n";
9049       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
9050       iteri (
9051         fun i col ->
9052           (match col with
9053            | name, FString ->
9054                pr "  v = caml_copy_string (%s->%s);\n" typ name
9055            | name, FBuffer ->
9056                pr "  v = caml_alloc_string (%s->%s_len);\n" typ name;
9057                pr "  memcpy (String_val (v), %s->%s, %s->%s_len);\n"
9058                  typ name typ name
9059            | name, FUUID ->
9060                pr "  v = caml_alloc_string (32);\n";
9061                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
9062            | name, (FBytes|FInt64|FUInt64) ->
9063                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
9064            | name, (FInt32|FUInt32) ->
9065                pr "  v = caml_copy_int32 (%s->%s);\n" typ name
9066            | name, FOptPercent ->
9067                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
9068                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
9069                pr "    v = caml_alloc (1, 0);\n";
9070                pr "    Store_field (v, 0, v2);\n";
9071                pr "  } else /* None */\n";
9072                pr "    v = Val_int (0);\n";
9073            | name, FChar ->
9074                pr "  v = Val_int (%s->%s);\n" typ name
9075           );
9076           pr "  Store_field (rv, %d, v);\n" i
9077       ) cols;
9078       pr "  CAMLreturn (rv);\n";
9079       pr "}\n";
9080       pr "\n";
9081   ) structs;
9082
9083   (* Emit a copy_TYPE_list function definition only if that function is used. *)
9084   List.iter (
9085     function
9086     | typ, (RStructListOnly | RStructAndList) ->
9087         (* generate the function for typ *)
9088         emit_ocaml_copy_list_function typ
9089     | typ, _ -> () (* empty *)
9090   ) (rstructs_used_by all_functions);
9091
9092   (* The wrappers. *)
9093   List.iter (
9094     fun (name, style, _, _, _, _, _) ->
9095       pr "/* Automatically generated wrapper for function\n";
9096       pr " * ";
9097       generate_ocaml_prototype name style;
9098       pr " */\n";
9099       pr "\n";
9100
9101       let params =
9102         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
9103
9104       let needs_extra_vs =
9105         match fst style with RConstOptString _ -> true | _ -> false in
9106
9107       pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9108       pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
9109       List.iter (pr ", value %s") (List.tl params); pr ");\n";
9110       pr "\n";
9111
9112       pr "CAMLprim value\n";
9113       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
9114       List.iter (pr ", value %s") (List.tl params);
9115       pr ")\n";
9116       pr "{\n";
9117
9118       (match params with
9119        | [p1; p2; p3; p4; p5] ->
9120            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
9121        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
9122            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
9123            pr "  CAMLxparam%d (%s);\n"
9124              (List.length rest) (String.concat ", " rest)
9125        | ps ->
9126            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
9127       );
9128       if not needs_extra_vs then
9129         pr "  CAMLlocal1 (rv);\n"
9130       else
9131         pr "  CAMLlocal3 (rv, v, v2);\n";
9132       pr "\n";
9133
9134       pr "  guestfs_h *g = Guestfs_val (gv);\n";
9135       pr "  if (g == NULL)\n";
9136       pr "    ocaml_guestfs_raise_closed (\"%s\");\n" name;
9137       pr "\n";
9138
9139       List.iter (
9140         function
9141         | Pathname n
9142         | Device n | Dev_or_Path n
9143         | String n
9144         | FileIn n
9145         | FileOut n
9146         | Key n ->
9147             (* Copy strings in case the GC moves them: RHBZ#604691 *)
9148             pr "  char *%s = guestfs_safe_strdup (g, String_val (%sv));\n" n n
9149         | OptString n ->
9150             pr "  char *%s =\n" n;
9151             pr "    %sv != Val_int (0) ?" n;
9152             pr "      guestfs_safe_strdup (g, String_val (Field (%sv, 0))) : NULL;\n" n
9153         | BufferIn n ->
9154             pr "  size_t %s_size = caml_string_length (%sv);\n" n n;
9155             pr "  char *%s = guestfs_safe_memdup (g, String_val (%sv), %s_size);\n" n n n
9156         | StringList n | DeviceList n ->
9157             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
9158         | Bool n ->
9159             pr "  int %s = Bool_val (%sv);\n" n n
9160         | Int n ->
9161             pr "  int %s = Int_val (%sv);\n" n n
9162         | Int64 n ->
9163             pr "  int64_t %s = Int64_val (%sv);\n" n n
9164       ) (snd style);
9165       let error_code =
9166         match fst style with
9167         | RErr -> pr "  int r;\n"; "-1"
9168         | RInt _ -> pr "  int r;\n"; "-1"
9169         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
9170         | RBool _ -> pr "  int r;\n"; "-1"
9171         | RConstString _ | RConstOptString _ ->
9172             pr "  const char *r;\n"; "NULL"
9173         | RString _ -> pr "  char *r;\n"; "NULL"
9174         | RStringList _ ->
9175             pr "  size_t i;\n";
9176             pr "  char **r;\n";
9177             "NULL"
9178         | RStruct (_, typ) ->
9179             pr "  struct guestfs_%s *r;\n" typ; "NULL"
9180         | RStructList (_, typ) ->
9181             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
9182         | RHashtable _ ->
9183             pr "  size_t i;\n";
9184             pr "  char **r;\n";
9185             "NULL"
9186         | RBufferOut _ ->
9187             pr "  char *r;\n";
9188             pr "  size_t size;\n";
9189             "NULL" in
9190       pr "\n";
9191
9192       pr "  caml_enter_blocking_section ();\n";
9193       pr "  r = guestfs_%s " name;
9194       generate_c_call_args ~handle:"g" style;
9195       pr ";\n";
9196       pr "  caml_leave_blocking_section ();\n";
9197
9198       (* Free strings if we copied them above. *)
9199       List.iter (
9200         function
9201         | Pathname n | Device n | Dev_or_Path n | String n | OptString n
9202         | FileIn n | FileOut n | BufferIn n | Key n ->
9203             pr "  free (%s);\n" n
9204         | StringList n | DeviceList n ->
9205             pr "  ocaml_guestfs_free_strings (%s);\n" n;
9206         | Bool _ | Int _ | Int64 _ -> ()
9207       ) (snd style);
9208
9209       pr "  if (r == %s)\n" error_code;
9210       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
9211       pr "\n";
9212
9213       (match fst style with
9214        | RErr -> pr "  rv = Val_unit;\n"
9215        | RInt _ -> pr "  rv = Val_int (r);\n"
9216        | RInt64 _ ->
9217            pr "  rv = caml_copy_int64 (r);\n"
9218        | RBool _ -> pr "  rv = Val_bool (r);\n"
9219        | RConstString _ ->
9220            pr "  rv = caml_copy_string (r);\n"
9221        | RConstOptString _ ->
9222            pr "  if (r) { /* Some string */\n";
9223            pr "    v = caml_alloc (1, 0);\n";
9224            pr "    v2 = caml_copy_string (r);\n";
9225            pr "    Store_field (v, 0, v2);\n";
9226            pr "  } else /* None */\n";
9227            pr "    v = Val_int (0);\n";
9228        | RString _ ->
9229            pr "  rv = caml_copy_string (r);\n";
9230            pr "  free (r);\n"
9231        | RStringList _ ->
9232            pr "  rv = caml_copy_string_array ((const char **) r);\n";
9233            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9234            pr "  free (r);\n"
9235        | RStruct (_, typ) ->
9236            pr "  rv = copy_%s (r);\n" typ;
9237            pr "  guestfs_free_%s (r);\n" typ;
9238        | RStructList (_, typ) ->
9239            pr "  rv = copy_%s_list (r);\n" typ;
9240            pr "  guestfs_free_%s_list (r);\n" typ;
9241        | RHashtable _ ->
9242            pr "  rv = copy_table (r);\n";
9243            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9244            pr "  free (r);\n";
9245        | RBufferOut _ ->
9246            pr "  rv = caml_alloc_string (size);\n";
9247            pr "  memcpy (String_val (rv), r, size);\n";
9248       );
9249
9250       pr "  CAMLreturn (rv);\n";
9251       pr "}\n";
9252       pr "\n";
9253
9254       if List.length params > 5 then (
9255         pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9256         pr "CAMLprim value ";
9257         pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
9258         pr "CAMLprim value\n";
9259         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
9260         pr "{\n";
9261         pr "  return ocaml_guestfs_%s (argv[0]" name;
9262         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
9263         pr ");\n";
9264         pr "}\n";
9265         pr "\n"
9266       )
9267   ) all_functions_sorted
9268
9269 and generate_ocaml_structure_decls () =
9270   List.iter (
9271     fun (typ, cols) ->
9272       pr "type %s = {\n" typ;
9273       List.iter (
9274         function
9275         | name, FString -> pr "  %s : string;\n" name
9276         | name, FBuffer -> pr "  %s : string;\n" name
9277         | name, FUUID -> pr "  %s : string;\n" name
9278         | name, (FBytes|FInt64|FUInt64) -> pr "  %s : int64;\n" name
9279         | name, (FInt32|FUInt32) -> pr "  %s : int32;\n" name
9280         | name, FChar -> pr "  %s : char;\n" name
9281         | name, FOptPercent -> pr "  %s : float option;\n" name
9282       ) cols;
9283       pr "}\n";
9284       pr "\n"
9285   ) structs
9286
9287 and generate_ocaml_prototype ?(is_external = false) name style =
9288   if is_external then pr "external " else pr "val ";
9289   pr "%s : t -> " name;
9290   List.iter (
9291     function
9292     | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _
9293     | BufferIn _ | Key _ -> pr "string -> "
9294     | OptString _ -> pr "string option -> "
9295     | StringList _ | DeviceList _ -> pr "string array -> "
9296     | Bool _ -> pr "bool -> "
9297     | Int _ -> pr "int -> "
9298     | Int64 _ -> pr "int64 -> "
9299   ) (snd style);
9300   (match fst style with
9301    | RErr -> pr "unit" (* all errors are turned into exceptions *)
9302    | RInt _ -> pr "int"
9303    | RInt64 _ -> pr "int64"
9304    | RBool _ -> pr "bool"
9305    | RConstString _ -> pr "string"
9306    | RConstOptString _ -> pr "string option"
9307    | RString _ | RBufferOut _ -> pr "string"
9308    | RStringList _ -> pr "string array"
9309    | RStruct (_, typ) -> pr "%s" typ
9310    | RStructList (_, typ) -> pr "%s array" typ
9311    | RHashtable _ -> pr "(string * string) list"
9312   );
9313   if is_external then (
9314     pr " = ";
9315     if List.length (snd style) + 1 > 5 then
9316       pr "\"ocaml_guestfs_%s_byte\" " name;
9317     pr "\"ocaml_guestfs_%s\"" name
9318   );
9319   pr "\n"
9320
9321 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
9322 and generate_perl_xs () =
9323   generate_header CStyle LGPLv2plus;
9324
9325   pr "\
9326 #include \"EXTERN.h\"
9327 #include \"perl.h\"
9328 #include \"XSUB.h\"
9329
9330 #include <guestfs.h>
9331
9332 #ifndef PRId64
9333 #define PRId64 \"lld\"
9334 #endif
9335
9336 static SV *
9337 my_newSVll(long long val) {
9338 #ifdef USE_64_BIT_ALL
9339   return newSViv(val);
9340 #else
9341   char buf[100];
9342   int len;
9343   len = snprintf(buf, 100, \"%%\" PRId64, val);
9344   return newSVpv(buf, len);
9345 #endif
9346 }
9347
9348 #ifndef PRIu64
9349 #define PRIu64 \"llu\"
9350 #endif
9351
9352 static SV *
9353 my_newSVull(unsigned long long val) {
9354 #ifdef USE_64_BIT_ALL
9355   return newSVuv(val);
9356 #else
9357   char buf[100];
9358   int len;
9359   len = snprintf(buf, 100, \"%%\" PRIu64, val);
9360   return newSVpv(buf, len);
9361 #endif
9362 }
9363
9364 /* http://www.perlmonks.org/?node_id=680842 */
9365 static char **
9366 XS_unpack_charPtrPtr (SV *arg) {
9367   char **ret;
9368   AV *av;
9369   I32 i;
9370
9371   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
9372     croak (\"array reference expected\");
9373
9374   av = (AV *)SvRV (arg);
9375   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
9376   if (!ret)
9377     croak (\"malloc failed\");
9378
9379   for (i = 0; i <= av_len (av); i++) {
9380     SV **elem = av_fetch (av, i, 0);
9381
9382     if (!elem || !*elem)
9383       croak (\"missing element in list\");
9384
9385     ret[i] = SvPV_nolen (*elem);
9386   }
9387
9388   ret[i] = NULL;
9389
9390   return ret;
9391 }
9392
9393 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
9394
9395 PROTOTYPES: ENABLE
9396
9397 guestfs_h *
9398 _create ()
9399    CODE:
9400       RETVAL = guestfs_create ();
9401       if (!RETVAL)
9402         croak (\"could not create guestfs handle\");
9403       guestfs_set_error_handler (RETVAL, NULL, NULL);
9404  OUTPUT:
9405       RETVAL
9406
9407 void
9408 DESTROY (sv)
9409       SV *sv;
9410  PPCODE:
9411       /* For the 'g' argument above we do the conversion explicitly and
9412        * don't rely on the typemap, because if the handle has been
9413        * explicitly closed we don't want the typemap conversion to
9414        * display an error.
9415        */
9416       HV *hv = (HV *) SvRV (sv);
9417       SV **svp = hv_fetch (hv, \"_g\", 2, 0);
9418       if (svp != NULL) {
9419         guestfs_h *g = (guestfs_h *) SvIV (*svp);
9420         assert (g != NULL);
9421         guestfs_close (g);
9422       }
9423
9424 void
9425 close (g)
9426       guestfs_h *g;
9427  PPCODE:
9428       guestfs_close (g);
9429       /* Avoid double-free in DESTROY method. */
9430       HV *hv = (HV *) SvRV (ST(0));
9431       (void) hv_delete (hv, \"_g\", 2, G_DISCARD);
9432
9433 ";
9434
9435   List.iter (
9436     fun (name, style, _, _, _, _, _) ->
9437       (match fst style with
9438        | RErr -> pr "void\n"
9439        | RInt _ -> pr "SV *\n"
9440        | RInt64 _ -> pr "SV *\n"
9441        | RBool _ -> pr "SV *\n"
9442        | RConstString _ -> pr "SV *\n"
9443        | RConstOptString _ -> pr "SV *\n"
9444        | RString _ -> pr "SV *\n"
9445        | RBufferOut _ -> pr "SV *\n"
9446        | RStringList _
9447        | RStruct _ | RStructList _
9448        | RHashtable _ ->
9449            pr "void\n" (* all lists returned implictly on the stack *)
9450       );
9451       (* Call and arguments. *)
9452       pr "%s (g" name;
9453       List.iter (
9454         fun arg -> pr ", %s" (name_of_argt arg)
9455       ) (snd style);
9456       pr ")\n";
9457       pr "      guestfs_h *g;\n";
9458       iteri (
9459         fun i ->
9460           function
9461           | Pathname n | Device n | Dev_or_Path n | String n
9462           | FileIn n | FileOut n | Key n ->
9463               pr "      char *%s;\n" n
9464           | BufferIn n ->
9465               pr "      char *%s;\n" n;
9466               pr "      size_t %s_size = SvCUR (ST(%d));\n" n (i+1)
9467           | OptString n ->
9468               (* http://www.perlmonks.org/?node_id=554277
9469                * Note that the implicit handle argument means we have
9470                * to add 1 to the ST(x) operator.
9471                *)
9472               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
9473           | StringList n | DeviceList n -> pr "      char **%s;\n" n
9474           | Bool n -> pr "      int %s;\n" n
9475           | Int n -> pr "      int %s;\n" n
9476           | Int64 n -> pr "      int64_t %s;\n" n
9477       ) (snd style);
9478
9479       let do_cleanups () =
9480         List.iter (
9481           function
9482           | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
9483           | Bool _ | Int _ | Int64 _
9484           | FileIn _ | FileOut _
9485           | BufferIn _ | Key _ -> ()
9486           | StringList n | DeviceList n -> pr "      free (%s);\n" n
9487         ) (snd style)
9488       in
9489
9490       (* Code. *)
9491       (match fst style with
9492        | RErr ->
9493            pr "PREINIT:\n";
9494            pr "      int r;\n";
9495            pr " PPCODE:\n";
9496            pr "      r = guestfs_%s " name;
9497            generate_c_call_args ~handle:"g" style;
9498            pr ";\n";
9499            do_cleanups ();
9500            pr "      if (r == -1)\n";
9501            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9502        | RInt n
9503        | RBool n ->
9504            pr "PREINIT:\n";
9505            pr "      int %s;\n" n;
9506            pr "   CODE:\n";
9507            pr "      %s = guestfs_%s " n name;
9508            generate_c_call_args ~handle:"g" style;
9509            pr ";\n";
9510            do_cleanups ();
9511            pr "      if (%s == -1)\n" n;
9512            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9513            pr "      RETVAL = newSViv (%s);\n" n;
9514            pr " OUTPUT:\n";
9515            pr "      RETVAL\n"
9516        | RInt64 n ->
9517            pr "PREINIT:\n";
9518            pr "      int64_t %s;\n" n;
9519            pr "   CODE:\n";
9520            pr "      %s = guestfs_%s " n name;
9521            generate_c_call_args ~handle:"g" style;
9522            pr ";\n";
9523            do_cleanups ();
9524            pr "      if (%s == -1)\n" n;
9525            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9526            pr "      RETVAL = my_newSVll (%s);\n" n;
9527            pr " OUTPUT:\n";
9528            pr "      RETVAL\n"
9529        | RConstString n ->
9530            pr "PREINIT:\n";
9531            pr "      const char *%s;\n" n;
9532            pr "   CODE:\n";
9533            pr "      %s = guestfs_%s " n name;
9534            generate_c_call_args ~handle:"g" style;
9535            pr ";\n";
9536            do_cleanups ();
9537            pr "      if (%s == NULL)\n" n;
9538            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9539            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9540            pr " OUTPUT:\n";
9541            pr "      RETVAL\n"
9542        | RConstOptString n ->
9543            pr "PREINIT:\n";
9544            pr "      const char *%s;\n" n;
9545            pr "   CODE:\n";
9546            pr "      %s = guestfs_%s " n name;
9547            generate_c_call_args ~handle:"g" style;
9548            pr ";\n";
9549            do_cleanups ();
9550            pr "      if (%s == NULL)\n" n;
9551            pr "        RETVAL = &PL_sv_undef;\n";
9552            pr "      else\n";
9553            pr "        RETVAL = newSVpv (%s, 0);\n" n;
9554            pr " OUTPUT:\n";
9555            pr "      RETVAL\n"
9556        | RString n ->
9557            pr "PREINIT:\n";
9558            pr "      char *%s;\n" n;
9559            pr "   CODE:\n";
9560            pr "      %s = guestfs_%s " n name;
9561            generate_c_call_args ~handle:"g" style;
9562            pr ";\n";
9563            do_cleanups ();
9564            pr "      if (%s == NULL)\n" n;
9565            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9566            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9567            pr "      free (%s);\n" n;
9568            pr " OUTPUT:\n";
9569            pr "      RETVAL\n"
9570        | RStringList n | RHashtable n ->
9571            pr "PREINIT:\n";
9572            pr "      char **%s;\n" n;
9573            pr "      size_t i, n;\n";
9574            pr " PPCODE:\n";
9575            pr "      %s = guestfs_%s " n name;
9576            generate_c_call_args ~handle:"g" style;
9577            pr ";\n";
9578            do_cleanups ();
9579            pr "      if (%s == NULL)\n" n;
9580            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9581            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
9582            pr "      EXTEND (SP, n);\n";
9583            pr "      for (i = 0; i < n; ++i) {\n";
9584            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
9585            pr "        free (%s[i]);\n" n;
9586            pr "      }\n";
9587            pr "      free (%s);\n" n;
9588        | RStruct (n, typ) ->
9589            let cols = cols_of_struct typ in
9590            generate_perl_struct_code typ cols name style n do_cleanups
9591        | RStructList (n, typ) ->
9592            let cols = cols_of_struct typ in
9593            generate_perl_struct_list_code typ cols name style n do_cleanups
9594        | RBufferOut n ->
9595            pr "PREINIT:\n";
9596            pr "      char *%s;\n" n;
9597            pr "      size_t size;\n";
9598            pr "   CODE:\n";
9599            pr "      %s = guestfs_%s " n name;
9600            generate_c_call_args ~handle:"g" style;
9601            pr ";\n";
9602            do_cleanups ();
9603            pr "      if (%s == NULL)\n" n;
9604            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9605            pr "      RETVAL = newSVpvn (%s, size);\n" n;
9606            pr "      free (%s);\n" n;
9607            pr " OUTPUT:\n";
9608            pr "      RETVAL\n"
9609       );
9610
9611       pr "\n"
9612   ) all_functions
9613
9614 and generate_perl_struct_list_code typ cols name style n do_cleanups =
9615   pr "PREINIT:\n";
9616   pr "      struct guestfs_%s_list *%s;\n" typ n;
9617   pr "      size_t i;\n";
9618   pr "      HV *hv;\n";
9619   pr " PPCODE:\n";
9620   pr "      %s = guestfs_%s " n name;
9621   generate_c_call_args ~handle:"g" style;
9622   pr ";\n";
9623   do_cleanups ();
9624   pr "      if (%s == NULL)\n" n;
9625   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9626   pr "      EXTEND (SP, %s->len);\n" n;
9627   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
9628   pr "        hv = newHV ();\n";
9629   List.iter (
9630     function
9631     | name, FString ->
9632         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
9633           name (String.length name) n name
9634     | name, FUUID ->
9635         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
9636           name (String.length name) n name
9637     | name, FBuffer ->
9638         pr "        (void) hv_store (hv, \"%s\", %d, newSVpvn (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
9639           name (String.length name) n name n name
9640     | name, (FBytes|FUInt64) ->
9641         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
9642           name (String.length name) n name
9643     | name, FInt64 ->
9644         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
9645           name (String.length name) n name
9646     | name, (FInt32|FUInt32) ->
9647         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9648           name (String.length name) n name
9649     | name, FChar ->
9650         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
9651           name (String.length name) n name
9652     | name, FOptPercent ->
9653         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9654           name (String.length name) n name
9655   ) cols;
9656   pr "        PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
9657   pr "      }\n";
9658   pr "      guestfs_free_%s_list (%s);\n" typ n
9659
9660 and generate_perl_struct_code typ cols name style n do_cleanups =
9661   pr "PREINIT:\n";
9662   pr "      struct guestfs_%s *%s;\n" typ n;
9663   pr " PPCODE:\n";
9664   pr "      %s = guestfs_%s " n name;
9665   generate_c_call_args ~handle:"g" style;
9666   pr ";\n";
9667   do_cleanups ();
9668   pr "      if (%s == NULL)\n" n;
9669   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9670   pr "      EXTEND (SP, 2 * %d);\n" (List.length cols);
9671   List.iter (
9672     fun ((name, _) as col) ->
9673       pr "      PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
9674
9675       match col with
9676       | name, FString ->
9677           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
9678             n name
9679       | name, FBuffer ->
9680           pr "      PUSHs (sv_2mortal (newSVpvn (%s->%s, %s->%s_len)));\n"
9681             n name n name
9682       | name, FUUID ->
9683           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
9684             n name
9685       | name, (FBytes|FUInt64) ->
9686           pr "      PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
9687             n name
9688       | name, FInt64 ->
9689           pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
9690             n name
9691       | name, (FInt32|FUInt32) ->
9692           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9693             n name
9694       | name, FChar ->
9695           pr "      PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
9696             n name
9697       | name, FOptPercent ->
9698           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9699             n name
9700   ) cols;
9701   pr "      free (%s);\n" n
9702
9703 (* Generate Sys/Guestfs.pm. *)
9704 and generate_perl_pm () =
9705   generate_header HashStyle LGPLv2plus;
9706
9707   pr "\
9708 =pod
9709
9710 =head1 NAME
9711
9712 Sys::Guestfs - Perl bindings for libguestfs
9713
9714 =head1 SYNOPSIS
9715
9716  use Sys::Guestfs;
9717
9718  my $h = Sys::Guestfs->new ();
9719  $h->add_drive ('guest.img');
9720  $h->launch ();
9721  $h->mount ('/dev/sda1', '/');
9722  $h->touch ('/hello');
9723  $h->sync ();
9724
9725 =head1 DESCRIPTION
9726
9727 The C<Sys::Guestfs> module provides a Perl XS binding to the
9728 libguestfs API for examining and modifying virtual machine
9729 disk images.
9730
9731 Amongst the things this is good for: making batch configuration
9732 changes to guests, getting disk used/free statistics (see also:
9733 virt-df), migrating between virtualization systems (see also:
9734 virt-p2v), performing partial backups, performing partial guest
9735 clones, cloning guests and changing registry/UUID/hostname info, and
9736 much else besides.
9737
9738 Libguestfs uses Linux kernel and qemu code, and can access any type of
9739 guest filesystem that Linux and qemu can, including but not limited
9740 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
9741 schemes, qcow, qcow2, vmdk.
9742
9743 Libguestfs provides ways to enumerate guest storage (eg. partitions,
9744 LVs, what filesystem is in each LV, etc.).  It can also run commands
9745 in the context of the guest.  Also you can access filesystems over
9746 FUSE.
9747
9748 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
9749 functions for using libguestfs from Perl, including integration
9750 with libvirt.
9751
9752 =head1 ERRORS
9753
9754 All errors turn into calls to C<croak> (see L<Carp(3)>).
9755
9756 =head1 METHODS
9757
9758 =over 4
9759
9760 =cut
9761
9762 package Sys::Guestfs;
9763
9764 use strict;
9765 use warnings;
9766
9767 # This version number changes whenever a new function
9768 # is added to the libguestfs API.  It is not directly
9769 # related to the libguestfs version number.
9770 use vars qw($VERSION);
9771 $VERSION = '0.%d';
9772
9773 require XSLoader;
9774 XSLoader::load ('Sys::Guestfs');
9775
9776 =item $h = Sys::Guestfs->new ();
9777
9778 Create a new guestfs handle.
9779
9780 =cut
9781
9782 sub new {
9783   my $proto = shift;
9784   my $class = ref ($proto) || $proto;
9785
9786   my $g = Sys::Guestfs::_create ();
9787   my $self = { _g => $g };
9788   bless $self, $class;
9789   return $self;
9790 }
9791
9792 =item $h->close ();
9793
9794 Explicitly close the guestfs handle.
9795
9796 B<Note:> You should not usually call this function.  The handle will
9797 be closed implicitly when its reference count goes to zero (eg.
9798 when it goes out of scope or the program ends).  This call is
9799 only required in some exceptional cases, such as where the program
9800 may contain cached references to the handle 'somewhere' and you
9801 really have to have the close happen right away.  After calling
9802 C<close> the program must not call any method (including C<close>)
9803 on the handle (but the implicit call to C<DESTROY> that happens
9804 when the final reference is cleaned up is OK).
9805
9806 =cut
9807
9808 " max_proc_nr;
9809
9810   (* Actions.  We only need to print documentation for these as
9811    * they are pulled in from the XS code automatically.
9812    *)
9813   List.iter (
9814     fun (name, style, _, flags, _, _, longdesc) ->
9815       if not (List.mem NotInDocs flags) then (
9816         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
9817         pr "=item ";
9818         generate_perl_prototype name style;
9819         pr "\n\n";
9820         pr "%s\n\n" longdesc;
9821         if List.mem ProtocolLimitWarning flags then
9822           pr "%s\n\n" protocol_limit_warning;
9823         if List.mem DangerWillRobinson flags then
9824           pr "%s\n\n" danger_will_robinson;
9825         match deprecation_notice flags with
9826         | None -> ()
9827         | Some txt -> pr "%s\n\n" txt
9828       )
9829   ) all_functions_sorted;
9830
9831   (* End of file. *)
9832   pr "\
9833 =cut
9834
9835 1;
9836
9837 =back
9838
9839 =head1 COPYRIGHT
9840
9841 Copyright (C) %s Red Hat Inc.
9842
9843 =head1 LICENSE
9844
9845 Please see the file COPYING.LIB for the full license.
9846
9847 =head1 SEE ALSO
9848
9849 L<guestfs(3)>,
9850 L<guestfish(1)>,
9851 L<http://libguestfs.org>,
9852 L<Sys::Guestfs::Lib(3)>.
9853
9854 =cut
9855 " copyright_years
9856
9857 and generate_perl_prototype name style =
9858   (match fst style with
9859    | RErr -> ()
9860    | RBool n
9861    | RInt n
9862    | RInt64 n
9863    | RConstString n
9864    | RConstOptString n
9865    | RString n
9866    | RBufferOut n -> pr "$%s = " n
9867    | RStruct (n,_)
9868    | RHashtable n -> pr "%%%s = " n
9869    | RStringList n
9870    | RStructList (n,_) -> pr "@%s = " n
9871   );
9872   pr "$h->%s (" name;
9873   let comma = ref false in
9874   List.iter (
9875     fun arg ->
9876       if !comma then pr ", ";
9877       comma := true;
9878       match arg with
9879       | Pathname n | Device n | Dev_or_Path n | String n
9880       | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n
9881       | BufferIn n | Key n ->
9882           pr "$%s" n
9883       | StringList n | DeviceList n ->
9884           pr "\\@%s" n
9885   ) (snd style);
9886   pr ");"
9887
9888 (* Generate Python C module. *)
9889 and generate_python_c () =
9890   generate_header CStyle LGPLv2plus;
9891
9892   pr "\
9893 #define PY_SSIZE_T_CLEAN 1
9894 #include <Python.h>
9895
9896 #if PY_VERSION_HEX < 0x02050000
9897 typedef int Py_ssize_t;
9898 #define PY_SSIZE_T_MAX INT_MAX
9899 #define PY_SSIZE_T_MIN INT_MIN
9900 #endif
9901
9902 #include <stdio.h>
9903 #include <stdlib.h>
9904 #include <assert.h>
9905
9906 #include \"guestfs.h\"
9907
9908 #ifndef HAVE_PYCAPSULE_NEW
9909 typedef struct {
9910   PyObject_HEAD
9911   guestfs_h *g;
9912 } Pyguestfs_Object;
9913 #endif
9914
9915 static guestfs_h *
9916 get_handle (PyObject *obj)
9917 {
9918   assert (obj);
9919   assert (obj != Py_None);
9920 #ifndef HAVE_PYCAPSULE_NEW
9921   return ((Pyguestfs_Object *) obj)->g;
9922 #else
9923   return (guestfs_h*) PyCapsule_GetPointer(obj, \"guestfs_h\");
9924 #endif
9925 }
9926
9927 static PyObject *
9928 put_handle (guestfs_h *g)
9929 {
9930   assert (g);
9931 #ifndef HAVE_PYCAPSULE_NEW
9932   return
9933     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
9934 #else
9935   return PyCapsule_New ((void *) g, \"guestfs_h\", NULL);
9936 #endif
9937 }
9938
9939 /* This list should be freed (but not the strings) after use. */
9940 static char **
9941 get_string_list (PyObject *obj)
9942 {
9943   size_t i, len;
9944   char **r;
9945
9946   assert (obj);
9947
9948   if (!PyList_Check (obj)) {
9949     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
9950     return NULL;
9951   }
9952
9953   Py_ssize_t slen = PyList_Size (obj);
9954   if (slen == -1) {
9955     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: PyList_Size failure\");
9956     return NULL;
9957   }
9958   len = (size_t) slen;
9959   r = malloc (sizeof (char *) * (len+1));
9960   if (r == NULL) {
9961     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
9962     return NULL;
9963   }
9964
9965   for (i = 0; i < len; ++i)
9966     r[i] = PyString_AsString (PyList_GetItem (obj, i));
9967   r[len] = NULL;
9968
9969   return r;
9970 }
9971
9972 static PyObject *
9973 put_string_list (char * const * const argv)
9974 {
9975   PyObject *list;
9976   int argc, i;
9977
9978   for (argc = 0; argv[argc] != NULL; ++argc)
9979     ;
9980
9981   list = PyList_New (argc);
9982   for (i = 0; i < argc; ++i)
9983     PyList_SetItem (list, i, PyString_FromString (argv[i]));
9984
9985   return list;
9986 }
9987
9988 static PyObject *
9989 put_table (char * const * const argv)
9990 {
9991   PyObject *list, *item;
9992   int argc, i;
9993
9994   for (argc = 0; argv[argc] != NULL; ++argc)
9995     ;
9996
9997   list = PyList_New (argc >> 1);
9998   for (i = 0; i < argc; i += 2) {
9999     item = PyTuple_New (2);
10000     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
10001     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
10002     PyList_SetItem (list, i >> 1, item);
10003   }
10004
10005   return list;
10006 }
10007
10008 static void
10009 free_strings (char **argv)
10010 {
10011   int argc;
10012
10013   for (argc = 0; argv[argc] != NULL; ++argc)
10014     free (argv[argc]);
10015   free (argv);
10016 }
10017
10018 static PyObject *
10019 py_guestfs_create (PyObject *self, PyObject *args)
10020 {
10021   guestfs_h *g;
10022
10023   g = guestfs_create ();
10024   if (g == NULL) {
10025     PyErr_SetString (PyExc_RuntimeError,
10026                      \"guestfs.create: failed to allocate handle\");
10027     return NULL;
10028   }
10029   guestfs_set_error_handler (g, NULL, NULL);
10030   /* This can return NULL, but in that case put_handle will have
10031    * set the Python error string.
10032    */
10033   return put_handle (g);
10034 }
10035
10036 static PyObject *
10037 py_guestfs_close (PyObject *self, PyObject *args)
10038 {
10039   PyObject *py_g;
10040   guestfs_h *g;
10041
10042   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
10043     return NULL;
10044   g = get_handle (py_g);
10045
10046   guestfs_close (g);
10047
10048   Py_INCREF (Py_None);
10049   return Py_None;
10050 }
10051
10052 ";
10053
10054   let emit_put_list_function typ =
10055     pr "static PyObject *\n";
10056     pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
10057     pr "{\n";
10058     pr "  PyObject *list;\n";
10059     pr "  size_t i;\n";
10060     pr "\n";
10061     pr "  list = PyList_New (%ss->len);\n" typ;
10062     pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
10063     pr "    PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
10064     pr "  return list;\n";
10065     pr "};\n";
10066     pr "\n"
10067   in
10068
10069   (* Structures, turned into Python dictionaries. *)
10070   List.iter (
10071     fun (typ, cols) ->
10072       pr "static PyObject *\n";
10073       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
10074       pr "{\n";
10075       pr "  PyObject *dict;\n";
10076       pr "\n";
10077       pr "  dict = PyDict_New ();\n";
10078       List.iter (
10079         function
10080         | name, FString ->
10081             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10082             pr "                        PyString_FromString (%s->%s));\n"
10083               typ name
10084         | name, FBuffer ->
10085             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10086             pr "                        PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
10087               typ name typ name
10088         | name, FUUID ->
10089             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10090             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
10091               typ name
10092         | name, (FBytes|FUInt64) ->
10093             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10094             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
10095               typ name
10096         | name, FInt64 ->
10097             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10098             pr "                        PyLong_FromLongLong (%s->%s));\n"
10099               typ name
10100         | name, FUInt32 ->
10101             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10102             pr "                        PyLong_FromUnsignedLong (%s->%s));\n"
10103               typ name
10104         | name, FInt32 ->
10105             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10106             pr "                        PyLong_FromLong (%s->%s));\n"
10107               typ name
10108         | name, FOptPercent ->
10109             pr "  if (%s->%s >= 0)\n" typ name;
10110             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
10111             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
10112               typ name;
10113             pr "  else {\n";
10114             pr "    Py_INCREF (Py_None);\n";
10115             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
10116             pr "  }\n"
10117         | name, FChar ->
10118             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10119             pr "                        PyString_FromStringAndSize (&dirent->%s, 1));\n" name
10120       ) cols;
10121       pr "  return dict;\n";
10122       pr "};\n";
10123       pr "\n";
10124
10125   ) structs;
10126
10127   (* Emit a put_TYPE_list function definition only if that function is used. *)
10128   List.iter (
10129     function
10130     | typ, (RStructListOnly | RStructAndList) ->
10131         (* generate the function for typ *)
10132         emit_put_list_function typ
10133     | typ, _ -> () (* empty *)
10134   ) (rstructs_used_by all_functions);
10135
10136   (* Python wrapper functions. *)
10137   List.iter (
10138     fun (name, style, _, _, _, _, _) ->
10139       pr "static PyObject *\n";
10140       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
10141       pr "{\n";
10142
10143       pr "  PyObject *py_g;\n";
10144       pr "  guestfs_h *g;\n";
10145       pr "  PyObject *py_r;\n";
10146
10147       let error_code =
10148         match fst style with
10149         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10150         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10151         | RConstString _ | RConstOptString _ ->
10152             pr "  const char *r;\n"; "NULL"
10153         | RString _ -> pr "  char *r;\n"; "NULL"
10154         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10155         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10156         | RStructList (_, typ) ->
10157             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10158         | RBufferOut _ ->
10159             pr "  char *r;\n";
10160             pr "  size_t size;\n";
10161             "NULL" in
10162
10163       List.iter (
10164         function
10165         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10166         | FileIn n | FileOut n ->
10167             pr "  const char *%s;\n" n
10168         | OptString n -> pr "  const char *%s;\n" n
10169         | BufferIn n ->
10170             pr "  const char *%s;\n" n;
10171             pr "  Py_ssize_t %s_size;\n" n
10172         | StringList n | DeviceList n ->
10173             pr "  PyObject *py_%s;\n" n;
10174             pr "  char **%s;\n" n
10175         | Bool n -> pr "  int %s;\n" n
10176         | Int n -> pr "  int %s;\n" n
10177         | Int64 n -> pr "  long long %s;\n" n
10178       ) (snd style);
10179
10180       pr "\n";
10181
10182       (* Convert the parameters. *)
10183       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
10184       List.iter (
10185         function
10186         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10187         | FileIn _ | FileOut _ -> pr "s"
10188         | OptString _ -> pr "z"
10189         | StringList _ | DeviceList _ -> pr "O"
10190         | Bool _ -> pr "i" (* XXX Python has booleans? *)
10191         | Int _ -> pr "i"
10192         | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
10193                              * emulate C's int/long/long long in Python?
10194                              *)
10195         | BufferIn _ -> pr "s#"
10196       ) (snd style);
10197       pr ":guestfs_%s\",\n" name;
10198       pr "                         &py_g";
10199       List.iter (
10200         function
10201         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10202         | FileIn n | FileOut n -> pr ", &%s" n
10203         | OptString n -> pr ", &%s" n
10204         | StringList n | DeviceList n -> pr ", &py_%s" n
10205         | Bool n -> pr ", &%s" n
10206         | Int n -> pr ", &%s" n
10207         | Int64 n -> pr ", &%s" n
10208         | BufferIn n -> pr ", &%s, &%s_size" n n
10209       ) (snd style);
10210
10211       pr "))\n";
10212       pr "    return NULL;\n";
10213
10214       pr "  g = get_handle (py_g);\n";
10215       List.iter (
10216         function
10217         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10218         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10219         | BufferIn _ -> ()
10220         | StringList n | DeviceList n ->
10221             pr "  %s = get_string_list (py_%s);\n" n n;
10222             pr "  if (!%s) return NULL;\n" n
10223       ) (snd style);
10224
10225       pr "\n";
10226
10227       pr "  r = guestfs_%s " name;
10228       generate_c_call_args ~handle:"g" style;
10229       pr ";\n";
10230
10231       List.iter (
10232         function
10233         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10234         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10235         | BufferIn _ -> ()
10236         | StringList n | DeviceList n ->
10237             pr "  free (%s);\n" n
10238       ) (snd style);
10239
10240       pr "  if (r == %s) {\n" error_code;
10241       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
10242       pr "    return NULL;\n";
10243       pr "  }\n";
10244       pr "\n";
10245
10246       (match fst style with
10247        | RErr ->
10248            pr "  Py_INCREF (Py_None);\n";
10249            pr "  py_r = Py_None;\n"
10250        | RInt _
10251        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
10252        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
10253        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
10254        | RConstOptString _ ->
10255            pr "  if (r)\n";
10256            pr "    py_r = PyString_FromString (r);\n";
10257            pr "  else {\n";
10258            pr "    Py_INCREF (Py_None);\n";
10259            pr "    py_r = Py_None;\n";
10260            pr "  }\n"
10261        | RString _ ->
10262            pr "  py_r = PyString_FromString (r);\n";
10263            pr "  free (r);\n"
10264        | RStringList _ ->
10265            pr "  py_r = put_string_list (r);\n";
10266            pr "  free_strings (r);\n"
10267        | RStruct (_, typ) ->
10268            pr "  py_r = put_%s (r);\n" typ;
10269            pr "  guestfs_free_%s (r);\n" typ
10270        | RStructList (_, typ) ->
10271            pr "  py_r = put_%s_list (r);\n" typ;
10272            pr "  guestfs_free_%s_list (r);\n" typ
10273        | RHashtable n ->
10274            pr "  py_r = put_table (r);\n";
10275            pr "  free_strings (r);\n"
10276        | RBufferOut _ ->
10277            pr "  py_r = PyString_FromStringAndSize (r, size);\n";
10278            pr "  free (r);\n"
10279       );
10280
10281       pr "  return py_r;\n";
10282       pr "}\n";
10283       pr "\n"
10284   ) all_functions;
10285
10286   (* Table of functions. *)
10287   pr "static PyMethodDef methods[] = {\n";
10288   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
10289   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
10290   List.iter (
10291     fun (name, _, _, _, _, _, _) ->
10292       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
10293         name name
10294   ) all_functions;
10295   pr "  { NULL, NULL, 0, NULL }\n";
10296   pr "};\n";
10297   pr "\n";
10298
10299   (* Init function. *)
10300   pr "\
10301 void
10302 initlibguestfsmod (void)
10303 {
10304   static int initialized = 0;
10305
10306   if (initialized) return;
10307   Py_InitModule ((char *) \"libguestfsmod\", methods);
10308   initialized = 1;
10309 }
10310 "
10311
10312 (* Generate Python module. *)
10313 and generate_python_py () =
10314   generate_header HashStyle LGPLv2plus;
10315
10316   pr "\
10317 u\"\"\"Python bindings for libguestfs
10318
10319 import guestfs
10320 g = guestfs.GuestFS ()
10321 g.add_drive (\"guest.img\")
10322 g.launch ()
10323 parts = g.list_partitions ()
10324
10325 The guestfs module provides a Python binding to the libguestfs API
10326 for examining and modifying virtual machine disk images.
10327
10328 Amongst the things this is good for: making batch configuration
10329 changes to guests, getting disk used/free statistics (see also:
10330 virt-df), migrating between virtualization systems (see also:
10331 virt-p2v), performing partial backups, performing partial guest
10332 clones, cloning guests and changing registry/UUID/hostname info, and
10333 much else besides.
10334
10335 Libguestfs uses Linux kernel and qemu code, and can access any type of
10336 guest filesystem that Linux and qemu can, including but not limited
10337 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
10338 schemes, qcow, qcow2, vmdk.
10339
10340 Libguestfs provides ways to enumerate guest storage (eg. partitions,
10341 LVs, what filesystem is in each LV, etc.).  It can also run commands
10342 in the context of the guest.  Also you can access filesystems over
10343 FUSE.
10344
10345 Errors which happen while using the API are turned into Python
10346 RuntimeError exceptions.
10347
10348 To create a guestfs handle you usually have to perform the following
10349 sequence of calls:
10350
10351 # Create the handle, call add_drive at least once, and possibly
10352 # several times if the guest has multiple block devices:
10353 g = guestfs.GuestFS ()
10354 g.add_drive (\"guest.img\")
10355
10356 # Launch the qemu subprocess and wait for it to become ready:
10357 g.launch ()
10358
10359 # Now you can issue commands, for example:
10360 logvols = g.lvs ()
10361
10362 \"\"\"
10363
10364 import libguestfsmod
10365
10366 class GuestFS:
10367     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
10368
10369     def __init__ (self):
10370         \"\"\"Create a new libguestfs handle.\"\"\"
10371         self._o = libguestfsmod.create ()
10372
10373     def __del__ (self):
10374         libguestfsmod.close (self._o)
10375
10376 ";
10377
10378   List.iter (
10379     fun (name, style, _, flags, _, _, longdesc) ->
10380       pr "    def %s " name;
10381       generate_py_call_args ~handle:"self" (snd style);
10382       pr ":\n";
10383
10384       if not (List.mem NotInDocs flags) then (
10385         let doc = replace_str longdesc "C<guestfs_" "C<g." in
10386         let doc =
10387           match fst style with
10388           | RErr | RInt _ | RInt64 _ | RBool _
10389           | RConstOptString _ | RConstString _
10390           | RString _ | RBufferOut _ -> doc
10391           | RStringList _ ->
10392               doc ^ "\n\nThis function returns a list of strings."
10393           | RStruct (_, typ) ->
10394               doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
10395           | RStructList (_, typ) ->
10396               doc ^ sprintf "\n\nThis function returns a list of %ss.  Each %s is represented as a dictionary." typ typ
10397           | RHashtable _ ->
10398               doc ^ "\n\nThis function returns a dictionary." in
10399         let doc =
10400           if List.mem ProtocolLimitWarning flags then
10401             doc ^ "\n\n" ^ protocol_limit_warning
10402           else doc in
10403         let doc =
10404           if List.mem DangerWillRobinson flags then
10405             doc ^ "\n\n" ^ danger_will_robinson
10406           else doc in
10407         let doc =
10408           match deprecation_notice flags with
10409           | None -> doc
10410           | Some txt -> doc ^ "\n\n" ^ txt in
10411         let doc = pod2text ~width:60 name doc in
10412         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
10413         let doc = String.concat "\n        " doc in
10414         pr "        u\"\"\"%s\"\"\"\n" doc;
10415       );
10416       pr "        return libguestfsmod.%s " name;
10417       generate_py_call_args ~handle:"self._o" (snd style);
10418       pr "\n";
10419       pr "\n";
10420   ) all_functions
10421
10422 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
10423 and generate_py_call_args ~handle args =
10424   pr "(%s" handle;
10425   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10426   pr ")"
10427
10428 (* Useful if you need the longdesc POD text as plain text.  Returns a
10429  * list of lines.
10430  *
10431  * Because this is very slow (the slowest part of autogeneration),
10432  * we memoize the results.
10433  *)
10434 and pod2text ~width name longdesc =
10435   let key = width, name, longdesc in
10436   try Hashtbl.find pod2text_memo key
10437   with Not_found ->
10438     let filename, chan = Filename.open_temp_file "gen" ".tmp" in
10439     fprintf chan "=head1 %s\n\n%s\n" name longdesc;
10440     close_out chan;
10441     let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
10442     let chan = open_process_in cmd in
10443     let lines = ref [] in
10444     let rec loop i =
10445       let line = input_line chan in
10446       if i = 1 then             (* discard the first line of output *)
10447         loop (i+1)
10448       else (
10449         let line = triml line in
10450         lines := line :: !lines;
10451         loop (i+1)
10452       ) in
10453     let lines = try loop 1 with End_of_file -> List.rev !lines in
10454     unlink filename;
10455     (match close_process_in chan with
10456      | WEXITED 0 -> ()
10457      | WEXITED i ->
10458          failwithf "pod2text: process exited with non-zero status (%d)" i
10459      | WSIGNALED i | WSTOPPED i ->
10460          failwithf "pod2text: process signalled or stopped by signal %d" i
10461     );
10462     Hashtbl.add pod2text_memo key lines;
10463     pod2text_memo_updated ();
10464     lines
10465
10466 (* Generate ruby bindings. *)
10467 and generate_ruby_c () =
10468   generate_header CStyle LGPLv2plus;
10469
10470   pr "\
10471 #include <stdio.h>
10472 #include <stdlib.h>
10473
10474 #include <ruby.h>
10475
10476 #include \"guestfs.h\"
10477
10478 #include \"extconf.h\"
10479
10480 /* For Ruby < 1.9 */
10481 #ifndef RARRAY_LEN
10482 #define RARRAY_LEN(r) (RARRAY((r))->len)
10483 #endif
10484
10485 static VALUE m_guestfs;                 /* guestfs module */
10486 static VALUE c_guestfs;                 /* guestfs_h handle */
10487 static VALUE e_Error;                   /* used for all errors */
10488
10489 static void ruby_guestfs_free (void *p)
10490 {
10491   if (!p) return;
10492   guestfs_close ((guestfs_h *) p);
10493 }
10494
10495 static VALUE ruby_guestfs_create (VALUE m)
10496 {
10497   guestfs_h *g;
10498
10499   g = guestfs_create ();
10500   if (!g)
10501     rb_raise (e_Error, \"failed to create guestfs handle\");
10502
10503   /* Don't print error messages to stderr by default. */
10504   guestfs_set_error_handler (g, NULL, NULL);
10505
10506   /* Wrap it, and make sure the close function is called when the
10507    * handle goes away.
10508    */
10509   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
10510 }
10511
10512 static VALUE ruby_guestfs_close (VALUE gv)
10513 {
10514   guestfs_h *g;
10515   Data_Get_Struct (gv, guestfs_h, g);
10516
10517   ruby_guestfs_free (g);
10518   DATA_PTR (gv) = NULL;
10519
10520   return Qnil;
10521 }
10522
10523 ";
10524
10525   List.iter (
10526     fun (name, style, _, _, _, _, _) ->
10527       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
10528       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
10529       pr ")\n";
10530       pr "{\n";
10531       pr "  guestfs_h *g;\n";
10532       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
10533       pr "  if (!g)\n";
10534       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
10535         name;
10536       pr "\n";
10537
10538       List.iter (
10539         function
10540         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10541         | FileIn n | FileOut n ->
10542             pr "  Check_Type (%sv, T_STRING);\n" n;
10543             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
10544             pr "  if (!%s)\n" n;
10545             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10546             pr "              \"%s\", \"%s\");\n" n name
10547         | BufferIn n ->
10548             pr "  Check_Type (%sv, T_STRING);\n" n;
10549             pr "  const char *%s = RSTRING (%sv)->ptr;\n" n n;
10550             pr "  if (!%s)\n" n;
10551             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10552             pr "              \"%s\", \"%s\");\n" n name;
10553             pr "  size_t %s_size = RSTRING (%sv)->len;\n" n n
10554         | OptString n ->
10555             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
10556         | StringList n | DeviceList n ->
10557             pr "  char **%s;\n" n;
10558             pr "  Check_Type (%sv, T_ARRAY);\n" n;
10559             pr "  {\n";
10560             pr "    size_t i, len;\n";
10561             pr "    len = RARRAY_LEN (%sv);\n" n;
10562             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
10563               n;
10564             pr "    for (i = 0; i < len; ++i) {\n";
10565             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
10566             pr "      %s[i] = StringValueCStr (v);\n" n;
10567             pr "    }\n";
10568             pr "    %s[len] = NULL;\n" n;
10569             pr "  }\n";
10570         | Bool n ->
10571             pr "  int %s = RTEST (%sv);\n" n n
10572         | Int n ->
10573             pr "  int %s = NUM2INT (%sv);\n" n n
10574         | Int64 n ->
10575             pr "  long long %s = NUM2LL (%sv);\n" n n
10576       ) (snd style);
10577       pr "\n";
10578
10579       let error_code =
10580         match fst style with
10581         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10582         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10583         | RConstString _ | RConstOptString _ ->
10584             pr "  const char *r;\n"; "NULL"
10585         | RString _ -> pr "  char *r;\n"; "NULL"
10586         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10587         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10588         | RStructList (_, typ) ->
10589             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10590         | RBufferOut _ ->
10591             pr "  char *r;\n";
10592             pr "  size_t size;\n";
10593             "NULL" in
10594       pr "\n";
10595
10596       pr "  r = guestfs_%s " name;
10597       generate_c_call_args ~handle:"g" style;
10598       pr ";\n";
10599
10600       List.iter (
10601         function
10602         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10603         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10604         | BufferIn _ -> ()
10605         | StringList n | DeviceList n ->
10606             pr "  free (%s);\n" n
10607       ) (snd style);
10608
10609       pr "  if (r == %s)\n" error_code;
10610       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
10611       pr "\n";
10612
10613       (match fst style with
10614        | RErr ->
10615            pr "  return Qnil;\n"
10616        | RInt _ | RBool _ ->
10617            pr "  return INT2NUM (r);\n"
10618        | RInt64 _ ->
10619            pr "  return ULL2NUM (r);\n"
10620        | RConstString _ ->
10621            pr "  return rb_str_new2 (r);\n";
10622        | RConstOptString _ ->
10623            pr "  if (r)\n";
10624            pr "    return rb_str_new2 (r);\n";
10625            pr "  else\n";
10626            pr "    return Qnil;\n";
10627        | RString _ ->
10628            pr "  VALUE rv = rb_str_new2 (r);\n";
10629            pr "  free (r);\n";
10630            pr "  return rv;\n";
10631        | RStringList _ ->
10632            pr "  size_t i, len = 0;\n";
10633            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
10634            pr "  VALUE rv = rb_ary_new2 (len);\n";
10635            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
10636            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
10637            pr "    free (r[i]);\n";
10638            pr "  }\n";
10639            pr "  free (r);\n";
10640            pr "  return rv;\n"
10641        | RStruct (_, typ) ->
10642            let cols = cols_of_struct typ in
10643            generate_ruby_struct_code typ cols
10644        | RStructList (_, typ) ->
10645            let cols = cols_of_struct typ in
10646            generate_ruby_struct_list_code typ cols
10647        | RHashtable _ ->
10648            pr "  VALUE rv = rb_hash_new ();\n";
10649            pr "  size_t i;\n";
10650            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
10651            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
10652            pr "    free (r[i]);\n";
10653            pr "    free (r[i+1]);\n";
10654            pr "  }\n";
10655            pr "  free (r);\n";
10656            pr "  return rv;\n"
10657        | RBufferOut _ ->
10658            pr "  VALUE rv = rb_str_new (r, size);\n";
10659            pr "  free (r);\n";
10660            pr "  return rv;\n";
10661       );
10662
10663       pr "}\n";
10664       pr "\n"
10665   ) all_functions;
10666
10667   pr "\
10668 /* Initialize the module. */
10669 void Init__guestfs ()
10670 {
10671   m_guestfs = rb_define_module (\"Guestfs\");
10672   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
10673   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
10674
10675   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
10676   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
10677
10678 ";
10679   (* Define the rest of the methods. *)
10680   List.iter (
10681     fun (name, style, _, _, _, _, _) ->
10682       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
10683       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
10684   ) all_functions;
10685
10686   pr "}\n"
10687
10688 (* Ruby code to return a struct. *)
10689 and generate_ruby_struct_code typ cols =
10690   pr "  VALUE rv = rb_hash_new ();\n";
10691   List.iter (
10692     function
10693     | name, FString ->
10694         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
10695     | name, FBuffer ->
10696         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
10697     | name, FUUID ->
10698         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
10699     | name, (FBytes|FUInt64) ->
10700         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10701     | name, FInt64 ->
10702         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
10703     | name, FUInt32 ->
10704         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
10705     | name, FInt32 ->
10706         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
10707     | name, FOptPercent ->
10708         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
10709     | name, FChar -> (* XXX wrong? *)
10710         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10711   ) cols;
10712   pr "  guestfs_free_%s (r);\n" typ;
10713   pr "  return rv;\n"
10714
10715 (* Ruby code to return a struct list. *)
10716 and generate_ruby_struct_list_code typ cols =
10717   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
10718   pr "  size_t i;\n";
10719   pr "  for (i = 0; i < r->len; ++i) {\n";
10720   pr "    VALUE hv = rb_hash_new ();\n";
10721   List.iter (
10722     function
10723     | name, FString ->
10724         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
10725     | name, FBuffer ->
10726         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
10727     | name, FUUID ->
10728         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
10729     | name, (FBytes|FUInt64) ->
10730         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10731     | name, FInt64 ->
10732         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
10733     | name, FUInt32 ->
10734         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
10735     | name, FInt32 ->
10736         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
10737     | name, FOptPercent ->
10738         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
10739     | name, FChar -> (* XXX wrong? *)
10740         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10741   ) cols;
10742   pr "    rb_ary_push (rv, hv);\n";
10743   pr "  }\n";
10744   pr "  guestfs_free_%s_list (r);\n" typ;
10745   pr "  return rv;\n"
10746
10747 (* Generate Java bindings GuestFS.java file. *)
10748 and generate_java_java () =
10749   generate_header CStyle LGPLv2plus;
10750
10751   pr "\
10752 package com.redhat.et.libguestfs;
10753
10754 import java.util.HashMap;
10755 import com.redhat.et.libguestfs.LibGuestFSException;
10756 import com.redhat.et.libguestfs.PV;
10757 import com.redhat.et.libguestfs.VG;
10758 import com.redhat.et.libguestfs.LV;
10759 import com.redhat.et.libguestfs.Stat;
10760 import com.redhat.et.libguestfs.StatVFS;
10761 import com.redhat.et.libguestfs.IntBool;
10762 import com.redhat.et.libguestfs.Dirent;
10763
10764 /**
10765  * The GuestFS object is a libguestfs handle.
10766  *
10767  * @author rjones
10768  */
10769 public class GuestFS {
10770   // Load the native code.
10771   static {
10772     System.loadLibrary (\"guestfs_jni\");
10773   }
10774
10775   /**
10776    * The native guestfs_h pointer.
10777    */
10778   long g;
10779
10780   /**
10781    * Create a libguestfs handle.
10782    *
10783    * @throws LibGuestFSException
10784    */
10785   public GuestFS () throws LibGuestFSException
10786   {
10787     g = _create ();
10788   }
10789   private native long _create () throws LibGuestFSException;
10790
10791   /**
10792    * Close a libguestfs handle.
10793    *
10794    * You can also leave handles to be collected by the garbage
10795    * collector, but this method ensures that the resources used
10796    * by the handle are freed up immediately.  If you call any
10797    * other methods after closing the handle, you will get an
10798    * exception.
10799    *
10800    * @throws LibGuestFSException
10801    */
10802   public void close () throws LibGuestFSException
10803   {
10804     if (g != 0)
10805       _close (g);
10806     g = 0;
10807   }
10808   private native void _close (long g) throws LibGuestFSException;
10809
10810   public void finalize () throws LibGuestFSException
10811   {
10812     close ();
10813   }
10814
10815 ";
10816
10817   List.iter (
10818     fun (name, style, _, flags, _, shortdesc, longdesc) ->
10819       if not (List.mem NotInDocs flags); then (
10820         let doc = replace_str longdesc "C<guestfs_" "C<g." in
10821         let doc =
10822           if List.mem ProtocolLimitWarning flags then
10823             doc ^ "\n\n" ^ protocol_limit_warning
10824           else doc in
10825         let doc =
10826           if List.mem DangerWillRobinson flags then
10827             doc ^ "\n\n" ^ danger_will_robinson
10828           else doc in
10829         let doc =
10830           match deprecation_notice flags with
10831           | None -> doc
10832           | Some txt -> doc ^ "\n\n" ^ txt in
10833         let doc = pod2text ~width:60 name doc in
10834         let doc = List.map (            (* RHBZ#501883 *)
10835           function
10836           | "" -> "<p>"
10837           | nonempty -> nonempty
10838         ) doc in
10839         let doc = String.concat "\n   * " doc in
10840
10841         pr "  /**\n";
10842         pr "   * %s\n" shortdesc;
10843         pr "   * <p>\n";
10844         pr "   * %s\n" doc;
10845         pr "   * @throws LibGuestFSException\n";
10846         pr "   */\n";
10847         pr "  ";
10848       );
10849       generate_java_prototype ~public:true ~semicolon:false name style;
10850       pr "\n";
10851       pr "  {\n";
10852       pr "    if (g == 0)\n";
10853       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
10854         name;
10855       pr "    ";
10856       if fst style <> RErr then pr "return ";
10857       pr "_%s " name;
10858       generate_java_call_args ~handle:"g" (snd style);
10859       pr ";\n";
10860       pr "  }\n";
10861       pr "  ";
10862       generate_java_prototype ~privat:true ~native:true name style;
10863       pr "\n";
10864       pr "\n";
10865   ) all_functions;
10866
10867   pr "}\n"
10868
10869 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
10870 and generate_java_call_args ~handle args =
10871   pr "(%s" handle;
10872   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10873   pr ")"
10874
10875 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
10876     ?(semicolon=true) name style =
10877   if privat then pr "private ";
10878   if public then pr "public ";
10879   if native then pr "native ";
10880
10881   (* return type *)
10882   (match fst style with
10883    | RErr -> pr "void ";
10884    | RInt _ -> pr "int ";
10885    | RInt64 _ -> pr "long ";
10886    | RBool _ -> pr "boolean ";
10887    | RConstString _ | RConstOptString _ | RString _
10888    | RBufferOut _ -> pr "String ";
10889    | RStringList _ -> pr "String[] ";
10890    | RStruct (_, typ) ->
10891        let name = java_name_of_struct typ in
10892        pr "%s " name;
10893    | RStructList (_, typ) ->
10894        let name = java_name_of_struct typ in
10895        pr "%s[] " name;
10896    | RHashtable _ -> pr "HashMap<String,String> ";
10897   );
10898
10899   if native then pr "_%s " name else pr "%s " name;
10900   pr "(";
10901   let needs_comma = ref false in
10902   if native then (
10903     pr "long g";
10904     needs_comma := true
10905   );
10906
10907   (* args *)
10908   List.iter (
10909     fun arg ->
10910       if !needs_comma then pr ", ";
10911       needs_comma := true;
10912
10913       match arg with
10914       | Pathname n
10915       | Device n | Dev_or_Path n
10916       | String n
10917       | OptString n
10918       | FileIn n
10919       | FileOut n
10920       | Key n ->
10921           pr "String %s" n
10922       | BufferIn n ->
10923           pr "byte[] %s" n
10924       | StringList n | DeviceList n ->
10925           pr "String[] %s" n
10926       | Bool n ->
10927           pr "boolean %s" n
10928       | Int n ->
10929           pr "int %s" n
10930       | Int64 n ->
10931           pr "long %s" n
10932   ) (snd style);
10933
10934   pr ")\n";
10935   pr "    throws LibGuestFSException";
10936   if semicolon then pr ";"
10937
10938 and generate_java_struct jtyp cols () =
10939   generate_header CStyle LGPLv2plus;
10940
10941   pr "\
10942 package com.redhat.et.libguestfs;
10943
10944 /**
10945  * Libguestfs %s structure.
10946  *
10947  * @author rjones
10948  * @see GuestFS
10949  */
10950 public class %s {
10951 " jtyp jtyp;
10952
10953   List.iter (
10954     function
10955     | name, FString
10956     | name, FUUID
10957     | name, FBuffer -> pr "  public String %s;\n" name
10958     | name, (FBytes|FUInt64|FInt64) -> pr "  public long %s;\n" name
10959     | name, (FUInt32|FInt32) -> pr "  public int %s;\n" name
10960     | name, FChar -> pr "  public char %s;\n" name
10961     | name, FOptPercent ->
10962         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
10963         pr "  public float %s;\n" name
10964   ) cols;
10965
10966   pr "}\n"
10967
10968 and generate_java_c () =
10969   generate_header CStyle LGPLv2plus;
10970
10971   pr "\
10972 #include <stdio.h>
10973 #include <stdlib.h>
10974 #include <string.h>
10975
10976 #include \"com_redhat_et_libguestfs_GuestFS.h\"
10977 #include \"guestfs.h\"
10978
10979 /* Note that this function returns.  The exception is not thrown
10980  * until after the wrapper function returns.
10981  */
10982 static void
10983 throw_exception (JNIEnv *env, const char *msg)
10984 {
10985   jclass cl;
10986   cl = (*env)->FindClass (env,
10987                           \"com/redhat/et/libguestfs/LibGuestFSException\");
10988   (*env)->ThrowNew (env, cl, msg);
10989 }
10990
10991 JNIEXPORT jlong JNICALL
10992 Java_com_redhat_et_libguestfs_GuestFS__1create
10993   (JNIEnv *env, jobject obj)
10994 {
10995   guestfs_h *g;
10996
10997   g = guestfs_create ();
10998   if (g == NULL) {
10999     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
11000     return 0;
11001   }
11002   guestfs_set_error_handler (g, NULL, NULL);
11003   return (jlong) (long) g;
11004 }
11005
11006 JNIEXPORT void JNICALL
11007 Java_com_redhat_et_libguestfs_GuestFS__1close
11008   (JNIEnv *env, jobject obj, jlong jg)
11009 {
11010   guestfs_h *g = (guestfs_h *) (long) jg;
11011   guestfs_close (g);
11012 }
11013
11014 ";
11015
11016   List.iter (
11017     fun (name, style, _, _, _, _, _) ->
11018       pr "JNIEXPORT ";
11019       (match fst style with
11020        | RErr -> pr "void ";
11021        | RInt _ -> pr "jint ";
11022        | RInt64 _ -> pr "jlong ";
11023        | RBool _ -> pr "jboolean ";
11024        | RConstString _ | RConstOptString _ | RString _
11025        | RBufferOut _ -> pr "jstring ";
11026        | RStruct _ | RHashtable _ ->
11027            pr "jobject ";
11028        | RStringList _ | RStructList _ ->
11029            pr "jobjectArray ";
11030       );
11031       pr "JNICALL\n";
11032       pr "Java_com_redhat_et_libguestfs_GuestFS_";
11033       pr "%s" (replace_str ("_" ^ name) "_" "_1");
11034       pr "\n";
11035       pr "  (JNIEnv *env, jobject obj, jlong jg";
11036       List.iter (
11037         function
11038         | Pathname n
11039         | Device n | Dev_or_Path n
11040         | String n
11041         | OptString n
11042         | FileIn n
11043         | FileOut n
11044         | Key n ->
11045             pr ", jstring j%s" n
11046         | BufferIn n ->
11047             pr ", jbyteArray j%s" n
11048         | StringList n | DeviceList n ->
11049             pr ", jobjectArray j%s" n
11050         | Bool n ->
11051             pr ", jboolean j%s" n
11052         | Int n ->
11053             pr ", jint j%s" n
11054         | Int64 n ->
11055             pr ", jlong j%s" n
11056       ) (snd style);
11057       pr ")\n";
11058       pr "{\n";
11059       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
11060       let error_code, no_ret =
11061         match fst style with
11062         | RErr -> pr "  int r;\n"; "-1", ""
11063         | RBool _
11064         | RInt _ -> pr "  int r;\n"; "-1", "0"
11065         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
11066         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11067         | RConstOptString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11068         | RString _ ->
11069             pr "  jstring jr;\n";
11070             pr "  char *r;\n"; "NULL", "NULL"
11071         | RStringList _ ->
11072             pr "  jobjectArray jr;\n";
11073             pr "  int r_len;\n";
11074             pr "  jclass cl;\n";
11075             pr "  jstring jstr;\n";
11076             pr "  char **r;\n"; "NULL", "NULL"
11077         | RStruct (_, typ) ->
11078             pr "  jobject jr;\n";
11079             pr "  jclass cl;\n";
11080             pr "  jfieldID fl;\n";
11081             pr "  struct guestfs_%s *r;\n" typ; "NULL", "NULL"
11082         | RStructList (_, typ) ->
11083             pr "  jobjectArray jr;\n";
11084             pr "  jclass cl;\n";
11085             pr "  jfieldID fl;\n";
11086             pr "  jobject jfl;\n";
11087             pr "  struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
11088         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL"
11089         | RBufferOut _ ->
11090             pr "  jstring jr;\n";
11091             pr "  char *r;\n";
11092             pr "  size_t size;\n";
11093             "NULL", "NULL" in
11094       List.iter (
11095         function
11096         | Pathname n
11097         | Device n | Dev_or_Path n
11098         | String n
11099         | OptString n
11100         | FileIn n
11101         | FileOut n
11102         | Key n ->
11103             pr "  const char *%s;\n" n
11104         | BufferIn n ->
11105             pr "  jbyte *%s;\n" n;
11106             pr "  size_t %s_size;\n" n
11107         | StringList n | DeviceList n ->
11108             pr "  int %s_len;\n" n;
11109             pr "  const char **%s;\n" n
11110         | Bool n
11111         | Int n ->
11112             pr "  int %s;\n" n
11113         | Int64 n ->
11114             pr "  int64_t %s;\n" n
11115       ) (snd style);
11116
11117       let needs_i =
11118         (match fst style with
11119          | RStringList _ | RStructList _ -> true
11120          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
11121          | RConstOptString _
11122          | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
11123           List.exists (function
11124                        | StringList _ -> true
11125                        | DeviceList _ -> true
11126                        | _ -> false) (snd style) in
11127       if needs_i then
11128         pr "  size_t i;\n";
11129
11130       pr "\n";
11131
11132       (* Get the parameters. *)
11133       List.iter (
11134         function
11135         | Pathname n
11136         | Device n | Dev_or_Path n
11137         | String n
11138         | FileIn n
11139         | FileOut n
11140         | Key n ->
11141             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
11142         | OptString n ->
11143             (* This is completely undocumented, but Java null becomes
11144              * a NULL parameter.
11145              *)
11146             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
11147         | BufferIn n ->
11148             pr "  %s = (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n;
11149             pr "  %s_size = (*env)->GetArrayLength (env, j%s);\n" n n
11150         | StringList n | DeviceList n ->
11151             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
11152             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
11153             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11154             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11155               n;
11156             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
11157             pr "  }\n";
11158             pr "  %s[%s_len] = NULL;\n" n n;
11159         | Bool n
11160         | Int n
11161         | Int64 n ->
11162             pr "  %s = j%s;\n" n n
11163       ) (snd style);
11164
11165       (* Make the call. *)
11166       pr "  r = guestfs_%s " name;
11167       generate_c_call_args ~handle:"g" style;
11168       pr ";\n";
11169
11170       (* Release the parameters. *)
11171       List.iter (
11172         function
11173         | Pathname n
11174         | Device n | Dev_or_Path n
11175         | String n
11176         | FileIn n
11177         | FileOut n
11178         | Key n ->
11179             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11180         | OptString n ->
11181             pr "  if (j%s)\n" n;
11182             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11183         | BufferIn n ->
11184             pr "  (*env)->ReleaseByteArrayElements (env, j%s, %s, 0);\n" n n
11185         | StringList n | DeviceList n ->
11186             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11187             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11188               n;
11189             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
11190             pr "  }\n";
11191             pr "  free (%s);\n" n
11192         | Bool n
11193         | Int n
11194         | Int64 n -> ()
11195       ) (snd style);
11196
11197       (* Check for errors. *)
11198       pr "  if (r == %s) {\n" error_code;
11199       pr "    throw_exception (env, guestfs_last_error (g));\n";
11200       pr "    return %s;\n" no_ret;
11201       pr "  }\n";
11202
11203       (* Return value. *)
11204       (match fst style with
11205        | RErr -> ()
11206        | RInt _ -> pr "  return (jint) r;\n"
11207        | RBool _ -> pr "  return (jboolean) r;\n"
11208        | RInt64 _ -> pr "  return (jlong) r;\n"
11209        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
11210        | RConstOptString _ ->
11211            pr "  return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
11212        | RString _ ->
11213            pr "  jr = (*env)->NewStringUTF (env, r);\n";
11214            pr "  free (r);\n";
11215            pr "  return jr;\n"
11216        | RStringList _ ->
11217            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
11218            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
11219            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
11220            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
11221            pr "  for (i = 0; i < r_len; ++i) {\n";
11222            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
11223            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
11224            pr "    free (r[i]);\n";
11225            pr "  }\n";
11226            pr "  free (r);\n";
11227            pr "  return jr;\n"
11228        | RStruct (_, typ) ->
11229            let jtyp = java_name_of_struct typ in
11230            let cols = cols_of_struct typ in
11231            generate_java_struct_return typ jtyp cols
11232        | RStructList (_, typ) ->
11233            let jtyp = java_name_of_struct typ in
11234            let cols = cols_of_struct typ in
11235            generate_java_struct_list_return typ jtyp cols
11236        | RHashtable _ ->
11237            (* XXX *)
11238            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
11239            pr "  return NULL;\n"
11240        | RBufferOut _ ->
11241            pr "  jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
11242            pr "  free (r);\n";
11243            pr "  return jr;\n"
11244       );
11245
11246       pr "}\n";
11247       pr "\n"
11248   ) all_functions
11249
11250 and generate_java_struct_return typ jtyp cols =
11251   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11252   pr "  jr = (*env)->AllocObject (env, cl);\n";
11253   List.iter (
11254     function
11255     | name, FString ->
11256         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11257         pr "  (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
11258     | name, FUUID ->
11259         pr "  {\n";
11260         pr "    char s[33];\n";
11261         pr "    memcpy (s, r->%s, 32);\n" name;
11262         pr "    s[32] = 0;\n";
11263         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11264         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11265         pr "  }\n";
11266     | name, FBuffer ->
11267         pr "  {\n";
11268         pr "    int len = r->%s_len;\n" name;
11269         pr "    char s[len+1];\n";
11270         pr "    memcpy (s, r->%s, len);\n" name;
11271         pr "    s[len] = 0;\n";
11272         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11273         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11274         pr "  }\n";
11275     | name, (FBytes|FUInt64|FInt64) ->
11276         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11277         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11278     | name, (FUInt32|FInt32) ->
11279         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11280         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11281     | name, FOptPercent ->
11282         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11283         pr "  (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
11284     | name, FChar ->
11285         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11286         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11287   ) cols;
11288   pr "  free (r);\n";
11289   pr "  return jr;\n"
11290
11291 and generate_java_struct_list_return typ jtyp cols =
11292   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11293   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
11294   pr "  for (i = 0; i < r->len; ++i) {\n";
11295   pr "    jfl = (*env)->AllocObject (env, cl);\n";
11296   List.iter (
11297     function
11298     | name, FString ->
11299         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11300         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
11301     | name, FUUID ->
11302         pr "    {\n";
11303         pr "      char s[33];\n";
11304         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
11305         pr "      s[32] = 0;\n";
11306         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11307         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11308         pr "    }\n";
11309     | name, FBuffer ->
11310         pr "    {\n";
11311         pr "      int len = r->val[i].%s_len;\n" name;
11312         pr "      char s[len+1];\n";
11313         pr "      memcpy (s, r->val[i].%s, len);\n" name;
11314         pr "      s[len] = 0;\n";
11315         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11316         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11317         pr "    }\n";
11318     | name, (FBytes|FUInt64|FInt64) ->
11319         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11320         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11321     | name, (FUInt32|FInt32) ->
11322         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11323         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11324     | name, FOptPercent ->
11325         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11326         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
11327     | name, FChar ->
11328         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11329         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11330   ) cols;
11331   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
11332   pr "  }\n";
11333   pr "  guestfs_free_%s_list (r);\n" typ;
11334   pr "  return jr;\n"
11335
11336 and generate_java_makefile_inc () =
11337   generate_header HashStyle GPLv2plus;
11338
11339   pr "java_built_sources = \\\n";
11340   List.iter (
11341     fun (typ, jtyp) ->
11342         pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
11343   ) java_structs;
11344   pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
11345
11346 and generate_haskell_hs () =
11347   generate_header HaskellStyle LGPLv2plus;
11348
11349   (* XXX We only know how to generate partial FFI for Haskell
11350    * at the moment.  Please help out!
11351    *)
11352   let can_generate style =
11353     match style with
11354     | RErr, _
11355     | RInt _, _
11356     | RInt64 _, _ -> true
11357     | RBool _, _
11358     | RConstString _, _
11359     | RConstOptString _, _
11360     | RString _, _
11361     | RStringList _, _
11362     | RStruct _, _
11363     | RStructList _, _
11364     | RHashtable _, _
11365     | RBufferOut _, _ -> false in
11366
11367   pr "\
11368 {-# INCLUDE <guestfs.h> #-}
11369 {-# LANGUAGE ForeignFunctionInterface #-}
11370
11371 module Guestfs (
11372   create";
11373
11374   (* List out the names of the actions we want to export. *)
11375   List.iter (
11376     fun (name, style, _, _, _, _, _) ->
11377       if can_generate style then pr ",\n  %s" name
11378   ) all_functions;
11379
11380   pr "
11381   ) where
11382
11383 -- Unfortunately some symbols duplicate ones already present
11384 -- in Prelude.  We don't know which, so we hard-code a list
11385 -- here.
11386 import Prelude hiding (truncate)
11387
11388 import Foreign
11389 import Foreign.C
11390 import Foreign.C.Types
11391 import IO
11392 import Control.Exception
11393 import Data.Typeable
11394
11395 data GuestfsS = GuestfsS            -- represents the opaque C struct
11396 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
11397 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
11398
11399 -- XXX define properly later XXX
11400 data PV = PV
11401 data VG = VG
11402 data LV = LV
11403 data IntBool = IntBool
11404 data Stat = Stat
11405 data StatVFS = StatVFS
11406 data Hashtable = Hashtable
11407
11408 foreign import ccall unsafe \"guestfs_create\" c_create
11409   :: IO GuestfsP
11410 foreign import ccall unsafe \"&guestfs_close\" c_close
11411   :: FunPtr (GuestfsP -> IO ())
11412 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
11413   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
11414
11415 create :: IO GuestfsH
11416 create = do
11417   p <- c_create
11418   c_set_error_handler p nullPtr nullPtr
11419   h <- newForeignPtr c_close p
11420   return h
11421
11422 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
11423   :: GuestfsP -> IO CString
11424
11425 -- last_error :: GuestfsH -> IO (Maybe String)
11426 -- last_error h = do
11427 --   str <- withForeignPtr h (\\p -> c_last_error p)
11428 --   maybePeek peekCString str
11429
11430 last_error :: GuestfsH -> IO (String)
11431 last_error h = do
11432   str <- withForeignPtr h (\\p -> c_last_error p)
11433   if (str == nullPtr)
11434     then return \"no error\"
11435     else peekCString str
11436
11437 ";
11438
11439   (* Generate wrappers for each foreign function. *)
11440   List.iter (
11441     fun (name, style, _, _, _, _, _) ->
11442       if can_generate style then (
11443         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
11444         pr "  :: ";
11445         generate_haskell_prototype ~handle:"GuestfsP" style;
11446         pr "\n";
11447         pr "\n";
11448         pr "%s :: " name;
11449         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
11450         pr "\n";
11451         pr "%s %s = do\n" name
11452           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
11453         pr "  r <- ";
11454         (* Convert pointer arguments using with* functions. *)
11455         List.iter (
11456           function
11457           | FileIn n
11458           | FileOut n
11459           | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
11460               pr "withCString %s $ \\%s -> " n n
11461           | BufferIn n ->
11462               pr "withCStringLen %s $ \\(%s, %s_size) -> " n n n
11463           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
11464           | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
11465           | Bool _ | Int _ | Int64 _ -> ()
11466         ) (snd style);
11467         (* Convert integer arguments. *)
11468         let args =
11469           List.map (
11470             function
11471             | Bool n -> sprintf "(fromBool %s)" n
11472             | Int n -> sprintf "(fromIntegral %s)" n
11473             | Int64 n -> sprintf "(fromIntegral %s)" n
11474             | FileIn n | FileOut n
11475             | Pathname n | Device n | Dev_or_Path n
11476             | String n | OptString n
11477             | StringList n | DeviceList n
11478             | Key n -> n
11479             | BufferIn n -> sprintf "%s (fromIntegral %s_size)" n n
11480           ) (snd style) in
11481         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
11482           (String.concat " " ("p" :: args));
11483         (match fst style with
11484          | RErr | RInt _ | RInt64 _ | RBool _ ->
11485              pr "  if (r == -1)\n";
11486              pr "    then do\n";
11487              pr "      err <- last_error h\n";
11488              pr "      fail err\n";
11489          | RConstString _ | RConstOptString _ | RString _
11490          | RStringList _ | RStruct _
11491          | RStructList _ | RHashtable _ | RBufferOut _ ->
11492              pr "  if (r == nullPtr)\n";
11493              pr "    then do\n";
11494              pr "      err <- last_error h\n";
11495              pr "      fail err\n";
11496         );
11497         (match fst style with
11498          | RErr ->
11499              pr "    else return ()\n"
11500          | RInt _ ->
11501              pr "    else return (fromIntegral r)\n"
11502          | RInt64 _ ->
11503              pr "    else return (fromIntegral r)\n"
11504          | RBool _ ->
11505              pr "    else return (toBool r)\n"
11506          | RConstString _
11507          | RConstOptString _
11508          | RString _
11509          | RStringList _
11510          | RStruct _
11511          | RStructList _
11512          | RHashtable _
11513          | RBufferOut _ ->
11514              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
11515         );
11516         pr "\n";
11517       )
11518   ) all_functions
11519
11520 and generate_haskell_prototype ~handle ?(hs = false) style =
11521   pr "%s -> " handle;
11522   let string = if hs then "String" else "CString" in
11523   let int = if hs then "Int" else "CInt" in
11524   let bool = if hs then "Bool" else "CInt" in
11525   let int64 = if hs then "Integer" else "Int64" in
11526   List.iter (
11527     fun arg ->
11528       (match arg with
11529        | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _ ->
11530            pr "%s" string
11531        | BufferIn _ ->
11532            if hs then pr "String"
11533            else pr "CString -> CInt"
11534        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
11535        | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
11536        | Bool _ -> pr "%s" bool
11537        | Int _ -> pr "%s" int
11538        | Int64 _ -> pr "%s" int
11539        | FileIn _ -> pr "%s" string
11540        | FileOut _ -> pr "%s" string
11541       );
11542       pr " -> ";
11543   ) (snd style);
11544   pr "IO (";
11545   (match fst style with
11546    | RErr -> if not hs then pr "CInt"
11547    | RInt _ -> pr "%s" int
11548    | RInt64 _ -> pr "%s" int64
11549    | RBool _ -> pr "%s" bool
11550    | RConstString _ -> pr "%s" string
11551    | RConstOptString _ -> pr "Maybe %s" string
11552    | RString _ -> pr "%s" string
11553    | RStringList _ -> pr "[%s]" string
11554    | RStruct (_, typ) ->
11555        let name = java_name_of_struct typ in
11556        pr "%s" name
11557    | RStructList (_, typ) ->
11558        let name = java_name_of_struct typ in
11559        pr "[%s]" name
11560    | RHashtable _ -> pr "Hashtable"
11561    | RBufferOut _ -> pr "%s" string
11562   );
11563   pr ")"
11564
11565 and generate_csharp () =
11566   generate_header CPlusPlusStyle LGPLv2plus;
11567
11568   (* XXX Make this configurable by the C# assembly users. *)
11569   let library = "libguestfs.so.0" in
11570
11571   pr "\
11572 // These C# bindings are highly experimental at present.
11573 //
11574 // Firstly they only work on Linux (ie. Mono).  In order to get them
11575 // to work on Windows (ie. .Net) you would need to port the library
11576 // itself to Windows first.
11577 //
11578 // The second issue is that some calls are known to be incorrect and
11579 // can cause Mono to segfault.  Particularly: calls which pass or
11580 // return string[], or return any structure value.  This is because
11581 // we haven't worked out the correct way to do this from C#.
11582 //
11583 // The third issue is that when compiling you get a lot of warnings.
11584 // We are not sure whether the warnings are important or not.
11585 //
11586 // Fourthly we do not routinely build or test these bindings as part
11587 // of the make && make check cycle, which means that regressions might
11588 // go unnoticed.
11589 //
11590 // Suggestions and patches are welcome.
11591
11592 // To compile:
11593 //
11594 // gmcs Libguestfs.cs
11595 // mono Libguestfs.exe
11596 //
11597 // (You'll probably want to add a Test class / static main function
11598 // otherwise this won't do anything useful).
11599
11600 using System;
11601 using System.IO;
11602 using System.Runtime.InteropServices;
11603 using System.Runtime.Serialization;
11604 using System.Collections;
11605
11606 namespace Guestfs
11607 {
11608   class Error : System.ApplicationException
11609   {
11610     public Error (string message) : base (message) {}
11611     protected Error (SerializationInfo info, StreamingContext context) {}
11612   }
11613
11614   class Guestfs
11615   {
11616     IntPtr _handle;
11617
11618     [DllImport (\"%s\")]
11619     static extern IntPtr guestfs_create ();
11620
11621     public Guestfs ()
11622     {
11623       _handle = guestfs_create ();
11624       if (_handle == IntPtr.Zero)
11625         throw new Error (\"could not create guestfs handle\");
11626     }
11627
11628     [DllImport (\"%s\")]
11629     static extern void guestfs_close (IntPtr h);
11630
11631     ~Guestfs ()
11632     {
11633       guestfs_close (_handle);
11634     }
11635
11636     [DllImport (\"%s\")]
11637     static extern string guestfs_last_error (IntPtr h);
11638
11639 " library library library;
11640
11641   (* Generate C# structure bindings.  We prefix struct names with
11642    * underscore because C# cannot have conflicting struct names and
11643    * method names (eg. "class stat" and "stat").
11644    *)
11645   List.iter (
11646     fun (typ, cols) ->
11647       pr "    [StructLayout (LayoutKind.Sequential)]\n";
11648       pr "    public class _%s {\n" typ;
11649       List.iter (
11650         function
11651         | name, FChar -> pr "      char %s;\n" name
11652         | name, FString -> pr "      string %s;\n" name
11653         | name, FBuffer ->
11654             pr "      uint %s_len;\n" name;
11655             pr "      string %s;\n" name
11656         | name, FUUID ->
11657             pr "      [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
11658             pr "      string %s;\n" name
11659         | name, FUInt32 -> pr "      uint %s;\n" name
11660         | name, FInt32 -> pr "      int %s;\n" name
11661         | name, (FUInt64|FBytes) -> pr "      ulong %s;\n" name
11662         | name, FInt64 -> pr "      long %s;\n" name
11663         | name, FOptPercent -> pr "      float %s; /* [0..100] or -1 */\n" name
11664       ) cols;
11665       pr "    }\n";
11666       pr "\n"
11667   ) structs;
11668
11669   (* Generate C# function bindings. *)
11670   List.iter (
11671     fun (name, style, _, _, _, shortdesc, _) ->
11672       let rec csharp_return_type () =
11673         match fst style with
11674         | RErr -> "void"
11675         | RBool n -> "bool"
11676         | RInt n -> "int"
11677         | RInt64 n -> "long"
11678         | RConstString n
11679         | RConstOptString n
11680         | RString n
11681         | RBufferOut n -> "string"
11682         | RStruct (_,n) -> "_" ^ n
11683         | RHashtable n -> "Hashtable"
11684         | RStringList n -> "string[]"
11685         | RStructList (_,n) -> sprintf "_%s[]" n
11686
11687       and c_return_type () =
11688         match fst style with
11689         | RErr
11690         | RBool _
11691         | RInt _ -> "int"
11692         | RInt64 _ -> "long"
11693         | RConstString _
11694         | RConstOptString _
11695         | RString _
11696         | RBufferOut _ -> "string"
11697         | RStruct (_,n) -> "_" ^ n
11698         | RHashtable _
11699         | RStringList _ -> "string[]"
11700         | RStructList (_,n) -> sprintf "_%s[]" n
11701
11702       and c_error_comparison () =
11703         match fst style with
11704         | RErr
11705         | RBool _
11706         | RInt _
11707         | RInt64 _ -> "== -1"
11708         | RConstString _
11709         | RConstOptString _
11710         | RString _
11711         | RBufferOut _
11712         | RStruct (_,_)
11713         | RHashtable _
11714         | RStringList _
11715         | RStructList (_,_) -> "== null"
11716
11717       and generate_extern_prototype () =
11718         pr "    static extern %s guestfs_%s (IntPtr h"
11719           (c_return_type ()) name;
11720         List.iter (
11721           function
11722           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11723           | FileIn n | FileOut n
11724           | Key n
11725           | BufferIn n ->
11726               pr ", [In] string %s" n
11727           | StringList n | DeviceList n ->
11728               pr ", [In] string[] %s" n
11729           | Bool n ->
11730               pr ", bool %s" n
11731           | Int n ->
11732               pr ", int %s" n
11733           | Int64 n ->
11734               pr ", long %s" n
11735         ) (snd style);
11736         pr ");\n"
11737
11738       and generate_public_prototype () =
11739         pr "    public %s %s (" (csharp_return_type ()) name;
11740         let comma = ref false in
11741         let next () =
11742           if !comma then pr ", ";
11743           comma := true
11744         in
11745         List.iter (
11746           function
11747           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11748           | FileIn n | FileOut n
11749           | Key n
11750           | BufferIn n ->
11751               next (); pr "string %s" n
11752           | StringList n | DeviceList n ->
11753               next (); pr "string[] %s" n
11754           | Bool n ->
11755               next (); pr "bool %s" n
11756           | Int n ->
11757               next (); pr "int %s" n
11758           | Int64 n ->
11759               next (); pr "long %s" n
11760         ) (snd style);
11761         pr ")\n"
11762
11763       and generate_call () =
11764         pr "guestfs_%s (_handle" name;
11765         List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
11766         pr ");\n";
11767       in
11768
11769       pr "    [DllImport (\"%s\")]\n" library;
11770       generate_extern_prototype ();
11771       pr "\n";
11772       pr "    /// <summary>\n";
11773       pr "    /// %s\n" shortdesc;
11774       pr "    /// </summary>\n";
11775       generate_public_prototype ();
11776       pr "    {\n";
11777       pr "      %s r;\n" (c_return_type ());
11778       pr "      r = ";
11779       generate_call ();
11780       pr "      if (r %s)\n" (c_error_comparison ());
11781       pr "        throw new Error (guestfs_last_error (_handle));\n";
11782       (match fst style with
11783        | RErr -> ()
11784        | RBool _ ->
11785            pr "      return r != 0 ? true : false;\n"
11786        | RHashtable _ ->
11787            pr "      Hashtable rr = new Hashtable ();\n";
11788            pr "      for (size_t i = 0; i < r.Length; i += 2)\n";
11789            pr "        rr.Add (r[i], r[i+1]);\n";
11790            pr "      return rr;\n"
11791        | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
11792        | RString _ | RBufferOut _ | RStruct _ | RStringList _
11793        | RStructList _ ->
11794            pr "      return r;\n"
11795       );
11796       pr "    }\n";
11797       pr "\n";
11798   ) all_functions_sorted;
11799
11800   pr "  }
11801 }
11802 "
11803
11804 and generate_bindtests () =
11805   generate_header CStyle LGPLv2plus;
11806
11807   pr "\
11808 #include <stdio.h>
11809 #include <stdlib.h>
11810 #include <inttypes.h>
11811 #include <string.h>
11812
11813 #include \"guestfs.h\"
11814 #include \"guestfs-internal.h\"
11815 #include \"guestfs-internal-actions.h\"
11816 #include \"guestfs_protocol.h\"
11817
11818 #define error guestfs_error
11819 #define safe_calloc guestfs_safe_calloc
11820 #define safe_malloc guestfs_safe_malloc
11821
11822 static void
11823 print_strings (char *const *argv)
11824 {
11825   size_t argc;
11826
11827   printf (\"[\");
11828   for (argc = 0; argv[argc] != NULL; ++argc) {
11829     if (argc > 0) printf (\", \");
11830     printf (\"\\\"%%s\\\"\", argv[argc]);
11831   }
11832   printf (\"]\\n\");
11833 }
11834
11835 /* The test0 function prints its parameters to stdout. */
11836 ";
11837
11838   let test0, tests =
11839     match test_functions with
11840     | [] -> assert false
11841     | test0 :: tests -> test0, tests in
11842
11843   let () =
11844     let (name, style, _, _, _, _, _) = test0 in
11845     generate_prototype ~extern:false ~semicolon:false ~newline:true
11846       ~handle:"g" ~prefix:"guestfs__" name style;
11847     pr "{\n";
11848     List.iter (
11849       function
11850       | Pathname n
11851       | Device n | Dev_or_Path n
11852       | String n
11853       | FileIn n
11854       | FileOut n
11855       | Key n -> pr "  printf (\"%%s\\n\", %s);\n" n
11856       | BufferIn n ->
11857           pr "  {\n";
11858           pr "    size_t i;\n";
11859           pr "    for (i = 0; i < %s_size; ++i)\n" n;
11860           pr "      printf (\"<%%02x>\", %s[i]);\n" n;
11861           pr "    printf (\"\\n\");\n";
11862           pr "  }\n";
11863       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
11864       | StringList n | DeviceList n -> pr "  print_strings (%s);\n" n
11865       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
11866       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
11867       | Int64 n -> pr "  printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
11868     ) (snd style);
11869     pr "  /* Java changes stdout line buffering so we need this: */\n";
11870     pr "  fflush (stdout);\n";
11871     pr "  return 0;\n";
11872     pr "}\n";
11873     pr "\n" in
11874
11875   List.iter (
11876     fun (name, style, _, _, _, _, _) ->
11877       if String.sub name (String.length name - 3) 3 <> "err" then (
11878         pr "/* Test normal return. */\n";
11879         generate_prototype ~extern:false ~semicolon:false ~newline:true
11880           ~handle:"g" ~prefix:"guestfs__" name style;
11881         pr "{\n";
11882         (match fst style with
11883          | RErr ->
11884              pr "  return 0;\n"
11885          | RInt _ ->
11886              pr "  int r;\n";
11887              pr "  sscanf (val, \"%%d\", &r);\n";
11888              pr "  return r;\n"
11889          | RInt64 _ ->
11890              pr "  int64_t r;\n";
11891              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
11892              pr "  return r;\n"
11893          | RBool _ ->
11894              pr "  return STREQ (val, \"true\");\n"
11895          | RConstString _
11896          | RConstOptString _ ->
11897              (* Can't return the input string here.  Return a static
11898               * string so we ensure we get a segfault if the caller
11899               * tries to free it.
11900               *)
11901              pr "  return \"static string\";\n"
11902          | RString _ ->
11903              pr "  return strdup (val);\n"
11904          | RStringList _ ->
11905              pr "  char **strs;\n";
11906              pr "  int n, i;\n";
11907              pr "  sscanf (val, \"%%d\", &n);\n";
11908              pr "  strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
11909              pr "  for (i = 0; i < n; ++i) {\n";
11910              pr "    strs[i] = safe_malloc (g, 16);\n";
11911              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
11912              pr "  }\n";
11913              pr "  strs[n] = NULL;\n";
11914              pr "  return strs;\n"
11915          | RStruct (_, typ) ->
11916              pr "  struct guestfs_%s *r;\n" typ;
11917              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
11918              pr "  return r;\n"
11919          | RStructList (_, typ) ->
11920              pr "  struct guestfs_%s_list *r;\n" typ;
11921              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
11922              pr "  sscanf (val, \"%%d\", &r->len);\n";
11923              pr "  r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
11924              pr "  return r;\n"
11925          | RHashtable _ ->
11926              pr "  char **strs;\n";
11927              pr "  int n, i;\n";
11928              pr "  sscanf (val, \"%%d\", &n);\n";
11929              pr "  strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
11930              pr "  for (i = 0; i < n; ++i) {\n";
11931              pr "    strs[i*2] = safe_malloc (g, 16);\n";
11932              pr "    strs[i*2+1] = safe_malloc (g, 16);\n";
11933              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
11934              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
11935              pr "  }\n";
11936              pr "  strs[n*2] = NULL;\n";
11937              pr "  return strs;\n"
11938          | RBufferOut _ ->
11939              pr "  return strdup (val);\n"
11940         );
11941         pr "}\n";
11942         pr "\n"
11943       ) else (
11944         pr "/* Test error return. */\n";
11945         generate_prototype ~extern:false ~semicolon:false ~newline:true
11946           ~handle:"g" ~prefix:"guestfs__" name style;
11947         pr "{\n";
11948         pr "  error (g, \"error\");\n";
11949         (match fst style with
11950          | RErr | RInt _ | RInt64 _ | RBool _ ->
11951              pr "  return -1;\n"
11952          | RConstString _ | RConstOptString _
11953          | RString _ | RStringList _ | RStruct _
11954          | RStructList _
11955          | RHashtable _
11956          | RBufferOut _ ->
11957              pr "  return NULL;\n"
11958         );
11959         pr "}\n";
11960         pr "\n"
11961       )
11962   ) tests
11963
11964 and generate_ocaml_bindtests () =
11965   generate_header OCamlStyle GPLv2plus;
11966
11967   pr "\
11968 let () =
11969   let g = Guestfs.create () in
11970 ";
11971
11972   let mkargs args =
11973     String.concat " " (
11974       List.map (
11975         function
11976         | CallString s -> "\"" ^ s ^ "\""
11977         | CallOptString None -> "None"
11978         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
11979         | CallStringList xs ->
11980             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
11981         | CallInt i when i >= 0 -> string_of_int i
11982         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
11983         | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
11984         | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
11985         | CallBool b -> string_of_bool b
11986         | CallBuffer s -> sprintf "%S" s
11987       ) args
11988     )
11989   in
11990
11991   generate_lang_bindtests (
11992     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
11993   );
11994
11995   pr "print_endline \"EOF\"\n"
11996
11997 and generate_perl_bindtests () =
11998   pr "#!/usr/bin/perl -w\n";
11999   generate_header HashStyle GPLv2plus;
12000
12001   pr "\
12002 use strict;
12003
12004 use Sys::Guestfs;
12005
12006 my $g = Sys::Guestfs->new ();
12007 ";
12008
12009   let mkargs args =
12010     String.concat ", " (
12011       List.map (
12012         function
12013         | CallString s -> "\"" ^ s ^ "\""
12014         | CallOptString None -> "undef"
12015         | CallOptString (Some s) -> sprintf "\"%s\"" s
12016         | CallStringList xs ->
12017             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12018         | CallInt i -> string_of_int i
12019         | CallInt64 i -> Int64.to_string i
12020         | CallBool b -> if b then "1" else "0"
12021         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12022       ) args
12023     )
12024   in
12025
12026   generate_lang_bindtests (
12027     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
12028   );
12029
12030   pr "print \"EOF\\n\"\n"
12031
12032 and generate_python_bindtests () =
12033   generate_header HashStyle GPLv2plus;
12034
12035   pr "\
12036 import guestfs
12037
12038 g = guestfs.GuestFS ()
12039 ";
12040
12041   let mkargs args =
12042     String.concat ", " (
12043       List.map (
12044         function
12045         | CallString s -> "\"" ^ s ^ "\""
12046         | CallOptString None -> "None"
12047         | CallOptString (Some s) -> sprintf "\"%s\"" s
12048         | CallStringList xs ->
12049             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12050         | CallInt i -> string_of_int i
12051         | CallInt64 i -> Int64.to_string i
12052         | CallBool b -> if b then "1" else "0"
12053         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12054       ) args
12055     )
12056   in
12057
12058   generate_lang_bindtests (
12059     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
12060   );
12061
12062   pr "print \"EOF\"\n"
12063
12064 and generate_ruby_bindtests () =
12065   generate_header HashStyle GPLv2plus;
12066
12067   pr "\
12068 require 'guestfs'
12069
12070 g = Guestfs::create()
12071 ";
12072
12073   let mkargs args =
12074     String.concat ", " (
12075       List.map (
12076         function
12077         | CallString s -> "\"" ^ s ^ "\""
12078         | CallOptString None -> "nil"
12079         | CallOptString (Some s) -> sprintf "\"%s\"" s
12080         | CallStringList xs ->
12081             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12082         | CallInt i -> string_of_int i
12083         | CallInt64 i -> Int64.to_string i
12084         | CallBool b -> string_of_bool b
12085         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12086       ) args
12087     )
12088   in
12089
12090   generate_lang_bindtests (
12091     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
12092   );
12093
12094   pr "print \"EOF\\n\"\n"
12095
12096 and generate_java_bindtests () =
12097   generate_header CStyle GPLv2plus;
12098
12099   pr "\
12100 import com.redhat.et.libguestfs.*;
12101
12102 public class Bindtests {
12103     public static void main (String[] argv)
12104     {
12105         try {
12106             GuestFS g = new GuestFS ();
12107 ";
12108
12109   let mkargs args =
12110     String.concat ", " (
12111       List.map (
12112         function
12113         | CallString s -> "\"" ^ s ^ "\""
12114         | CallOptString None -> "null"
12115         | CallOptString (Some s) -> sprintf "\"%s\"" s
12116         | CallStringList xs ->
12117             "new String[]{" ^
12118               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
12119         | CallInt i -> string_of_int i
12120         | CallInt64 i -> Int64.to_string i
12121         | CallBool b -> string_of_bool b
12122         | CallBuffer s ->
12123             "new byte[] { " ^ String.concat "," (
12124               map_chars (fun c -> string_of_int (Char.code c)) s
12125             ) ^ " }"
12126       ) args
12127     )
12128   in
12129
12130   generate_lang_bindtests (
12131     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
12132   );
12133
12134   pr "
12135             System.out.println (\"EOF\");
12136         }
12137         catch (Exception exn) {
12138             System.err.println (exn);
12139             System.exit (1);
12140         }
12141     }
12142 }
12143 "
12144
12145 and generate_haskell_bindtests () =
12146   generate_header HaskellStyle GPLv2plus;
12147
12148   pr "\
12149 module Bindtests where
12150 import qualified Guestfs
12151
12152 main = do
12153   g <- Guestfs.create
12154 ";
12155
12156   let mkargs args =
12157     String.concat " " (
12158       List.map (
12159         function
12160         | CallString s -> "\"" ^ s ^ "\""
12161         | CallOptString None -> "Nothing"
12162         | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
12163         | CallStringList xs ->
12164             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12165         | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
12166         | CallInt i -> string_of_int i
12167         | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
12168         | CallInt64 i -> Int64.to_string i
12169         | CallBool true -> "True"
12170         | CallBool false -> "False"
12171         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12172       ) args
12173     )
12174   in
12175
12176   generate_lang_bindtests (
12177     fun f args -> pr "  Guestfs.%s g %s\n" f (mkargs args)
12178   );
12179
12180   pr "  putStrLn \"EOF\"\n"
12181
12182 (* Language-independent bindings tests - we do it this way to
12183  * ensure there is parity in testing bindings across all languages.
12184  *)
12185 and generate_lang_bindtests call =
12186   call "test0" [CallString "abc"; CallOptString (Some "def");
12187                 CallStringList []; CallBool false;
12188                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12189                 CallBuffer "abc\000abc"];
12190   call "test0" [CallString "abc"; CallOptString None;
12191                 CallStringList []; CallBool false;
12192                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12193                 CallBuffer "abc\000abc"];
12194   call "test0" [CallString ""; CallOptString (Some "def");
12195                 CallStringList []; CallBool false;
12196                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12197                 CallBuffer "abc\000abc"];
12198   call "test0" [CallString ""; CallOptString (Some "");
12199                 CallStringList []; CallBool false;
12200                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12201                 CallBuffer "abc\000abc"];
12202   call "test0" [CallString "abc"; CallOptString (Some "def");
12203                 CallStringList ["1"]; CallBool false;
12204                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12205                 CallBuffer "abc\000abc"];
12206   call "test0" [CallString "abc"; CallOptString (Some "def");
12207                 CallStringList ["1"; "2"]; CallBool false;
12208                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12209                 CallBuffer "abc\000abc"];
12210   call "test0" [CallString "abc"; CallOptString (Some "def");
12211                 CallStringList ["1"]; CallBool true;
12212                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12213                 CallBuffer "abc\000abc"];
12214   call "test0" [CallString "abc"; CallOptString (Some "def");
12215                 CallStringList ["1"]; CallBool false;
12216                 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456";
12217                 CallBuffer "abc\000abc"];
12218   call "test0" [CallString "abc"; CallOptString (Some "def");
12219                 CallStringList ["1"]; CallBool false;
12220                 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456";
12221                 CallBuffer "abc\000abc"];
12222   call "test0" [CallString "abc"; CallOptString (Some "def");
12223                 CallStringList ["1"]; CallBool false;
12224                 CallInt 1; CallInt64 1L; CallString "123"; CallString "456";
12225                 CallBuffer "abc\000abc"];
12226   call "test0" [CallString "abc"; CallOptString (Some "def");
12227                 CallStringList ["1"]; CallBool false;
12228                 CallInt 2; CallInt64 2L; CallString "123"; CallString "456";
12229                 CallBuffer "abc\000abc"];
12230   call "test0" [CallString "abc"; CallOptString (Some "def");
12231                 CallStringList ["1"]; CallBool false;
12232                 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456";
12233                 CallBuffer "abc\000abc"];
12234   call "test0" [CallString "abc"; CallOptString (Some "def");
12235                 CallStringList ["1"]; CallBool false;
12236                 CallInt 0; CallInt64 0L; CallString ""; CallString "";
12237                 CallBuffer "abc\000abc"]
12238
12239 (* XXX Add here tests of the return and error functions. *)
12240
12241 and generate_max_proc_nr () =
12242   pr "%d\n" max_proc_nr
12243
12244 let output_to filename k =
12245   let filename_new = filename ^ ".new" in
12246   chan := open_out filename_new;
12247   k ();
12248   close_out !chan;
12249   chan := Pervasives.stdout;
12250
12251   (* Is the new file different from the current file? *)
12252   if Sys.file_exists filename && files_equal filename filename_new then
12253     unlink filename_new                 (* same, so skip it *)
12254   else (
12255     (* different, overwrite old one *)
12256     (try chmod filename 0o644 with Unix_error _ -> ());
12257     rename filename_new filename;
12258     chmod filename 0o444;
12259     printf "written %s\n%!" filename;
12260   )
12261
12262 let perror msg = function
12263   | Unix_error (err, _, _) ->
12264       eprintf "%s: %s\n" msg (error_message err)
12265   | exn ->
12266       eprintf "%s: %s\n" msg (Printexc.to_string exn)
12267
12268 (* Main program. *)
12269 let () =
12270   let lock_fd =
12271     try openfile "HACKING" [O_RDWR] 0
12272     with
12273     | Unix_error (ENOENT, _, _) ->
12274         eprintf "\
12275 You are probably running this from the wrong directory.
12276 Run it from the top source directory using the command
12277   src/generator.ml
12278 ";
12279         exit 1
12280     | exn ->
12281         perror "open: HACKING" exn;
12282         exit 1 in
12283
12284   (* Acquire a lock so parallel builds won't try to run the generator
12285    * twice at the same time.  Subsequent builds will wait for the first
12286    * one to finish.  Note the lock is released implicitly when the
12287    * program exits.
12288    *)
12289   (try lockf lock_fd F_LOCK 1
12290    with exn ->
12291      perror "lock: HACKING" exn;
12292      exit 1);
12293
12294   check_functions ();
12295
12296   output_to "src/guestfs_protocol.x" generate_xdr;
12297   output_to "src/guestfs-structs.h" generate_structs_h;
12298   output_to "src/guestfs-actions.h" generate_actions_h;
12299   output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
12300   output_to "src/actions.c" generate_client_actions;
12301   output_to "src/bindtests.c" generate_bindtests;
12302   output_to "src/guestfs-structs.pod" generate_structs_pod;
12303   output_to "src/guestfs-actions.pod" generate_actions_pod;
12304   output_to "src/guestfs-availability.pod" generate_availability_pod;
12305   output_to "src/MAX_PROC_NR" generate_max_proc_nr;
12306   output_to "src/libguestfs.syms" generate_linker_script;
12307   output_to "daemon/actions.h" generate_daemon_actions_h;
12308   output_to "daemon/stubs.c" generate_daemon_actions;
12309   output_to "daemon/names.c" generate_daemon_names;
12310   output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
12311   output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
12312   output_to "capitests/tests.c" generate_tests;
12313   output_to "fish/cmds.c" generate_fish_cmds;
12314   output_to "fish/completion.c" generate_fish_completion;
12315   output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
12316   output_to "ocaml/guestfs.mli" generate_ocaml_mli;
12317   output_to "ocaml/guestfs.ml" generate_ocaml_ml;
12318   output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
12319   output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
12320   output_to "perl/Guestfs.xs" generate_perl_xs;
12321   output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
12322   output_to "perl/bindtests.pl" generate_perl_bindtests;
12323   output_to "python/guestfs-py.c" generate_python_c;
12324   output_to "python/guestfs.py" generate_python_py;
12325   output_to "python/bindtests.py" generate_python_bindtests;
12326   output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
12327   output_to "ruby/bindtests.rb" generate_ruby_bindtests;
12328   output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
12329
12330   List.iter (
12331     fun (typ, jtyp) ->
12332       let cols = cols_of_struct typ in
12333       let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
12334       output_to filename (generate_java_struct jtyp cols);
12335   ) java_structs;
12336
12337   output_to "java/Makefile.inc" generate_java_makefile_inc;
12338   output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
12339   output_to "java/Bindtests.java" generate_java_bindtests;
12340   output_to "haskell/Guestfs.hs" generate_haskell_hs;
12341   output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
12342   output_to "csharp/Libguestfs.cs" generate_csharp;
12343
12344   (* Always generate this file last, and unconditionally.  It's used
12345    * by the Makefile to know when we must re-run the generator.
12346    *)
12347   let chan = open_out "src/stamp-generator" in
12348   fprintf chan "1\n";
12349   close_out chan;
12350
12351   printf "generated %d lines of code\n" !lines