fish: Add guestfish -N lvfs for creating formatted LVs.
[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   | Progress              (* function can generate progress messages *)
196
197 and fish_output_t =
198   | FishOutputOctal       (* for int return, print in octal *)
199   | FishOutputHexadecimal (* for int return, print in hex *)
200
201 (* You can supply zero or as many tests as you want per API call.
202  *
203  * Note that the test environment has 3 block devices, of size 500MB,
204  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
205  * a fourth ISO block device with some known files on it (/dev/sdd).
206  *
207  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
208  * Number of cylinders was 63 for IDE emulated disks with precisely
209  * the same size.  How exactly this is calculated is a mystery.
210  *
211  * The ISO block device (/dev/sdd) comes from images/test.iso.
212  *
213  * To be able to run the tests in a reasonable amount of time,
214  * the virtual machine and block devices are reused between tests.
215  * So don't try testing kill_subprocess :-x
216  *
217  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
218  *
219  * Don't assume anything about the previous contents of the block
220  * devices.  Use 'Init*' to create some initial scenarios.
221  *
222  * You can add a prerequisite clause to any individual test.  This
223  * is a run-time check, which, if it fails, causes the test to be
224  * skipped.  Useful if testing a command which might not work on
225  * all variations of libguestfs builds.  A test that has prerequisite
226  * of 'Always' is run unconditionally.
227  *
228  * In addition, packagers can skip individual tests by setting the
229  * environment variables:     eg:
230  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
231  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
232  *)
233 type tests = (test_init * test_prereq * test) list
234 and test =
235     (* Run the command sequence and just expect nothing to fail. *)
236   | TestRun of seq
237
238     (* Run the command sequence and expect the output of the final
239      * command to be the string.
240      *)
241   | TestOutput of seq * string
242
243     (* Run the command sequence and expect the output of the final
244      * command to be the list of strings.
245      *)
246   | TestOutputList of seq * string list
247
248     (* Run the command sequence and expect the output of the final
249      * command to be the list of block devices (could be either
250      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
251      * character of each string).
252      *)
253   | TestOutputListOfDevices of seq * string list
254
255     (* Run the command sequence and expect the output of the final
256      * command to be the integer.
257      *)
258   | TestOutputInt of seq * int
259
260     (* Run the command sequence and expect the output of the final
261      * command to be <op> <int>, eg. ">=", "1".
262      *)
263   | TestOutputIntOp of seq * string * int
264
265     (* Run the command sequence and expect the output of the final
266      * command to be a true value (!= 0 or != NULL).
267      *)
268   | TestOutputTrue of seq
269
270     (* Run the command sequence and expect the output of the final
271      * command to be a false value (== 0 or == NULL, but not an error).
272      *)
273   | TestOutputFalse of seq
274
275     (* Run the command sequence and expect the output of the final
276      * command to be a list of the given length (but don't care about
277      * content).
278      *)
279   | TestOutputLength of seq * int
280
281     (* Run the command sequence and expect the output of the final
282      * command to be a buffer (RBufferOut), ie. string + size.
283      *)
284   | TestOutputBuffer of seq * string
285
286     (* Run the command sequence and expect the output of the final
287      * command to be a structure.
288      *)
289   | TestOutputStruct of seq * test_field_compare list
290
291     (* Run the command sequence and expect the final command (only)
292      * to fail.
293      *)
294   | TestLastFail of seq
295
296 and test_field_compare =
297   | CompareWithInt of string * int
298   | CompareWithIntOp of string * string * int
299   | CompareWithString of string * string
300   | CompareFieldsIntEq of string * string
301   | CompareFieldsStrEq of string * string
302
303 (* Test prerequisites. *)
304 and test_prereq =
305     (* Test always runs. *)
306   | Always
307
308     (* Test is currently disabled - eg. it fails, or it tests some
309      * unimplemented feature.
310      *)
311   | Disabled
312
313     (* 'string' is some C code (a function body) that should return
314      * true or false.  The test will run if the code returns true.
315      *)
316   | If of string
317
318     (* As for 'If' but the test runs _unless_ the code returns true. *)
319   | Unless of string
320
321     (* Run the test only if 'string' is available in the daemon. *)
322   | IfAvailable of string
323
324 (* Some initial scenarios for testing. *)
325 and test_init =
326     (* Do nothing, block devices could contain random stuff including
327      * LVM PVs, and some filesystems might be mounted.  This is usually
328      * a bad idea.
329      *)
330   | InitNone
331
332     (* Block devices are empty and no filesystems are mounted. *)
333   | InitEmpty
334
335     (* /dev/sda contains a single partition /dev/sda1, with random
336      * content.  /dev/sdb and /dev/sdc may have random content.
337      * No LVM.
338      *)
339   | InitPartition
340
341     (* /dev/sda contains a single partition /dev/sda1, which is formatted
342      * as ext2, empty [except for lost+found] and mounted on /.
343      * /dev/sdb and /dev/sdc may have random content.
344      * No LVM.
345      *)
346   | InitBasicFS
347
348     (* /dev/sda:
349      *   /dev/sda1 (is a PV):
350      *     /dev/VG/LV (size 8MB):
351      *       formatted as ext2, empty [except for lost+found], mounted on /
352      * /dev/sdb and /dev/sdc may have random content.
353      *)
354   | InitBasicFSonLVM
355
356     (* /dev/sdd (the ISO, see images/ directory in source)
357      * is mounted on /
358      *)
359   | InitISOFS
360
361 (* Sequence of commands for testing. *)
362 and seq = cmd list
363 and cmd = string list
364
365 (* Note about long descriptions: When referring to another
366  * action, use the format C<guestfs_other> (ie. the full name of
367  * the C function).  This will be replaced as appropriate in other
368  * language bindings.
369  *
370  * Apart from that, long descriptions are just perldoc paragraphs.
371  *)
372
373 (* Generate a random UUID (used in tests). *)
374 let uuidgen () =
375   let chan = open_process_in "uuidgen" in
376   let uuid = input_line chan in
377   (match close_process_in chan with
378    | WEXITED 0 -> ()
379    | WEXITED _ ->
380        failwith "uuidgen: process exited with non-zero status"
381    | WSIGNALED _ | WSTOPPED _ ->
382        failwith "uuidgen: process signalled or stopped by signal"
383   );
384   uuid
385
386 (* These test functions are used in the language binding tests. *)
387
388 let test_all_args = [
389   String "str";
390   OptString "optstr";
391   StringList "strlist";
392   Bool "b";
393   Int "integer";
394   Int64 "integer64";
395   FileIn "filein";
396   FileOut "fileout";
397   BufferIn "bufferin";
398 ]
399
400 let test_all_rets = [
401   (* except for RErr, which is tested thoroughly elsewhere *)
402   "test0rint",         RInt "valout";
403   "test0rint64",       RInt64 "valout";
404   "test0rbool",        RBool "valout";
405   "test0rconststring", RConstString "valout";
406   "test0rconstoptstring", RConstOptString "valout";
407   "test0rstring",      RString "valout";
408   "test0rstringlist",  RStringList "valout";
409   "test0rstruct",      RStruct ("valout", "lvm_pv");
410   "test0rstructlist",  RStructList ("valout", "lvm_pv");
411   "test0rhashtable",   RHashtable "valout";
412 ]
413
414 let test_functions = [
415   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
416    [],
417    "internal test function - do not use",
418    "\
419 This is an internal test function which is used to test whether
420 the automatically generated bindings can handle every possible
421 parameter type correctly.
422
423 It echos the contents of each parameter to stdout.
424
425 You probably don't want to call this function.");
426 ] @ List.flatten (
427   List.map (
428     fun (name, ret) ->
429       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
430         [],
431         "internal test function - do not use",
432         "\
433 This is an internal test function which is used to test whether
434 the automatically generated bindings can handle every possible
435 return type correctly.
436
437 It converts string C<val> to the return type.
438
439 You probably don't want to call this function.");
440        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
441         [],
442         "internal test function - do not use",
443         "\
444 This is an internal test function which is used to test whether
445 the automatically generated bindings can handle every possible
446 return type correctly.
447
448 This function always returns an error.
449
450 You probably don't want to call this function.")]
451   ) test_all_rets
452 )
453
454 (* non_daemon_functions are any functions which don't get processed
455  * in the daemon, eg. functions for setting and getting local
456  * configuration values.
457  *)
458
459 let non_daemon_functions = test_functions @ [
460   ("launch", (RErr, []), -1, [FishAlias "run"],
461    [],
462    "launch the qemu subprocess",
463    "\
464 Internally libguestfs is implemented by running a virtual machine
465 using L<qemu(1)>.
466
467 You should call this after configuring the handle
468 (eg. adding drives) but before performing any actions.");
469
470   ("wait_ready", (RErr, []), -1, [NotInFish],
471    [],
472    "wait until the qemu subprocess launches (no op)",
473    "\
474 This function is a no op.
475
476 In versions of the API E<lt> 1.0.71 you had to call this function
477 just after calling C<guestfs_launch> to wait for the launch
478 to complete.  However this is no longer necessary because
479 C<guestfs_launch> now does the waiting.
480
481 If you see any calls to this function in code then you can just
482 remove them, unless you want to retain compatibility with older
483 versions of the API.");
484
485   ("kill_subprocess", (RErr, []), -1, [],
486    [],
487    "kill the qemu subprocess",
488    "\
489 This kills the qemu subprocess.  You should never need to call this.");
490
491   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
492    [],
493    "add an image to examine or modify",
494    "\
495 This function adds a virtual machine disk image C<filename> to the
496 guest.  The first time you call this function, the disk appears as IDE
497 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
498 so on.
499
500 You don't necessarily need to be root when using libguestfs.  However
501 you obviously do need sufficient permissions to access the filename
502 for whatever operations you want to perform (ie. read access if you
503 just want to read the image or write access if you want to modify the
504 image).
505
506 This is equivalent to the qemu parameter
507 C<-drive file=filename,cache=off,if=...>.
508
509 C<cache=off> is omitted in cases where it is not supported by
510 the underlying filesystem.
511
512 C<if=...> is set at compile time by the configuration option
513 C<./configure --with-drive-if=...>.  In the rare case where you
514 might need to change this at run time, use C<guestfs_add_drive_with_if>
515 or C<guestfs_add_drive_ro_with_if>.
516
517 Note that this call checks for the existence of C<filename>.  This
518 stops you from specifying other types of drive which are supported
519 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
520 the general C<guestfs_config> call instead.");
521
522   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
523    [],
524    "add a CD-ROM disk image to examine",
525    "\
526 This function adds a virtual CD-ROM disk image to the guest.
527
528 This is equivalent to the qemu parameter C<-cdrom filename>.
529
530 Notes:
531
532 =over 4
533
534 =item *
535
536 This call checks for the existence of C<filename>.  This
537 stops you from specifying other types of drive which are supported
538 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
539 the general C<guestfs_config> call instead.
540
541 =item *
542
543 If you just want to add an ISO file (often you use this as an
544 efficient way to transfer large files into the guest), then you
545 should probably use C<guestfs_add_drive_ro> instead.
546
547 =back");
548
549   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
550    [],
551    "add a drive in snapshot mode (read-only)",
552    "\
553 This adds a drive in snapshot mode, making it effectively
554 read-only.
555
556 Note that writes to the device are allowed, and will be seen for
557 the duration of the guestfs handle, but they are written
558 to a temporary file which is discarded as soon as the guestfs
559 handle is closed.  We don't currently have any method to enable
560 changes to be committed, although qemu can support this.
561
562 This is equivalent to the qemu parameter
563 C<-drive file=filename,snapshot=on,if=...>.
564
565 C<if=...> is set at compile time by the configuration option
566 C<./configure --with-drive-if=...>.  In the rare case where you
567 might need to change this at run time, use C<guestfs_add_drive_with_if>
568 or C<guestfs_add_drive_ro_with_if>.
569
570 Note that this call checks for the existence of C<filename>.  This
571 stops you from specifying other types of drive which are supported
572 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
573 the general C<guestfs_config> call instead.");
574
575   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
576    [],
577    "add qemu parameters",
578    "\
579 This can be used to add arbitrary qemu command line parameters
580 of the form C<-param value>.  Actually it's not quite arbitrary - we
581 prevent you from setting some parameters which would interfere with
582 parameters that we use.
583
584 The first character of C<param> string must be a C<-> (dash).
585
586 C<value> can be NULL.");
587
588   ("set_qemu", (RErr, [OptString "qemu"]), -1, [FishAlias "qemu"],
589    [],
590    "set the qemu binary",
591    "\
592 Set the qemu binary that we will use.
593
594 The default is chosen when the library was compiled by the
595 configure script.
596
597 You can also override this by setting the C<LIBGUESTFS_QEMU>
598 environment variable.
599
600 Setting C<qemu> to C<NULL> restores the default qemu binary.
601
602 Note that you should call this function as early as possible
603 after creating the handle.  This is because some pre-launch
604 operations depend on testing qemu features (by running C<qemu -help>).
605 If the qemu binary changes, we don't retest features, and
606 so you might see inconsistent results.  Using the environment
607 variable C<LIBGUESTFS_QEMU> is safest of all since that picks
608 the qemu binary at the same time as the handle is created.");
609
610   ("get_qemu", (RConstString "qemu", []), -1, [],
611    [InitNone, Always, TestRun (
612       [["get_qemu"]])],
613    "get the qemu binary",
614    "\
615 Return the current qemu binary.
616
617 This is always non-NULL.  If it wasn't set already, then this will
618 return the default qemu binary name.");
619
620   ("set_path", (RErr, [OptString "searchpath"]), -1, [FishAlias "path"],
621    [],
622    "set the search path",
623    "\
624 Set the path that libguestfs searches for kernel and initrd.img.
625
626 The default is C<$libdir/guestfs> unless overridden by setting
627 C<LIBGUESTFS_PATH> environment variable.
628
629 Setting C<path> to C<NULL> restores the default path.");
630
631   ("get_path", (RConstString "path", []), -1, [],
632    [InitNone, Always, TestRun (
633       [["get_path"]])],
634    "get the search path",
635    "\
636 Return the current search path.
637
638 This is always non-NULL.  If it wasn't set already, then this will
639 return the default path.");
640
641   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
642    [],
643    "add options to kernel command line",
644    "\
645 This function is used to add additional options to the
646 guest kernel command line.
647
648 The default is C<NULL> unless overridden by setting
649 C<LIBGUESTFS_APPEND> environment variable.
650
651 Setting C<append> to C<NULL> means I<no> additional options
652 are passed (libguestfs always adds a few of its own).");
653
654   ("get_append", (RConstOptString "append", []), -1, [],
655    (* This cannot be tested with the current framework.  The
656     * function can return NULL in normal operations, which the
657     * test framework interprets as an error.
658     *)
659    [],
660    "get the additional kernel options",
661    "\
662 Return the additional kernel options which are added to the
663 guest kernel command line.
664
665 If C<NULL> then no options are added.");
666
667   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
668    [],
669    "set autosync mode",
670    "\
671 If C<autosync> is true, this enables autosync.  Libguestfs will make a
672 best effort attempt to run C<guestfs_umount_all> followed by
673 C<guestfs_sync> when the handle is closed
674 (also if the program exits without closing handles).
675
676 This is disabled by default (except in guestfish where it is
677 enabled by default).");
678
679   ("get_autosync", (RBool "autosync", []), -1, [],
680    [InitNone, Always, TestRun (
681       [["get_autosync"]])],
682    "get autosync mode",
683    "\
684 Get the autosync flag.");
685
686   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
687    [],
688    "set verbose mode",
689    "\
690 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
691
692 Verbose messages are disabled unless the environment variable
693 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
694
695   ("get_verbose", (RBool "verbose", []), -1, [],
696    [],
697    "get verbose mode",
698    "\
699 This returns the verbose messages flag.");
700
701   ("is_ready", (RBool "ready", []), -1, [],
702    [InitNone, Always, TestOutputTrue (
703       [["is_ready"]])],
704    "is ready to accept commands",
705    "\
706 This returns true iff this handle is ready to accept commands
707 (in the C<READY> state).
708
709 For more information on states, see L<guestfs(3)>.");
710
711   ("is_config", (RBool "config", []), -1, [],
712    [InitNone, Always, TestOutputFalse (
713       [["is_config"]])],
714    "is in configuration state",
715    "\
716 This returns true iff this handle is being configured
717 (in the C<CONFIG> state).
718
719 For more information on states, see L<guestfs(3)>.");
720
721   ("is_launching", (RBool "launching", []), -1, [],
722    [InitNone, Always, TestOutputFalse (
723       [["is_launching"]])],
724    "is launching subprocess",
725    "\
726 This returns true iff this handle is launching the subprocess
727 (in the C<LAUNCHING> state).
728
729 For more information on states, see L<guestfs(3)>.");
730
731   ("is_busy", (RBool "busy", []), -1, [],
732    [InitNone, Always, TestOutputFalse (
733       [["is_busy"]])],
734    "is busy processing a command",
735    "\
736 This returns true iff this handle is busy processing a command
737 (in the C<BUSY> state).
738
739 For more information on states, see L<guestfs(3)>.");
740
741   ("get_state", (RInt "state", []), -1, [],
742    [],
743    "get the current state",
744    "\
745 This returns the current state as an opaque integer.  This is
746 only useful for printing debug and internal error messages.
747
748 For more information on states, see L<guestfs(3)>.");
749
750   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
751    [InitNone, Always, TestOutputInt (
752       [["set_memsize"; "500"];
753        ["get_memsize"]], 500)],
754    "set memory allocated to the qemu subprocess",
755    "\
756 This sets the memory size in megabytes allocated to the
757 qemu subprocess.  This only has any effect if called before
758 C<guestfs_launch>.
759
760 You can also change this by setting the environment
761 variable C<LIBGUESTFS_MEMSIZE> before the handle is
762 created.
763
764 For more information on the architecture of libguestfs,
765 see L<guestfs(3)>.");
766
767   ("get_memsize", (RInt "memsize", []), -1, [],
768    [InitNone, Always, TestOutputIntOp (
769       [["get_memsize"]], ">=", 256)],
770    "get memory allocated to the qemu subprocess",
771    "\
772 This gets the memory size in megabytes allocated to the
773 qemu subprocess.
774
775 If C<guestfs_set_memsize> was not called
776 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
777 then this returns the compiled-in default value for memsize.
778
779 For more information on the architecture of libguestfs,
780 see L<guestfs(3)>.");
781
782   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
783    [InitNone, Always, TestOutputIntOp (
784       [["get_pid"]], ">=", 1)],
785    "get PID of qemu subprocess",
786    "\
787 Return the process ID of the qemu subprocess.  If there is no
788 qemu subprocess, then this will return an error.
789
790 This is an internal call used for debugging and testing.");
791
792   ("version", (RStruct ("version", "version"), []), -1, [],
793    [InitNone, Always, TestOutputStruct (
794       [["version"]], [CompareWithInt ("major", 1)])],
795    "get the library version number",
796    "\
797 Return the libguestfs version number that the program is linked
798 against.
799
800 Note that because of dynamic linking this is not necessarily
801 the version of libguestfs that you compiled against.  You can
802 compile the program, and then at runtime dynamically link
803 against a completely different C<libguestfs.so> library.
804
805 This call was added in version C<1.0.58>.  In previous
806 versions of libguestfs there was no way to get the version
807 number.  From C code you can use dynamic linker functions
808 to find out if this symbol exists (if it doesn't, then
809 it's an earlier version).
810
811 The call returns a structure with four elements.  The first
812 three (C<major>, C<minor> and C<release>) are numbers and
813 correspond to the usual version triplet.  The fourth element
814 (C<extra>) is a string and is normally empty, but may be
815 used for distro-specific information.
816
817 To construct the original version string:
818 C<$major.$minor.$release$extra>
819
820 See also: L<guestfs(3)/LIBGUESTFS VERSION NUMBERS>.
821
822 I<Note:> Don't use this call to test for availability
823 of features.  In enterprise distributions we backport
824 features from later versions into earlier versions,
825 making this an unreliable way to test for features.
826 Use C<guestfs_available> instead.");
827
828   ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
829    [InitNone, Always, TestOutputTrue (
830       [["set_selinux"; "true"];
831        ["get_selinux"]])],
832    "set SELinux enabled or disabled at appliance boot",
833    "\
834 This sets the selinux flag that is passed to the appliance
835 at boot time.  The default is C<selinux=0> (disabled).
836
837 Note that if SELinux is enabled, it is always in
838 Permissive mode (C<enforcing=0>).
839
840 For more information on the architecture of libguestfs,
841 see L<guestfs(3)>.");
842
843   ("get_selinux", (RBool "selinux", []), -1, [],
844    [],
845    "get SELinux enabled flag",
846    "\
847 This returns the current setting of the selinux flag which
848 is passed to the appliance at boot time.  See C<guestfs_set_selinux>.
849
850 For more information on the architecture of libguestfs,
851 see L<guestfs(3)>.");
852
853   ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
854    [InitNone, Always, TestOutputFalse (
855       [["set_trace"; "false"];
856        ["get_trace"]])],
857    "enable or disable command traces",
858    "\
859 If the command trace flag is set to 1, then commands are
860 printed on stderr before they are executed in a format
861 which is very similar to the one used by guestfish.  In
862 other words, you can run a program with this enabled, and
863 you will get out a script which you can feed to guestfish
864 to perform the same set of actions.
865
866 If you want to trace C API calls into libguestfs (and
867 other libraries) then possibly a better way is to use
868 the external ltrace(1) command.
869
870 Command traces are disabled unless the environment variable
871 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
872
873   ("get_trace", (RBool "trace", []), -1, [],
874    [],
875    "get command trace enabled flag",
876    "\
877 Return the command trace flag.");
878
879   ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
880    [InitNone, Always, TestOutputFalse (
881       [["set_direct"; "false"];
882        ["get_direct"]])],
883    "enable or disable direct appliance mode",
884    "\
885 If the direct appliance mode flag is enabled, then stdin and
886 stdout are passed directly through to the appliance once it
887 is launched.
888
889 One consequence of this is that log messages aren't caught
890 by the library and handled by C<guestfs_set_log_message_callback>,
891 but go straight to stdout.
892
893 You probably don't want to use this unless you know what you
894 are doing.
895
896 The default is disabled.");
897
898   ("get_direct", (RBool "direct", []), -1, [],
899    [],
900    "get direct appliance mode flag",
901    "\
902 Return the direct appliance mode flag.");
903
904   ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
905    [InitNone, Always, TestOutputTrue (
906       [["set_recovery_proc"; "true"];
907        ["get_recovery_proc"]])],
908    "enable or disable the recovery process",
909    "\
910 If this is called with the parameter C<false> then
911 C<guestfs_launch> does not create a recovery process.  The
912 purpose of the recovery process is to stop runaway qemu
913 processes in the case where the main program aborts abruptly.
914
915 This only has any effect if called before C<guestfs_launch>,
916 and the default is true.
917
918 About the only time when you would want to disable this is
919 if the main process will fork itself into the background
920 (\"daemonize\" itself).  In this case the recovery process
921 thinks that the main program has disappeared and so kills
922 qemu, which is not very helpful.");
923
924   ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
925    [],
926    "get recovery process enabled flag",
927    "\
928 Return the recovery process enabled flag.");
929
930   ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
931    [],
932    "add a drive specifying the QEMU block emulation to use",
933    "\
934 This is the same as C<guestfs_add_drive> but it allows you
935 to specify the QEMU interface emulation to use at run time.");
936
937   ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
938    [],
939    "add a drive read-only specifying the QEMU block emulation to use",
940    "\
941 This is the same as C<guestfs_add_drive_ro> but it allows you
942 to specify the QEMU interface emulation to use at run time.");
943
944   ("file_architecture", (RString "arch", [Pathname "filename"]), -1, [],
945    [InitISOFS, Always, TestOutput (
946       [["file_architecture"; "/bin-i586-dynamic"]], "i386");
947     InitISOFS, Always, TestOutput (
948       [["file_architecture"; "/bin-sparc-dynamic"]], "sparc");
949     InitISOFS, Always, TestOutput (
950       [["file_architecture"; "/bin-win32.exe"]], "i386");
951     InitISOFS, Always, TestOutput (
952       [["file_architecture"; "/bin-win64.exe"]], "x86_64");
953     InitISOFS, Always, TestOutput (
954       [["file_architecture"; "/bin-x86_64-dynamic"]], "x86_64");
955     InitISOFS, Always, TestOutput (
956       [["file_architecture"; "/lib-i586.so"]], "i386");
957     InitISOFS, Always, TestOutput (
958       [["file_architecture"; "/lib-sparc.so"]], "sparc");
959     InitISOFS, Always, TestOutput (
960       [["file_architecture"; "/lib-win32.dll"]], "i386");
961     InitISOFS, Always, TestOutput (
962       [["file_architecture"; "/lib-win64.dll"]], "x86_64");
963     InitISOFS, Always, TestOutput (
964       [["file_architecture"; "/lib-x86_64.so"]], "x86_64");
965     InitISOFS, Always, TestOutput (
966       [["file_architecture"; "/initrd-x86_64.img"]], "x86_64");
967     InitISOFS, Always, TestOutput (
968       [["file_architecture"; "/initrd-x86_64.img.gz"]], "x86_64");],
969    "detect the architecture of a binary file",
970    "\
971 This detects the architecture of the binary C<filename>,
972 and returns it if known.
973
974 Currently defined architectures are:
975
976 =over 4
977
978 =item \"i386\"
979
980 This string is returned for all 32 bit i386, i486, i586, i686 binaries
981 irrespective of the precise processor requirements of the binary.
982
983 =item \"x86_64\"
984
985 64 bit x86-64.
986
987 =item \"sparc\"
988
989 32 bit SPARC.
990
991 =item \"sparc64\"
992
993 64 bit SPARC V9 and above.
994
995 =item \"ia64\"
996
997 Intel Itanium.
998
999 =item \"ppc\"
1000
1001 32 bit Power PC.
1002
1003 =item \"ppc64\"
1004
1005 64 bit Power PC.
1006
1007 =back
1008
1009 Libguestfs may return other architecture strings in future.
1010
1011 The function works on at least the following types of files:
1012
1013 =over 4
1014
1015 =item *
1016
1017 many types of Un*x and Linux binary
1018
1019 =item *
1020
1021 many types of Un*x and Linux shared library
1022
1023 =item *
1024
1025 Windows Win32 and Win64 binaries
1026
1027 =item *
1028
1029 Windows Win32 and Win64 DLLs
1030
1031 Win32 binaries and DLLs return C<i386>.
1032
1033 Win64 binaries and DLLs return C<x86_64>.
1034
1035 =item *
1036
1037 Linux kernel modules
1038
1039 =item *
1040
1041 Linux new-style initrd images
1042
1043 =item *
1044
1045 some non-x86 Linux vmlinuz kernels
1046
1047 =back
1048
1049 What it can't do currently:
1050
1051 =over 4
1052
1053 =item *
1054
1055 static libraries (libfoo.a)
1056
1057 =item *
1058
1059 Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
1060
1061 =item *
1062
1063 x86 Linux vmlinuz kernels
1064
1065 x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and
1066 compressed code, and are horribly hard to unpack.  If you want to find
1067 the architecture of a kernel, use the architecture of the associated
1068 initrd or kernel module(s) instead.
1069
1070 =back");
1071
1072   ("inspect_os", (RStringList "roots", []), -1, [],
1073    [],
1074    "inspect disk and return list of operating systems found",
1075    "\
1076 This function uses other libguestfs functions and certain
1077 heuristics to inspect the disk(s) (usually disks belonging to
1078 a virtual machine), looking for operating systems.
1079
1080 The list returned is empty if no operating systems were found.
1081
1082 If one operating system was found, then this returns a list with
1083 a single element, which is the name of the root filesystem of
1084 this operating system.  It is also possible for this function
1085 to return a list containing more than one element, indicating
1086 a dual-boot or multi-boot virtual machine, with each element being
1087 the root filesystem of one of the operating systems.
1088
1089 You can pass the root string(s) returned to other
1090 C<guestfs_inspect_get_*> functions in order to query further
1091 information about each operating system, such as the name
1092 and version.
1093
1094 This function uses other libguestfs features such as
1095 C<guestfs_mount_ro> and C<guestfs_umount_all> in order to mount
1096 and unmount filesystems and look at the contents.  This should
1097 be called with no disks currently mounted.  The function may also
1098 use Augeas, so any existing Augeas handle will be closed.
1099
1100 This function cannot decrypt encrypted disks.  The caller
1101 must do that first (supplying the necessary keys) if the
1102 disk is encrypted.
1103
1104 Please read L<guestfs(3)/INSPECTION> for more details.");
1105
1106   ("inspect_get_type", (RString "name", [Device "root"]), -1, [],
1107    [],
1108    "get type of inspected operating system",
1109    "\
1110 This function should only be called with a root device string
1111 as returned by C<guestfs_inspect_os>.
1112
1113 This returns the type of the inspected operating system.
1114 Currently defined types are:
1115
1116 =over 4
1117
1118 =item \"linux\"
1119
1120 Any Linux-based operating system.
1121
1122 =item \"windows\"
1123
1124 Any Microsoft Windows operating system.
1125
1126 =item \"unknown\"
1127
1128 The operating system type could not be determined.
1129
1130 =back
1131
1132 Future versions of libguestfs may return other strings here.
1133 The caller should be prepared to handle any string.
1134
1135 Please read L<guestfs(3)/INSPECTION> for more details.");
1136
1137   ("inspect_get_arch", (RString "arch", [Device "root"]), -1, [],
1138    [],
1139    "get architecture of inspected operating system",
1140    "\
1141 This function should only be called with a root device string
1142 as returned by C<guestfs_inspect_os>.
1143
1144 This returns the architecture of the inspected operating system.
1145 The possible return values are listed under
1146 C<guestfs_file_architecture>.
1147
1148 If the architecture could not be determined, then the
1149 string C<unknown> is returned.
1150
1151 Please read L<guestfs(3)/INSPECTION> for more details.");
1152
1153   ("inspect_get_distro", (RString "distro", [Device "root"]), -1, [],
1154    [],
1155    "get distro of inspected operating system",
1156    "\
1157 This function should only be called with a root device string
1158 as returned by C<guestfs_inspect_os>.
1159
1160 This returns the distro (distribution) of the inspected operating
1161 system.
1162
1163 Currently defined distros are:
1164
1165 =over 4
1166
1167 =item \"debian\"
1168
1169 Debian or a Debian-derived distro such as Ubuntu.
1170
1171 =item \"fedora\"
1172
1173 Fedora.
1174
1175 =item \"redhat-based\"
1176
1177 Some Red Hat-derived distro.
1178
1179 =item \"rhel\"
1180
1181 Red Hat Enterprise Linux and some derivatives.
1182
1183 =item \"windows\"
1184
1185 Windows does not have distributions.  This string is
1186 returned if the OS type is Windows.
1187
1188 =item \"unknown\"
1189
1190 The distro could not be determined.
1191
1192 =back
1193
1194 Future versions of libguestfs may return other strings here.
1195 The caller should be prepared to handle any string.
1196
1197 Please read L<guestfs(3)/INSPECTION> for more details.");
1198
1199   ("inspect_get_major_version", (RInt "major", [Device "root"]), -1, [],
1200    [],
1201    "get major version of inspected operating system",
1202    "\
1203 This function should only be called with a root device string
1204 as returned by C<guestfs_inspect_os>.
1205
1206 This returns the major version number of the inspected operating
1207 system.
1208
1209 Windows uses a consistent versioning scheme which is I<not>
1210 reflected in the popular public names used by the operating system.
1211 Notably the operating system known as \"Windows 7\" is really
1212 version 6.1 (ie. major = 6, minor = 1).  You can find out the
1213 real versions corresponding to releases of Windows by consulting
1214 Wikipedia or MSDN.
1215
1216 If the version could not be determined, then C<0> is returned.
1217
1218 Please read L<guestfs(3)/INSPECTION> for more details.");
1219
1220   ("inspect_get_minor_version", (RInt "minor", [Device "root"]), -1, [],
1221    [],
1222    "get minor version of inspected operating system",
1223    "\
1224 This function should only be called with a root device string
1225 as returned by C<guestfs_inspect_os>.
1226
1227 This returns the minor version number of the inspected operating
1228 system.
1229
1230 If the version could not be determined, then C<0> is returned.
1231
1232 Please read L<guestfs(3)/INSPECTION> for more details.
1233 See also C<guestfs_inspect_get_major_version>.");
1234
1235   ("inspect_get_product_name", (RString "product", [Device "root"]), -1, [],
1236    [],
1237    "get product name of inspected operating system",
1238    "\
1239 This function should only be called with a root device string
1240 as returned by C<guestfs_inspect_os>.
1241
1242 This returns the product name of the inspected operating
1243 system.  The product name is generally some freeform string
1244 which can be displayed to the user, but should not be
1245 parsed by programs.
1246
1247 If the product name could not be determined, then the
1248 string C<unknown> is returned.
1249
1250 Please read L<guestfs(3)/INSPECTION> for more details.");
1251
1252   ("inspect_get_mountpoints", (RHashtable "mountpoints", [Device "root"]), -1, [],
1253    [],
1254    "get mountpoints of inspected operating system",
1255    "\
1256 This function should only be called with a root device string
1257 as returned by C<guestfs_inspect_os>.
1258
1259 This returns a hash of where we think the filesystems
1260 associated with this operating system should be mounted.
1261 Callers should note that this is at best an educated guess
1262 made by reading configuration files such as C</etc/fstab>.
1263
1264 Each element in the returned hashtable has a key which
1265 is the path of the mountpoint (eg. C</boot>) and a value
1266 which is the filesystem that would be mounted there
1267 (eg. C</dev/sda1>).
1268
1269 Non-mounted devices such as swap devices are I<not>
1270 returned in this list.
1271
1272 Please read L<guestfs(3)/INSPECTION> for more details.
1273 See also C<guestfs_inspect_get_filesystems>.");
1274
1275   ("inspect_get_filesystems", (RStringList "filesystems", [Device "root"]), -1, [],
1276    [],
1277    "get filesystems associated with inspected operating system",
1278    "\
1279 This function should only be called with a root device string
1280 as returned by C<guestfs_inspect_os>.
1281
1282 This returns a list of all the filesystems that we think
1283 are associated with this operating system.  This includes
1284 the root filesystem, other ordinary filesystems, and
1285 non-mounted devices like swap partitions.
1286
1287 In the case of a multi-boot virtual machine, it is possible
1288 for a filesystem to be shared between operating systems.
1289
1290 Please read L<guestfs(3)/INSPECTION> for more details.
1291 See also C<guestfs_inspect_get_mountpoints>.");
1292
1293   ("set_network", (RErr, [Bool "network"]), -1, [FishAlias "network"],
1294    [],
1295    "set enable network flag",
1296    "\
1297 If C<network> is true, then the network is enabled in the
1298 libguestfs appliance.  The default is false.
1299
1300 This affects whether commands are able to access the network
1301 (see L<guestfs(3)/RUNNING COMMANDS>).
1302
1303 You must call this before calling C<guestfs_launch>, otherwise
1304 it has no effect.");
1305
1306   ("get_network", (RBool "network", []), -1, [],
1307    [],
1308    "get enable network flag",
1309    "\
1310 This returns the enable network flag.");
1311
1312 ]
1313
1314 (* daemon_functions are any functions which cause some action
1315  * to take place in the daemon.
1316  *)
1317
1318 let daemon_functions = [
1319   ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
1320    [InitEmpty, Always, TestOutput (
1321       [["part_disk"; "/dev/sda"; "mbr"];
1322        ["mkfs"; "ext2"; "/dev/sda1"];
1323        ["mount"; "/dev/sda1"; "/"];
1324        ["write"; "/new"; "new file contents"];
1325        ["cat"; "/new"]], "new file contents")],
1326    "mount a guest disk at a position in the filesystem",
1327    "\
1328 Mount a guest disk at a position in the filesystem.  Block devices
1329 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
1330 the guest.  If those block devices contain partitions, they will have
1331 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
1332 names can be used.
1333
1334 The rules are the same as for L<mount(2)>:  A filesystem must
1335 first be mounted on C</> before others can be mounted.  Other
1336 filesystems can only be mounted on directories which already
1337 exist.
1338
1339 The mounted filesystem is writable, if we have sufficient permissions
1340 on the underlying device.
1341
1342 B<Important note:>
1343 When you use this call, the filesystem options C<sync> and C<noatime>
1344 are set implicitly.  This was originally done because we thought it
1345 would improve reliability, but it turns out that I<-o sync> has a
1346 very large negative performance impact and negligible effect on
1347 reliability.  Therefore we recommend that you avoid using
1348 C<guestfs_mount> in any code that needs performance, and instead
1349 use C<guestfs_mount_options> (use an empty string for the first
1350 parameter if you don't want any options).");
1351
1352   ("sync", (RErr, []), 2, [],
1353    [ InitEmpty, Always, TestRun [["sync"]]],
1354    "sync disks, writes are flushed through to the disk image",
1355    "\
1356 This syncs the disk, so that any writes are flushed through to the
1357 underlying disk image.
1358
1359 You should always call this if you have modified a disk image, before
1360 closing the handle.");
1361
1362   ("touch", (RErr, [Pathname "path"]), 3, [],
1363    [InitBasicFS, Always, TestOutputTrue (
1364       [["touch"; "/new"];
1365        ["exists"; "/new"]])],
1366    "update file timestamps or create a new file",
1367    "\
1368 Touch acts like the L<touch(1)> command.  It can be used to
1369 update the timestamps on a file, or, if the file does not exist,
1370 to create a new zero-length file.
1371
1372 This command only works on regular files, and will fail on other
1373 file types such as directories, symbolic links, block special etc.");
1374
1375   ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
1376    [InitISOFS, Always, TestOutput (
1377       [["cat"; "/known-2"]], "abcdef\n")],
1378    "list the contents of a file",
1379    "\
1380 Return the contents of the file named C<path>.
1381
1382 Note that this function cannot correctly handle binary files
1383 (specifically, files containing C<\\0> character which is treated
1384 as end of string).  For those you need to use the C<guestfs_read_file>
1385 or C<guestfs_download> functions which have a more complex interface.");
1386
1387   ("ll", (RString "listing", [Pathname "directory"]), 5, [],
1388    [], (* XXX Tricky to test because it depends on the exact format
1389         * of the 'ls -l' command, which changes between F10 and F11.
1390         *)
1391    "list the files in a directory (long format)",
1392    "\
1393 List the files in C<directory> (relative to the root directory,
1394 there is no cwd) in the format of 'ls -la'.
1395
1396 This command is mostly useful for interactive sessions.  It
1397 is I<not> intended that you try to parse the output string.");
1398
1399   ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
1400    [InitBasicFS, Always, TestOutputList (
1401       [["touch"; "/new"];
1402        ["touch"; "/newer"];
1403        ["touch"; "/newest"];
1404        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
1405    "list the files in a directory",
1406    "\
1407 List the files in C<directory> (relative to the root directory,
1408 there is no cwd).  The '.' and '..' entries are not returned, but
1409 hidden files are shown.
1410
1411 This command is mostly useful for interactive sessions.  Programs
1412 should probably use C<guestfs_readdir> instead.");
1413
1414   ("list_devices", (RStringList "devices", []), 7, [],
1415    [InitEmpty, Always, TestOutputListOfDevices (
1416       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1417    "list the block devices",
1418    "\
1419 List all the block devices.
1420
1421 The full block device names are returned, eg. C</dev/sda>");
1422
1423   ("list_partitions", (RStringList "partitions", []), 8, [],
1424    [InitBasicFS, Always, TestOutputListOfDevices (
1425       [["list_partitions"]], ["/dev/sda1"]);
1426     InitEmpty, Always, TestOutputListOfDevices (
1427       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1428        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1429    "list the partitions",
1430    "\
1431 List all the partitions detected on all block devices.
1432
1433 The full partition device names are returned, eg. C</dev/sda1>
1434
1435 This does not return logical volumes.  For that you will need to
1436 call C<guestfs_lvs>.");
1437
1438   ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1439    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1440       [["pvs"]], ["/dev/sda1"]);
1441     InitEmpty, Always, TestOutputListOfDevices (
1442       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1443        ["pvcreate"; "/dev/sda1"];
1444        ["pvcreate"; "/dev/sda2"];
1445        ["pvcreate"; "/dev/sda3"];
1446        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1447    "list the LVM physical volumes (PVs)",
1448    "\
1449 List all the physical volumes detected.  This is the equivalent
1450 of the L<pvs(8)> command.
1451
1452 This returns a list of just the device names that contain
1453 PVs (eg. C</dev/sda2>).
1454
1455 See also C<guestfs_pvs_full>.");
1456
1457   ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1458    [InitBasicFSonLVM, Always, TestOutputList (
1459       [["vgs"]], ["VG"]);
1460     InitEmpty, Always, TestOutputList (
1461       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1462        ["pvcreate"; "/dev/sda1"];
1463        ["pvcreate"; "/dev/sda2"];
1464        ["pvcreate"; "/dev/sda3"];
1465        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1466        ["vgcreate"; "VG2"; "/dev/sda3"];
1467        ["vgs"]], ["VG1"; "VG2"])],
1468    "list the LVM volume groups (VGs)",
1469    "\
1470 List all the volumes groups detected.  This is the equivalent
1471 of the L<vgs(8)> command.
1472
1473 This returns a list of just the volume group names that were
1474 detected (eg. C<VolGroup00>).
1475
1476 See also C<guestfs_vgs_full>.");
1477
1478   ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1479    [InitBasicFSonLVM, Always, TestOutputList (
1480       [["lvs"]], ["/dev/VG/LV"]);
1481     InitEmpty, Always, TestOutputList (
1482       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1483        ["pvcreate"; "/dev/sda1"];
1484        ["pvcreate"; "/dev/sda2"];
1485        ["pvcreate"; "/dev/sda3"];
1486        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1487        ["vgcreate"; "VG2"; "/dev/sda3"];
1488        ["lvcreate"; "LV1"; "VG1"; "50"];
1489        ["lvcreate"; "LV2"; "VG1"; "50"];
1490        ["lvcreate"; "LV3"; "VG2"; "50"];
1491        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1492    "list the LVM logical volumes (LVs)",
1493    "\
1494 List all the logical volumes detected.  This is the equivalent
1495 of the L<lvs(8)> command.
1496
1497 This returns a list of the logical volume device names
1498 (eg. C</dev/VolGroup00/LogVol00>).
1499
1500 See also C<guestfs_lvs_full>.");
1501
1502   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1503    [], (* XXX how to test? *)
1504    "list the LVM physical volumes (PVs)",
1505    "\
1506 List all the physical volumes detected.  This is the equivalent
1507 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
1508
1509   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1510    [], (* XXX how to test? *)
1511    "list the LVM volume groups (VGs)",
1512    "\
1513 List all the volumes groups detected.  This is the equivalent
1514 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
1515
1516   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1517    [], (* XXX how to test? *)
1518    "list the LVM logical volumes (LVs)",
1519    "\
1520 List all the logical volumes detected.  This is the equivalent
1521 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
1522
1523   ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1524    [InitISOFS, Always, TestOutputList (
1525       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1526     InitISOFS, Always, TestOutputList (
1527       [["read_lines"; "/empty"]], [])],
1528    "read file as lines",
1529    "\
1530 Return the contents of the file named C<path>.
1531
1532 The file contents are returned as a list of lines.  Trailing
1533 C<LF> and C<CRLF> character sequences are I<not> returned.
1534
1535 Note that this function cannot correctly handle binary files
1536 (specifically, files containing C<\\0> character which is treated
1537 as end of line).  For those you need to use the C<guestfs_read_file>
1538 function which has a more complex interface.");
1539
1540   ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1541    [], (* XXX Augeas code needs tests. *)
1542    "create a new Augeas handle",
1543    "\
1544 Create a new Augeas handle for editing configuration files.
1545 If there was any previous Augeas handle associated with this
1546 guestfs session, then it is closed.
1547
1548 You must call this before using any other C<guestfs_aug_*>
1549 commands.
1550
1551 C<root> is the filesystem root.  C<root> must not be NULL,
1552 use C</> instead.
1553
1554 The flags are the same as the flags defined in
1555 E<lt>augeas.hE<gt>, the logical I<or> of the following
1556 integers:
1557
1558 =over 4
1559
1560 =item C<AUG_SAVE_BACKUP> = 1
1561
1562 Keep the original file with a C<.augsave> extension.
1563
1564 =item C<AUG_SAVE_NEWFILE> = 2
1565
1566 Save changes into a file with extension C<.augnew>, and
1567 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
1568
1569 =item C<AUG_TYPE_CHECK> = 4
1570
1571 Typecheck lenses (can be expensive).
1572
1573 =item C<AUG_NO_STDINC> = 8
1574
1575 Do not use standard load path for modules.
1576
1577 =item C<AUG_SAVE_NOOP> = 16
1578
1579 Make save a no-op, just record what would have been changed.
1580
1581 =item C<AUG_NO_LOAD> = 32
1582
1583 Do not load the tree in C<guestfs_aug_init>.
1584
1585 =back
1586
1587 To close the handle, you can call C<guestfs_aug_close>.
1588
1589 To find out more about Augeas, see L<http://augeas.net/>.");
1590
1591   ("aug_close", (RErr, []), 26, [Optional "augeas"],
1592    [], (* XXX Augeas code needs tests. *)
1593    "close the current Augeas handle",
1594    "\
1595 Close the current Augeas handle and free up any resources
1596 used by it.  After calling this, you have to call
1597 C<guestfs_aug_init> again before you can use any other
1598 Augeas functions.");
1599
1600   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1601    [], (* XXX Augeas code needs tests. *)
1602    "define an Augeas variable",
1603    "\
1604 Defines an Augeas variable C<name> whose value is the result
1605 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1606 undefined.
1607
1608 On success this returns the number of nodes in C<expr>, or
1609 C<0> if C<expr> evaluates to something which is not a nodeset.");
1610
1611   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1612    [], (* XXX Augeas code needs tests. *)
1613    "define an Augeas node",
1614    "\
1615 Defines a variable C<name> whose value is the result of
1616 evaluating C<expr>.
1617
1618 If C<expr> evaluates to an empty nodeset, a node is created,
1619 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1620 C<name> will be the nodeset containing that single node.
1621
1622 On success this returns a pair containing the
1623 number of nodes in the nodeset, and a boolean flag
1624 if a node was created.");
1625
1626   ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1627    [], (* XXX Augeas code needs tests. *)
1628    "look up the value of an Augeas path",
1629    "\
1630 Look up the value associated with C<path>.  If C<path>
1631 matches exactly one node, the C<value> is returned.");
1632
1633   ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1634    [], (* XXX Augeas code needs tests. *)
1635    "set Augeas path to value",
1636    "\
1637 Set the value associated with C<path> to C<val>.
1638
1639 In the Augeas API, it is possible to clear a node by setting
1640 the value to NULL.  Due to an oversight in the libguestfs API
1641 you cannot do that with this call.  Instead you must use the
1642 C<guestfs_aug_clear> call.");
1643
1644   ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1645    [], (* XXX Augeas code needs tests. *)
1646    "insert a sibling Augeas node",
1647    "\
1648 Create a new sibling C<label> for C<path>, inserting it into
1649 the tree before or after C<path> (depending on the boolean
1650 flag C<before>).
1651
1652 C<path> must match exactly one existing node in the tree, and
1653 C<label> must be a label, ie. not contain C</>, C<*> or end
1654 with a bracketed index C<[N]>.");
1655
1656   ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1657    [], (* XXX Augeas code needs tests. *)
1658    "remove an Augeas path",
1659    "\
1660 Remove C<path> and all of its children.
1661
1662 On success this returns the number of entries which were removed.");
1663
1664   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1665    [], (* XXX Augeas code needs tests. *)
1666    "move Augeas node",
1667    "\
1668 Move the node C<src> to C<dest>.  C<src> must match exactly
1669 one node.  C<dest> is overwritten if it exists.");
1670
1671   ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1672    [], (* XXX Augeas code needs tests. *)
1673    "return Augeas nodes which match augpath",
1674    "\
1675 Returns a list of paths which match the path expression C<path>.
1676 The returned paths are sufficiently qualified so that they match
1677 exactly one node in the current tree.");
1678
1679   ("aug_save", (RErr, []), 25, [Optional "augeas"],
1680    [], (* XXX Augeas code needs tests. *)
1681    "write all pending Augeas changes to disk",
1682    "\
1683 This writes all pending changes to disk.
1684
1685 The flags which were passed to C<guestfs_aug_init> affect exactly
1686 how files are saved.");
1687
1688   ("aug_load", (RErr, []), 27, [Optional "augeas"],
1689    [], (* XXX Augeas code needs tests. *)
1690    "load files into the tree",
1691    "\
1692 Load files into the tree.
1693
1694 See C<aug_load> in the Augeas documentation for the full gory
1695 details.");
1696
1697   ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1698    [], (* XXX Augeas code needs tests. *)
1699    "list Augeas nodes under augpath",
1700    "\
1701 This is just a shortcut for listing C<guestfs_aug_match>
1702 C<path/*> and sorting the resulting nodes into alphabetical order.");
1703
1704   ("rm", (RErr, [Pathname "path"]), 29, [],
1705    [InitBasicFS, Always, TestRun
1706       [["touch"; "/new"];
1707        ["rm"; "/new"]];
1708     InitBasicFS, Always, TestLastFail
1709       [["rm"; "/new"]];
1710     InitBasicFS, Always, TestLastFail
1711       [["mkdir"; "/new"];
1712        ["rm"; "/new"]]],
1713    "remove a file",
1714    "\
1715 Remove the single file C<path>.");
1716
1717   ("rmdir", (RErr, [Pathname "path"]), 30, [],
1718    [InitBasicFS, Always, TestRun
1719       [["mkdir"; "/new"];
1720        ["rmdir"; "/new"]];
1721     InitBasicFS, Always, TestLastFail
1722       [["rmdir"; "/new"]];
1723     InitBasicFS, Always, TestLastFail
1724       [["touch"; "/new"];
1725        ["rmdir"; "/new"]]],
1726    "remove a directory",
1727    "\
1728 Remove the single directory C<path>.");
1729
1730   ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1731    [InitBasicFS, Always, TestOutputFalse
1732       [["mkdir"; "/new"];
1733        ["mkdir"; "/new/foo"];
1734        ["touch"; "/new/foo/bar"];
1735        ["rm_rf"; "/new"];
1736        ["exists"; "/new"]]],
1737    "remove a file or directory recursively",
1738    "\
1739 Remove the file or directory C<path>, recursively removing the
1740 contents if its a directory.  This is like the C<rm -rf> shell
1741 command.");
1742
1743   ("mkdir", (RErr, [Pathname "path"]), 32, [],
1744    [InitBasicFS, Always, TestOutputTrue
1745       [["mkdir"; "/new"];
1746        ["is_dir"; "/new"]];
1747     InitBasicFS, Always, TestLastFail
1748       [["mkdir"; "/new/foo/bar"]]],
1749    "create a directory",
1750    "\
1751 Create a directory named C<path>.");
1752
1753   ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1754    [InitBasicFS, Always, TestOutputTrue
1755       [["mkdir_p"; "/new/foo/bar"];
1756        ["is_dir"; "/new/foo/bar"]];
1757     InitBasicFS, Always, TestOutputTrue
1758       [["mkdir_p"; "/new/foo/bar"];
1759        ["is_dir"; "/new/foo"]];
1760     InitBasicFS, Always, TestOutputTrue
1761       [["mkdir_p"; "/new/foo/bar"];
1762        ["is_dir"; "/new"]];
1763     (* Regression tests for RHBZ#503133: *)
1764     InitBasicFS, Always, TestRun
1765       [["mkdir"; "/new"];
1766        ["mkdir_p"; "/new"]];
1767     InitBasicFS, Always, TestLastFail
1768       [["touch"; "/new"];
1769        ["mkdir_p"; "/new"]]],
1770    "create a directory and parents",
1771    "\
1772 Create a directory named C<path>, creating any parent directories
1773 as necessary.  This is like the C<mkdir -p> shell command.");
1774
1775   ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1776    [], (* XXX Need stat command to test *)
1777    "change file mode",
1778    "\
1779 Change the mode (permissions) of C<path> to C<mode>.  Only
1780 numeric modes are supported.
1781
1782 I<Note>: When using this command from guestfish, C<mode>
1783 by default would be decimal, unless you prefix it with
1784 C<0> to get octal, ie. use C<0700> not C<700>.
1785
1786 The mode actually set is affected by the umask.");
1787
1788   ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1789    [], (* XXX Need stat command to test *)
1790    "change file owner and group",
1791    "\
1792 Change the file owner to C<owner> and group to C<group>.
1793
1794 Only numeric uid and gid are supported.  If you want to use
1795 names, you will need to locate and parse the password file
1796 yourself (Augeas support makes this relatively easy).");
1797
1798   ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1799    [InitISOFS, Always, TestOutputTrue (
1800       [["exists"; "/empty"]]);
1801     InitISOFS, Always, TestOutputTrue (
1802       [["exists"; "/directory"]])],
1803    "test if file or directory exists",
1804    "\
1805 This returns C<true> if and only if there is a file, directory
1806 (or anything) with the given C<path> name.
1807
1808 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1809
1810   ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1811    [InitISOFS, Always, TestOutputTrue (
1812       [["is_file"; "/known-1"]]);
1813     InitISOFS, Always, TestOutputFalse (
1814       [["is_file"; "/directory"]])],
1815    "test if file exists",
1816    "\
1817 This returns C<true> if and only if there is a file
1818 with the given C<path> name.  Note that it returns false for
1819 other objects like directories.
1820
1821 See also C<guestfs_stat>.");
1822
1823   ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1824    [InitISOFS, Always, TestOutputFalse (
1825       [["is_dir"; "/known-3"]]);
1826     InitISOFS, Always, TestOutputTrue (
1827       [["is_dir"; "/directory"]])],
1828    "test if file exists",
1829    "\
1830 This returns C<true> if and only if there is a directory
1831 with the given C<path> name.  Note that it returns false for
1832 other objects like files.
1833
1834 See also C<guestfs_stat>.");
1835
1836   ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1837    [InitEmpty, Always, TestOutputListOfDevices (
1838       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1839        ["pvcreate"; "/dev/sda1"];
1840        ["pvcreate"; "/dev/sda2"];
1841        ["pvcreate"; "/dev/sda3"];
1842        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1843    "create an LVM physical volume",
1844    "\
1845 This creates an LVM physical volume on the named C<device>,
1846 where C<device> should usually be a partition name such
1847 as C</dev/sda1>.");
1848
1849   ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1850    [InitEmpty, Always, TestOutputList (
1851       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1852        ["pvcreate"; "/dev/sda1"];
1853        ["pvcreate"; "/dev/sda2"];
1854        ["pvcreate"; "/dev/sda3"];
1855        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1856        ["vgcreate"; "VG2"; "/dev/sda3"];
1857        ["vgs"]], ["VG1"; "VG2"])],
1858    "create an LVM volume group",
1859    "\
1860 This creates an LVM volume group called C<volgroup>
1861 from the non-empty list of physical volumes C<physvols>.");
1862
1863   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1864    [InitEmpty, Always, TestOutputList (
1865       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1866        ["pvcreate"; "/dev/sda1"];
1867        ["pvcreate"; "/dev/sda2"];
1868        ["pvcreate"; "/dev/sda3"];
1869        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1870        ["vgcreate"; "VG2"; "/dev/sda3"];
1871        ["lvcreate"; "LV1"; "VG1"; "50"];
1872        ["lvcreate"; "LV2"; "VG1"; "50"];
1873        ["lvcreate"; "LV3"; "VG2"; "50"];
1874        ["lvcreate"; "LV4"; "VG2"; "50"];
1875        ["lvcreate"; "LV5"; "VG2"; "50"];
1876        ["lvs"]],
1877       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1878        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1879    "create an LVM logical volume",
1880    "\
1881 This creates an LVM logical volume called C<logvol>
1882 on the volume group C<volgroup>, with C<size> megabytes.");
1883
1884   ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1885    [InitEmpty, Always, TestOutput (
1886       [["part_disk"; "/dev/sda"; "mbr"];
1887        ["mkfs"; "ext2"; "/dev/sda1"];
1888        ["mount_options"; ""; "/dev/sda1"; "/"];
1889        ["write"; "/new"; "new file contents"];
1890        ["cat"; "/new"]], "new file contents")],
1891    "make a filesystem",
1892    "\
1893 This creates a filesystem on C<device> (usually a partition
1894 or LVM logical volume).  The filesystem type is C<fstype>, for
1895 example C<ext3>.");
1896
1897   ("sfdisk", (RErr, [Device "device";
1898                      Int "cyls"; Int "heads"; Int "sectors";
1899                      StringList "lines"]), 43, [DangerWillRobinson],
1900    [],
1901    "create partitions on a block device",
1902    "\
1903 This is a direct interface to the L<sfdisk(8)> program for creating
1904 partitions on block devices.
1905
1906 C<device> should be a block device, for example C</dev/sda>.
1907
1908 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1909 and sectors on the device, which are passed directly to sfdisk as
1910 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1911 of these, then the corresponding parameter is omitted.  Usually for
1912 'large' disks, you can just pass C<0> for these, but for small
1913 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1914 out the right geometry and you will need to tell it.
1915
1916 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1917 information refer to the L<sfdisk(8)> manpage.
1918
1919 To create a single partition occupying the whole disk, you would
1920 pass C<lines> as a single element list, when the single element being
1921 the string C<,> (comma).
1922
1923 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1924 C<guestfs_part_init>");
1925
1926   ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning; DeprecatedBy "write"],
1927    (* Regression test for RHBZ#597135. *)
1928    [InitBasicFS, Always, TestLastFail
1929       [["write_file"; "/new"; "abc"; "10000"]]],
1930    "create a file",
1931    "\
1932 This call creates a file called C<path>.  The contents of the
1933 file is the string C<content> (which can contain any 8 bit data),
1934 with length C<size>.
1935
1936 As a special case, if C<size> is C<0>
1937 then the length is calculated using C<strlen> (so in this case
1938 the content cannot contain embedded ASCII NULs).
1939
1940 I<NB.> Owing to a bug, writing content containing ASCII NUL
1941 characters does I<not> work, even if the length is specified.");
1942
1943   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1944    [InitEmpty, Always, TestOutputListOfDevices (
1945       [["part_disk"; "/dev/sda"; "mbr"];
1946        ["mkfs"; "ext2"; "/dev/sda1"];
1947        ["mount_options"; ""; "/dev/sda1"; "/"];
1948        ["mounts"]], ["/dev/sda1"]);
1949     InitEmpty, Always, TestOutputList (
1950       [["part_disk"; "/dev/sda"; "mbr"];
1951        ["mkfs"; "ext2"; "/dev/sda1"];
1952        ["mount_options"; ""; "/dev/sda1"; "/"];
1953        ["umount"; "/"];
1954        ["mounts"]], [])],
1955    "unmount a filesystem",
1956    "\
1957 This unmounts the given filesystem.  The filesystem may be
1958 specified either by its mountpoint (path) or the device which
1959 contains the filesystem.");
1960
1961   ("mounts", (RStringList "devices", []), 46, [],
1962    [InitBasicFS, Always, TestOutputListOfDevices (
1963       [["mounts"]], ["/dev/sda1"])],
1964    "show mounted filesystems",
1965    "\
1966 This returns the list of currently mounted filesystems.  It returns
1967 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1968
1969 Some internal mounts are not shown.
1970
1971 See also: C<guestfs_mountpoints>");
1972
1973   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1974    [InitBasicFS, Always, TestOutputList (
1975       [["umount_all"];
1976        ["mounts"]], []);
1977     (* check that umount_all can unmount nested mounts correctly: *)
1978     InitEmpty, Always, TestOutputList (
1979       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1980        ["mkfs"; "ext2"; "/dev/sda1"];
1981        ["mkfs"; "ext2"; "/dev/sda2"];
1982        ["mkfs"; "ext2"; "/dev/sda3"];
1983        ["mount_options"; ""; "/dev/sda1"; "/"];
1984        ["mkdir"; "/mp1"];
1985        ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1986        ["mkdir"; "/mp1/mp2"];
1987        ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1988        ["mkdir"; "/mp1/mp2/mp3"];
1989        ["umount_all"];
1990        ["mounts"]], [])],
1991    "unmount all filesystems",
1992    "\
1993 This unmounts all mounted filesystems.
1994
1995 Some internal mounts are not unmounted by this call.");
1996
1997   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1998    [],
1999    "remove all LVM LVs, VGs and PVs",
2000    "\
2001 This command removes all LVM logical volumes, volume groups
2002 and physical volumes.");
2003
2004   ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
2005    [InitISOFS, Always, TestOutput (
2006       [["file"; "/empty"]], "empty");
2007     InitISOFS, Always, TestOutput (
2008       [["file"; "/known-1"]], "ASCII text");
2009     InitISOFS, Always, TestLastFail (
2010       [["file"; "/notexists"]]);
2011     InitISOFS, Always, TestOutput (
2012       [["file"; "/abssymlink"]], "symbolic link");
2013     InitISOFS, Always, TestOutput (
2014       [["file"; "/directory"]], "directory")],
2015    "determine file type",
2016    "\
2017 This call uses the standard L<file(1)> command to determine
2018 the type or contents of the file.
2019
2020 This call will also transparently look inside various types
2021 of compressed file.
2022
2023 The exact command which runs is C<file -zb path>.  Note in
2024 particular that the filename is not prepended to the output
2025 (the C<-b> option).
2026
2027 This command can also be used on C</dev/> devices
2028 (and partitions, LV names).  You can for example use this
2029 to determine if a device contains a filesystem, although
2030 it's usually better to use C<guestfs_vfs_type>.
2031
2032 If the C<path> does not begin with C</dev/> then
2033 this command only works for the content of regular files.
2034 For other file types (directory, symbolic link etc) it
2035 will just return the string C<directory> etc.");
2036
2037   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
2038    [InitBasicFS, Always, TestOutput (
2039       [["upload"; "test-command"; "/test-command"];
2040        ["chmod"; "0o755"; "/test-command"];
2041        ["command"; "/test-command 1"]], "Result1");
2042     InitBasicFS, Always, TestOutput (
2043       [["upload"; "test-command"; "/test-command"];
2044        ["chmod"; "0o755"; "/test-command"];
2045        ["command"; "/test-command 2"]], "Result2\n");
2046     InitBasicFS, Always, TestOutput (
2047       [["upload"; "test-command"; "/test-command"];
2048        ["chmod"; "0o755"; "/test-command"];
2049        ["command"; "/test-command 3"]], "\nResult3");
2050     InitBasicFS, Always, TestOutput (
2051       [["upload"; "test-command"; "/test-command"];
2052        ["chmod"; "0o755"; "/test-command"];
2053        ["command"; "/test-command 4"]], "\nResult4\n");
2054     InitBasicFS, Always, TestOutput (
2055       [["upload"; "test-command"; "/test-command"];
2056        ["chmod"; "0o755"; "/test-command"];
2057        ["command"; "/test-command 5"]], "\nResult5\n\n");
2058     InitBasicFS, Always, TestOutput (
2059       [["upload"; "test-command"; "/test-command"];
2060        ["chmod"; "0o755"; "/test-command"];
2061        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
2062     InitBasicFS, Always, TestOutput (
2063       [["upload"; "test-command"; "/test-command"];
2064        ["chmod"; "0o755"; "/test-command"];
2065        ["command"; "/test-command 7"]], "");
2066     InitBasicFS, Always, TestOutput (
2067       [["upload"; "test-command"; "/test-command"];
2068        ["chmod"; "0o755"; "/test-command"];
2069        ["command"; "/test-command 8"]], "\n");
2070     InitBasicFS, Always, TestOutput (
2071       [["upload"; "test-command"; "/test-command"];
2072        ["chmod"; "0o755"; "/test-command"];
2073        ["command"; "/test-command 9"]], "\n\n");
2074     InitBasicFS, Always, TestOutput (
2075       [["upload"; "test-command"; "/test-command"];
2076        ["chmod"; "0o755"; "/test-command"];
2077        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
2078     InitBasicFS, Always, TestOutput (
2079       [["upload"; "test-command"; "/test-command"];
2080        ["chmod"; "0o755"; "/test-command"];
2081        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
2082     InitBasicFS, Always, TestLastFail (
2083       [["upload"; "test-command"; "/test-command"];
2084        ["chmod"; "0o755"; "/test-command"];
2085        ["command"; "/test-command"]])],
2086    "run a command from the guest filesystem",
2087    "\
2088 This call runs a command from the guest filesystem.  The
2089 filesystem must be mounted, and must contain a compatible
2090 operating system (ie. something Linux, with the same
2091 or compatible processor architecture).
2092
2093 The single parameter is an argv-style list of arguments.
2094 The first element is the name of the program to run.
2095 Subsequent elements are parameters.  The list must be
2096 non-empty (ie. must contain a program name).  Note that
2097 the command runs directly, and is I<not> invoked via
2098 the shell (see C<guestfs_sh>).
2099
2100 The return value is anything printed to I<stdout> by
2101 the command.
2102
2103 If the command returns a non-zero exit status, then
2104 this function returns an error message.  The error message
2105 string is the content of I<stderr> from the command.
2106
2107 The C<$PATH> environment variable will contain at least
2108 C</usr/bin> and C</bin>.  If you require a program from
2109 another location, you should provide the full path in the
2110 first parameter.
2111
2112 Shared libraries and data files required by the program
2113 must be available on filesystems which are mounted in the
2114 correct places.  It is the caller's responsibility to ensure
2115 all filesystems that are needed are mounted at the right
2116 locations.");
2117
2118   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
2119    [InitBasicFS, Always, TestOutputList (
2120       [["upload"; "test-command"; "/test-command"];
2121        ["chmod"; "0o755"; "/test-command"];
2122        ["command_lines"; "/test-command 1"]], ["Result1"]);
2123     InitBasicFS, Always, TestOutputList (
2124       [["upload"; "test-command"; "/test-command"];
2125        ["chmod"; "0o755"; "/test-command"];
2126        ["command_lines"; "/test-command 2"]], ["Result2"]);
2127     InitBasicFS, Always, TestOutputList (
2128       [["upload"; "test-command"; "/test-command"];
2129        ["chmod"; "0o755"; "/test-command"];
2130        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
2131     InitBasicFS, Always, TestOutputList (
2132       [["upload"; "test-command"; "/test-command"];
2133        ["chmod"; "0o755"; "/test-command"];
2134        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
2135     InitBasicFS, Always, TestOutputList (
2136       [["upload"; "test-command"; "/test-command"];
2137        ["chmod"; "0o755"; "/test-command"];
2138        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
2139     InitBasicFS, Always, TestOutputList (
2140       [["upload"; "test-command"; "/test-command"];
2141        ["chmod"; "0o755"; "/test-command"];
2142        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
2143     InitBasicFS, Always, TestOutputList (
2144       [["upload"; "test-command"; "/test-command"];
2145        ["chmod"; "0o755"; "/test-command"];
2146        ["command_lines"; "/test-command 7"]], []);
2147     InitBasicFS, Always, TestOutputList (
2148       [["upload"; "test-command"; "/test-command"];
2149        ["chmod"; "0o755"; "/test-command"];
2150        ["command_lines"; "/test-command 8"]], [""]);
2151     InitBasicFS, Always, TestOutputList (
2152       [["upload"; "test-command"; "/test-command"];
2153        ["chmod"; "0o755"; "/test-command"];
2154        ["command_lines"; "/test-command 9"]], ["";""]);
2155     InitBasicFS, Always, TestOutputList (
2156       [["upload"; "test-command"; "/test-command"];
2157        ["chmod"; "0o755"; "/test-command"];
2158        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
2159     InitBasicFS, Always, TestOutputList (
2160       [["upload"; "test-command"; "/test-command"];
2161        ["chmod"; "0o755"; "/test-command"];
2162        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
2163    "run a command, returning lines",
2164    "\
2165 This is the same as C<guestfs_command>, but splits the
2166 result into a list of lines.
2167
2168 See also: C<guestfs_sh_lines>");
2169
2170   ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
2171    [InitISOFS, Always, TestOutputStruct (
2172       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
2173    "get file information",
2174    "\
2175 Returns file information for the given C<path>.
2176
2177 This is the same as the C<stat(2)> system call.");
2178
2179   ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
2180    [InitISOFS, Always, TestOutputStruct (
2181       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
2182    "get file information for a symbolic link",
2183    "\
2184 Returns file information for the given C<path>.
2185
2186 This is the same as C<guestfs_stat> except that if C<path>
2187 is a symbolic link, then the link is stat-ed, not the file it
2188 refers to.
2189
2190 This is the same as the C<lstat(2)> system call.");
2191
2192   ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
2193    [InitISOFS, Always, TestOutputStruct (
2194       [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
2195    "get file system statistics",
2196    "\
2197 Returns file system statistics for any mounted file system.
2198 C<path> should be a file or directory in the mounted file system
2199 (typically it is the mount point itself, but it doesn't need to be).
2200
2201 This is the same as the C<statvfs(2)> system call.");
2202
2203   ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
2204    [], (* XXX test *)
2205    "get ext2/ext3/ext4 superblock details",
2206    "\
2207 This returns the contents of the ext2, ext3 or ext4 filesystem
2208 superblock on C<device>.
2209
2210 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
2211 manpage for more details.  The list of fields returned isn't
2212 clearly defined, and depends on both the version of C<tune2fs>
2213 that libguestfs was built against, and the filesystem itself.");
2214
2215   ("blockdev_setro", (RErr, [Device "device"]), 56, [],
2216    [InitEmpty, Always, TestOutputTrue (
2217       [["blockdev_setro"; "/dev/sda"];
2218        ["blockdev_getro"; "/dev/sda"]])],
2219    "set block device to read-only",
2220    "\
2221 Sets the block device named C<device> to read-only.
2222
2223 This uses the L<blockdev(8)> command.");
2224
2225   ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
2226    [InitEmpty, Always, TestOutputFalse (
2227       [["blockdev_setrw"; "/dev/sda"];
2228        ["blockdev_getro"; "/dev/sda"]])],
2229    "set block device to read-write",
2230    "\
2231 Sets the block device named C<device> to read-write.
2232
2233 This uses the L<blockdev(8)> command.");
2234
2235   ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
2236    [InitEmpty, Always, TestOutputTrue (
2237       [["blockdev_setro"; "/dev/sda"];
2238        ["blockdev_getro"; "/dev/sda"]])],
2239    "is block device set to read-only",
2240    "\
2241 Returns a boolean indicating if the block device is read-only
2242 (true if read-only, false if not).
2243
2244 This uses the L<blockdev(8)> command.");
2245
2246   ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
2247    [InitEmpty, Always, TestOutputInt (
2248       [["blockdev_getss"; "/dev/sda"]], 512)],
2249    "get sectorsize of block device",
2250    "\
2251 This returns the size of sectors on a block device.
2252 Usually 512, but can be larger for modern devices.
2253
2254 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
2255 for that).
2256
2257 This uses the L<blockdev(8)> command.");
2258
2259   ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
2260    [InitEmpty, Always, TestOutputInt (
2261       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
2262    "get blocksize of block device",
2263    "\
2264 This returns the block size of a device.
2265
2266 (Note this is different from both I<size in blocks> and
2267 I<filesystem block size>).
2268
2269 This uses the L<blockdev(8)> command.");
2270
2271   ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
2272    [], (* XXX test *)
2273    "set blocksize of block device",
2274    "\
2275 This sets the block size of a device.
2276
2277 (Note this is different from both I<size in blocks> and
2278 I<filesystem block size>).
2279
2280 This uses the L<blockdev(8)> command.");
2281
2282   ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
2283    [InitEmpty, Always, TestOutputInt (
2284       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
2285    "get total size of device in 512-byte sectors",
2286    "\
2287 This returns the size of the device in units of 512-byte sectors
2288 (even if the sectorsize isn't 512 bytes ... weird).
2289
2290 See also C<guestfs_blockdev_getss> for the real sector size of
2291 the device, and C<guestfs_blockdev_getsize64> for the more
2292 useful I<size in bytes>.
2293
2294 This uses the L<blockdev(8)> command.");
2295
2296   ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
2297    [InitEmpty, Always, TestOutputInt (
2298       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
2299    "get total size of device in bytes",
2300    "\
2301 This returns the size of the device in bytes.
2302
2303 See also C<guestfs_blockdev_getsz>.
2304
2305 This uses the L<blockdev(8)> command.");
2306
2307   ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
2308    [InitEmpty, Always, TestRun
2309       [["blockdev_flushbufs"; "/dev/sda"]]],
2310    "flush device buffers",
2311    "\
2312 This tells the kernel to flush internal buffers associated
2313 with C<device>.
2314
2315 This uses the L<blockdev(8)> command.");
2316
2317   ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
2318    [InitEmpty, Always, TestRun
2319       [["blockdev_rereadpt"; "/dev/sda"]]],
2320    "reread partition table",
2321    "\
2322 Reread the partition table on C<device>.
2323
2324 This uses the L<blockdev(8)> command.");
2325
2326   ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
2327    [InitBasicFS, Always, TestOutput (
2328       (* Pick a file from cwd which isn't likely to change. *)
2329       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2330        ["checksum"; "md5"; "/COPYING.LIB"]],
2331       Digest.to_hex (Digest.file "COPYING.LIB"))],
2332    "upload a file from the local machine",
2333    "\
2334 Upload local file C<filename> to C<remotefilename> on the
2335 filesystem.
2336
2337 C<filename> can also be a named pipe.
2338
2339 See also C<guestfs_download>.");
2340
2341   ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [Progress],
2342    [InitBasicFS, Always, TestOutput (
2343       (* Pick a file from cwd which isn't likely to change. *)
2344       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2345        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
2346        ["upload"; "testdownload.tmp"; "/upload"];
2347        ["checksum"; "md5"; "/upload"]],
2348       Digest.to_hex (Digest.file "COPYING.LIB"))],
2349    "download a file to the local machine",
2350    "\
2351 Download file C<remotefilename> and save it as C<filename>
2352 on the local machine.
2353
2354 C<filename> can also be a named pipe.
2355
2356 See also C<guestfs_upload>, C<guestfs_cat>.");
2357
2358   ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
2359    [InitISOFS, Always, TestOutput (
2360       [["checksum"; "crc"; "/known-3"]], "2891671662");
2361     InitISOFS, Always, TestLastFail (
2362       [["checksum"; "crc"; "/notexists"]]);
2363     InitISOFS, Always, TestOutput (
2364       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
2365     InitISOFS, Always, TestOutput (
2366       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
2367     InitISOFS, Always, TestOutput (
2368       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
2369     InitISOFS, Always, TestOutput (
2370       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
2371     InitISOFS, Always, TestOutput (
2372       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
2373     InitISOFS, Always, TestOutput (
2374       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6");
2375     (* Test for RHBZ#579608, absolute symbolic links. *)
2376     InitISOFS, Always, TestOutput (
2377       [["checksum"; "sha512"; "/abssymlink"]], "5f57d0639bc95081c53afc63a449403883818edc64da48930ad6b1a4fb49be90404686877743fbcd7c99811f3def7df7bc22635c885c6a8cf79c806b43451c1a")],
2378    "compute MD5, SHAx or CRC checksum of file",
2379    "\
2380 This call computes the MD5, SHAx or CRC checksum of the
2381 file named C<path>.
2382
2383 The type of checksum to compute is given by the C<csumtype>
2384 parameter which must have one of the following values:
2385
2386 =over 4
2387
2388 =item C<crc>
2389
2390 Compute the cyclic redundancy check (CRC) specified by POSIX
2391 for the C<cksum> command.
2392
2393 =item C<md5>
2394
2395 Compute the MD5 hash (using the C<md5sum> program).
2396
2397 =item C<sha1>
2398
2399 Compute the SHA1 hash (using the C<sha1sum> program).
2400
2401 =item C<sha224>
2402
2403 Compute the SHA224 hash (using the C<sha224sum> program).
2404
2405 =item C<sha256>
2406
2407 Compute the SHA256 hash (using the C<sha256sum> program).
2408
2409 =item C<sha384>
2410
2411 Compute the SHA384 hash (using the C<sha384sum> program).
2412
2413 =item C<sha512>
2414
2415 Compute the SHA512 hash (using the C<sha512sum> program).
2416
2417 =back
2418
2419 The checksum is returned as a printable string.
2420
2421 To get the checksum for a device, use C<guestfs_checksum_device>.
2422
2423 To get the checksums for many files, use C<guestfs_checksums_out>.");
2424
2425   ("tar_in", (RErr, [FileIn "tarfile"; Pathname "directory"]), 69, [],
2426    [InitBasicFS, Always, TestOutput (
2427       [["tar_in"; "../images/helloworld.tar"; "/"];
2428        ["cat"; "/hello"]], "hello\n")],
2429    "unpack tarfile to directory",
2430    "\
2431 This command uploads and unpacks local file C<tarfile> (an
2432 I<uncompressed> tar file) into C<directory>.
2433
2434 To upload a compressed tarball, use C<guestfs_tgz_in>
2435 or C<guestfs_txz_in>.");
2436
2437   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2438    [],
2439    "pack directory into tarfile",
2440    "\
2441 This command packs the contents of C<directory> and downloads
2442 it to local file C<tarfile>.
2443
2444 To download a compressed tarball, use C<guestfs_tgz_out>
2445 or C<guestfs_txz_out>.");
2446
2447   ("tgz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 71, [],
2448    [InitBasicFS, Always, TestOutput (
2449       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2450        ["cat"; "/hello"]], "hello\n")],
2451    "unpack compressed tarball to directory",
2452    "\
2453 This command uploads and unpacks local file C<tarball> (a
2454 I<gzip compressed> tar file) into C<directory>.
2455
2456 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2457
2458   ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2459    [],
2460    "pack directory into compressed tarball",
2461    "\
2462 This command packs the contents of C<directory> and downloads
2463 it to local file C<tarball>.
2464
2465 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2466
2467   ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2468    [InitBasicFS, Always, TestLastFail (
2469       [["umount"; "/"];
2470        ["mount_ro"; "/dev/sda1"; "/"];
2471        ["touch"; "/new"]]);
2472     InitBasicFS, Always, TestOutput (
2473       [["write"; "/new"; "data"];
2474        ["umount"; "/"];
2475        ["mount_ro"; "/dev/sda1"; "/"];
2476        ["cat"; "/new"]], "data")],
2477    "mount a guest disk, read-only",
2478    "\
2479 This is the same as the C<guestfs_mount> command, but it
2480 mounts the filesystem with the read-only (I<-o ro>) flag.");
2481
2482   ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2483    [],
2484    "mount a guest disk with mount options",
2485    "\
2486 This is the same as the C<guestfs_mount> command, but it
2487 allows you to set the mount options as for the
2488 L<mount(8)> I<-o> flag.
2489
2490 If the C<options> parameter is an empty string, then
2491 no options are passed (all options default to whatever
2492 the filesystem uses).");
2493
2494   ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2495    [],
2496    "mount a guest disk with mount options and vfstype",
2497    "\
2498 This is the same as the C<guestfs_mount> command, but it
2499 allows you to set both the mount options and the vfstype
2500 as for the L<mount(8)> I<-o> and I<-t> flags.");
2501
2502   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2503    [],
2504    "debugging and internals",
2505    "\
2506 The C<guestfs_debug> command exposes some internals of
2507 C<guestfsd> (the guestfs daemon) that runs inside the
2508 qemu subprocess.
2509
2510 There is no comprehensive help for this command.  You have
2511 to look at the file C<daemon/debug.c> in the libguestfs source
2512 to find out what you can do.");
2513
2514   ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2515    [InitEmpty, Always, TestOutputList (
2516       [["part_disk"; "/dev/sda"; "mbr"];
2517        ["pvcreate"; "/dev/sda1"];
2518        ["vgcreate"; "VG"; "/dev/sda1"];
2519        ["lvcreate"; "LV1"; "VG"; "50"];
2520        ["lvcreate"; "LV2"; "VG"; "50"];
2521        ["lvremove"; "/dev/VG/LV1"];
2522        ["lvs"]], ["/dev/VG/LV2"]);
2523     InitEmpty, Always, TestOutputList (
2524       [["part_disk"; "/dev/sda"; "mbr"];
2525        ["pvcreate"; "/dev/sda1"];
2526        ["vgcreate"; "VG"; "/dev/sda1"];
2527        ["lvcreate"; "LV1"; "VG"; "50"];
2528        ["lvcreate"; "LV2"; "VG"; "50"];
2529        ["lvremove"; "/dev/VG"];
2530        ["lvs"]], []);
2531     InitEmpty, Always, TestOutputList (
2532       [["part_disk"; "/dev/sda"; "mbr"];
2533        ["pvcreate"; "/dev/sda1"];
2534        ["vgcreate"; "VG"; "/dev/sda1"];
2535        ["lvcreate"; "LV1"; "VG"; "50"];
2536        ["lvcreate"; "LV2"; "VG"; "50"];
2537        ["lvremove"; "/dev/VG"];
2538        ["vgs"]], ["VG"])],
2539    "remove an LVM logical volume",
2540    "\
2541 Remove an LVM logical volume C<device>, where C<device> is
2542 the path to the LV, such as C</dev/VG/LV>.
2543
2544 You can also remove all LVs in a volume group by specifying
2545 the VG name, C</dev/VG>.");
2546
2547   ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2548    [InitEmpty, Always, TestOutputList (
2549       [["part_disk"; "/dev/sda"; "mbr"];
2550        ["pvcreate"; "/dev/sda1"];
2551        ["vgcreate"; "VG"; "/dev/sda1"];
2552        ["lvcreate"; "LV1"; "VG"; "50"];
2553        ["lvcreate"; "LV2"; "VG"; "50"];
2554        ["vgremove"; "VG"];
2555        ["lvs"]], []);
2556     InitEmpty, Always, TestOutputList (
2557       [["part_disk"; "/dev/sda"; "mbr"];
2558        ["pvcreate"; "/dev/sda1"];
2559        ["vgcreate"; "VG"; "/dev/sda1"];
2560        ["lvcreate"; "LV1"; "VG"; "50"];
2561        ["lvcreate"; "LV2"; "VG"; "50"];
2562        ["vgremove"; "VG"];
2563        ["vgs"]], [])],
2564    "remove an LVM volume group",
2565    "\
2566 Remove an LVM volume group C<vgname>, (for example C<VG>).
2567
2568 This also forcibly removes all logical volumes in the volume
2569 group (if any).");
2570
2571   ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2572    [InitEmpty, Always, TestOutputListOfDevices (
2573       [["part_disk"; "/dev/sda"; "mbr"];
2574        ["pvcreate"; "/dev/sda1"];
2575        ["vgcreate"; "VG"; "/dev/sda1"];
2576        ["lvcreate"; "LV1"; "VG"; "50"];
2577        ["lvcreate"; "LV2"; "VG"; "50"];
2578        ["vgremove"; "VG"];
2579        ["pvremove"; "/dev/sda1"];
2580        ["lvs"]], []);
2581     InitEmpty, Always, TestOutputListOfDevices (
2582       [["part_disk"; "/dev/sda"; "mbr"];
2583        ["pvcreate"; "/dev/sda1"];
2584        ["vgcreate"; "VG"; "/dev/sda1"];
2585        ["lvcreate"; "LV1"; "VG"; "50"];
2586        ["lvcreate"; "LV2"; "VG"; "50"];
2587        ["vgremove"; "VG"];
2588        ["pvremove"; "/dev/sda1"];
2589        ["vgs"]], []);
2590     InitEmpty, Always, TestOutputListOfDevices (
2591       [["part_disk"; "/dev/sda"; "mbr"];
2592        ["pvcreate"; "/dev/sda1"];
2593        ["vgcreate"; "VG"; "/dev/sda1"];
2594        ["lvcreate"; "LV1"; "VG"; "50"];
2595        ["lvcreate"; "LV2"; "VG"; "50"];
2596        ["vgremove"; "VG"];
2597        ["pvremove"; "/dev/sda1"];
2598        ["pvs"]], [])],
2599    "remove an LVM physical volume",
2600    "\
2601 This wipes a physical volume C<device> so that LVM will no longer
2602 recognise it.
2603
2604 The implementation uses the C<pvremove> command which refuses to
2605 wipe physical volumes that contain any volume groups, so you have
2606 to remove those first.");
2607
2608   ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2609    [InitBasicFS, Always, TestOutput (
2610       [["set_e2label"; "/dev/sda1"; "testlabel"];
2611        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2612    "set the ext2/3/4 filesystem label",
2613    "\
2614 This sets the ext2/3/4 filesystem label of the filesystem on
2615 C<device> to C<label>.  Filesystem labels are limited to
2616 16 characters.
2617
2618 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2619 to return the existing label on a filesystem.");
2620
2621   ("get_e2label", (RString "label", [Device "device"]), 81, [DeprecatedBy "vfs_label"],
2622    [],
2623    "get the ext2/3/4 filesystem label",
2624    "\
2625 This returns the ext2/3/4 filesystem label of the filesystem on
2626 C<device>.");
2627
2628   ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2629    (let uuid = uuidgen () in
2630     [InitBasicFS, Always, TestOutput (
2631        [["set_e2uuid"; "/dev/sda1"; uuid];
2632         ["get_e2uuid"; "/dev/sda1"]], uuid);
2633      InitBasicFS, Always, TestOutput (
2634        [["set_e2uuid"; "/dev/sda1"; "clear"];
2635         ["get_e2uuid"; "/dev/sda1"]], "");
2636      (* We can't predict what UUIDs will be, so just check the commands run. *)
2637      InitBasicFS, Always, TestRun (
2638        [["set_e2uuid"; "/dev/sda1"; "random"]]);
2639      InitBasicFS, Always, TestRun (
2640        [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2641    "set the ext2/3/4 filesystem UUID",
2642    "\
2643 This sets the ext2/3/4 filesystem UUID of the filesystem on
2644 C<device> to C<uuid>.  The format of the UUID and alternatives
2645 such as C<clear>, C<random> and C<time> are described in the
2646 L<tune2fs(8)> manpage.
2647
2648 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2649 to return the existing UUID of a filesystem.");
2650
2651   ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [DeprecatedBy "vfs_uuid"],
2652    (* Regression test for RHBZ#597112. *)
2653    (let uuid = uuidgen () in
2654     [InitBasicFS, Always, TestOutput (
2655        [["mke2journal"; "1024"; "/dev/sdb"];
2656         ["set_e2uuid"; "/dev/sdb"; uuid];
2657         ["get_e2uuid"; "/dev/sdb"]], uuid)]),
2658    "get the ext2/3/4 filesystem UUID",
2659    "\
2660 This returns the ext2/3/4 filesystem UUID of the filesystem on
2661 C<device>.");
2662
2663   ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [FishOutput FishOutputHexadecimal],
2664    [InitBasicFS, Always, TestOutputInt (
2665       [["umount"; "/dev/sda1"];
2666        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2667     InitBasicFS, Always, TestOutputInt (
2668       [["umount"; "/dev/sda1"];
2669        ["zero"; "/dev/sda1"];
2670        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2671    "run the filesystem checker",
2672    "\
2673 This runs the filesystem checker (fsck) on C<device> which
2674 should have filesystem type C<fstype>.
2675
2676 The returned integer is the status.  See L<fsck(8)> for the
2677 list of status codes from C<fsck>.
2678
2679 Notes:
2680
2681 =over 4
2682
2683 =item *
2684
2685 Multiple status codes can be summed together.
2686
2687 =item *
2688
2689 A non-zero return code can mean \"success\", for example if
2690 errors have been corrected on the filesystem.
2691
2692 =item *
2693
2694 Checking or repairing NTFS volumes is not supported
2695 (by linux-ntfs).
2696
2697 =back
2698
2699 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2700
2701   ("zero", (RErr, [Device "device"]), 85, [Progress],
2702    [InitBasicFS, Always, TestOutput (
2703       [["umount"; "/dev/sda1"];
2704        ["zero"; "/dev/sda1"];
2705        ["file"; "/dev/sda1"]], "data")],
2706    "write zeroes to the device",
2707    "\
2708 This command writes zeroes over the first few blocks of C<device>.
2709
2710 How many blocks are zeroed isn't specified (but it's I<not> enough
2711 to securely wipe the device).  It should be sufficient to remove
2712 any partition tables, filesystem superblocks and so on.
2713
2714 See also: C<guestfs_zero_device>, C<guestfs_scrub_device>.");
2715
2716   ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2717    (* See:
2718     * https://bugzilla.redhat.com/show_bug.cgi?id=484986
2719     * https://bugzilla.redhat.com/show_bug.cgi?id=479760
2720     *)
2721    [InitBasicFS, Always, TestOutputTrue (
2722       [["mkdir_p"; "/boot/grub"];
2723        ["write"; "/boot/grub/device.map"; "(hd0) /dev/vda"];
2724        ["grub_install"; "/"; "/dev/vda"];
2725        ["is_dir"; "/boot"]])],
2726    "install GRUB",
2727    "\
2728 This command installs GRUB (the Grand Unified Bootloader) on
2729 C<device>, with the root directory being C<root>.
2730
2731 Note: If grub-install reports the error
2732 \"No suitable drive was found in the generated device map.\"
2733 it may be that you need to create a C</boot/grub/device.map>
2734 file first that contains the mapping between grub device names
2735 and Linux device names.  It is usually sufficient to create
2736 a file containing:
2737
2738  (hd0) /dev/vda
2739
2740 replacing C</dev/vda> with the name of the installation device.");
2741
2742   ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2743    [InitBasicFS, Always, TestOutput (
2744       [["write"; "/old"; "file content"];
2745        ["cp"; "/old"; "/new"];
2746        ["cat"; "/new"]], "file content");
2747     InitBasicFS, Always, TestOutputTrue (
2748       [["write"; "/old"; "file content"];
2749        ["cp"; "/old"; "/new"];
2750        ["is_file"; "/old"]]);
2751     InitBasicFS, Always, TestOutput (
2752       [["write"; "/old"; "file content"];
2753        ["mkdir"; "/dir"];
2754        ["cp"; "/old"; "/dir/new"];
2755        ["cat"; "/dir/new"]], "file content")],
2756    "copy a file",
2757    "\
2758 This copies a file from C<src> to C<dest> where C<dest> is
2759 either a destination filename or destination directory.");
2760
2761   ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2762    [InitBasicFS, Always, TestOutput (
2763       [["mkdir"; "/olddir"];
2764        ["mkdir"; "/newdir"];
2765        ["write"; "/olddir/file"; "file content"];
2766        ["cp_a"; "/olddir"; "/newdir"];
2767        ["cat"; "/newdir/olddir/file"]], "file content")],
2768    "copy a file or directory recursively",
2769    "\
2770 This copies a file or directory from C<src> to C<dest>
2771 recursively using the C<cp -a> command.");
2772
2773   ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2774    [InitBasicFS, Always, TestOutput (
2775       [["write"; "/old"; "file content"];
2776        ["mv"; "/old"; "/new"];
2777        ["cat"; "/new"]], "file content");
2778     InitBasicFS, Always, TestOutputFalse (
2779       [["write"; "/old"; "file content"];
2780        ["mv"; "/old"; "/new"];
2781        ["is_file"; "/old"]])],
2782    "move a file",
2783    "\
2784 This moves a file from C<src> to C<dest> where C<dest> is
2785 either a destination filename or destination directory.");
2786
2787   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2788    [InitEmpty, Always, TestRun (
2789       [["drop_caches"; "3"]])],
2790    "drop kernel page cache, dentries and inodes",
2791    "\
2792 This instructs the guest kernel to drop its page cache,
2793 and/or dentries and inode caches.  The parameter C<whattodrop>
2794 tells the kernel what precisely to drop, see
2795 L<http://linux-mm.org/Drop_Caches>
2796
2797 Setting C<whattodrop> to 3 should drop everything.
2798
2799 This automatically calls L<sync(2)> before the operation,
2800 so that the maximum guest memory is freed.");
2801
2802   ("dmesg", (RString "kmsgs", []), 91, [],
2803    [InitEmpty, Always, TestRun (
2804       [["dmesg"]])],
2805    "return kernel messages",
2806    "\
2807 This returns the kernel messages (C<dmesg> output) from
2808 the guest kernel.  This is sometimes useful for extended
2809 debugging of problems.
2810
2811 Another way to get the same information is to enable
2812 verbose messages with C<guestfs_set_verbose> or by setting
2813 the environment variable C<LIBGUESTFS_DEBUG=1> before
2814 running the program.");
2815
2816   ("ping_daemon", (RErr, []), 92, [],
2817    [InitEmpty, Always, TestRun (
2818       [["ping_daemon"]])],
2819    "ping the guest daemon",
2820    "\
2821 This is a test probe into the guestfs daemon running inside
2822 the qemu subprocess.  Calling this function checks that the
2823 daemon responds to the ping message, without affecting the daemon
2824 or attached block device(s) in any other way.");
2825
2826   ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2827    [InitBasicFS, Always, TestOutputTrue (
2828       [["write"; "/file1"; "contents of a file"];
2829        ["cp"; "/file1"; "/file2"];
2830        ["equal"; "/file1"; "/file2"]]);
2831     InitBasicFS, Always, TestOutputFalse (
2832       [["write"; "/file1"; "contents of a file"];
2833        ["write"; "/file2"; "contents of another file"];
2834        ["equal"; "/file1"; "/file2"]]);
2835     InitBasicFS, Always, TestLastFail (
2836       [["equal"; "/file1"; "/file2"]])],
2837    "test if two files have equal contents",
2838    "\
2839 This compares the two files C<file1> and C<file2> and returns
2840 true if their content is exactly equal, or false otherwise.
2841
2842 The external L<cmp(1)> program is used for the comparison.");
2843
2844   ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2845    [InitISOFS, Always, TestOutputList (
2846       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2847     InitISOFS, Always, TestOutputList (
2848       [["strings"; "/empty"]], []);
2849     (* Test for RHBZ#579608, absolute symbolic links. *)
2850     InitISOFS, Always, TestRun (
2851       [["strings"; "/abssymlink"]])],
2852    "print the printable strings in a file",
2853    "\
2854 This runs the L<strings(1)> command on a file and returns
2855 the list of printable strings found.");
2856
2857   ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2858    [InitISOFS, Always, TestOutputList (
2859       [["strings_e"; "b"; "/known-5"]], []);
2860     InitBasicFS, Always, TestOutputList (
2861       [["write"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"];
2862        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2863    "print the printable strings in a file",
2864    "\
2865 This is like the C<guestfs_strings> command, but allows you to
2866 specify the encoding of strings that are looked for in
2867 the source file C<path>.
2868
2869 Allowed encodings are:
2870
2871 =over 4
2872
2873 =item s
2874
2875 Single 7-bit-byte characters like ASCII and the ASCII-compatible
2876 parts of ISO-8859-X (this is what C<guestfs_strings> uses).
2877
2878 =item S
2879
2880 Single 8-bit-byte characters.
2881
2882 =item b
2883
2884 16-bit big endian strings such as those encoded in
2885 UTF-16BE or UCS-2BE.
2886
2887 =item l (lower case letter L)
2888
2889 16-bit little endian such as UTF-16LE and UCS-2LE.
2890 This is useful for examining binaries in Windows guests.
2891
2892 =item B
2893
2894 32-bit big endian such as UCS-4BE.
2895
2896 =item L
2897
2898 32-bit little endian such as UCS-4LE.
2899
2900 =back
2901
2902 The returned strings are transcoded to UTF-8.");
2903
2904   ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2905    [InitISOFS, Always, TestOutput (
2906       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2907     (* Test for RHBZ#501888c2 regression which caused large hexdump
2908      * commands to segfault.
2909      *)
2910     InitISOFS, Always, TestRun (
2911       [["hexdump"; "/100krandom"]]);
2912     (* Test for RHBZ#579608, absolute symbolic links. *)
2913     InitISOFS, Always, TestRun (
2914       [["hexdump"; "/abssymlink"]])],
2915    "dump a file in hexadecimal",
2916    "\
2917 This runs C<hexdump -C> on the given C<path>.  The result is
2918 the human-readable, canonical hex dump of the file.");
2919
2920   ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2921    [InitNone, Always, TestOutput (
2922       [["part_disk"; "/dev/sda"; "mbr"];
2923        ["mkfs"; "ext3"; "/dev/sda1"];
2924        ["mount_options"; ""; "/dev/sda1"; "/"];
2925        ["write"; "/new"; "test file"];
2926        ["umount"; "/dev/sda1"];
2927        ["zerofree"; "/dev/sda1"];
2928        ["mount_options"; ""; "/dev/sda1"; "/"];
2929        ["cat"; "/new"]], "test file")],
2930    "zero unused inodes and disk blocks on ext2/3 filesystem",
2931    "\
2932 This runs the I<zerofree> program on C<device>.  This program
2933 claims to zero unused inodes and disk blocks on an ext2/3
2934 filesystem, thus making it possible to compress the filesystem
2935 more effectively.
2936
2937 You should B<not> run this program if the filesystem is
2938 mounted.
2939
2940 It is possible that using this program can damage the filesystem
2941 or data on the filesystem.");
2942
2943   ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2944    [],
2945    "resize an LVM physical volume",
2946    "\
2947 This resizes (expands or shrinks) an existing LVM physical
2948 volume to match the new size of the underlying device.");
2949
2950   ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2951                        Int "cyls"; Int "heads"; Int "sectors";
2952                        String "line"]), 99, [DangerWillRobinson],
2953    [],
2954    "modify a single partition on a block device",
2955    "\
2956 This runs L<sfdisk(8)> option to modify just the single
2957 partition C<n> (note: C<n> counts from 1).
2958
2959 For other parameters, see C<guestfs_sfdisk>.  You should usually
2960 pass C<0> for the cyls/heads/sectors parameters.
2961
2962 See also: C<guestfs_part_add>");
2963
2964   ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2965    [],
2966    "display the partition table",
2967    "\
2968 This displays the partition table on C<device>, in the
2969 human-readable output of the L<sfdisk(8)> command.  It is
2970 not intended to be parsed.
2971
2972 See also: C<guestfs_part_list>");
2973
2974   ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2975    [],
2976    "display the kernel geometry",
2977    "\
2978 This displays the kernel's idea of the geometry of C<device>.
2979
2980 The result is in human-readable format, and not designed to
2981 be parsed.");
2982
2983   ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2984    [],
2985    "display the disk geometry from the partition table",
2986    "\
2987 This displays the disk geometry of C<device> read from the
2988 partition table.  Especially in the case where the underlying
2989 block device has been resized, this can be different from the
2990 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2991
2992 The result is in human-readable format, and not designed to
2993 be parsed.");
2994
2995   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2996    [],
2997    "activate or deactivate all volume groups",
2998    "\
2999 This command activates or (if C<activate> is false) deactivates
3000 all logical volumes in all volume groups.
3001 If activated, then they are made known to the
3002 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3003 then those devices disappear.
3004
3005 This command is the same as running C<vgchange -a y|n>");
3006
3007   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
3008    [],
3009    "activate or deactivate some volume groups",
3010    "\
3011 This command activates or (if C<activate> is false) deactivates
3012 all logical volumes in the listed volume groups C<volgroups>.
3013 If activated, then they are made known to the
3014 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3015 then those devices disappear.
3016
3017 This command is the same as running C<vgchange -a y|n volgroups...>
3018
3019 Note that if C<volgroups> is an empty list then B<all> volume groups
3020 are activated or deactivated.");
3021
3022   ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
3023    [InitNone, Always, TestOutput (
3024       [["part_disk"; "/dev/sda"; "mbr"];
3025        ["pvcreate"; "/dev/sda1"];
3026        ["vgcreate"; "VG"; "/dev/sda1"];
3027        ["lvcreate"; "LV"; "VG"; "10"];
3028        ["mkfs"; "ext2"; "/dev/VG/LV"];
3029        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3030        ["write"; "/new"; "test content"];
3031        ["umount"; "/"];
3032        ["lvresize"; "/dev/VG/LV"; "20"];
3033        ["e2fsck_f"; "/dev/VG/LV"];
3034        ["resize2fs"; "/dev/VG/LV"];
3035        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3036        ["cat"; "/new"]], "test content");
3037     InitNone, Always, TestRun (
3038       (* Make an LV smaller to test RHBZ#587484. *)
3039       [["part_disk"; "/dev/sda"; "mbr"];
3040        ["pvcreate"; "/dev/sda1"];
3041        ["vgcreate"; "VG"; "/dev/sda1"];
3042        ["lvcreate"; "LV"; "VG"; "20"];
3043        ["lvresize"; "/dev/VG/LV"; "10"]])],
3044    "resize an LVM logical volume",
3045    "\
3046 This resizes (expands or shrinks) an existing LVM logical
3047 volume to C<mbytes>.  When reducing, data in the reduced part
3048 is lost.");
3049
3050   ("resize2fs", (RErr, [Device "device"]), 106, [],
3051    [], (* lvresize tests this *)
3052    "resize an ext2, ext3 or ext4 filesystem",
3053    "\
3054 This resizes an ext2, ext3 or ext4 filesystem to match the size of
3055 the underlying device.
3056
3057 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
3058 on the C<device> before calling this command.  For unknown reasons
3059 C<resize2fs> sometimes gives an error about this and sometimes not.
3060 In any case, it is always safe to call C<guestfs_e2fsck_f> before
3061 calling this function.");
3062
3063   ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
3064    [InitBasicFS, Always, TestOutputList (
3065       [["find"; "/"]], ["lost+found"]);
3066     InitBasicFS, Always, TestOutputList (
3067       [["touch"; "/a"];
3068        ["mkdir"; "/b"];
3069        ["touch"; "/b/c"];
3070        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
3071     InitBasicFS, Always, TestOutputList (
3072       [["mkdir_p"; "/a/b/c"];
3073        ["touch"; "/a/b/c/d"];
3074        ["find"; "/a/b/"]], ["c"; "c/d"])],
3075    "find all files and directories",
3076    "\
3077 This command lists out all files and directories, recursively,
3078 starting at C<directory>.  It is essentially equivalent to
3079 running the shell command C<find directory -print> but some
3080 post-processing happens on the output, described below.
3081
3082 This returns a list of strings I<without any prefix>.  Thus
3083 if the directory structure was:
3084
3085  /tmp/a
3086  /tmp/b
3087  /tmp/c/d
3088
3089 then the returned list from C<guestfs_find> C</tmp> would be
3090 4 elements:
3091
3092  a
3093  b
3094  c
3095  c/d
3096
3097 If C<directory> is not a directory, then this command returns
3098 an error.
3099
3100 The returned list is sorted.
3101
3102 See also C<guestfs_find0>.");
3103
3104   ("e2fsck_f", (RErr, [Device "device"]), 108, [],
3105    [], (* lvresize tests this *)
3106    "check an ext2/ext3 filesystem",
3107    "\
3108 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
3109 filesystem checker on C<device>, noninteractively (C<-p>),
3110 even if the filesystem appears to be clean (C<-f>).
3111
3112 This command is only needed because of C<guestfs_resize2fs>
3113 (q.v.).  Normally you should use C<guestfs_fsck>.");
3114
3115   ("sleep", (RErr, [Int "secs"]), 109, [],
3116    [InitNone, Always, TestRun (
3117       [["sleep"; "1"]])],
3118    "sleep for some seconds",
3119    "\
3120 Sleep for C<secs> seconds.");
3121
3122   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
3123    [InitNone, Always, TestOutputInt (
3124       [["part_disk"; "/dev/sda"; "mbr"];
3125        ["mkfs"; "ntfs"; "/dev/sda1"];
3126        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
3127     InitNone, Always, TestOutputInt (
3128       [["part_disk"; "/dev/sda"; "mbr"];
3129        ["mkfs"; "ext2"; "/dev/sda1"];
3130        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
3131    "probe NTFS volume",
3132    "\
3133 This command runs the L<ntfs-3g.probe(8)> command which probes
3134 an NTFS C<device> for mountability.  (Not all NTFS volumes can
3135 be mounted read-write, and some cannot be mounted at all).
3136
3137 C<rw> is a boolean flag.  Set it to true if you want to test
3138 if the volume can be mounted read-write.  Set it to false if
3139 you want to test if the volume can be mounted read-only.
3140
3141 The return value is an integer which C<0> if the operation
3142 would succeed, or some non-zero value documented in the
3143 L<ntfs-3g.probe(8)> manual page.");
3144
3145   ("sh", (RString "output", [String "command"]), 111, [],
3146    [], (* XXX needs tests *)
3147    "run a command via the shell",
3148    "\
3149 This call runs a command from the guest filesystem via the
3150 guest's C</bin/sh>.
3151
3152 This is like C<guestfs_command>, but passes the command to:
3153
3154  /bin/sh -c \"command\"
3155
3156 Depending on the guest's shell, this usually results in
3157 wildcards being expanded, shell expressions being interpolated
3158 and so on.
3159
3160 All the provisos about C<guestfs_command> apply to this call.");
3161
3162   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
3163    [], (* XXX needs tests *)
3164    "run a command via the shell returning lines",
3165    "\
3166 This is the same as C<guestfs_sh>, but splits the result
3167 into a list of lines.
3168
3169 See also: C<guestfs_command_lines>");
3170
3171   ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
3172    (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
3173     * code in stubs.c, since all valid glob patterns must start with "/".
3174     * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
3175     *)
3176    [InitBasicFS, Always, TestOutputList (
3177       [["mkdir_p"; "/a/b/c"];
3178        ["touch"; "/a/b/c/d"];
3179        ["touch"; "/a/b/c/e"];
3180        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3181     InitBasicFS, Always, TestOutputList (
3182       [["mkdir_p"; "/a/b/c"];
3183        ["touch"; "/a/b/c/d"];
3184        ["touch"; "/a/b/c/e"];
3185        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3186     InitBasicFS, Always, TestOutputList (
3187       [["mkdir_p"; "/a/b/c"];
3188        ["touch"; "/a/b/c/d"];
3189        ["touch"; "/a/b/c/e"];
3190        ["glob_expand"; "/a/*/x/*"]], [])],
3191    "expand a wildcard path",
3192    "\
3193 This command searches for all the pathnames matching
3194 C<pattern> according to the wildcard expansion rules
3195 used by the shell.
3196
3197 If no paths match, then this returns an empty list
3198 (note: not an error).
3199
3200 It is just a wrapper around the C L<glob(3)> function
3201 with flags C<GLOB_MARK|GLOB_BRACE>.
3202 See that manual page for more details.");
3203
3204   ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
3205    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
3206       [["scrub_device"; "/dev/sdc"]])],
3207    "scrub (securely wipe) a device",
3208    "\
3209 This command writes patterns over C<device> to make data retrieval
3210 more difficult.
3211
3212 It is an interface to the L<scrub(1)> program.  See that
3213 manual page for more details.");
3214
3215   ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
3216    [InitBasicFS, Always, TestRun (
3217       [["write"; "/file"; "content"];
3218        ["scrub_file"; "/file"]])],
3219    "scrub (securely wipe) a file",
3220    "\
3221 This command writes patterns over a file to make data retrieval
3222 more difficult.
3223
3224 The file is I<removed> after scrubbing.
3225
3226 It is an interface to the L<scrub(1)> program.  See that
3227 manual page for more details.");
3228
3229   ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
3230    [], (* XXX needs testing *)
3231    "scrub (securely wipe) free space",
3232    "\
3233 This command creates the directory C<dir> and then fills it
3234 with files until the filesystem is full, and scrubs the files
3235 as for C<guestfs_scrub_file>, and deletes them.
3236 The intention is to scrub any free space on the partition
3237 containing C<dir>.
3238
3239 It is an interface to the L<scrub(1)> program.  See that
3240 manual page for more details.");
3241
3242   ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
3243    [InitBasicFS, Always, TestRun (
3244       [["mkdir"; "/tmp"];
3245        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
3246    "create a temporary directory",
3247    "\
3248 This command creates a temporary directory.  The
3249 C<template> parameter should be a full pathname for the
3250 temporary directory name with the final six characters being
3251 \"XXXXXX\".
3252
3253 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
3254 the second one being suitable for Windows filesystems.
3255
3256 The name of the temporary directory that was created
3257 is returned.
3258
3259 The temporary directory is created with mode 0700
3260 and is owned by root.
3261
3262 The caller is responsible for deleting the temporary
3263 directory and its contents after use.
3264
3265 See also: L<mkdtemp(3)>");
3266
3267   ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
3268    [InitISOFS, Always, TestOutputInt (
3269       [["wc_l"; "/10klines"]], 10000);
3270     (* Test for RHBZ#579608, absolute symbolic links. *)
3271     InitISOFS, Always, TestOutputInt (
3272       [["wc_l"; "/abssymlink"]], 10000)],
3273    "count lines in a file",
3274    "\
3275 This command counts the lines in a file, using the
3276 C<wc -l> external command.");
3277
3278   ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
3279    [InitISOFS, Always, TestOutputInt (
3280       [["wc_w"; "/10klines"]], 10000)],
3281    "count words in a file",
3282    "\
3283 This command counts the words in a file, using the
3284 C<wc -w> external command.");
3285
3286   ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
3287    [InitISOFS, Always, TestOutputInt (
3288       [["wc_c"; "/100kallspaces"]], 102400)],
3289    "count characters in a file",
3290    "\
3291 This command counts the characters in a file, using the
3292 C<wc -c> external command.");
3293
3294   ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
3295    [InitISOFS, Always, TestOutputList (
3296       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"]);
3297     (* Test for RHBZ#579608, absolute symbolic links. *)
3298     InitISOFS, Always, TestOutputList (
3299       [["head"; "/abssymlink"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
3300    "return first 10 lines of a file",
3301    "\
3302 This command returns up to the first 10 lines of a file as
3303 a list of strings.");
3304
3305   ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
3306    [InitISOFS, Always, TestOutputList (
3307       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3308     InitISOFS, Always, TestOutputList (
3309       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3310     InitISOFS, Always, TestOutputList (
3311       [["head_n"; "0"; "/10klines"]], [])],
3312    "return first N lines of a file",
3313    "\
3314 If the parameter C<nrlines> is a positive number, this returns the first
3315 C<nrlines> lines of the file C<path>.
3316
3317 If the parameter C<nrlines> is a negative number, this returns lines
3318 from the file C<path>, excluding the last C<nrlines> lines.
3319
3320 If the parameter C<nrlines> is zero, this returns an empty list.");
3321
3322   ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
3323    [InitISOFS, Always, TestOutputList (
3324       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
3325    "return last 10 lines of a file",
3326    "\
3327 This command returns up to the last 10 lines of a file as
3328 a list of strings.");
3329
3330   ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
3331    [InitISOFS, Always, TestOutputList (
3332       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3333     InitISOFS, Always, TestOutputList (
3334       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3335     InitISOFS, Always, TestOutputList (
3336       [["tail_n"; "0"; "/10klines"]], [])],
3337    "return last N lines of a file",
3338    "\
3339 If the parameter C<nrlines> is a positive number, this returns the last
3340 C<nrlines> lines of the file C<path>.
3341
3342 If the parameter C<nrlines> is a negative number, this returns lines
3343 from the file C<path>, starting with the C<-nrlines>th line.
3344
3345 If the parameter C<nrlines> is zero, this returns an empty list.");
3346
3347   ("df", (RString "output", []), 125, [],
3348    [], (* XXX Tricky to test because it depends on the exact format
3349         * of the 'df' command and other imponderables.
3350         *)
3351    "report file system disk space usage",
3352    "\
3353 This command runs the C<df> command to report disk space used.
3354
3355 This command is mostly useful for interactive sessions.  It
3356 is I<not> intended that you try to parse the output string.
3357 Use C<statvfs> from programs.");
3358
3359   ("df_h", (RString "output", []), 126, [],
3360    [], (* XXX Tricky to test because it depends on the exact format
3361         * of the 'df' command and other imponderables.
3362         *)
3363    "report file system disk space usage (human readable)",
3364    "\
3365 This command runs the C<df -h> command to report disk space used
3366 in human-readable format.
3367
3368 This command is mostly useful for interactive sessions.  It
3369 is I<not> intended that you try to parse the output string.
3370 Use C<statvfs> from programs.");
3371
3372   ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
3373    [InitISOFS, Always, TestOutputInt (
3374       [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
3375    "estimate file space usage",
3376    "\
3377 This command runs the C<du -s> command to estimate file space
3378 usage for C<path>.
3379
3380 C<path> can be a file or a directory.  If C<path> is a directory
3381 then the estimate includes the contents of the directory and all
3382 subdirectories (recursively).
3383
3384 The result is the estimated size in I<kilobytes>
3385 (ie. units of 1024 bytes).");
3386
3387   ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
3388    [InitISOFS, Always, TestOutputList (
3389       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
3390    "list files in an initrd",
3391    "\
3392 This command lists out files contained in an initrd.
3393
3394 The files are listed without any initial C</> character.  The
3395 files are listed in the order they appear (not necessarily
3396 alphabetical).  Directory names are listed as separate items.
3397
3398 Old Linux kernels (2.4 and earlier) used a compressed ext2
3399 filesystem as initrd.  We I<only> support the newer initramfs
3400 format (compressed cpio files).");
3401
3402   ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
3403    [],
3404    "mount a file using the loop device",
3405    "\
3406 This command lets you mount C<file> (a filesystem image
3407 in a file) on a mount point.  It is entirely equivalent to
3408 the command C<mount -o loop file mountpoint>.");
3409
3410   ("mkswap", (RErr, [Device "device"]), 130, [],
3411    [InitEmpty, Always, TestRun (
3412       [["part_disk"; "/dev/sda"; "mbr"];
3413        ["mkswap"; "/dev/sda1"]])],
3414    "create a swap partition",
3415    "\
3416 Create a swap partition on C<device>.");
3417
3418   ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
3419    [InitEmpty, Always, TestRun (
3420       [["part_disk"; "/dev/sda"; "mbr"];
3421        ["mkswap_L"; "hello"; "/dev/sda1"]])],
3422    "create a swap partition with a label",
3423    "\
3424 Create a swap partition on C<device> with label C<label>.
3425
3426 Note that you cannot attach a swap label to a block device
3427 (eg. C</dev/sda>), just to a partition.  This appears to be
3428 a limitation of the kernel or swap tools.");
3429
3430   ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
3431    (let uuid = uuidgen () in
3432     [InitEmpty, Always, TestRun (
3433        [["part_disk"; "/dev/sda"; "mbr"];
3434         ["mkswap_U"; uuid; "/dev/sda1"]])]),
3435    "create a swap partition with an explicit UUID",
3436    "\
3437 Create a swap partition on C<device> with UUID C<uuid>.");
3438
3439   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
3440    [InitBasicFS, Always, TestOutputStruct (
3441       [["mknod"; "0o10777"; "0"; "0"; "/node"];
3442        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
3443        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
3444     InitBasicFS, Always, TestOutputStruct (
3445       [["mknod"; "0o60777"; "66"; "99"; "/node"];
3446        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3447    "make block, character or FIFO devices",
3448    "\
3449 This call creates block or character special devices, or
3450 named pipes (FIFOs).
3451
3452 The C<mode> parameter should be the mode, using the standard
3453 constants.  C<devmajor> and C<devminor> are the
3454 device major and minor numbers, only used when creating block
3455 and character special devices.
3456
3457 Note that, just like L<mknod(2)>, the mode must be bitwise
3458 OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
3459 just creates a regular file).  These constants are
3460 available in the standard Linux header files, or you can use
3461 C<guestfs_mknod_b>, C<guestfs_mknod_c> or C<guestfs_mkfifo>
3462 which are wrappers around this command which bitwise OR
3463 in the appropriate constant for you.
3464
3465 The mode actually set is affected by the umask.");
3466
3467   ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
3468    [InitBasicFS, Always, TestOutputStruct (
3469       [["mkfifo"; "0o777"; "/node"];
3470        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
3471    "make FIFO (named pipe)",
3472    "\
3473 This call creates a FIFO (named pipe) called C<path> with
3474 mode C<mode>.  It is just a convenient wrapper around
3475 C<guestfs_mknod>.
3476
3477 The mode actually set is affected by the umask.");
3478
3479   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
3480    [InitBasicFS, Always, TestOutputStruct (
3481       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
3482        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3483    "make block device node",
3484    "\
3485 This call creates a block device node called C<path> with
3486 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3487 It is just a convenient wrapper around C<guestfs_mknod>.
3488
3489 The mode actually set is affected by the umask.");
3490
3491   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
3492    [InitBasicFS, Always, TestOutputStruct (
3493       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
3494        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
3495    "make char device node",
3496    "\
3497 This call creates a char device node called C<path> with
3498 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3499 It is just a convenient wrapper around C<guestfs_mknod>.
3500
3501 The mode actually set is affected by the umask.");
3502
3503   ("umask", (RInt "oldmask", [Int "mask"]), 137, [FishOutput FishOutputOctal],
3504    [InitEmpty, Always, TestOutputInt (
3505       [["umask"; "0o22"]], 0o22)],
3506    "set file mode creation mask (umask)",
3507    "\
3508 This function sets the mask used for creating new files and
3509 device nodes to C<mask & 0777>.
3510
3511 Typical umask values would be C<022> which creates new files
3512 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3513 C<002> which creates new files with permissions like
3514 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3515
3516 The default umask is C<022>.  This is important because it
3517 means that directories and device nodes will be created with
3518 C<0644> or C<0755> mode even if you specify C<0777>.
3519
3520 See also C<guestfs_get_umask>,
3521 L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3522
3523 This call returns the previous umask.");
3524
3525   ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3526    [],
3527    "read directories entries",
3528    "\
3529 This returns the list of directory entries in directory C<dir>.
3530
3531 All entries in the directory are returned, including C<.> and
3532 C<..>.  The entries are I<not> sorted, but returned in the same
3533 order as the underlying filesystem.
3534
3535 Also this call returns basic file type information about each
3536 file.  The C<ftyp> field will contain one of the following characters:
3537
3538 =over 4
3539
3540 =item 'b'
3541
3542 Block special
3543
3544 =item 'c'
3545
3546 Char special
3547
3548 =item 'd'
3549
3550 Directory
3551
3552 =item 'f'
3553
3554 FIFO (named pipe)
3555
3556 =item 'l'
3557
3558 Symbolic link
3559
3560 =item 'r'
3561
3562 Regular file
3563
3564 =item 's'
3565
3566 Socket
3567
3568 =item 'u'
3569
3570 Unknown file type
3571
3572 =item '?'
3573
3574 The L<readdir(3)> call returned a C<d_type> field with an
3575 unexpected value
3576
3577 =back
3578
3579 This function is primarily intended for use by programs.  To
3580 get a simple list of names, use C<guestfs_ls>.  To get a printable
3581 directory for human consumption, use C<guestfs_ll>.");
3582
3583   ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3584    [],
3585    "create partitions on a block device",
3586    "\
3587 This is a simplified interface to the C<guestfs_sfdisk>
3588 command, where partition sizes are specified in megabytes
3589 only (rounded to the nearest cylinder) and you don't need
3590 to specify the cyls, heads and sectors parameters which
3591 were rarely if ever used anyway.
3592
3593 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3594 and C<guestfs_part_disk>");
3595
3596   ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3597    [],
3598    "determine file type inside a compressed file",
3599    "\
3600 This command runs C<file> after first decompressing C<path>
3601 using C<method>.
3602
3603 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3604
3605 Since 1.0.63, use C<guestfs_file> instead which can now
3606 process compressed files.");
3607
3608   ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3609    [],
3610    "list extended attributes of a file or directory",
3611    "\
3612 This call lists the extended attributes of the file or directory
3613 C<path>.
3614
3615 At the system call level, this is a combination of the
3616 L<listxattr(2)> and L<getxattr(2)> calls.
3617
3618 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3619
3620   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3621    [],
3622    "list extended attributes of a file or directory",
3623    "\
3624 This is the same as C<guestfs_getxattrs>, but if C<path>
3625 is a symbolic link, then it returns the extended attributes
3626 of the link itself.");
3627
3628   ("setxattr", (RErr, [String "xattr";
3629                        String "val"; Int "vallen"; (* will be BufferIn *)
3630                        Pathname "path"]), 143, [Optional "linuxxattrs"],
3631    [],
3632    "set extended attribute of a file or directory",
3633    "\
3634 This call sets the extended attribute named C<xattr>
3635 of the file C<path> to the value C<val> (of length C<vallen>).
3636 The value is arbitrary 8 bit data.
3637
3638 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3639
3640   ("lsetxattr", (RErr, [String "xattr";
3641                         String "val"; Int "vallen"; (* will be BufferIn *)
3642                         Pathname "path"]), 144, [Optional "linuxxattrs"],
3643    [],
3644    "set extended attribute of a file or directory",
3645    "\
3646 This is the same as C<guestfs_setxattr>, but if C<path>
3647 is a symbolic link, then it sets an extended attribute
3648 of the link itself.");
3649
3650   ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3651    [],
3652    "remove extended attribute of a file or directory",
3653    "\
3654 This call removes the extended attribute named C<xattr>
3655 of the file C<path>.
3656
3657 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3658
3659   ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3660    [],
3661    "remove extended attribute of a file or directory",
3662    "\
3663 This is the same as C<guestfs_removexattr>, but if C<path>
3664 is a symbolic link, then it removes an extended attribute
3665 of the link itself.");
3666
3667   ("mountpoints", (RHashtable "mps", []), 147, [],
3668    [],
3669    "show mountpoints",
3670    "\
3671 This call is similar to C<guestfs_mounts>.  That call returns
3672 a list of devices.  This one returns a hash table (map) of
3673 device name to directory where the device is mounted.");
3674
3675   ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3676    (* This is a special case: while you would expect a parameter
3677     * of type "Pathname", that doesn't work, because it implies
3678     * NEED_ROOT in the generated calling code in stubs.c, and
3679     * this function cannot use NEED_ROOT.
3680     *)
3681    [],
3682    "create a mountpoint",
3683    "\
3684 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3685 specialized calls that can be used to create extra mountpoints
3686 before mounting the first filesystem.
3687
3688 These calls are I<only> necessary in some very limited circumstances,
3689 mainly the case where you want to mount a mix of unrelated and/or
3690 read-only filesystems together.
3691
3692 For example, live CDs often contain a \"Russian doll\" nest of
3693 filesystems, an ISO outer layer, with a squashfs image inside, with
3694 an ext2/3 image inside that.  You can unpack this as follows
3695 in guestfish:
3696
3697  add-ro Fedora-11-i686-Live.iso
3698  run
3699  mkmountpoint /cd
3700  mkmountpoint /squash
3701  mkmountpoint /ext3
3702  mount /dev/sda /cd
3703  mount-loop /cd/LiveOS/squashfs.img /squash
3704  mount-loop /squash/LiveOS/ext3fs.img /ext3
3705
3706 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3707
3708   ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3709    [],
3710    "remove a mountpoint",
3711    "\
3712 This calls removes a mountpoint that was previously created
3713 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3714 for full details.");
3715
3716   ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3717    [InitISOFS, Always, TestOutputBuffer (
3718       [["read_file"; "/known-4"]], "abc\ndef\nghi");
3719     (* Test various near large, large and too large files (RHBZ#589039). *)
3720     InitBasicFS, Always, TestLastFail (
3721       [["touch"; "/a"];
3722        ["truncate_size"; "/a"; "4194303"]; (* GUESTFS_MESSAGE_MAX - 1 *)
3723        ["read_file"; "/a"]]);
3724     InitBasicFS, Always, TestLastFail (
3725       [["touch"; "/a"];
3726        ["truncate_size"; "/a"; "4194304"]; (* GUESTFS_MESSAGE_MAX *)
3727        ["read_file"; "/a"]]);
3728     InitBasicFS, Always, TestLastFail (
3729       [["touch"; "/a"];
3730        ["truncate_size"; "/a"; "41943040"]; (* GUESTFS_MESSAGE_MAX * 10 *)
3731        ["read_file"; "/a"]])],
3732    "read a file",
3733    "\
3734 This calls returns the contents of the file C<path> as a
3735 buffer.
3736
3737 Unlike C<guestfs_cat>, this function can correctly
3738 handle files that contain embedded ASCII NUL characters.
3739 However unlike C<guestfs_download>, this function is limited
3740 in the total size of file that can be handled.");
3741
3742   ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3743    [InitISOFS, Always, TestOutputList (
3744       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3745     InitISOFS, Always, TestOutputList (
3746       [["grep"; "nomatch"; "/test-grep.txt"]], []);
3747     (* Test for RHBZ#579608, absolute symbolic links. *)
3748     InitISOFS, Always, TestOutputList (
3749       [["grep"; "nomatch"; "/abssymlink"]], [])],
3750    "return lines matching a pattern",
3751    "\
3752 This calls the external C<grep> program and returns the
3753 matching lines.");
3754
3755   ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3756    [InitISOFS, Always, TestOutputList (
3757       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3758    "return lines matching a pattern",
3759    "\
3760 This calls the external C<egrep> program and returns the
3761 matching lines.");
3762
3763   ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3764    [InitISOFS, Always, TestOutputList (
3765       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3766    "return lines matching a pattern",
3767    "\
3768 This calls the external C<fgrep> program and returns the
3769 matching lines.");
3770
3771   ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3772    [InitISOFS, Always, TestOutputList (
3773       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3774    "return lines matching a pattern",
3775    "\
3776 This calls the external C<grep -i> program and returns the
3777 matching lines.");
3778
3779   ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3780    [InitISOFS, Always, TestOutputList (
3781       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3782    "return lines matching a pattern",
3783    "\
3784 This calls the external C<egrep -i> program and returns the
3785 matching lines.");
3786
3787   ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3788    [InitISOFS, Always, TestOutputList (
3789       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3790    "return lines matching a pattern",
3791    "\
3792 This calls the external C<fgrep -i> program and returns the
3793 matching lines.");
3794
3795   ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3796    [InitISOFS, Always, TestOutputList (
3797       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3798    "return lines matching a pattern",
3799    "\
3800 This calls the external C<zgrep> program and returns the
3801 matching lines.");
3802
3803   ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3804    [InitISOFS, Always, TestOutputList (
3805       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3806    "return lines matching a pattern",
3807    "\
3808 This calls the external C<zegrep> program and returns the
3809 matching lines.");
3810
3811   ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3812    [InitISOFS, Always, TestOutputList (
3813       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3814    "return lines matching a pattern",
3815    "\
3816 This calls the external C<zfgrep> program and returns the
3817 matching lines.");
3818
3819   ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3820    [InitISOFS, Always, TestOutputList (
3821       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3822    "return lines matching a pattern",
3823    "\
3824 This calls the external C<zgrep -i> program and returns the
3825 matching lines.");
3826
3827   ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3828    [InitISOFS, Always, TestOutputList (
3829       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3830    "return lines matching a pattern",
3831    "\
3832 This calls the external C<zegrep -i> program and returns the
3833 matching lines.");
3834
3835   ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3836    [InitISOFS, Always, TestOutputList (
3837       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3838    "return lines matching a pattern",
3839    "\
3840 This calls the external C<zfgrep -i> program and returns the
3841 matching lines.");
3842
3843   ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3844    [InitISOFS, Always, TestOutput (
3845       [["realpath"; "/../directory"]], "/directory")],
3846    "canonicalized absolute pathname",
3847    "\
3848 Return the canonicalized absolute pathname of C<path>.  The
3849 returned path has no C<.>, C<..> or symbolic link path elements.");
3850
3851   ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3852    [InitBasicFS, Always, TestOutputStruct (
3853       [["touch"; "/a"];
3854        ["ln"; "/a"; "/b"];
3855        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3856    "create a hard link",
3857    "\
3858 This command creates a hard link using the C<ln> command.");
3859
3860   ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3861    [InitBasicFS, Always, TestOutputStruct (
3862       [["touch"; "/a"];
3863        ["touch"; "/b"];
3864        ["ln_f"; "/a"; "/b"];
3865        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3866    "create a hard link",
3867    "\
3868 This command creates a hard link using the C<ln -f> command.
3869 The C<-f> option removes the link (C<linkname>) if it exists already.");
3870
3871   ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3872    [InitBasicFS, Always, TestOutputStruct (
3873       [["touch"; "/a"];
3874        ["ln_s"; "a"; "/b"];
3875        ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3876    "create a symbolic link",
3877    "\
3878 This command creates a symbolic link using the C<ln -s> command.");
3879
3880   ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3881    [InitBasicFS, Always, TestOutput (
3882       [["mkdir_p"; "/a/b"];
3883        ["touch"; "/a/b/c"];
3884        ["ln_sf"; "../d"; "/a/b/c"];
3885        ["readlink"; "/a/b/c"]], "../d")],
3886    "create a symbolic link",
3887    "\
3888 This command creates a symbolic link using the C<ln -sf> command,
3889 The C<-f> option removes the link (C<linkname>) if it exists already.");
3890
3891   ("readlink", (RString "link", [Pathname "path"]), 168, [],
3892    [] (* XXX tested above *),
3893    "read the target of a symbolic link",
3894    "\
3895 This command reads the target of a symbolic link.");
3896
3897   ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [DeprecatedBy "fallocate64"],
3898    [InitBasicFS, Always, TestOutputStruct (
3899       [["fallocate"; "/a"; "1000000"];
3900        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3901    "preallocate a file in the guest filesystem",
3902    "\
3903 This command preallocates a file (containing zero bytes) named
3904 C<path> of size C<len> bytes.  If the file exists already, it
3905 is overwritten.
3906
3907 Do not confuse this with the guestfish-specific
3908 C<alloc> command which allocates a file in the host and
3909 attaches it as a device.");
3910
3911   ("swapon_device", (RErr, [Device "device"]), 170, [],
3912    [InitPartition, Always, TestRun (
3913       [["mkswap"; "/dev/sda1"];
3914        ["swapon_device"; "/dev/sda1"];
3915        ["swapoff_device"; "/dev/sda1"]])],
3916    "enable swap on device",
3917    "\
3918 This command enables the libguestfs appliance to use the
3919 swap device or partition named C<device>.  The increased
3920 memory is made available for all commands, for example
3921 those run using C<guestfs_command> or C<guestfs_sh>.
3922
3923 Note that you should not swap to existing guest swap
3924 partitions unless you know what you are doing.  They may
3925 contain hibernation information, or other information that
3926 the guest doesn't want you to trash.  You also risk leaking
3927 information about the host to the guest this way.  Instead,
3928 attach a new host device to the guest and swap on that.");
3929
3930   ("swapoff_device", (RErr, [Device "device"]), 171, [],
3931    [], (* XXX tested by swapon_device *)
3932    "disable swap on device",
3933    "\
3934 This command disables the libguestfs appliance swap
3935 device or partition named C<device>.
3936 See C<guestfs_swapon_device>.");
3937
3938   ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3939    [InitBasicFS, Always, TestRun (
3940       [["fallocate"; "/swap"; "8388608"];
3941        ["mkswap_file"; "/swap"];
3942        ["swapon_file"; "/swap"];
3943        ["swapoff_file"; "/swap"]])],
3944    "enable swap on file",
3945    "\
3946 This command enables swap to a file.
3947 See C<guestfs_swapon_device> for other notes.");
3948
3949   ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3950    [], (* XXX tested by swapon_file *)
3951    "disable swap on file",
3952    "\
3953 This command disables the libguestfs appliance swap on file.");
3954
3955   ("swapon_label", (RErr, [String "label"]), 174, [],
3956    [InitEmpty, Always, TestRun (
3957       [["part_disk"; "/dev/sdb"; "mbr"];
3958        ["mkswap_L"; "swapit"; "/dev/sdb1"];
3959        ["swapon_label"; "swapit"];
3960        ["swapoff_label"; "swapit"];
3961        ["zero"; "/dev/sdb"];
3962        ["blockdev_rereadpt"; "/dev/sdb"]])],
3963    "enable swap on labeled swap partition",
3964    "\
3965 This command enables swap to a labeled swap partition.
3966 See C<guestfs_swapon_device> for other notes.");
3967
3968   ("swapoff_label", (RErr, [String "label"]), 175, [],
3969    [], (* XXX tested by swapon_label *)
3970    "disable swap on labeled swap partition",
3971    "\
3972 This command disables the libguestfs appliance swap on
3973 labeled swap partition.");
3974
3975   ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3976    (let uuid = uuidgen () in
3977     [InitEmpty, Always, TestRun (
3978        [["mkswap_U"; uuid; "/dev/sdb"];
3979         ["swapon_uuid"; uuid];
3980         ["swapoff_uuid"; uuid]])]),
3981    "enable swap on swap partition by UUID",
3982    "\
3983 This command enables swap to a swap partition with the given UUID.
3984 See C<guestfs_swapon_device> for other notes.");
3985
3986   ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3987    [], (* XXX tested by swapon_uuid *)
3988    "disable swap on swap partition by UUID",
3989    "\
3990 This command disables the libguestfs appliance swap partition
3991 with the given UUID.");
3992
3993   ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3994    [InitBasicFS, Always, TestRun (
3995       [["fallocate"; "/swap"; "8388608"];
3996        ["mkswap_file"; "/swap"]])],
3997    "create a swap file",
3998    "\
3999 Create a swap file.
4000
4001 This command just writes a swap file signature to an existing
4002 file.  To create the file itself, use something like C<guestfs_fallocate>.");
4003
4004   ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
4005    [InitISOFS, Always, TestRun (
4006       [["inotify_init"; "0"]])],
4007    "create an inotify handle",
4008    "\
4009 This command creates a new inotify handle.
4010 The inotify subsystem can be used to notify events which happen to
4011 objects in the guest filesystem.
4012
4013 C<maxevents> is the maximum number of events which will be
4014 queued up between calls to C<guestfs_inotify_read> or
4015 C<guestfs_inotify_files>.
4016 If this is passed as C<0>, then the kernel (or previously set)
4017 default is used.  For Linux 2.6.29 the default was 16384 events.
4018 Beyond this limit, the kernel throws away events, but records
4019 the fact that it threw them away by setting a flag
4020 C<IN_Q_OVERFLOW> in the returned structure list (see
4021 C<guestfs_inotify_read>).
4022
4023 Before any events are generated, you have to add some
4024 watches to the internal watch list.  See:
4025 C<guestfs_inotify_add_watch>,
4026 C<guestfs_inotify_rm_watch> and
4027 C<guestfs_inotify_watch_all>.
4028
4029 Queued up events should be read periodically by calling
4030 C<guestfs_inotify_read>
4031 (or C<guestfs_inotify_files> which is just a helpful
4032 wrapper around C<guestfs_inotify_read>).  If you don't
4033 read the events out often enough then you risk the internal
4034 queue overflowing.
4035
4036 The handle should be closed after use by calling
4037 C<guestfs_inotify_close>.  This also removes any
4038 watches automatically.
4039
4040 See also L<inotify(7)> for an overview of the inotify interface
4041 as exposed by the Linux kernel, which is roughly what we expose
4042 via libguestfs.  Note that there is one global inotify handle
4043 per libguestfs instance.");
4044
4045   ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
4046    [InitBasicFS, Always, TestOutputList (
4047       [["inotify_init"; "0"];
4048        ["inotify_add_watch"; "/"; "1073741823"];
4049        ["touch"; "/a"];
4050        ["touch"; "/b"];
4051        ["inotify_files"]], ["a"; "b"])],
4052    "add an inotify watch",
4053    "\
4054 Watch C<path> for the events listed in C<mask>.
4055
4056 Note that if C<path> is a directory then events within that
4057 directory are watched, but this does I<not> happen recursively
4058 (in subdirectories).
4059
4060 Note for non-C or non-Linux callers: the inotify events are
4061 defined by the Linux kernel ABI and are listed in
4062 C</usr/include/sys/inotify.h>.");
4063
4064   ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
4065    [],
4066    "remove an inotify watch",
4067    "\
4068 Remove a previously defined inotify watch.
4069 See C<guestfs_inotify_add_watch>.");
4070
4071   ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
4072    [],
4073    "return list of inotify events",
4074    "\
4075 Return the complete queue of events that have happened
4076 since the previous read call.
4077
4078 If no events have happened, this returns an empty list.
4079
4080 I<Note>: In order to make sure that all events have been
4081 read, you must call this function repeatedly until it
4082 returns an empty list.  The reason is that the call will
4083 read events up to the maximum appliance-to-host message
4084 size and leave remaining events in the queue.");
4085
4086   ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
4087    [],
4088    "return list of watched files that had events",
4089    "\
4090 This function is a helpful wrapper around C<guestfs_inotify_read>
4091 which just returns a list of pathnames of objects that were
4092 touched.  The returned pathnames are sorted and deduplicated.");
4093
4094   ("inotify_close", (RErr, []), 184, [Optional "inotify"],
4095    [],
4096    "close the inotify handle",
4097    "\
4098 This closes the inotify handle which was previously
4099 opened by inotify_init.  It removes all watches, throws
4100 away any pending events, and deallocates all resources.");
4101
4102   ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
4103    [],
4104    "set SELinux security context",
4105    "\
4106 This sets the SELinux security context of the daemon
4107 to the string C<context>.
4108
4109 See the documentation about SELINUX in L<guestfs(3)>.");
4110
4111   ("getcon", (RString "context", []), 186, [Optional "selinux"],
4112    [],
4113    "get SELinux security context",
4114    "\
4115 This gets the SELinux security context of the daemon.
4116
4117 See the documentation about SELINUX in L<guestfs(3)>,
4118 and C<guestfs_setcon>");
4119
4120   ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
4121    [InitEmpty, Always, TestOutput (
4122       [["part_disk"; "/dev/sda"; "mbr"];
4123        ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
4124        ["mount_options"; ""; "/dev/sda1"; "/"];
4125        ["write"; "/new"; "new file contents"];
4126        ["cat"; "/new"]], "new file contents");
4127     InitEmpty, Always, TestRun (
4128       [["part_disk"; "/dev/sda"; "mbr"];
4129        ["mkfs_b"; "vfat"; "32768"; "/dev/sda1"]]);
4130     InitEmpty, Always, TestLastFail (
4131       [["part_disk"; "/dev/sda"; "mbr"];
4132        ["mkfs_b"; "vfat"; "32769"; "/dev/sda1"]]);
4133     InitEmpty, Always, TestLastFail (
4134       [["part_disk"; "/dev/sda"; "mbr"];
4135        ["mkfs_b"; "vfat"; "33280"; "/dev/sda1"]]);
4136     InitEmpty, IfAvailable "ntfsprogs", TestRun (
4137       [["part_disk"; "/dev/sda"; "mbr"];
4138        ["mkfs_b"; "ntfs"; "32768"; "/dev/sda1"]])],
4139    "make a filesystem with block size",
4140    "\
4141 This call is similar to C<guestfs_mkfs>, but it allows you to
4142 control the block size of the resulting filesystem.  Supported
4143 block sizes depend on the filesystem type, but typically they
4144 are C<1024>, C<2048> or C<4096> only.
4145
4146 For VFAT and NTFS the C<blocksize> parameter is treated as
4147 the requested cluster size.");
4148
4149   ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
4150    [InitEmpty, Always, TestOutput (
4151       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4152        ["mke2journal"; "4096"; "/dev/sda1"];
4153        ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
4154        ["mount_options"; ""; "/dev/sda2"; "/"];
4155        ["write"; "/new"; "new file contents"];
4156        ["cat"; "/new"]], "new file contents")],
4157    "make ext2/3/4 external journal",
4158    "\
4159 This creates an ext2 external journal on C<device>.  It is equivalent
4160 to the command:
4161
4162  mke2fs -O journal_dev -b blocksize device");
4163
4164   ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
4165    [InitEmpty, Always, TestOutput (
4166       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4167        ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
4168        ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
4169        ["mount_options"; ""; "/dev/sda2"; "/"];
4170        ["write"; "/new"; "new file contents"];
4171        ["cat"; "/new"]], "new file contents")],
4172    "make ext2/3/4 external journal with label",
4173    "\
4174 This creates an ext2 external journal on C<device> with label C<label>.");
4175
4176   ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
4177    (let uuid = uuidgen () in
4178     [InitEmpty, Always, TestOutput (
4179        [["sfdiskM"; "/dev/sda"; ",100 ,"];
4180         ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
4181         ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
4182         ["mount_options"; ""; "/dev/sda2"; "/"];
4183         ["write"; "/new"; "new file contents"];
4184         ["cat"; "/new"]], "new file contents")]),
4185    "make ext2/3/4 external journal with UUID",
4186    "\
4187 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
4188
4189   ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
4190    [],
4191    "make ext2/3/4 filesystem with external journal",
4192    "\
4193 This creates an ext2/3/4 filesystem on C<device> with
4194 an external journal on C<journal>.  It is equivalent
4195 to the command:
4196
4197  mke2fs -t fstype -b blocksize -J device=<journal> <device>
4198
4199 See also C<guestfs_mke2journal>.");
4200
4201   ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
4202    [],
4203    "make ext2/3/4 filesystem with external journal",
4204    "\
4205 This creates an ext2/3/4 filesystem on C<device> with
4206 an external journal on the journal labeled C<label>.
4207
4208 See also C<guestfs_mke2journal_L>.");
4209
4210   ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
4211    [],
4212    "make ext2/3/4 filesystem with external journal",
4213    "\
4214 This creates an ext2/3/4 filesystem on C<device> with
4215 an external journal on the journal with UUID C<uuid>.
4216
4217 See also C<guestfs_mke2journal_U>.");
4218
4219   ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
4220    [InitNone, Always, TestRun [["modprobe"; "fat"]]],
4221    "load a kernel module",
4222    "\
4223 This loads a kernel module in the appliance.
4224
4225 The kernel module must have been whitelisted when libguestfs
4226 was built (see C<appliance/kmod.whitelist.in> in the source).");
4227
4228   ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
4229    [InitNone, Always, TestOutput (
4230       [["echo_daemon"; "This is a test"]], "This is a test"
4231     )],
4232    "echo arguments back to the client",
4233    "\
4234 This command concatenates the list of C<words> passed with single spaces
4235 between them and returns the resulting string.
4236
4237 You can use this command to test the connection through to the daemon.
4238
4239 See also C<guestfs_ping_daemon>.");
4240
4241   ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
4242    [], (* There is a regression test for this. *)
4243    "find all files and directories, returning NUL-separated list",
4244    "\
4245 This command lists out all files and directories, recursively,
4246 starting at C<directory>, placing the resulting list in the
4247 external file called C<files>.
4248
4249 This command works the same way as C<guestfs_find> with the
4250 following exceptions:
4251
4252 =over 4
4253
4254 =item *
4255
4256 The resulting list is written to an external file.
4257
4258 =item *
4259
4260 Items (filenames) in the result are separated
4261 by C<\\0> characters.  See L<find(1)> option I<-print0>.
4262
4263 =item *
4264
4265 This command is not limited in the number of names that it
4266 can return.
4267
4268 =item *
4269
4270 The result list is not sorted.
4271
4272 =back");
4273
4274   ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
4275    [InitISOFS, Always, TestOutput (
4276       [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
4277     InitISOFS, Always, TestOutput (
4278       [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
4279     InitISOFS, Always, TestOutput (
4280       [["case_sensitive_path"; "/Known-1"]], "/known-1");
4281     InitISOFS, Always, TestLastFail (
4282       [["case_sensitive_path"; "/Known-1/"]]);
4283     InitBasicFS, Always, TestOutput (
4284       [["mkdir"; "/a"];
4285        ["mkdir"; "/a/bbb"];
4286        ["touch"; "/a/bbb/c"];
4287        ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
4288     InitBasicFS, Always, TestOutput (
4289       [["mkdir"; "/a"];
4290        ["mkdir"; "/a/bbb"];
4291        ["touch"; "/a/bbb/c"];
4292        ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
4293     InitBasicFS, Always, TestLastFail (
4294       [["mkdir"; "/a"];
4295        ["mkdir"; "/a/bbb"];
4296        ["touch"; "/a/bbb/c"];
4297        ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
4298    "return true path on case-insensitive filesystem",
4299    "\
4300 This can be used to resolve case insensitive paths on
4301 a filesystem which is case sensitive.  The use case is
4302 to resolve paths which you have read from Windows configuration
4303 files or the Windows Registry, to the true path.
4304
4305 The command handles a peculiarity of the Linux ntfs-3g
4306 filesystem driver (and probably others), which is that although
4307 the underlying filesystem is case-insensitive, the driver
4308 exports the filesystem to Linux as case-sensitive.
4309
4310 One consequence of this is that special directories such
4311 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
4312 (or other things) depending on the precise details of how
4313 they were created.  In Windows itself this would not be
4314 a problem.
4315
4316 Bug or feature?  You decide:
4317 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
4318
4319 This function resolves the true case of each element in the
4320 path and returns the case-sensitive path.
4321
4322 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
4323 might return C<\"/WINDOWS/system32\"> (the exact return value
4324 would depend on details of how the directories were originally
4325 created under Windows).
4326
4327 I<Note>:
4328 This function does not handle drive names, backslashes etc.
4329
4330 See also C<guestfs_realpath>.");
4331
4332   ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
4333    [InitBasicFS, Always, TestOutput (
4334       [["vfs_type"; "/dev/sda1"]], "ext2")],
4335    "get the Linux VFS type corresponding to a mounted device",
4336    "\
4337 This command gets the filesystem type corresponding to
4338 the filesystem on C<device>.
4339
4340 For most filesystems, the result is the name of the Linux
4341 VFS module which would be used to mount this filesystem
4342 if you mounted it without specifying the filesystem type.
4343 For example a string such as C<ext3> or C<ntfs>.");
4344
4345   ("truncate", (RErr, [Pathname "path"]), 199, [],
4346    [InitBasicFS, Always, TestOutputStruct (
4347       [["write"; "/test"; "some stuff so size is not zero"];
4348        ["truncate"; "/test"];
4349        ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
4350    "truncate a file to zero size",
4351    "\
4352 This command truncates C<path> to a zero-length file.  The
4353 file must exist already.");
4354
4355   ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
4356    [InitBasicFS, Always, TestOutputStruct (
4357       [["touch"; "/test"];
4358        ["truncate_size"; "/test"; "1000"];
4359        ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
4360    "truncate a file to a particular size",
4361    "\
4362 This command truncates C<path> to size C<size> bytes.  The file
4363 must exist already.
4364
4365 If the current file size is less than C<size> then
4366 the file is extended to the required size with zero bytes.
4367 This creates a sparse file (ie. disk blocks are not allocated
4368 for the file until you write to it).  To create a non-sparse
4369 file of zeroes, use C<guestfs_fallocate64> instead.");
4370
4371   ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
4372    [InitBasicFS, Always, TestOutputStruct (
4373       [["touch"; "/test"];
4374        ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
4375        ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
4376    "set timestamp of a file with nanosecond precision",
4377    "\
4378 This command sets the timestamps of a file with nanosecond
4379 precision.
4380
4381 C<atsecs, atnsecs> are the last access time (atime) in secs and
4382 nanoseconds from the epoch.
4383
4384 C<mtsecs, mtnsecs> are the last modification time (mtime) in
4385 secs and nanoseconds from the epoch.
4386
4387 If the C<*nsecs> field contains the special value C<-1> then
4388 the corresponding timestamp is set to the current time.  (The
4389 C<*secs> field is ignored in this case).
4390
4391 If the C<*nsecs> field contains the special value C<-2> then
4392 the corresponding timestamp is left unchanged.  (The
4393 C<*secs> field is ignored in this case).");
4394
4395   ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
4396    [InitBasicFS, Always, TestOutputStruct (
4397       [["mkdir_mode"; "/test"; "0o111"];
4398        ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
4399    "create a directory with a particular mode",
4400    "\
4401 This command creates a directory, setting the initial permissions
4402 of the directory to C<mode>.
4403
4404 For common Linux filesystems, the actual mode which is set will
4405 be C<mode & ~umask & 01777>.  Non-native-Linux filesystems may
4406 interpret the mode in other ways.
4407
4408 See also C<guestfs_mkdir>, C<guestfs_umask>");
4409
4410   ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
4411    [], (* XXX *)
4412    "change file owner and group",
4413    "\
4414 Change the file owner to C<owner> and group to C<group>.
4415 This is like C<guestfs_chown> but if C<path> is a symlink then
4416 the link itself is changed, not the target.
4417
4418 Only numeric uid and gid are supported.  If you want to use
4419 names, you will need to locate and parse the password file
4420 yourself (Augeas support makes this relatively easy).");
4421
4422   ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
4423    [], (* XXX *)
4424    "lstat on multiple files",
4425    "\
4426 This call allows you to perform the C<guestfs_lstat> operation
4427 on multiple files, where all files are in the directory C<path>.
4428 C<names> is the list of files from this directory.
4429
4430 On return you get a list of stat structs, with a one-to-one
4431 correspondence to the C<names> list.  If any name did not exist
4432 or could not be lstat'd, then the C<ino> field of that structure
4433 is set to C<-1>.
4434
4435 This call is intended for programs that want to efficiently
4436 list a directory contents without making many round-trips.
4437 See also C<guestfs_lxattrlist> for a similarly efficient call
4438 for getting extended attributes.  Very long directory listings
4439 might cause the protocol message size to be exceeded, causing
4440 this call to fail.  The caller must split up such requests
4441 into smaller groups of names.");
4442
4443   ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
4444    [], (* XXX *)
4445    "lgetxattr on multiple files",
4446    "\
4447 This call allows you to get the extended attributes
4448 of multiple files, where all files are in the directory C<path>.
4449 C<names> is the list of files from this directory.
4450
4451 On return you get a flat list of xattr structs which must be
4452 interpreted sequentially.  The first xattr struct always has a zero-length
4453 C<attrname>.  C<attrval> in this struct is zero-length
4454 to indicate there was an error doing C<lgetxattr> for this
4455 file, I<or> is a C string which is a decimal number
4456 (the number of following attributes for this file, which could
4457 be C<\"0\">).  Then after the first xattr struct are the
4458 zero or more attributes for the first named file.
4459 This repeats for the second and subsequent files.
4460
4461 This call is intended for programs that want to efficiently
4462 list a directory contents without making many round-trips.
4463 See also C<guestfs_lstatlist> for a similarly efficient call
4464 for getting standard stats.  Very long directory listings
4465 might cause the protocol message size to be exceeded, causing
4466 this call to fail.  The caller must split up such requests
4467 into smaller groups of names.");
4468
4469   ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
4470    [], (* XXX *)
4471    "readlink on multiple files",
4472    "\
4473 This call allows you to do a C<readlink> operation
4474 on multiple files, where all files are in the directory C<path>.
4475 C<names> is the list of files from this directory.
4476
4477 On return you get a list of strings, with a one-to-one
4478 correspondence to the C<names> list.  Each string is the
4479 value of the symbolic link.
4480
4481 If the C<readlink(2)> operation fails on any name, then
4482 the corresponding result string is the empty string C<\"\">.
4483 However the whole operation is completed even if there
4484 were C<readlink(2)> errors, and so you can call this
4485 function with names where you don't know if they are
4486 symbolic links already (albeit slightly less efficient).
4487
4488 This call is intended for programs that want to efficiently
4489 list a directory contents without making many round-trips.
4490 Very long directory listings might cause the protocol
4491 message size to be exceeded, causing
4492 this call to fail.  The caller must split up such requests
4493 into smaller groups of names.");
4494
4495   ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
4496    [InitISOFS, Always, TestOutputBuffer (
4497       [["pread"; "/known-4"; "1"; "3"]], "\n");
4498     InitISOFS, Always, TestOutputBuffer (
4499       [["pread"; "/empty"; "0"; "100"]], "")],
4500    "read part of a file",
4501    "\
4502 This command lets you read part of a file.  It reads C<count>
4503 bytes of the file, starting at C<offset>, from file C<path>.
4504
4505 This may read fewer bytes than requested.  For further details
4506 see the L<pread(2)> system call.
4507
4508 See also C<guestfs_pwrite>.");
4509
4510   ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
4511    [InitEmpty, Always, TestRun (
4512       [["part_init"; "/dev/sda"; "gpt"]])],
4513    "create an empty partition table",
4514    "\
4515 This creates an empty partition table on C<device> of one of the
4516 partition types listed below.  Usually C<parttype> should be
4517 either C<msdos> or C<gpt> (for large disks).
4518
4519 Initially there are no partitions.  Following this, you should
4520 call C<guestfs_part_add> for each partition required.
4521
4522 Possible values for C<parttype> are:
4523
4524 =over 4
4525
4526 =item B<efi> | B<gpt>
4527
4528 Intel EFI / GPT partition table.
4529
4530 This is recommended for >= 2 TB partitions that will be accessed
4531 from Linux and Intel-based Mac OS X.  It also has limited backwards
4532 compatibility with the C<mbr> format.
4533
4534 =item B<mbr> | B<msdos>
4535
4536 The standard PC \"Master Boot Record\" (MBR) format used
4537 by MS-DOS and Windows.  This partition type will B<only> work
4538 for device sizes up to 2 TB.  For large disks we recommend
4539 using C<gpt>.
4540
4541 =back
4542
4543 Other partition table types that may work but are not
4544 supported include:
4545
4546 =over 4
4547
4548 =item B<aix>
4549
4550 AIX disk labels.
4551
4552 =item B<amiga> | B<rdb>
4553
4554 Amiga \"Rigid Disk Block\" format.
4555
4556 =item B<bsd>
4557
4558 BSD disk labels.
4559
4560 =item B<dasd>
4561
4562 DASD, used on IBM mainframes.
4563
4564 =item B<dvh>
4565
4566 MIPS/SGI volumes.
4567
4568 =item B<mac>
4569
4570 Old Mac partition format.  Modern Macs use C<gpt>.
4571
4572 =item B<pc98>
4573
4574 NEC PC-98 format, common in Japan apparently.
4575
4576 =item B<sun>
4577
4578 Sun disk labels.
4579
4580 =back");
4581
4582   ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4583    [InitEmpty, Always, TestRun (
4584       [["part_init"; "/dev/sda"; "mbr"];
4585        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4586     InitEmpty, Always, TestRun (
4587       [["part_init"; "/dev/sda"; "gpt"];
4588        ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4589        ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4590     InitEmpty, Always, TestRun (
4591       [["part_init"; "/dev/sda"; "mbr"];
4592        ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4593        ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4594        ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4595        ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4596    "add a partition to the device",
4597    "\
4598 This command adds a partition to C<device>.  If there is no partition
4599 table on the device, call C<guestfs_part_init> first.
4600
4601 The C<prlogex> parameter is the type of partition.  Normally you
4602 should pass C<p> or C<primary> here, but MBR partition tables also
4603 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4604 types.
4605
4606 C<startsect> and C<endsect> are the start and end of the partition
4607 in I<sectors>.  C<endsect> may be negative, which means it counts
4608 backwards from the end of the disk (C<-1> is the last sector).
4609
4610 Creating a partition which covers the whole disk is not so easy.
4611 Use C<guestfs_part_disk> to do that.");
4612
4613   ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4614    [InitEmpty, Always, TestRun (
4615       [["part_disk"; "/dev/sda"; "mbr"]]);
4616     InitEmpty, Always, TestRun (
4617       [["part_disk"; "/dev/sda"; "gpt"]])],
4618    "partition whole disk with a single primary partition",
4619    "\
4620 This command is simply a combination of C<guestfs_part_init>
4621 followed by C<guestfs_part_add> to create a single primary partition
4622 covering the whole disk.
4623
4624 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4625 but other possible values are described in C<guestfs_part_init>.");
4626
4627   ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4628    [InitEmpty, Always, TestRun (
4629       [["part_disk"; "/dev/sda"; "mbr"];
4630        ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4631    "make a partition bootable",
4632    "\
4633 This sets the bootable flag on partition numbered C<partnum> on
4634 device C<device>.  Note that partitions are numbered from 1.
4635
4636 The bootable flag is used by some operating systems (notably
4637 Windows) to determine which partition to boot from.  It is by
4638 no means universally recognized.");
4639
4640   ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4641    [InitEmpty, Always, TestRun (
4642       [["part_disk"; "/dev/sda"; "gpt"];
4643        ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4644    "set partition name",
4645    "\
4646 This sets the partition name on partition numbered C<partnum> on
4647 device C<device>.  Note that partitions are numbered from 1.
4648
4649 The partition name can only be set on certain types of partition
4650 table.  This works on C<gpt> but not on C<mbr> partitions.");
4651
4652   ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4653    [], (* XXX Add a regression test for this. *)
4654    "list partitions on a device",
4655    "\
4656 This command parses the partition table on C<device> and
4657 returns the list of partitions found.
4658
4659 The fields in the returned structure are:
4660
4661 =over 4
4662
4663 =item B<part_num>
4664
4665 Partition number, counting from 1.
4666
4667 =item B<part_start>
4668
4669 Start of the partition I<in bytes>.  To get sectors you have to
4670 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4671
4672 =item B<part_end>
4673
4674 End of the partition in bytes.
4675
4676 =item B<part_size>
4677
4678 Size of the partition in bytes.
4679
4680 =back");
4681
4682   ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4683    [InitEmpty, Always, TestOutput (
4684       [["part_disk"; "/dev/sda"; "gpt"];
4685        ["part_get_parttype"; "/dev/sda"]], "gpt")],
4686    "get the partition table type",
4687    "\
4688 This command examines the partition table on C<device> and
4689 returns the partition table type (format) being used.
4690
4691 Common return values include: C<msdos> (a DOS/Windows style MBR
4692 partition table), C<gpt> (a GPT/EFI-style partition table).  Other
4693 values are possible, although unusual.  See C<guestfs_part_init>
4694 for a full list.");
4695
4696   ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [Progress],
4697    [InitBasicFS, Always, TestOutputBuffer (
4698       [["fill"; "0x63"; "10"; "/test"];
4699        ["read_file"; "/test"]], "cccccccccc")],
4700    "fill a file with octets",
4701    "\
4702 This command creates a new file called C<path>.  The initial
4703 content of the file is C<len> octets of C<c>, where C<c>
4704 must be a number in the range C<[0..255]>.
4705
4706 To fill a file with zero bytes (sparsely), it is
4707 much more efficient to use C<guestfs_truncate_size>.
4708 To create a file with a pattern of repeating bytes
4709 use C<guestfs_fill_pattern>.");
4710
4711   ("available", (RErr, [StringList "groups"]), 216, [],
4712    [InitNone, Always, TestRun [["available"; ""]]],
4713    "test availability of some parts of the API",
4714    "\
4715 This command is used to check the availability of some
4716 groups of functionality in the appliance, which not all builds of
4717 the libguestfs appliance will be able to provide.
4718
4719 The libguestfs groups, and the functions that those
4720 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4721 You can also fetch this list at runtime by calling
4722 C<guestfs_available_all_groups>.
4723
4724 The argument C<groups> is a list of group names, eg:
4725 C<[\"inotify\", \"augeas\"]> would check for the availability of
4726 the Linux inotify functions and Augeas (configuration file
4727 editing) functions.
4728
4729 The command returns no error if I<all> requested groups are available.
4730
4731 It fails with an error if one or more of the requested
4732 groups is unavailable in the appliance.
4733
4734 If an unknown group name is included in the
4735 list of groups then an error is always returned.
4736
4737 I<Notes:>
4738
4739 =over 4
4740
4741 =item *
4742
4743 You must call C<guestfs_launch> before calling this function.
4744
4745 The reason is because we don't know what groups are
4746 supported by the appliance/daemon until it is running and can
4747 be queried.
4748
4749 =item *
4750
4751 If a group of functions is available, this does not necessarily
4752 mean that they will work.  You still have to check for errors
4753 when calling individual API functions even if they are
4754 available.
4755
4756 =item *
4757
4758 It is usually the job of distro packagers to build
4759 complete functionality into the libguestfs appliance.
4760 Upstream libguestfs, if built from source with all
4761 requirements satisfied, will support everything.
4762
4763 =item *
4764
4765 This call was added in version C<1.0.80>.  In previous
4766 versions of libguestfs all you could do would be to speculatively
4767 execute a command to find out if the daemon implemented it.
4768 See also C<guestfs_version>.
4769
4770 =back");
4771
4772   ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4773    [InitBasicFS, Always, TestOutputBuffer (
4774       [["write"; "/src"; "hello, world"];
4775        ["dd"; "/src"; "/dest"];
4776        ["read_file"; "/dest"]], "hello, world")],
4777    "copy from source to destination using dd",
4778    "\
4779 This command copies from one source device or file C<src>
4780 to another destination device or file C<dest>.  Normally you
4781 would use this to copy to or from a device or partition, for
4782 example to duplicate a filesystem.
4783
4784 If the destination is a device, it must be as large or larger
4785 than the source file or device, otherwise the copy will fail.
4786 This command cannot do partial copies (see C<guestfs_copy_size>).");
4787
4788   ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4789    [InitBasicFS, Always, TestOutputInt (
4790       [["write"; "/file"; "hello, world"];
4791        ["filesize"; "/file"]], 12)],
4792    "return the size of the file in bytes",
4793    "\
4794 This command returns the size of C<file> in bytes.
4795
4796 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4797 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4798 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4799
4800   ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4801    [InitBasicFSonLVM, Always, TestOutputList (
4802       [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4803        ["lvs"]], ["/dev/VG/LV2"])],
4804    "rename an LVM logical volume",
4805    "\
4806 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4807
4808   ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4809    [InitBasicFSonLVM, Always, TestOutputList (
4810       [["umount"; "/"];
4811        ["vg_activate"; "false"; "VG"];
4812        ["vgrename"; "VG"; "VG2"];
4813        ["vg_activate"; "true"; "VG2"];
4814        ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4815        ["vgs"]], ["VG2"])],
4816    "rename an LVM volume group",
4817    "\
4818 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4819
4820   ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4821    [InitISOFS, Always, TestOutputBuffer (
4822       [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4823    "list the contents of a single file in an initrd",
4824    "\
4825 This command unpacks the file C<filename> from the initrd file
4826 called C<initrdpath>.  The filename must be given I<without> the
4827 initial C</> character.
4828
4829 For example, in guestfish you could use the following command
4830 to examine the boot script (usually called C</init>)
4831 contained in a Linux initrd or initramfs image:
4832
4833  initrd-cat /boot/initrd-<version>.img init
4834
4835 See also C<guestfs_initrd_list>.");
4836
4837   ("pvuuid", (RString "uuid", [Device "device"]), 222, [],
4838    [],
4839    "get the UUID of a physical volume",
4840    "\
4841 This command returns the UUID of the LVM PV C<device>.");
4842
4843   ("vguuid", (RString "uuid", [String "vgname"]), 223, [],
4844    [],
4845    "get the UUID of a volume group",
4846    "\
4847 This command returns the UUID of the LVM VG named C<vgname>.");
4848
4849   ("lvuuid", (RString "uuid", [Device "device"]), 224, [],
4850    [],
4851    "get the UUID of a logical volume",
4852    "\
4853 This command returns the UUID of the LVM LV C<device>.");
4854
4855   ("vgpvuuids", (RStringList "uuids", [String "vgname"]), 225, [],
4856    [],
4857    "get the PV UUIDs containing the volume group",
4858    "\
4859 Given a VG called C<vgname>, this returns the UUIDs of all
4860 the physical volumes that this volume group resides on.
4861
4862 You can use this along with C<guestfs_pvs> and C<guestfs_pvuuid>
4863 calls to associate physical volumes and volume groups.
4864
4865 See also C<guestfs_vglvuuids>.");
4866
4867   ("vglvuuids", (RStringList "uuids", [String "vgname"]), 226, [],
4868    [],
4869    "get the LV UUIDs of all LVs in the volume group",
4870    "\
4871 Given a VG called C<vgname>, this returns the UUIDs of all
4872 the logical volumes created in this volume group.
4873
4874 You can use this along with C<guestfs_lvs> and C<guestfs_lvuuid>
4875 calls to associate logical volumes and volume groups.
4876
4877 See also C<guestfs_vgpvuuids>.");
4878
4879   ("copy_size", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"; Int64 "size"]), 227, [Progress],
4880    [InitBasicFS, Always, TestOutputBuffer (
4881       [["write"; "/src"; "hello, world"];
4882        ["copy_size"; "/src"; "/dest"; "5"];
4883        ["read_file"; "/dest"]], "hello")],
4884    "copy size bytes from source to destination using dd",
4885    "\
4886 This command copies exactly C<size> bytes from one source device
4887 or file C<src> to another destination device or file C<dest>.
4888
4889 Note this will fail if the source is too short or if the destination
4890 is not large enough.");
4891
4892   ("zero_device", (RErr, [Device "device"]), 228, [DangerWillRobinson; Progress],
4893    [InitBasicFSonLVM, Always, TestRun (
4894       [["zero_device"; "/dev/VG/LV"]])],
4895    "write zeroes to an entire device",
4896    "\
4897 This command writes zeroes over the entire C<device>.  Compare
4898 with C<guestfs_zero> which just zeroes the first few blocks of
4899 a device.");
4900
4901   ("txz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 229, [Optional "xz"],
4902    [InitBasicFS, Always, TestOutput (
4903       [["txz_in"; "../images/helloworld.tar.xz"; "/"];
4904        ["cat"; "/hello"]], "hello\n")],
4905    "unpack compressed tarball to directory",
4906    "\
4907 This command uploads and unpacks local file C<tarball> (an
4908 I<xz compressed> tar file) into C<directory>.");
4909
4910   ("txz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 230, [Optional "xz"],
4911    [],
4912    "pack directory into compressed tarball",
4913    "\
4914 This command packs the contents of C<directory> and downloads
4915 it to local file C<tarball> (as an xz compressed tar archive).");
4916
4917   ("ntfsresize", (RErr, [Device "device"]), 231, [Optional "ntfsprogs"],
4918    [],
4919    "resize an NTFS filesystem",
4920    "\
4921 This command resizes an NTFS filesystem, expanding or
4922 shrinking it to the size of the underlying device.
4923 See also L<ntfsresize(8)>.");
4924
4925   ("vgscan", (RErr, []), 232, [],
4926    [InitEmpty, Always, TestRun (
4927       [["vgscan"]])],
4928    "rescan for LVM physical volumes, volume groups and logical volumes",
4929    "\
4930 This rescans all block devices and rebuilds the list of LVM
4931 physical volumes, volume groups and logical volumes.");
4932
4933   ("part_del", (RErr, [Device "device"; Int "partnum"]), 233, [],
4934    [InitEmpty, Always, TestRun (
4935       [["part_init"; "/dev/sda"; "mbr"];
4936        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4937        ["part_del"; "/dev/sda"; "1"]])],
4938    "delete a partition",
4939    "\
4940 This command deletes the partition numbered C<partnum> on C<device>.
4941
4942 Note that in the case of MBR partitioning, deleting an
4943 extended partition also deletes any logical partitions
4944 it contains.");
4945
4946   ("part_get_bootable", (RBool "bootable", [Device "device"; Int "partnum"]), 234, [],
4947    [InitEmpty, Always, TestOutputTrue (
4948       [["part_init"; "/dev/sda"; "mbr"];
4949        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4950        ["part_set_bootable"; "/dev/sda"; "1"; "true"];
4951        ["part_get_bootable"; "/dev/sda"; "1"]])],
4952    "return true if a partition is bootable",
4953    "\
4954 This command returns true if the partition C<partnum> on
4955 C<device> has the bootable flag set.
4956
4957 See also C<guestfs_part_set_bootable>.");
4958
4959   ("part_get_mbr_id", (RInt "idbyte", [Device "device"; Int "partnum"]), 235, [FishOutput FishOutputHexadecimal],
4960    [InitEmpty, Always, TestOutputInt (
4961       [["part_init"; "/dev/sda"; "mbr"];
4962        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4963        ["part_set_mbr_id"; "/dev/sda"; "1"; "0x7f"];
4964        ["part_get_mbr_id"; "/dev/sda"; "1"]], 0x7f)],
4965    "get the MBR type byte (ID byte) from a partition",
4966    "\
4967 Returns the MBR type byte (also known as the ID byte) from
4968 the numbered partition C<partnum>.
4969
4970 Note that only MBR (old DOS-style) partitions have type bytes.
4971 You will get undefined results for other partition table
4972 types (see C<guestfs_part_get_parttype>).");
4973
4974   ("part_set_mbr_id", (RErr, [Device "device"; Int "partnum"; Int "idbyte"]), 236, [],
4975    [], (* tested by part_get_mbr_id *)
4976    "set the MBR type byte (ID byte) of a partition",
4977    "\
4978 Sets the MBR type byte (also known as the ID byte) of
4979 the numbered partition C<partnum> to C<idbyte>.  Note
4980 that the type bytes quoted in most documentation are
4981 in fact hexadecimal numbers, but usually documented
4982 without any leading \"0x\" which might be confusing.
4983
4984 Note that only MBR (old DOS-style) partitions have type bytes.
4985 You will get undefined results for other partition table
4986 types (see C<guestfs_part_get_parttype>).");
4987
4988   ("checksum_device", (RString "checksum", [String "csumtype"; Device "device"]), 237, [],
4989    [InitISOFS, Always, TestOutput (
4990       [["checksum_device"; "md5"; "/dev/sdd"]],
4991       (Digest.to_hex (Digest.file "images/test.iso")))],
4992    "compute MD5, SHAx or CRC checksum of the contents of a device",
4993    "\
4994 This call computes the MD5, SHAx or CRC checksum of the
4995 contents of the device named C<device>.  For the types of
4996 checksums supported see the C<guestfs_checksum> command.");
4997
4998   ("lvresize_free", (RErr, [Device "lv"; Int "percent"]), 238, [Optional "lvm2"],
4999    [InitNone, Always, TestRun (
5000       [["part_disk"; "/dev/sda"; "mbr"];
5001        ["pvcreate"; "/dev/sda1"];
5002        ["vgcreate"; "VG"; "/dev/sda1"];
5003        ["lvcreate"; "LV"; "VG"; "10"];
5004        ["lvresize_free"; "/dev/VG/LV"; "100"]])],
5005    "expand an LV to fill free space",
5006    "\
5007 This expands an existing logical volume C<lv> so that it fills
5008 C<pc>% of the remaining free space in the volume group.  Commonly
5009 you would call this with pc = 100 which expands the logical volume
5010 as much as possible, using all remaining free space in the volume
5011 group.");
5012
5013   ("aug_clear", (RErr, [String "augpath"]), 239, [Optional "augeas"],
5014    [], (* XXX Augeas code needs tests. *)
5015    "clear Augeas path",
5016    "\
5017 Set the value associated with C<path> to C<NULL>.  This
5018 is the same as the L<augtool(1)> C<clear> command.");
5019
5020   ("get_umask", (RInt "mask", []), 240, [FishOutput FishOutputOctal],
5021    [InitEmpty, Always, TestOutputInt (
5022       [["get_umask"]], 0o22)],
5023    "get the current umask",
5024    "\
5025 Return the current umask.  By default the umask is C<022>
5026 unless it has been set by calling C<guestfs_umask>.");
5027
5028   ("debug_upload", (RErr, [FileIn "filename"; String "tmpname"; Int "mode"]), 241, [],
5029    [],
5030    "upload a file to the appliance (internal use only)",
5031    "\
5032 The C<guestfs_debug_upload> command uploads a file to
5033 the libguestfs appliance.
5034
5035 There is no comprehensive help for this command.  You have
5036 to look at the file C<daemon/debug.c> in the libguestfs source
5037 to find out what it is for.");
5038
5039   ("base64_in", (RErr, [FileIn "base64file"; Pathname "filename"]), 242, [],
5040    [InitBasicFS, Always, TestOutput (
5041       [["base64_in"; "../images/hello.b64"; "/hello"];
5042        ["cat"; "/hello"]], "hello\n")],
5043    "upload base64-encoded data to file",
5044    "\
5045 This command uploads base64-encoded data from C<base64file>
5046 to C<filename>.");
5047
5048   ("base64_out", (RErr, [Pathname "filename"; FileOut "base64file"]), 243, [],
5049    [],
5050    "download file and encode as base64",
5051    "\
5052 This command downloads the contents of C<filename>, writing
5053 it out to local file C<base64file> encoded as base64.");
5054
5055   ("checksums_out", (RErr, [String "csumtype"; Pathname "directory"; FileOut "sumsfile"]), 244, [],
5056    [],
5057    "compute MD5, SHAx or CRC checksum of files in a directory",
5058    "\
5059 This command computes the checksums of all regular files in
5060 C<directory> and then emits a list of those checksums to
5061 the local output file C<sumsfile>.
5062
5063 This can be used for verifying the integrity of a virtual
5064 machine.  However to be properly secure you should pay
5065 attention to the output of the checksum command (it uses
5066 the ones from GNU coreutils).  In particular when the
5067 filename is not printable, coreutils uses a special
5068 backslash syntax.  For more information, see the GNU
5069 coreutils info file.");
5070
5071   ("fill_pattern", (RErr, [String "pattern"; Int "len"; Pathname "path"]), 245, [Progress],
5072    [InitBasicFS, Always, TestOutputBuffer (
5073       [["fill_pattern"; "abcdefghijklmnopqrstuvwxyz"; "28"; "/test"];
5074        ["read_file"; "/test"]], "abcdefghijklmnopqrstuvwxyzab")],
5075    "fill a file with a repeating pattern of bytes",
5076    "\
5077 This function is like C<guestfs_fill> except that it creates
5078 a new file of length C<len> containing the repeating pattern
5079 of bytes in C<pattern>.  The pattern is truncated if necessary
5080 to ensure the length of the file is exactly C<len> bytes.");
5081
5082   ("write", (RErr, [Pathname "path"; BufferIn "content"]), 246, [ProtocolLimitWarning],
5083    [InitBasicFS, Always, TestOutput (
5084       [["write"; "/new"; "new file contents"];
5085        ["cat"; "/new"]], "new file contents");
5086     InitBasicFS, Always, TestOutput (
5087       [["write"; "/new"; "\nnew file contents\n"];
5088        ["cat"; "/new"]], "\nnew file contents\n");
5089     InitBasicFS, Always, TestOutput (
5090       [["write"; "/new"; "\n\n"];
5091        ["cat"; "/new"]], "\n\n");
5092     InitBasicFS, Always, TestOutput (
5093       [["write"; "/new"; ""];
5094        ["cat"; "/new"]], "");
5095     InitBasicFS, Always, TestOutput (
5096       [["write"; "/new"; "\n\n\n"];
5097        ["cat"; "/new"]], "\n\n\n");
5098     InitBasicFS, Always, TestOutput (
5099       [["write"; "/new"; "\n"];
5100        ["cat"; "/new"]], "\n")],
5101    "create a new file",
5102    "\
5103 This call creates a file called C<path>.  The content of the
5104 file is the string C<content> (which can contain any 8 bit data).");
5105
5106   ("pwrite", (RInt "nbytes", [Pathname "path"; BufferIn "content"; Int64 "offset"]), 247, [ProtocolLimitWarning],
5107    [InitBasicFS, Always, TestOutput (
5108       [["write"; "/new"; "new file contents"];
5109        ["pwrite"; "/new"; "data"; "4"];
5110        ["cat"; "/new"]], "new data contents");
5111     InitBasicFS, Always, TestOutput (
5112       [["write"; "/new"; "new file contents"];
5113        ["pwrite"; "/new"; "is extended"; "9"];
5114        ["cat"; "/new"]], "new file is extended");
5115     InitBasicFS, Always, TestOutput (
5116       [["write"; "/new"; "new file contents"];
5117        ["pwrite"; "/new"; ""; "4"];
5118        ["cat"; "/new"]], "new file contents")],
5119    "write to part of a file",
5120    "\
5121 This command writes to part of a file.  It writes the data
5122 buffer C<content> to the file C<path> starting at offset C<offset>.
5123
5124 This command implements the L<pwrite(2)> system call, and like
5125 that system call it may not write the full data requested.  The
5126 return value is the number of bytes that were actually written
5127 to the file.  This could even be 0, although short writes are
5128 unlikely for regular files in ordinary circumstances.
5129
5130 See also C<guestfs_pread>.");
5131
5132   ("resize2fs_size", (RErr, [Device "device"; Int64 "size"]), 248, [],
5133    [],
5134    "resize an ext2, ext3 or ext4 filesystem (with size)",
5135    "\
5136 This command is the same as C<guestfs_resize2fs> except that it
5137 allows you to specify the new size (in bytes) explicitly.");
5138
5139   ("pvresize_size", (RErr, [Device "device"; Int64 "size"]), 249, [Optional "lvm2"],
5140    [],
5141    "resize an LVM physical volume (with size)",
5142    "\
5143 This command is the same as C<guestfs_pvresize> except that it
5144 allows you to specify the new size (in bytes) explicitly.");
5145
5146   ("ntfsresize_size", (RErr, [Device "device"; Int64 "size"]), 250, [Optional "ntfsprogs"],
5147    [],
5148    "resize an NTFS filesystem (with size)",
5149    "\
5150 This command is the same as C<guestfs_ntfsresize> except that it
5151 allows you to specify the new size (in bytes) explicitly.");
5152
5153   ("available_all_groups", (RStringList "groups", []), 251, [],
5154    [InitNone, Always, TestRun [["available_all_groups"]]],
5155    "return a list of all optional groups",
5156    "\
5157 This command returns a list of all optional groups that this
5158 daemon knows about.  Note this returns both supported and unsupported
5159 groups.  To find out which ones the daemon can actually support
5160 you have to call C<guestfs_available> on each member of the
5161 returned list.
5162
5163 See also C<guestfs_available> and L<guestfs(3)/AVAILABILITY>.");
5164
5165   ("fallocate64", (RErr, [Pathname "path"; Int64 "len"]), 252, [],
5166    [InitBasicFS, Always, TestOutputStruct (
5167       [["fallocate64"; "/a"; "1000000"];
5168        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
5169    "preallocate a file in the guest filesystem",
5170    "\
5171 This command preallocates a file (containing zero bytes) named
5172 C<path> of size C<len> bytes.  If the file exists already, it
5173 is overwritten.
5174
5175 Note that this call allocates disk blocks for the file.
5176 To create a sparse file use C<guestfs_truncate_size> instead.
5177
5178 The deprecated call C<guestfs_fallocate> does the same,
5179 but owing to an oversight it only allowed 30 bit lengths
5180 to be specified, effectively limiting the maximum size
5181 of files created through that call to 1GB.
5182
5183 Do not confuse this with the guestfish-specific
5184 C<alloc> and C<sparse> commands which create
5185 a file in the host and attach it as a device.");
5186
5187   ("vfs_label", (RString "label", [Device "device"]), 253, [],
5188    [InitBasicFS, Always, TestOutput (
5189        [["set_e2label"; "/dev/sda1"; "LTEST"];
5190         ["vfs_label"; "/dev/sda1"]], "LTEST")],
5191    "get the filesystem label",
5192    "\
5193 This returns the filesystem label of the filesystem on
5194 C<device>.
5195
5196 If the filesystem is unlabeled, this returns the empty string.
5197
5198 To find a filesystem from the label, use C<guestfs_findfs_label>.");
5199
5200   ("vfs_uuid", (RString "uuid", [Device "device"]), 254, [],
5201    (let uuid = uuidgen () in
5202     [InitBasicFS, Always, TestOutput (
5203        [["set_e2uuid"; "/dev/sda1"; uuid];
5204         ["vfs_uuid"; "/dev/sda1"]], uuid)]),
5205    "get the filesystem UUID",
5206    "\
5207 This returns the filesystem UUID of the filesystem on
5208 C<device>.
5209
5210 If the filesystem does not have a UUID, this returns the empty string.
5211
5212 To find a filesystem from the UUID, use C<guestfs_findfs_uuid>.");
5213
5214   ("lvm_set_filter", (RErr, [DeviceList "devices"]), 255, [Optional "lvm2"],
5215    (* Can't be tested with the current framework because
5216     * the VG is being used by the mounted filesystem, so
5217     * the vgchange -an command we do first will fail.
5218     *)
5219     [],
5220    "set LVM device filter",
5221    "\
5222 This sets the LVM device filter so that LVM will only be
5223 able to \"see\" the block devices in the list C<devices>,
5224 and will ignore all other attached block devices.
5225
5226 Where disk image(s) contain duplicate PVs or VGs, this
5227 command is useful to get LVM to ignore the duplicates, otherwise
5228 LVM can get confused.  Note also there are two types
5229 of duplication possible: either cloned PVs/VGs which have
5230 identical UUIDs; or VGs that are not cloned but just happen
5231 to have the same name.  In normal operation you cannot
5232 create this situation, but you can do it outside LVM, eg.
5233 by cloning disk images or by bit twiddling inside the LVM
5234 metadata.
5235
5236 This command also clears the LVM cache and performs a volume
5237 group scan.
5238
5239 You can filter whole block devices or individual partitions.
5240
5241 You cannot use this if any VG is currently in use (eg.
5242 contains a mounted filesystem), even if you are not
5243 filtering out that VG.");
5244
5245   ("lvm_clear_filter", (RErr, []), 256, [],
5246    [], (* see note on lvm_set_filter *)
5247    "clear LVM device filter",
5248    "\
5249 This undoes the effect of C<guestfs_lvm_set_filter>.  LVM
5250 will be able to see every block device.
5251
5252 This command also clears the LVM cache and performs a volume
5253 group scan.");
5254
5255   ("luks_open", (RErr, [Device "device"; Key "key"; String "mapname"]), 257, [Optional "luks"],
5256    [],
5257    "open a LUKS-encrypted block device",
5258    "\
5259 This command opens a block device which has been encrypted
5260 according to the Linux Unified Key Setup (LUKS) standard.
5261
5262 C<device> is the encrypted block device or partition.
5263
5264 The caller must supply one of the keys associated with the
5265 LUKS block device, in the C<key> parameter.
5266
5267 This creates a new block device called C</dev/mapper/mapname>.
5268 Reads and writes to this block device are decrypted from and
5269 encrypted to the underlying C<device> respectively.
5270
5271 If this block device contains LVM volume groups, then
5272 calling C<guestfs_vgscan> followed by C<guestfs_vg_activate_all>
5273 will make them visible.");
5274
5275   ("luks_open_ro", (RErr, [Device "device"; Key "key"; String "mapname"]), 258, [Optional "luks"],
5276    [],
5277    "open a LUKS-encrypted block device read-only",
5278    "\
5279 This is the same as C<guestfs_luks_open> except that a read-only
5280 mapping is created.");
5281
5282   ("luks_close", (RErr, [Device "device"]), 259, [Optional "luks"],
5283    [],
5284    "close a LUKS device",
5285    "\
5286 This closes a LUKS device that was created earlier by
5287 C<guestfs_luks_open> or C<guestfs_luks_open_ro>.  The
5288 C<device> parameter must be the name of the LUKS mapping
5289 device (ie. C</dev/mapper/mapname>) and I<not> the name
5290 of the underlying block device.");
5291
5292   ("luks_format", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 260, [Optional "luks"; DangerWillRobinson],
5293    [],
5294    "format a block device as a LUKS encrypted device",
5295    "\
5296 This command erases existing data on C<device> and formats
5297 the device as a LUKS encrypted device.  C<key> is the
5298 initial key, which is added to key slot C<slot>.  (LUKS
5299 supports 8 key slots, numbered 0-7).");
5300
5301   ("luks_format_cipher", (RErr, [Device "device"; Key "key"; Int "keyslot"; String "cipher"]), 261, [Optional "luks"; DangerWillRobinson],
5302    [],
5303    "format a block device as a LUKS encrypted device",
5304    "\
5305 This command is the same as C<guestfs_luks_format> but
5306 it also allows you to set the C<cipher> used.");
5307
5308   ("luks_add_key", (RErr, [Device "device"; Key "key"; Key "newkey"; Int "keyslot"]), 262, [Optional "luks"],
5309    [],
5310    "add a key on a LUKS encrypted device",
5311    "\
5312 This command adds a new key on LUKS device C<device>.
5313 C<key> is any existing key, and is used to access the device.
5314 C<newkey> is the new key to add.  C<keyslot> is the key slot
5315 that will be replaced.
5316
5317 Note that if C<keyslot> already contains a key, then this
5318 command will fail.  You have to use C<guestfs_luks_kill_slot>
5319 first to remove that key.");
5320
5321   ("luks_kill_slot", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 263, [Optional "luks"],
5322    [],
5323    "remove a key from a LUKS encrypted device",
5324    "\
5325 This command deletes the key in key slot C<keyslot> from the
5326 encrypted LUKS device C<device>.  C<key> must be one of the
5327 I<other> keys.");
5328
5329   ("is_lv", (RBool "lvflag", [Device "device"]), 264, [Optional "lvm2"],
5330    [InitBasicFSonLVM, IfAvailable "lvm2", TestOutputTrue (
5331       [["is_lv"; "/dev/VG/LV"]]);
5332     InitBasicFSonLVM, IfAvailable "lvm2", TestOutputFalse (
5333       [["is_lv"; "/dev/sda1"]])],
5334    "test if device is a logical volume",
5335    "\
5336 This command tests whether C<device> is a logical volume, and
5337 returns true iff this is the case.");
5338
5339   ("findfs_uuid", (RString "device", [String "uuid"]), 265, [],
5340    [],
5341    "find a filesystem by UUID",
5342    "\
5343 This command searches the filesystems and returns the one
5344 which has the given UUID.  An error is returned if no such
5345 filesystem can be found.
5346
5347 To find the UUID of a filesystem, use C<guestfs_vfs_uuid>.");
5348
5349   ("findfs_label", (RString "device", [String "label"]), 266, [],
5350    [],
5351    "find a filesystem by label",
5352    "\
5353 This command searches the filesystems and returns the one
5354 which has the given label.  An error is returned if no such
5355 filesystem can be found.
5356
5357 To find the label of a filesystem, use C<guestfs_vfs_label>.");
5358
5359 ]
5360
5361 let all_functions = non_daemon_functions @ daemon_functions
5362
5363 (* In some places we want the functions to be displayed sorted
5364  * alphabetically, so this is useful:
5365  *)
5366 let all_functions_sorted =
5367   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
5368                compare n1 n2) all_functions
5369
5370 (* This is used to generate the src/MAX_PROC_NR file which
5371  * contains the maximum procedure number, a surrogate for the
5372  * ABI version number.  See src/Makefile.am for the details.
5373  *)
5374 let max_proc_nr =
5375   let proc_nrs = List.map (
5376     fun (_, _, proc_nr, _, _, _, _) -> proc_nr
5377   ) daemon_functions in
5378   List.fold_left max 0 proc_nrs
5379
5380 (* Field types for structures. *)
5381 type field =
5382   | FChar                       (* C 'char' (really, a 7 bit byte). *)
5383   | FString                     (* nul-terminated ASCII string, NOT NULL. *)
5384   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
5385   | FUInt32
5386   | FInt32
5387   | FUInt64
5388   | FInt64
5389   | FBytes                      (* Any int measure that counts bytes. *)
5390   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
5391   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
5392
5393 (* Because we generate extra parsing code for LVM command line tools,
5394  * we have to pull out the LVM columns separately here.
5395  *)
5396 let lvm_pv_cols = [
5397   "pv_name", FString;
5398   "pv_uuid", FUUID;
5399   "pv_fmt", FString;
5400   "pv_size", FBytes;
5401   "dev_size", FBytes;
5402   "pv_free", FBytes;
5403   "pv_used", FBytes;
5404   "pv_attr", FString (* XXX *);
5405   "pv_pe_count", FInt64;
5406   "pv_pe_alloc_count", FInt64;
5407   "pv_tags", FString;
5408   "pe_start", FBytes;
5409   "pv_mda_count", FInt64;
5410   "pv_mda_free", FBytes;
5411   (* Not in Fedora 10:
5412      "pv_mda_size", FBytes;
5413   *)
5414 ]
5415 let lvm_vg_cols = [
5416   "vg_name", FString;
5417   "vg_uuid", FUUID;
5418   "vg_fmt", FString;
5419   "vg_attr", FString (* XXX *);
5420   "vg_size", FBytes;
5421   "vg_free", FBytes;
5422   "vg_sysid", FString;
5423   "vg_extent_size", FBytes;
5424   "vg_extent_count", FInt64;
5425   "vg_free_count", FInt64;
5426   "max_lv", FInt64;
5427   "max_pv", FInt64;
5428   "pv_count", FInt64;
5429   "lv_count", FInt64;
5430   "snap_count", FInt64;
5431   "vg_seqno", FInt64;
5432   "vg_tags", FString;
5433   "vg_mda_count", FInt64;
5434   "vg_mda_free", FBytes;
5435   (* Not in Fedora 10:
5436      "vg_mda_size", FBytes;
5437   *)
5438 ]
5439 let lvm_lv_cols = [
5440   "lv_name", FString;
5441   "lv_uuid", FUUID;
5442   "lv_attr", FString (* XXX *);
5443   "lv_major", FInt64;
5444   "lv_minor", FInt64;
5445   "lv_kernel_major", FInt64;
5446   "lv_kernel_minor", FInt64;
5447   "lv_size", FBytes;
5448   "seg_count", FInt64;
5449   "origin", FString;
5450   "snap_percent", FOptPercent;
5451   "copy_percent", FOptPercent;
5452   "move_pv", FString;
5453   "lv_tags", FString;
5454   "mirror_log", FString;
5455   "modules", FString;
5456 ]
5457
5458 (* Names and fields in all structures (in RStruct and RStructList)
5459  * that we support.
5460  *)
5461 let structs = [
5462   (* The old RIntBool return type, only ever used for aug_defnode.  Do
5463    * not use this struct in any new code.
5464    *)
5465   "int_bool", [
5466     "i", FInt32;                (* for historical compatibility *)
5467     "b", FInt32;                (* for historical compatibility *)
5468   ];
5469
5470   (* LVM PVs, VGs, LVs. *)
5471   "lvm_pv", lvm_pv_cols;
5472   "lvm_vg", lvm_vg_cols;
5473   "lvm_lv", lvm_lv_cols;
5474
5475   (* Column names and types from stat structures.
5476    * NB. Can't use things like 'st_atime' because glibc header files
5477    * define some of these as macros.  Ugh.
5478    *)
5479   "stat", [
5480     "dev", FInt64;
5481     "ino", FInt64;
5482     "mode", FInt64;
5483     "nlink", FInt64;
5484     "uid", FInt64;
5485     "gid", FInt64;
5486     "rdev", FInt64;
5487     "size", FInt64;
5488     "blksize", FInt64;
5489     "blocks", FInt64;
5490     "atime", FInt64;
5491     "mtime", FInt64;
5492     "ctime", FInt64;
5493   ];
5494   "statvfs", [
5495     "bsize", FInt64;
5496     "frsize", FInt64;
5497     "blocks", FInt64;
5498     "bfree", FInt64;
5499     "bavail", FInt64;
5500     "files", FInt64;
5501     "ffree", FInt64;
5502     "favail", FInt64;
5503     "fsid", FInt64;
5504     "flag", FInt64;
5505     "namemax", FInt64;
5506   ];
5507
5508   (* Column names in dirent structure. *)
5509   "dirent", [
5510     "ino", FInt64;
5511     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
5512     "ftyp", FChar;
5513     "name", FString;
5514   ];
5515
5516   (* Version numbers. *)
5517   "version", [
5518     "major", FInt64;
5519     "minor", FInt64;
5520     "release", FInt64;
5521     "extra", FString;
5522   ];
5523
5524   (* Extended attribute. *)
5525   "xattr", [
5526     "attrname", FString;
5527     "attrval", FBuffer;
5528   ];
5529
5530   (* Inotify events. *)
5531   "inotify_event", [
5532     "in_wd", FInt64;
5533     "in_mask", FUInt32;
5534     "in_cookie", FUInt32;
5535     "in_name", FString;
5536   ];
5537
5538   (* Partition table entry. *)
5539   "partition", [
5540     "part_num", FInt32;
5541     "part_start", FBytes;
5542     "part_end", FBytes;
5543     "part_size", FBytes;
5544   ];
5545 ] (* end of structs *)
5546
5547 (* Ugh, Java has to be different ..
5548  * These names are also used by the Haskell bindings.
5549  *)
5550 let java_structs = [
5551   "int_bool", "IntBool";
5552   "lvm_pv", "PV";
5553   "lvm_vg", "VG";
5554   "lvm_lv", "LV";
5555   "stat", "Stat";
5556   "statvfs", "StatVFS";
5557   "dirent", "Dirent";
5558   "version", "Version";
5559   "xattr", "XAttr";
5560   "inotify_event", "INotifyEvent";
5561   "partition", "Partition";
5562 ]
5563
5564 (* What structs are actually returned. *)
5565 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
5566
5567 (* Returns a list of RStruct/RStructList structs that are returned
5568  * by any function.  Each element of returned list is a pair:
5569  *
5570  * (structname, RStructOnly)
5571  *    == there exists function which returns RStruct (_, structname)
5572  * (structname, RStructListOnly)
5573  *    == there exists function which returns RStructList (_, structname)
5574  * (structname, RStructAndList)
5575  *    == there are functions returning both RStruct (_, structname)
5576  *                                      and RStructList (_, structname)
5577  *)
5578 let rstructs_used_by functions =
5579   (* ||| is a "logical OR" for rstructs_used_t *)
5580   let (|||) a b =
5581     match a, b with
5582     | RStructAndList, _
5583     | _, RStructAndList -> RStructAndList
5584     | RStructOnly, RStructListOnly
5585     | RStructListOnly, RStructOnly -> RStructAndList
5586     | RStructOnly, RStructOnly -> RStructOnly
5587     | RStructListOnly, RStructListOnly -> RStructListOnly
5588   in
5589
5590   let h = Hashtbl.create 13 in
5591
5592   (* if elem->oldv exists, update entry using ||| operator,
5593    * else just add elem->newv to the hash
5594    *)
5595   let update elem newv =
5596     try  let oldv = Hashtbl.find h elem in
5597          Hashtbl.replace h elem (newv ||| oldv)
5598     with Not_found -> Hashtbl.add h elem newv
5599   in
5600
5601   List.iter (
5602     fun (_, style, _, _, _, _, _) ->
5603       match fst style with
5604       | RStruct (_, structname) -> update structname RStructOnly
5605       | RStructList (_, structname) -> update structname RStructListOnly
5606       | _ -> ()
5607   ) functions;
5608
5609   (* return key->values as a list of (key,value) *)
5610   Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
5611
5612 (* Used for testing language bindings. *)
5613 type callt =
5614   | CallString of string
5615   | CallOptString of string option
5616   | CallStringList of string list
5617   | CallInt of int
5618   | CallInt64 of int64
5619   | CallBool of bool
5620   | CallBuffer of string
5621
5622 (* Used for the guestfish -N (prepared disk images) option.
5623  * Note that the longdescs are indented by 2 spaces.
5624  *)
5625 let prepopts = [
5626   ("disk",
5627    "create a blank disk",
5628    [ "size", "100M", "the size of the disk image" ],
5629    "  Create a blank disk, size 100MB (by default).
5630
5631   The default size can be changed by supplying an optional parameter.");
5632
5633   ("part",
5634    "create a partitioned disk",
5635    [ "size", "100M", "the size of the disk image";
5636      "partition", "mbr", "partition table type" ],
5637    "  Create a disk with a single partition.  By default the size of the disk
5638   is 100MB (the available space in the partition will be a tiny bit smaller)
5639   and the partition table will be MBR (old DOS-style).
5640
5641   These defaults can be changed by supplying optional parameters.");
5642
5643   ("fs",
5644    "create a filesystem",
5645    [ "filesystem", "ext2", "the type of filesystem to use";
5646      "size", "100M", "the size of the disk image";
5647      "partition", "mbr", "partition table type" ],
5648    "  Create a disk with a single partition, with the partition containing
5649   an empty filesystem.  This defaults to creating a 100MB disk (the available
5650   space in the filesystem will be a tiny bit smaller) with an MBR (old
5651   DOS-style) partition table and an ext2 filesystem.
5652
5653   These defaults can be changed by supplying optional parameters.");
5654
5655   ("lv",
5656    "create a disk with logical volume",
5657    [ "name", "/dev/VG/LV", "the name of the VG and LV to use";
5658      "size", "100M", "the size of the disk image";
5659      "partition", "mbr", "partition table type" ],
5660    "  Create a disk with a single partition, set up the partition as an
5661   LVM2 physical volume, and place a volume group and logical volume
5662   on there.  This defaults to creating a 100MB disk with the VG and
5663   LV called /dev/VG/LV.  You can change the name of the VG and LV
5664   by supplying an alternate name as the first optional parameter.
5665
5666   Note this does not create a filesystem.  Use 'lvfs' to do that.");
5667
5668   ("lvfs",
5669    "create a disk with logical volume and filesystem",
5670    [ "name", "/dev/VG/LV", "the name of the VG and LV to use";
5671      "filesystem", "ext2", "the type of filesystem to use";
5672      "size", "100M", "the size of the disk image";
5673      "partition", "mbr", "partition table type" ],
5674    "  Create a disk with a single partition, set up the partition as an
5675   LVM2 physical volume, and place a volume group and logical volume
5676   on there.  Then format the LV with a filesystem.  This defaults to
5677   creating a 100MB disk with the VG and LV called /dev/VG/LV, with an
5678   ext2 filesystem.");
5679
5680 ]
5681
5682 (* Used to memoize the result of pod2text. *)
5683 let pod2text_memo_filename = "src/.pod2text.data"
5684 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
5685   try
5686     let chan = open_in pod2text_memo_filename in
5687     let v = input_value chan in
5688     close_in chan;
5689     v
5690   with
5691     _ -> Hashtbl.create 13
5692 let pod2text_memo_updated () =
5693   let chan = open_out pod2text_memo_filename in
5694   output_value chan pod2text_memo;
5695   close_out chan
5696
5697 (* Useful functions.
5698  * Note we don't want to use any external OCaml libraries which
5699  * makes this a bit harder than it should be.
5700  *)
5701 module StringMap = Map.Make (String)
5702
5703 let failwithf fs = ksprintf failwith fs
5704
5705 let unique = let i = ref 0 in fun () -> incr i; !i
5706
5707 let replace_char s c1 c2 =
5708   let s2 = String.copy s in
5709   let r = ref false in
5710   for i = 0 to String.length s2 - 1 do
5711     if String.unsafe_get s2 i = c1 then (
5712       String.unsafe_set s2 i c2;
5713       r := true
5714     )
5715   done;
5716   if not !r then s else s2
5717
5718 let isspace c =
5719   c = ' '
5720   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
5721
5722 let triml ?(test = isspace) str =
5723   let i = ref 0 in
5724   let n = ref (String.length str) in
5725   while !n > 0 && test str.[!i]; do
5726     decr n;
5727     incr i
5728   done;
5729   if !i = 0 then str
5730   else String.sub str !i !n
5731
5732 let trimr ?(test = isspace) str =
5733   let n = ref (String.length str) in
5734   while !n > 0 && test str.[!n-1]; do
5735     decr n
5736   done;
5737   if !n = String.length str then str
5738   else String.sub str 0 !n
5739
5740 let trim ?(test = isspace) str =
5741   trimr ~test (triml ~test str)
5742
5743 let rec find s sub =
5744   let len = String.length s in
5745   let sublen = String.length sub in
5746   let rec loop i =
5747     if i <= len-sublen then (
5748       let rec loop2 j =
5749         if j < sublen then (
5750           if s.[i+j] = sub.[j] then loop2 (j+1)
5751           else -1
5752         ) else
5753           i (* found *)
5754       in
5755       let r = loop2 0 in
5756       if r = -1 then loop (i+1) else r
5757     ) else
5758       -1 (* not found *)
5759   in
5760   loop 0
5761
5762 let rec replace_str s s1 s2 =
5763   let len = String.length s in
5764   let sublen = String.length s1 in
5765   let i = find s s1 in
5766   if i = -1 then s
5767   else (
5768     let s' = String.sub s 0 i in
5769     let s'' = String.sub s (i+sublen) (len-i-sublen) in
5770     s' ^ s2 ^ replace_str s'' s1 s2
5771   )
5772
5773 let rec string_split sep str =
5774   let len = String.length str in
5775   let seplen = String.length sep in
5776   let i = find str sep in
5777   if i = -1 then [str]
5778   else (
5779     let s' = String.sub str 0 i in
5780     let s'' = String.sub str (i+seplen) (len-i-seplen) in
5781     s' :: string_split sep s''
5782   )
5783
5784 let files_equal n1 n2 =
5785   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
5786   match Sys.command cmd with
5787   | 0 -> true
5788   | 1 -> false
5789   | i -> failwithf "%s: failed with error code %d" cmd i
5790
5791 let rec filter_map f = function
5792   | [] -> []
5793   | x :: xs ->
5794       match f x with
5795       | Some y -> y :: filter_map f xs
5796       | None -> filter_map f xs
5797
5798 let rec find_map f = function
5799   | [] -> raise Not_found
5800   | x :: xs ->
5801       match f x with
5802       | Some y -> y
5803       | None -> find_map f xs
5804
5805 let iteri f xs =
5806   let rec loop i = function
5807     | [] -> ()
5808     | x :: xs -> f i x; loop (i+1) xs
5809   in
5810   loop 0 xs
5811
5812 let mapi f xs =
5813   let rec loop i = function
5814     | [] -> []
5815     | x :: xs -> let r = f i x in r :: loop (i+1) xs
5816   in
5817   loop 0 xs
5818
5819 let count_chars c str =
5820   let count = ref 0 in
5821   for i = 0 to String.length str - 1 do
5822     if c = String.unsafe_get str i then incr count
5823   done;
5824   !count
5825
5826 let explode str =
5827   let r = ref [] in
5828   for i = 0 to String.length str - 1 do
5829     let c = String.unsafe_get str i in
5830     r := c :: !r;
5831   done;
5832   List.rev !r
5833
5834 let map_chars f str =
5835   List.map f (explode str)
5836
5837 let name_of_argt = function
5838   | Pathname n | Device n | Dev_or_Path n | String n | OptString n
5839   | StringList n | DeviceList n | Bool n | Int n | Int64 n
5840   | FileIn n | FileOut n | BufferIn n | Key n -> n
5841
5842 let java_name_of_struct typ =
5843   try List.assoc typ java_structs
5844   with Not_found ->
5845     failwithf
5846       "java_name_of_struct: no java_structs entry corresponding to %s" typ
5847
5848 let cols_of_struct typ =
5849   try List.assoc typ structs
5850   with Not_found ->
5851     failwithf "cols_of_struct: unknown struct %s" typ
5852
5853 let seq_of_test = function
5854   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
5855   | TestOutputListOfDevices (s, _)
5856   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
5857   | TestOutputTrue s | TestOutputFalse s
5858   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
5859   | TestOutputStruct (s, _)
5860   | TestLastFail s -> s
5861
5862 (* Handling for function flags. *)
5863 let progress_message =
5864   "This long-running command can generate progress notification messages
5865 so that the caller can display a progress bar or indicator.
5866 To receive these messages, the caller must register a progress
5867 callback.  See L<guestfs(3)/guestfs_set_progress_callback>."
5868
5869 let protocol_limit_warning =
5870   "Because of the message protocol, there is a transfer limit
5871 of somewhere between 2MB and 4MB.  See L<guestfs(3)/PROTOCOL LIMITS>."
5872
5873 let danger_will_robinson =
5874   "B<This command is dangerous.  Without careful use you
5875 can easily destroy all your data>."
5876
5877 let deprecation_notice flags =
5878   try
5879     let alt =
5880       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
5881     let txt =
5882       sprintf "This function is deprecated.
5883 In new code, use the C<%s> call instead.
5884
5885 Deprecated functions will not be removed from the API, but the
5886 fact that they are deprecated indicates that there are problems
5887 with correct use of these functions." alt in
5888     Some txt
5889   with
5890     Not_found -> None
5891
5892 (* Create list of optional groups. *)
5893 let optgroups =
5894   let h = Hashtbl.create 13 in
5895   List.iter (
5896     fun (name, _, _, flags, _, _, _) ->
5897       List.iter (
5898         function
5899         | Optional group ->
5900             let names = try Hashtbl.find h group with Not_found -> [] in
5901             Hashtbl.replace h group (name :: names)
5902         | _ -> ()
5903       ) flags
5904   ) daemon_functions;
5905   let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
5906   let groups =
5907     List.map (
5908       fun group -> group, List.sort compare (Hashtbl.find h group)
5909     ) groups in
5910   List.sort (fun x y -> compare (fst x) (fst y)) groups
5911
5912 (* Check function names etc. for consistency. *)
5913 let check_functions () =
5914   let contains_uppercase str =
5915     let len = String.length str in
5916     let rec loop i =
5917       if i >= len then false
5918       else (
5919         let c = str.[i] in
5920         if c >= 'A' && c <= 'Z' then true
5921         else loop (i+1)
5922       )
5923     in
5924     loop 0
5925   in
5926
5927   (* Check function names. *)
5928   List.iter (
5929     fun (name, _, _, _, _, _, _) ->
5930       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
5931         failwithf "function name %s does not need 'guestfs' prefix" name;
5932       if name = "" then
5933         failwithf "function name is empty";
5934       if name.[0] < 'a' || name.[0] > 'z' then
5935         failwithf "function name %s must start with lowercase a-z" name;
5936       if String.contains name '-' then
5937         failwithf "function name %s should not contain '-', use '_' instead."
5938           name
5939   ) all_functions;
5940
5941   (* Check function parameter/return names. *)
5942   List.iter (
5943     fun (name, style, _, _, _, _, _) ->
5944       let check_arg_ret_name n =
5945         if contains_uppercase n then
5946           failwithf "%s param/ret %s should not contain uppercase chars"
5947             name n;
5948         if String.contains n '-' || String.contains n '_' then
5949           failwithf "%s param/ret %s should not contain '-' or '_'"
5950             name n;
5951         if n = "value" then
5952           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;
5953         if n = "int" || n = "char" || n = "short" || n = "long" then
5954           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
5955         if n = "i" || n = "n" then
5956           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
5957         if n = "argv" || n = "args" then
5958           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
5959
5960         (* List Haskell, OCaml and C keywords here.
5961          * http://www.haskell.org/haskellwiki/Keywords
5962          * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
5963          * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
5964          * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
5965          *   |perl -pe 's/(.+)/"$1";/'|fmt -70
5966          * Omitting _-containing words, since they're handled above.
5967          * Omitting the OCaml reserved word, "val", is ok,
5968          * and saves us from renaming several parameters.
5969          *)
5970         let reserved = [
5971           "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
5972           "char"; "class"; "const"; "constraint"; "continue"; "data";
5973           "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
5974           "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
5975           "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
5976           "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
5977           "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
5978           "interface";
5979           "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
5980           "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
5981           "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
5982           "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
5983           "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
5984           "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
5985           "volatile"; "when"; "where"; "while";
5986           ] in
5987         if List.mem n reserved then
5988           failwithf "%s has param/ret using reserved word %s" name n;
5989       in
5990
5991       (match fst style with
5992        | RErr -> ()
5993        | RInt n | RInt64 n | RBool n
5994        | RConstString n | RConstOptString n | RString n
5995        | RStringList n | RStruct (n, _) | RStructList (n, _)
5996        | RHashtable n | RBufferOut n ->
5997            check_arg_ret_name n
5998       );
5999       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
6000   ) all_functions;
6001
6002   (* Check short descriptions. *)
6003   List.iter (
6004     fun (name, _, _, _, _, shortdesc, _) ->
6005       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
6006         failwithf "short description of %s should begin with lowercase." name;
6007       let c = shortdesc.[String.length shortdesc-1] in
6008       if c = '\n' || c = '.' then
6009         failwithf "short description of %s should not end with . or \\n." name
6010   ) all_functions;
6011
6012   (* Check long descriptions. *)
6013   List.iter (
6014     fun (name, _, _, _, _, _, longdesc) ->
6015       if longdesc.[String.length longdesc-1] = '\n' then
6016         failwithf "long description of %s should not end with \\n." name
6017   ) all_functions;
6018
6019   (* Check proc_nrs. *)
6020   List.iter (
6021     fun (name, _, proc_nr, _, _, _, _) ->
6022       if proc_nr <= 0 then
6023         failwithf "daemon function %s should have proc_nr > 0" name
6024   ) daemon_functions;
6025
6026   List.iter (
6027     fun (name, _, proc_nr, _, _, _, _) ->
6028       if proc_nr <> -1 then
6029         failwithf "non-daemon function %s should have proc_nr -1" name
6030   ) non_daemon_functions;
6031
6032   let proc_nrs =
6033     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
6034       daemon_functions in
6035   let proc_nrs =
6036     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
6037   let rec loop = function
6038     | [] -> ()
6039     | [_] -> ()
6040     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
6041         loop rest
6042     | (name1,nr1) :: (name2,nr2) :: _ ->
6043         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
6044           name1 name2 nr1 nr2
6045   in
6046   loop proc_nrs;
6047
6048   (* Check tests. *)
6049   List.iter (
6050     function
6051       (* Ignore functions that have no tests.  We generate a
6052        * warning when the user does 'make check' instead.
6053        *)
6054     | name, _, _, _, [], _, _ -> ()
6055     | name, _, _, _, tests, _, _ ->
6056         let funcs =
6057           List.map (
6058             fun (_, _, test) ->
6059               match seq_of_test test with
6060               | [] ->
6061                   failwithf "%s has a test containing an empty sequence" name
6062               | cmds -> List.map List.hd cmds
6063           ) tests in
6064         let funcs = List.flatten funcs in
6065
6066         let tested = List.mem name funcs in
6067
6068         if not tested then
6069           failwithf "function %s has tests but does not test itself" name
6070   ) all_functions
6071
6072 (* 'pr' prints to the current output file. *)
6073 let chan = ref Pervasives.stdout
6074 let lines = ref 0
6075 let pr fs =
6076   ksprintf
6077     (fun str ->
6078        let i = count_chars '\n' str in
6079        lines := !lines + i;
6080        output_string !chan str
6081     ) fs
6082
6083 let copyright_years =
6084   let this_year = 1900 + (localtime (time ())).tm_year in
6085   if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
6086
6087 (* Generate a header block in a number of standard styles. *)
6088 type comment_style =
6089     CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
6090 type license = GPLv2plus | LGPLv2plus
6091
6092 let generate_header ?(extra_inputs = []) comment license =
6093   let inputs = "src/generator.ml" :: extra_inputs in
6094   let c = match comment with
6095     | CStyle ->         pr "/* "; " *"
6096     | CPlusPlusStyle -> pr "// "; "//"
6097     | HashStyle ->      pr "# ";  "#"
6098     | OCamlStyle ->     pr "(* "; " *"
6099     | HaskellStyle ->   pr "{- "; "  " in
6100   pr "libguestfs generated file\n";
6101   pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
6102   List.iter (pr "%s   %s\n" c) inputs;
6103   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
6104   pr "%s\n" c;
6105   pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
6106   pr "%s\n" c;
6107   (match license with
6108    | GPLv2plus ->
6109        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
6110        pr "%s it under the terms of the GNU General Public License as published by\n" c;
6111        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
6112        pr "%s (at your option) any later version.\n" c;
6113        pr "%s\n" c;
6114        pr "%s This program is distributed in the hope that it will be useful,\n" c;
6115        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6116        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
6117        pr "%s GNU General Public License for more details.\n" c;
6118        pr "%s\n" c;
6119        pr "%s You should have received a copy of the GNU General Public License along\n" c;
6120        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
6121        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
6122
6123    | LGPLv2plus ->
6124        pr "%s This library is free software; you can redistribute it and/or\n" c;
6125        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
6126        pr "%s License as published by the Free Software Foundation; either\n" c;
6127        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
6128        pr "%s\n" c;
6129        pr "%s This library is distributed in the hope that it will be useful,\n" c;
6130        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6131        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
6132        pr "%s Lesser General Public License for more details.\n" c;
6133        pr "%s\n" c;
6134        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
6135        pr "%s License along with this library; if not, write to the Free Software\n" c;
6136        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
6137   );
6138   (match comment with
6139    | CStyle -> pr " */\n"
6140    | CPlusPlusStyle
6141    | HashStyle -> ()
6142    | OCamlStyle -> pr " *)\n"
6143    | HaskellStyle -> pr "-}\n"
6144   );
6145   pr "\n"
6146
6147 (* Start of main code generation functions below this line. *)
6148
6149 (* Generate the pod documentation for the C API. *)
6150 let rec generate_actions_pod () =
6151   List.iter (
6152     fun (shortname, style, _, flags, _, _, longdesc) ->
6153       if not (List.mem NotInDocs flags) then (
6154         let name = "guestfs_" ^ shortname in
6155         pr "=head2 %s\n\n" name;
6156         pr " ";
6157         generate_prototype ~extern:false ~handle:"g" name style;
6158         pr "\n\n";
6159         pr "%s\n\n" longdesc;
6160         (match fst style with
6161          | RErr ->
6162              pr "This function returns 0 on success or -1 on error.\n\n"
6163          | RInt _ ->
6164              pr "On error this function returns -1.\n\n"
6165          | RInt64 _ ->
6166              pr "On error this function returns -1.\n\n"
6167          | RBool _ ->
6168              pr "This function returns a C truth value on success or -1 on error.\n\n"
6169          | RConstString _ ->
6170              pr "This function returns a string, or NULL on error.
6171 The string is owned by the guest handle and must I<not> be freed.\n\n"
6172          | RConstOptString _ ->
6173              pr "This function returns a string which may be NULL.
6174 There is no way to return an error from this function.
6175 The string is owned by the guest handle and must I<not> be freed.\n\n"
6176          | RString _ ->
6177              pr "This function returns a string, or NULL on error.
6178 I<The caller must free the returned string after use>.\n\n"
6179          | RStringList _ ->
6180              pr "This function returns a NULL-terminated array of strings
6181 (like L<environ(3)>), or NULL if there was an error.
6182 I<The caller must free the strings and the array after use>.\n\n"
6183          | RStruct (_, typ) ->
6184              pr "This function returns a C<struct guestfs_%s *>,
6185 or NULL if there was an error.
6186 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
6187          | RStructList (_, typ) ->
6188              pr "This function returns a C<struct guestfs_%s_list *>
6189 (see E<lt>guestfs-structs.hE<gt>),
6190 or NULL if there was an error.
6191 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
6192          | RHashtable _ ->
6193              pr "This function returns a NULL-terminated array of
6194 strings, or NULL if there was an error.
6195 The array of strings will always have length C<2n+1>, where
6196 C<n> keys and values alternate, followed by the trailing NULL entry.
6197 I<The caller must free the strings and the array after use>.\n\n"
6198          | RBufferOut _ ->
6199              pr "This function returns a buffer, or NULL on error.
6200 The size of the returned buffer is written to C<*size_r>.
6201 I<The caller must free the returned buffer after use>.\n\n"
6202         );
6203         if List.mem Progress flags then
6204           pr "%s\n\n" progress_message;
6205         if List.mem ProtocolLimitWarning flags then
6206           pr "%s\n\n" protocol_limit_warning;
6207         if List.mem DangerWillRobinson flags then
6208           pr "%s\n\n" danger_will_robinson;
6209         if List.exists (function Key _ -> true | _ -> false) (snd style) then
6210           pr "This function takes a key or passphrase parameter which
6211 could contain sensitive material.  Read the section
6212 L</KEYS AND PASSPHRASES> for more information.\n\n";
6213         match deprecation_notice flags with
6214         | None -> ()
6215         | Some txt -> pr "%s\n\n" txt
6216       )
6217   ) all_functions_sorted
6218
6219 and generate_structs_pod () =
6220   (* Structs documentation. *)
6221   List.iter (
6222     fun (typ, cols) ->
6223       pr "=head2 guestfs_%s\n" typ;
6224       pr "\n";
6225       pr " struct guestfs_%s {\n" typ;
6226       List.iter (
6227         function
6228         | name, FChar -> pr "   char %s;\n" name
6229         | name, FUInt32 -> pr "   uint32_t %s;\n" name
6230         | name, FInt32 -> pr "   int32_t %s;\n" name
6231         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
6232         | name, FInt64 -> pr "   int64_t %s;\n" name
6233         | name, FString -> pr "   char *%s;\n" name
6234         | name, FBuffer ->
6235             pr "   /* The next two fields describe a byte array. */\n";
6236             pr "   uint32_t %s_len;\n" name;
6237             pr "   char *%s;\n" name
6238         | name, FUUID ->
6239             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
6240             pr "   char %s[32];\n" name
6241         | name, FOptPercent ->
6242             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
6243             pr "   float %s;\n" name
6244       ) cols;
6245       pr " };\n";
6246       pr " \n";
6247       pr " struct guestfs_%s_list {\n" typ;
6248       pr "   uint32_t len; /* Number of elements in list. */\n";
6249       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
6250       pr " };\n";
6251       pr " \n";
6252       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
6253       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
6254         typ typ;
6255       pr "\n"
6256   ) structs
6257
6258 and generate_availability_pod () =
6259   (* Availability documentation. *)
6260   pr "=over 4\n";
6261   pr "\n";
6262   List.iter (
6263     fun (group, functions) ->
6264       pr "=item B<%s>\n" group;
6265       pr "\n";
6266       pr "The following functions:\n";
6267       List.iter (pr "L</guestfs_%s>\n") functions;
6268       pr "\n"
6269   ) optgroups;
6270   pr "=back\n";
6271   pr "\n"
6272
6273 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
6274  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
6275  *
6276  * We have to use an underscore instead of a dash because otherwise
6277  * rpcgen generates incorrect code.
6278  *
6279  * This header is NOT exported to clients, but see also generate_structs_h.
6280  *)
6281 and generate_xdr () =
6282   generate_header CStyle LGPLv2plus;
6283
6284   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
6285   pr "typedef string guestfs_str<>;\n";
6286   pr "\n";
6287
6288   (* Internal structures. *)
6289   List.iter (
6290     function
6291     | typ, cols ->
6292         pr "struct guestfs_int_%s {\n" typ;
6293         List.iter (function
6294                    | name, FChar -> pr "  char %s;\n" name
6295                    | name, FString -> pr "  string %s<>;\n" name
6296                    | name, FBuffer -> pr "  opaque %s<>;\n" name
6297                    | name, FUUID -> pr "  opaque %s[32];\n" name
6298                    | name, (FInt32|FUInt32) -> pr "  int %s;\n" name
6299                    | name, (FInt64|FUInt64|FBytes) -> pr "  hyper %s;\n" name
6300                    | name, FOptPercent -> pr "  float %s;\n" name
6301                   ) cols;
6302         pr "};\n";
6303         pr "\n";
6304         pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
6305         pr "\n";
6306   ) structs;
6307
6308   List.iter (
6309     fun (shortname, style, _, _, _, _, _) ->
6310       let name = "guestfs_" ^ shortname in
6311
6312       (match snd style with
6313        | [] -> ()
6314        | args ->
6315            pr "struct %s_args {\n" name;
6316            List.iter (
6317              function
6318              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6319                  pr "  string %s<>;\n" n
6320              | OptString n -> pr "  guestfs_str *%s;\n" n
6321              | StringList n | DeviceList n -> pr "  guestfs_str %s<>;\n" n
6322              | Bool n -> pr "  bool %s;\n" n
6323              | Int n -> pr "  int %s;\n" n
6324              | Int64 n -> pr "  hyper %s;\n" n
6325              | BufferIn n ->
6326                  pr "  opaque %s<>;\n" n
6327              | FileIn _ | FileOut _ -> ()
6328            ) args;
6329            pr "};\n\n"
6330       );
6331       (match fst style with
6332        | RErr -> ()
6333        | RInt n ->
6334            pr "struct %s_ret {\n" name;
6335            pr "  int %s;\n" n;
6336            pr "};\n\n"
6337        | RInt64 n ->
6338            pr "struct %s_ret {\n" name;
6339            pr "  hyper %s;\n" n;
6340            pr "};\n\n"
6341        | RBool n ->
6342            pr "struct %s_ret {\n" name;
6343            pr "  bool %s;\n" n;
6344            pr "};\n\n"
6345        | RConstString _ | RConstOptString _ ->
6346            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6347        | RString n ->
6348            pr "struct %s_ret {\n" name;
6349            pr "  string %s<>;\n" n;
6350            pr "};\n\n"
6351        | RStringList n ->
6352            pr "struct %s_ret {\n" name;
6353            pr "  guestfs_str %s<>;\n" n;
6354            pr "};\n\n"
6355        | RStruct (n, typ) ->
6356            pr "struct %s_ret {\n" name;
6357            pr "  guestfs_int_%s %s;\n" typ n;
6358            pr "};\n\n"
6359        | RStructList (n, typ) ->
6360            pr "struct %s_ret {\n" name;
6361            pr "  guestfs_int_%s_list %s;\n" typ n;
6362            pr "};\n\n"
6363        | RHashtable n ->
6364            pr "struct %s_ret {\n" name;
6365            pr "  guestfs_str %s<>;\n" n;
6366            pr "};\n\n"
6367        | RBufferOut n ->
6368            pr "struct %s_ret {\n" name;
6369            pr "  opaque %s<>;\n" n;
6370            pr "};\n\n"
6371       );
6372   ) daemon_functions;
6373
6374   (* Table of procedure numbers. *)
6375   pr "enum guestfs_procedure {\n";
6376   List.iter (
6377     fun (shortname, _, proc_nr, _, _, _, _) ->
6378       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
6379   ) daemon_functions;
6380   pr "  GUESTFS_PROC_NR_PROCS\n";
6381   pr "};\n";
6382   pr "\n";
6383
6384   (* Having to choose a maximum message size is annoying for several
6385    * reasons (it limits what we can do in the API), but it (a) makes
6386    * the protocol a lot simpler, and (b) provides a bound on the size
6387    * of the daemon which operates in limited memory space.
6388    *)
6389   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
6390   pr "\n";
6391
6392   (* Message header, etc. *)
6393   pr "\
6394 /* The communication protocol is now documented in the guestfs(3)
6395  * manpage.
6396  */
6397
6398 const GUESTFS_PROGRAM = 0x2000F5F5;
6399 const GUESTFS_PROTOCOL_VERSION = 2;
6400
6401 /* These constants must be larger than any possible message length. */
6402 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
6403 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
6404 const GUESTFS_PROGRESS_FLAG = 0xffff5555;
6405
6406 enum guestfs_message_direction {
6407   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
6408   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
6409 };
6410
6411 enum guestfs_message_status {
6412   GUESTFS_STATUS_OK = 0,
6413   GUESTFS_STATUS_ERROR = 1
6414 };
6415
6416 ";
6417
6418   pr "const GUESTFS_ERROR_LEN = %d;\n" (64 * 1024);
6419   pr "\n";
6420
6421   pr "\
6422 struct guestfs_message_error {
6423   int linux_errno;                   /* Linux errno if available. */
6424   string error_message<GUESTFS_ERROR_LEN>;
6425 };
6426
6427 struct guestfs_message_header {
6428   unsigned prog;                     /* GUESTFS_PROGRAM */
6429   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
6430   guestfs_procedure proc;            /* GUESTFS_PROC_x */
6431   guestfs_message_direction direction;
6432   unsigned serial;                   /* message serial number */
6433   guestfs_message_status status;
6434 };
6435
6436 const GUESTFS_MAX_CHUNK_SIZE = 8192;
6437
6438 struct guestfs_chunk {
6439   int cancel;                        /* if non-zero, transfer is cancelled */
6440   /* data size is 0 bytes if the transfer has finished successfully */
6441   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
6442 };
6443
6444 /* Progress notifications.  Daemon self-limits these messages to
6445  * at most one per second.  The daemon can send these messages
6446  * at any time, and the caller should discard unexpected messages.
6447  * 'position' and 'total' have undefined units; however they may
6448  * have meaning for some calls.
6449  *
6450  * NB. guestfs___recv_from_daemon assumes the XDR-encoded
6451  * structure is 24 bytes long.
6452  */
6453 struct guestfs_progress {
6454   guestfs_procedure proc;            /* @0:  GUESTFS_PROC_x */
6455   unsigned serial;                   /* @4:  message serial number */
6456   unsigned hyper position;           /* @8:  0 <= position <= total */
6457   unsigned hyper total;              /* @16: total size of operation */
6458                                      /* @24: size of structure */
6459 };
6460 "
6461
6462 (* Generate the guestfs-structs.h file. *)
6463 and generate_structs_h () =
6464   generate_header CStyle LGPLv2plus;
6465
6466   (* This is a public exported header file containing various
6467    * structures.  The structures are carefully written to have
6468    * exactly the same in-memory format as the XDR structures that
6469    * we use on the wire to the daemon.  The reason for creating
6470    * copies of these structures here is just so we don't have to
6471    * export the whole of guestfs_protocol.h (which includes much
6472    * unrelated and XDR-dependent stuff that we don't want to be
6473    * public, or required by clients).
6474    *
6475    * To reiterate, we will pass these structures to and from the
6476    * client with a simple assignment or memcpy, so the format
6477    * must be identical to what rpcgen / the RFC defines.
6478    *)
6479
6480   (* Public structures. *)
6481   List.iter (
6482     fun (typ, cols) ->
6483       pr "struct guestfs_%s {\n" typ;
6484       List.iter (
6485         function
6486         | name, FChar -> pr "  char %s;\n" name
6487         | name, FString -> pr "  char *%s;\n" name
6488         | name, FBuffer ->
6489             pr "  uint32_t %s_len;\n" name;
6490             pr "  char *%s;\n" name
6491         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
6492         | name, FUInt32 -> pr "  uint32_t %s;\n" name
6493         | name, FInt32 -> pr "  int32_t %s;\n" name
6494         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
6495         | name, FInt64 -> pr "  int64_t %s;\n" name
6496         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
6497       ) cols;
6498       pr "};\n";
6499       pr "\n";
6500       pr "struct guestfs_%s_list {\n" typ;
6501       pr "  uint32_t len;\n";
6502       pr "  struct guestfs_%s *val;\n" typ;
6503       pr "};\n";
6504       pr "\n";
6505       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
6506       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
6507       pr "\n"
6508   ) structs
6509
6510 (* Generate the guestfs-actions.h file. *)
6511 and generate_actions_h () =
6512   generate_header CStyle LGPLv2plus;
6513   List.iter (
6514     fun (shortname, style, _, flags, _, _, _) ->
6515       let name = "guestfs_" ^ shortname in
6516
6517       let deprecated =
6518         List.exists (function DeprecatedBy _ -> true | _ -> false) flags in
6519       let test0 =
6520         String.length shortname >= 5 && String.sub shortname 0 5 = "test0" in
6521       let debug =
6522         String.length shortname >= 5 && String.sub shortname 0 5 = "debug" in
6523       if not deprecated && not test0 && not debug then
6524         pr "#define LIBGUESTFS_HAVE_%s 1\n" (String.uppercase shortname);
6525
6526       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6527         name style
6528   ) all_functions_sorted
6529
6530 (* Generate the guestfs-internal-actions.h file. *)
6531 and generate_internal_actions_h () =
6532   generate_header CStyle LGPLv2plus;
6533   List.iter (
6534     fun (shortname, style, _, _, _, _, _) ->
6535       let name = "guestfs__" ^ shortname in
6536       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6537         name style
6538   ) non_daemon_functions
6539
6540 (* Generate the client-side dispatch stubs. *)
6541 and generate_client_actions () =
6542   generate_header CStyle LGPLv2plus;
6543
6544   pr "\
6545 #include <stdio.h>
6546 #include <stdlib.h>
6547 #include <stdint.h>
6548 #include <string.h>
6549 #include <inttypes.h>
6550
6551 #include \"guestfs.h\"
6552 #include \"guestfs-internal.h\"
6553 #include \"guestfs-internal-actions.h\"
6554 #include \"guestfs_protocol.h\"
6555
6556 /* Check the return message from a call for validity. */
6557 static int
6558 check_reply_header (guestfs_h *g,
6559                     const struct guestfs_message_header *hdr,
6560                     unsigned int proc_nr, unsigned int serial)
6561 {
6562   if (hdr->prog != GUESTFS_PROGRAM) {
6563     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
6564     return -1;
6565   }
6566   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
6567     error (g, \"wrong protocol version (%%d/%%d)\",
6568            hdr->vers, GUESTFS_PROTOCOL_VERSION);
6569     return -1;
6570   }
6571   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
6572     error (g, \"unexpected message direction (%%d/%%d)\",
6573            hdr->direction, GUESTFS_DIRECTION_REPLY);
6574     return -1;
6575   }
6576   if (hdr->proc != proc_nr) {
6577     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
6578     return -1;
6579   }
6580   if (hdr->serial != serial) {
6581     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
6582     return -1;
6583   }
6584
6585   return 0;
6586 }
6587
6588 /* Check we are in the right state to run a high-level action. */
6589 static int
6590 check_state (guestfs_h *g, const char *caller)
6591 {
6592   if (!guestfs__is_ready (g)) {
6593     if (guestfs__is_config (g) || guestfs__is_launching (g))
6594       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
6595         caller);
6596     else
6597       error (g, \"%%s called from the wrong state, %%d != READY\",
6598         caller, guestfs__get_state (g));
6599     return -1;
6600   }
6601   return 0;
6602 }
6603
6604 ";
6605
6606   let error_code_of = function
6607     | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
6608     | RConstString _ | RConstOptString _
6609     | RString _ | RStringList _
6610     | RStruct _ | RStructList _
6611     | RHashtable _ | RBufferOut _ -> "NULL"
6612   in
6613
6614   (* Generate code to check String-like parameters are not passed in
6615    * as NULL (returning an error if they are).
6616    *)
6617   let check_null_strings shortname style =
6618     let pr_newline = ref false in
6619     List.iter (
6620       function
6621       (* parameters which should not be NULL *)
6622       | String n
6623       | Device n
6624       | Pathname n
6625       | Dev_or_Path n
6626       | FileIn n
6627       | FileOut n
6628       | BufferIn n
6629       | StringList n
6630       | DeviceList n
6631       | Key n ->
6632           pr "  if (%s == NULL) {\n" n;
6633           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
6634           pr "           \"%s\", \"%s\");\n" shortname n;
6635           pr "    return %s;\n" (error_code_of (fst style));
6636           pr "  }\n";
6637           pr_newline := true
6638
6639       (* can be NULL *)
6640       | OptString _
6641
6642       (* not applicable *)
6643       | Bool _
6644       | Int _
6645       | Int64 _ -> ()
6646     ) (snd style);
6647
6648     if !pr_newline then pr "\n";
6649   in
6650
6651   (* Generate code to generate guestfish call traces. *)
6652   let trace_call shortname style =
6653     pr "  if (guestfs__get_trace (g)) {\n";
6654
6655     let needs_i =
6656       List.exists (function
6657                    | StringList _ | DeviceList _ -> true
6658                    | _ -> false) (snd style) in
6659     if needs_i then (
6660       pr "    size_t i;\n";
6661       pr "\n"
6662     );
6663
6664     pr "    fprintf (stderr, \"%s\");\n" shortname;
6665     List.iter (
6666       function
6667       | String n                        (* strings *)
6668       | Device n
6669       | Pathname n
6670       | Dev_or_Path n
6671       | FileIn n
6672       | FileOut n
6673       | BufferIn n
6674       | Key n ->
6675           (* guestfish doesn't support string escaping, so neither do we *)
6676           pr "    fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
6677       | OptString n ->                  (* string option *)
6678           pr "    if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
6679           pr "    else fprintf (stderr, \" null\");\n"
6680       | StringList n
6681       | DeviceList n ->                 (* string list *)
6682           pr "    fputc (' ', stderr);\n";
6683           pr "    fputc ('\"', stderr);\n";
6684           pr "    for (i = 0; %s[i]; ++i) {\n" n;
6685           pr "      if (i > 0) fputc (' ', stderr);\n";
6686           pr "      fputs (%s[i], stderr);\n" n;
6687           pr "    }\n";
6688           pr "    fputc ('\"', stderr);\n";
6689       | Bool n ->                       (* boolean *)
6690           pr "    fputs (%s ? \" true\" : \" false\", stderr);\n" n
6691       | Int n ->                        (* int *)
6692           pr "    fprintf (stderr, \" %%d\", %s);\n" n
6693       | Int64 n ->
6694           pr "    fprintf (stderr, \" %%\" PRIi64, %s);\n" n
6695     ) (snd style);
6696     pr "    fputc ('\\n', stderr);\n";
6697     pr "  }\n";
6698     pr "\n";
6699   in
6700
6701   (* For non-daemon functions, generate a wrapper around each function. *)
6702   List.iter (
6703     fun (shortname, style, _, _, _, _, _) ->
6704       let name = "guestfs_" ^ shortname in
6705
6706       generate_prototype ~extern:false ~semicolon:false ~newline:true
6707         ~handle:"g" name style;
6708       pr "{\n";
6709       check_null_strings shortname style;
6710       trace_call shortname style;
6711       pr "  return guestfs__%s " shortname;
6712       generate_c_call_args ~handle:"g" style;
6713       pr ";\n";
6714       pr "}\n";
6715       pr "\n"
6716   ) non_daemon_functions;
6717
6718   (* Client-side stubs for each function. *)
6719   List.iter (
6720     fun (shortname, style, _, _, _, _, _) ->
6721       let name = "guestfs_" ^ shortname in
6722       let error_code = error_code_of (fst style) in
6723
6724       (* Generate the action stub. *)
6725       generate_prototype ~extern:false ~semicolon:false ~newline:true
6726         ~handle:"g" name style;
6727
6728       pr "{\n";
6729
6730       (match snd style with
6731        | [] -> ()
6732        | _ -> pr "  struct %s_args args;\n" name
6733       );
6734
6735       pr "  guestfs_message_header hdr;\n";
6736       pr "  guestfs_message_error err;\n";
6737       let has_ret =
6738         match fst style with
6739         | RErr -> false
6740         | RConstString _ | RConstOptString _ ->
6741             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6742         | RInt _ | RInt64 _
6743         | RBool _ | RString _ | RStringList _
6744         | RStruct _ | RStructList _
6745         | RHashtable _ | RBufferOut _ ->
6746             pr "  struct %s_ret ret;\n" name;
6747             true in
6748
6749       pr "  int serial;\n";
6750       pr "  int r;\n";
6751       pr "\n";
6752       check_null_strings shortname style;
6753       trace_call shortname style;
6754       pr "  if (check_state (g, \"%s\") == -1) return %s;\n"
6755         shortname error_code;
6756       pr "  guestfs___set_busy (g);\n";
6757       pr "\n";
6758
6759       (* Send the main header and arguments. *)
6760       (match snd style with
6761        | [] ->
6762            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
6763              (String.uppercase shortname)
6764        | args ->
6765            List.iter (
6766              function
6767              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6768                  pr "  args.%s = (char *) %s;\n" n n
6769              | OptString n ->
6770                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
6771              | StringList n | DeviceList n ->
6772                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
6773                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
6774              | Bool n ->
6775                  pr "  args.%s = %s;\n" n n
6776              | Int n ->
6777                  pr "  args.%s = %s;\n" n n
6778              | Int64 n ->
6779                  pr "  args.%s = %s;\n" n n
6780              | FileIn _ | FileOut _ -> ()
6781              | BufferIn n ->
6782                  pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
6783                  pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
6784                  pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
6785                    shortname;
6786                  pr "    guestfs___end_busy (g);\n";
6787                  pr "    return %s;\n" error_code;
6788                  pr "  }\n";
6789                  pr "  args.%s.%s_val = (char *) %s;\n" n n n;
6790                  pr "  args.%s.%s_len = %s_size;\n" n n n
6791            ) args;
6792            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
6793              (String.uppercase shortname);
6794            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
6795              name;
6796       );
6797       pr "  if (serial == -1) {\n";
6798       pr "    guestfs___end_busy (g);\n";
6799       pr "    return %s;\n" error_code;
6800       pr "  }\n";
6801       pr "\n";
6802
6803       (* Send any additional files (FileIn) requested. *)
6804       let need_read_reply_label = ref false in
6805       List.iter (
6806         function
6807         | FileIn n ->
6808             pr "  r = guestfs___send_file (g, %s);\n" n;
6809             pr "  if (r == -1) {\n";
6810             pr "    guestfs___end_busy (g);\n";
6811             pr "    return %s;\n" error_code;
6812             pr "  }\n";
6813             pr "  if (r == -2) /* daemon cancelled */\n";
6814             pr "    goto read_reply;\n";
6815             need_read_reply_label := true;
6816             pr "\n";
6817         | _ -> ()
6818       ) (snd style);
6819
6820       (* Wait for the reply from the remote end. *)
6821       if !need_read_reply_label then pr " read_reply:\n";
6822       pr "  memset (&hdr, 0, sizeof hdr);\n";
6823       pr "  memset (&err, 0, sizeof err);\n";
6824       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
6825       pr "\n";
6826       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
6827       if not has_ret then
6828         pr "NULL, NULL"
6829       else
6830         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
6831       pr ");\n";
6832
6833       pr "  if (r == -1) {\n";
6834       pr "    guestfs___end_busy (g);\n";
6835       pr "    return %s;\n" error_code;
6836       pr "  }\n";
6837       pr "\n";
6838
6839       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
6840         (String.uppercase shortname);
6841       pr "    guestfs___end_busy (g);\n";
6842       pr "    return %s;\n" error_code;
6843       pr "  }\n";
6844       pr "\n";
6845
6846       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
6847       pr "    error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
6848       pr "    free (err.error_message);\n";
6849       pr "    guestfs___end_busy (g);\n";
6850       pr "    return %s;\n" error_code;
6851       pr "  }\n";
6852       pr "\n";
6853
6854       (* Expecting to receive further files (FileOut)? *)
6855       List.iter (
6856         function
6857         | FileOut n ->
6858             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
6859             pr "    guestfs___end_busy (g);\n";
6860             pr "    return %s;\n" error_code;
6861             pr "  }\n";
6862             pr "\n";
6863         | _ -> ()
6864       ) (snd style);
6865
6866       pr "  guestfs___end_busy (g);\n";
6867
6868       (match fst style with
6869        | RErr -> pr "  return 0;\n"
6870        | RInt n | RInt64 n | RBool n ->
6871            pr "  return ret.%s;\n" n
6872        | RConstString _ | RConstOptString _ ->
6873            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6874        | RString n ->
6875            pr "  return ret.%s; /* caller will free */\n" n
6876        | RStringList n | RHashtable n ->
6877            pr "  /* caller will free this, but we need to add a NULL entry */\n";
6878            pr "  ret.%s.%s_val =\n" n n;
6879            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
6880            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
6881              n n;
6882            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
6883            pr "  return ret.%s.%s_val;\n" n n
6884        | RStruct (n, _) ->
6885            pr "  /* caller will free this */\n";
6886            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6887        | RStructList (n, _) ->
6888            pr "  /* caller will free this */\n";
6889            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6890        | RBufferOut n ->
6891            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
6892            pr "   * _val might be NULL here.  To make the API saner for\n";
6893            pr "   * callers, we turn this case into a unique pointer (using\n";
6894            pr "   * malloc(1)).\n";
6895            pr "   */\n";
6896            pr "  if (ret.%s.%s_len > 0) {\n" n n;
6897            pr "    *size_r = ret.%s.%s_len;\n" n n;
6898            pr "    return ret.%s.%s_val; /* caller will free */\n" n n;
6899            pr "  } else {\n";
6900            pr "    free (ret.%s.%s_val);\n" n n;
6901            pr "    char *p = safe_malloc (g, 1);\n";
6902            pr "    *size_r = ret.%s.%s_len;\n" n n;
6903            pr "    return p;\n";
6904            pr "  }\n";
6905       );
6906
6907       pr "}\n\n"
6908   ) daemon_functions;
6909
6910   (* Functions to free structures. *)
6911   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
6912   pr " * structure format is identical to the XDR format.  See note in\n";
6913   pr " * generator.ml.\n";
6914   pr " */\n";
6915   pr "\n";
6916
6917   List.iter (
6918     fun (typ, _) ->
6919       pr "void\n";
6920       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
6921       pr "{\n";
6922       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
6923       pr "  free (x);\n";
6924       pr "}\n";
6925       pr "\n";
6926
6927       pr "void\n";
6928       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
6929       pr "{\n";
6930       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
6931       pr "  free (x);\n";
6932       pr "}\n";
6933       pr "\n";
6934
6935   ) structs;
6936
6937 (* Generate daemon/actions.h. *)
6938 and generate_daemon_actions_h () =
6939   generate_header CStyle GPLv2plus;
6940
6941   pr "#include \"../src/guestfs_protocol.h\"\n";
6942   pr "\n";
6943
6944   List.iter (
6945     fun (name, style, _, _, _, _, _) ->
6946       generate_prototype
6947         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
6948         name style;
6949   ) daemon_functions
6950
6951 (* Generate the linker script which controls the visibility of
6952  * symbols in the public ABI and ensures no other symbols get
6953  * exported accidentally.
6954  *)
6955 and generate_linker_script () =
6956   generate_header HashStyle GPLv2plus;
6957
6958   let globals = [
6959     "guestfs_create";
6960     "guestfs_close";
6961     "guestfs_get_error_handler";
6962     "guestfs_get_out_of_memory_handler";
6963     "guestfs_get_private";
6964     "guestfs_last_error";
6965     "guestfs_set_close_callback";
6966     "guestfs_set_error_handler";
6967     "guestfs_set_launch_done_callback";
6968     "guestfs_set_log_message_callback";
6969     "guestfs_set_out_of_memory_handler";
6970     "guestfs_set_private";
6971     "guestfs_set_progress_callback";
6972     "guestfs_set_subprocess_quit_callback";
6973
6974     (* Unofficial parts of the API: the bindings code use these
6975      * functions, so it is useful to export them.
6976      *)
6977     "guestfs_safe_calloc";
6978     "guestfs_safe_malloc";
6979     "guestfs_safe_strdup";
6980     "guestfs_safe_memdup";
6981   ] in
6982   let functions =
6983     List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
6984       all_functions in
6985   let structs =
6986     List.concat (
6987       List.map (fun (typ, _) ->
6988                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
6989         structs
6990     ) in
6991   let globals = List.sort compare (globals @ functions @ structs) in
6992
6993   pr "{\n";
6994   pr "    global:\n";
6995   List.iter (pr "        %s;\n") globals;
6996   pr "\n";
6997
6998   pr "    local:\n";
6999   pr "        *;\n";
7000   pr "};\n"
7001
7002 (* Generate the server-side stubs. *)
7003 and generate_daemon_actions () =
7004   generate_header CStyle GPLv2plus;
7005
7006   pr "#include <config.h>\n";
7007   pr "\n";
7008   pr "#include <stdio.h>\n";
7009   pr "#include <stdlib.h>\n";
7010   pr "#include <string.h>\n";
7011   pr "#include <inttypes.h>\n";
7012   pr "#include <rpc/types.h>\n";
7013   pr "#include <rpc/xdr.h>\n";
7014   pr "\n";
7015   pr "#include \"daemon.h\"\n";
7016   pr "#include \"c-ctype.h\"\n";
7017   pr "#include \"../src/guestfs_protocol.h\"\n";
7018   pr "#include \"actions.h\"\n";
7019   pr "\n";
7020
7021   List.iter (
7022     fun (name, style, _, _, _, _, _) ->
7023       (* Generate server-side stubs. *)
7024       pr "static void %s_stub (XDR *xdr_in)\n" name;
7025       pr "{\n";
7026       let error_code =
7027         match fst style with
7028         | RErr | RInt _ -> pr "  int r;\n"; "-1"
7029         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
7030         | RBool _ -> pr "  int r;\n"; "-1"
7031         | RConstString _ | RConstOptString _ ->
7032             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7033         | RString _ -> pr "  char *r;\n"; "NULL"
7034         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
7035         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
7036         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
7037         | RBufferOut _ ->
7038             pr "  size_t size = 1;\n";
7039             pr "  char *r;\n";
7040             "NULL" in
7041
7042       (match snd style with
7043        | [] -> ()
7044        | args ->
7045            pr "  struct guestfs_%s_args args;\n" name;
7046            List.iter (
7047              function
7048              | Device n | Dev_or_Path n
7049              | Pathname n
7050              | String n
7051              | Key n -> ()
7052              | OptString n -> pr "  char *%s;\n" n
7053              | StringList n | DeviceList n -> pr "  char **%s;\n" n
7054              | Bool n -> pr "  int %s;\n" n
7055              | Int n -> pr "  int %s;\n" n
7056              | Int64 n -> pr "  int64_t %s;\n" n
7057              | FileIn _ | FileOut _ -> ()
7058              | BufferIn n ->
7059                  pr "  const char *%s;\n" n;
7060                  pr "  size_t %s_size;\n" n
7061            ) args
7062       );
7063       pr "\n";
7064
7065       let is_filein =
7066         List.exists (function FileIn _ -> true | _ -> false) (snd style) in
7067
7068       (match snd style with
7069        | [] -> ()
7070        | args ->
7071            pr "  memset (&args, 0, sizeof args);\n";
7072            pr "\n";
7073            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
7074            if is_filein then
7075              pr "    if (cancel_receive () != -2)\n";
7076            pr "      reply_with_error (\"daemon failed to decode procedure arguments\");\n";
7077            pr "    goto done;\n";
7078            pr "  }\n";
7079            let pr_args n =
7080              pr "  char *%s = args.%s;\n" n n
7081            in
7082            let pr_list_handling_code n =
7083              pr "  %s = realloc (args.%s.%s_val,\n" n n n;
7084              pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
7085              pr "  if (%s == NULL) {\n" n;
7086              if is_filein then
7087                pr "    if (cancel_receive () != -2)\n";
7088              pr "      reply_with_perror (\"realloc\");\n";
7089              pr "    goto done;\n";
7090              pr "  }\n";
7091              pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
7092              pr "  args.%s.%s_val = %s;\n" n n n;
7093            in
7094            List.iter (
7095              function
7096              | Pathname n ->
7097                  pr_args n;
7098                  pr "  ABS_PATH (%s, %s, goto done);\n"
7099                    n (if is_filein then "cancel_receive ()" else "0");
7100              | Device n ->
7101                  pr_args n;
7102                  pr "  RESOLVE_DEVICE (%s, %s, goto done);\n"
7103                    n (if is_filein then "cancel_receive ()" else "0");
7104              | Dev_or_Path n ->
7105                  pr_args n;
7106                  pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
7107                    n (if is_filein then "cancel_receive ()" else "0");
7108              | String n | Key n -> pr_args n
7109              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
7110              | StringList n ->
7111                  pr_list_handling_code n;
7112              | DeviceList n ->
7113                  pr_list_handling_code n;
7114                  pr "  /* Ensure that each is a device,\n";
7115                  pr "   * and perform device name translation.\n";
7116                  pr "   */\n";
7117                  pr "  {\n";
7118                  pr "    size_t i;\n";
7119                  pr "    for (i = 0; %s[i] != NULL; ++i)\n" n;
7120                  pr "      RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
7121                    (if is_filein then "cancel_receive ()" else "0");
7122                  pr "  }\n";
7123              | Bool n -> pr "  %s = args.%s;\n" n n
7124              | Int n -> pr "  %s = args.%s;\n" n n
7125              | Int64 n -> pr "  %s = args.%s;\n" n n
7126              | FileIn _ | FileOut _ -> ()
7127              | BufferIn n ->
7128                  pr "  %s = args.%s.%s_val;\n" n n n;
7129                  pr "  %s_size = args.%s.%s_len;\n" n n n
7130            ) args;
7131            pr "\n"
7132       );
7133
7134       (* this is used at least for do_equal *)
7135       if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
7136         (* Emit NEED_ROOT just once, even when there are two or
7137            more Pathname args *)
7138         pr "  NEED_ROOT (%s, goto done);\n"
7139           (if is_filein then "cancel_receive ()" else "0");
7140       );
7141
7142       (* Don't want to call the impl with any FileIn or FileOut
7143        * parameters, since these go "outside" the RPC protocol.
7144        *)
7145       let args' =
7146         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
7147           (snd style) in
7148       pr "  r = do_%s " name;
7149       generate_c_call_args (fst style, args');
7150       pr ";\n";
7151
7152       (match fst style with
7153        | RErr | RInt _ | RInt64 _ | RBool _
7154        | RConstString _ | RConstOptString _
7155        | RString _ | RStringList _ | RHashtable _
7156        | RStruct (_, _) | RStructList (_, _) ->
7157            pr "  if (r == %s)\n" error_code;
7158            pr "    /* do_%s has already called reply_with_error */\n" name;
7159            pr "    goto done;\n";
7160            pr "\n"
7161        | RBufferOut _ ->
7162            pr "  /* size == 0 && r == NULL could be a non-error case (just\n";
7163            pr "   * an ordinary zero-length buffer), so be careful ...\n";
7164            pr "   */\n";
7165            pr "  if (size == 1 && r == %s)\n" error_code;
7166            pr "    /* do_%s has already called reply_with_error */\n" name;
7167            pr "    goto done;\n";
7168            pr "\n"
7169       );
7170
7171       (* If there are any FileOut parameters, then the impl must
7172        * send its own reply.
7173        *)
7174       let no_reply =
7175         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
7176       if no_reply then
7177         pr "  /* do_%s has already sent a reply */\n" name
7178       else (
7179         match fst style with
7180         | RErr -> pr "  reply (NULL, NULL);\n"
7181         | RInt n | RInt64 n | RBool n ->
7182             pr "  struct guestfs_%s_ret ret;\n" name;
7183             pr "  ret.%s = r;\n" n;
7184             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7185               name
7186         | RConstString _ | RConstOptString _ ->
7187             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7188         | RString n ->
7189             pr "  struct guestfs_%s_ret ret;\n" name;
7190             pr "  ret.%s = r;\n" n;
7191             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7192               name;
7193             pr "  free (r);\n"
7194         | RStringList n | RHashtable n ->
7195             pr "  struct guestfs_%s_ret ret;\n" name;
7196             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
7197             pr "  ret.%s.%s_val = r;\n" n n;
7198             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7199               name;
7200             pr "  free_strings (r);\n"
7201         | RStruct (n, _) ->
7202             pr "  struct guestfs_%s_ret ret;\n" name;
7203             pr "  ret.%s = *r;\n" n;
7204             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7205               name;
7206             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7207               name
7208         | RStructList (n, _) ->
7209             pr "  struct guestfs_%s_ret ret;\n" name;
7210             pr "  ret.%s = *r;\n" n;
7211             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7212               name;
7213             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7214               name
7215         | RBufferOut n ->
7216             pr "  struct guestfs_%s_ret ret;\n" name;
7217             pr "  ret.%s.%s_val = r;\n" n n;
7218             pr "  ret.%s.%s_len = size;\n" n n;
7219             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7220               name;
7221             pr "  free (r);\n"
7222       );
7223
7224       (* Free the args. *)
7225       pr "done:\n";
7226       (match snd style with
7227        | [] -> ()
7228        | _ ->
7229            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
7230              name
7231       );
7232       pr "  return;\n";
7233       pr "}\n\n";
7234   ) daemon_functions;
7235
7236   (* Dispatch function. *)
7237   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
7238   pr "{\n";
7239   pr "  switch (proc_nr) {\n";
7240
7241   List.iter (
7242     fun (name, style, _, _, _, _, _) ->
7243       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
7244       pr "      %s_stub (xdr_in);\n" name;
7245       pr "      break;\n"
7246   ) daemon_functions;
7247
7248   pr "    default:\n";
7249   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";
7250   pr "  }\n";
7251   pr "}\n";
7252   pr "\n";
7253
7254   (* LVM columns and tokenization functions. *)
7255   (* XXX This generates crap code.  We should rethink how we
7256    * do this parsing.
7257    *)
7258   List.iter (
7259     function
7260     | typ, cols ->
7261         pr "static const char *lvm_%s_cols = \"%s\";\n"
7262           typ (String.concat "," (List.map fst cols));
7263         pr "\n";
7264
7265         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
7266         pr "{\n";
7267         pr "  char *tok, *p, *next;\n";
7268         pr "  size_t i, j;\n";
7269         pr "\n";
7270         (*
7271           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
7272           pr "\n";
7273         *)
7274         pr "  if (!str) {\n";
7275         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
7276         pr "    return -1;\n";
7277         pr "  }\n";
7278         pr "  if (!*str || c_isspace (*str)) {\n";
7279         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
7280         pr "    return -1;\n";
7281         pr "  }\n";
7282         pr "  tok = str;\n";
7283         List.iter (
7284           fun (name, coltype) ->
7285             pr "  if (!tok) {\n";
7286             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
7287             pr "    return -1;\n";
7288             pr "  }\n";
7289             pr "  p = strchrnul (tok, ',');\n";
7290             pr "  if (*p) next = p+1; else next = NULL;\n";
7291             pr "  *p = '\\0';\n";
7292             (match coltype with
7293              | FString ->
7294                  pr "  r->%s = strdup (tok);\n" name;
7295                  pr "  if (r->%s == NULL) {\n" name;
7296                  pr "    perror (\"strdup\");\n";
7297                  pr "    return -1;\n";
7298                  pr "  }\n"
7299              | FUUID ->
7300                  pr "  for (i = j = 0; i < 32; ++j) {\n";
7301                  pr "    if (tok[j] == '\\0') {\n";
7302                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
7303                  pr "      return -1;\n";
7304                  pr "    } else if (tok[j] != '-')\n";
7305                  pr "      r->%s[i++] = tok[j];\n" name;
7306                  pr "  }\n";
7307              | FBytes ->
7308                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
7309                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7310                  pr "    return -1;\n";
7311                  pr "  }\n";
7312              | FInt64 ->
7313                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
7314                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7315                  pr "    return -1;\n";
7316                  pr "  }\n";
7317              | FOptPercent ->
7318                  pr "  if (tok[0] == '\\0')\n";
7319                  pr "    r->%s = -1;\n" name;
7320                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
7321                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7322                  pr "    return -1;\n";
7323                  pr "  }\n";
7324              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
7325                  assert false (* can never be an LVM column *)
7326             );
7327             pr "  tok = next;\n";
7328         ) cols;
7329
7330         pr "  if (tok != NULL) {\n";
7331         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
7332         pr "    return -1;\n";
7333         pr "  }\n";
7334         pr "  return 0;\n";
7335         pr "}\n";
7336         pr "\n";
7337
7338         pr "guestfs_int_lvm_%s_list *\n" typ;
7339         pr "parse_command_line_%ss (void)\n" typ;
7340         pr "{\n";
7341         pr "  char *out, *err;\n";
7342         pr "  char *p, *pend;\n";
7343         pr "  int r, i;\n";
7344         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
7345         pr "  void *newp;\n";
7346         pr "\n";
7347         pr "  ret = malloc (sizeof *ret);\n";
7348         pr "  if (!ret) {\n";
7349         pr "    reply_with_perror (\"malloc\");\n";
7350         pr "    return NULL;\n";
7351         pr "  }\n";
7352         pr "\n";
7353         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
7354         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
7355         pr "\n";
7356         pr "  r = command (&out, &err,\n";
7357         pr "           \"lvm\", \"%ss\",\n" typ;
7358         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
7359         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
7360         pr "  if (r == -1) {\n";
7361         pr "    reply_with_error (\"%%s\", err);\n";
7362         pr "    free (out);\n";
7363         pr "    free (err);\n";
7364         pr "    free (ret);\n";
7365         pr "    return NULL;\n";
7366         pr "  }\n";
7367         pr "\n";
7368         pr "  free (err);\n";
7369         pr "\n";
7370         pr "  /* Tokenize each line of the output. */\n";
7371         pr "  p = out;\n";
7372         pr "  i = 0;\n";
7373         pr "  while (p) {\n";
7374         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
7375         pr "    if (pend) {\n";
7376         pr "      *pend = '\\0';\n";
7377         pr "      pend++;\n";
7378         pr "    }\n";
7379         pr "\n";
7380         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
7381         pr "      p++;\n";
7382         pr "\n";
7383         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
7384         pr "      p = pend;\n";
7385         pr "      continue;\n";
7386         pr "    }\n";
7387         pr "\n";
7388         pr "    /* Allocate some space to store this next entry. */\n";
7389         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
7390         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
7391         pr "    if (newp == NULL) {\n";
7392         pr "      reply_with_perror (\"realloc\");\n";
7393         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7394         pr "      free (ret);\n";
7395         pr "      free (out);\n";
7396         pr "      return NULL;\n";
7397         pr "    }\n";
7398         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
7399         pr "\n";
7400         pr "    /* Tokenize the next entry. */\n";
7401         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
7402         pr "    if (r == -1) {\n";
7403         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
7404         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7405         pr "      free (ret);\n";
7406         pr "      free (out);\n";
7407         pr "      return NULL;\n";
7408         pr "    }\n";
7409         pr "\n";
7410         pr "    ++i;\n";
7411         pr "    p = pend;\n";
7412         pr "  }\n";
7413         pr "\n";
7414         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
7415         pr "\n";
7416         pr "  free (out);\n";
7417         pr "  return ret;\n";
7418         pr "}\n"
7419
7420   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
7421
7422 (* Generate a list of function names, for debugging in the daemon.. *)
7423 and generate_daemon_names () =
7424   generate_header CStyle GPLv2plus;
7425
7426   pr "#include <config.h>\n";
7427   pr "\n";
7428   pr "#include \"daemon.h\"\n";
7429   pr "\n";
7430
7431   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
7432   pr "const char *function_names[] = {\n";
7433   List.iter (
7434     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
7435   ) daemon_functions;
7436   pr "};\n";
7437
7438 (* Generate the optional groups for the daemon to implement
7439  * guestfs_available.
7440  *)
7441 and generate_daemon_optgroups_c () =
7442   generate_header CStyle GPLv2plus;
7443
7444   pr "#include <config.h>\n";
7445   pr "\n";
7446   pr "#include \"daemon.h\"\n";
7447   pr "#include \"optgroups.h\"\n";
7448   pr "\n";
7449
7450   pr "struct optgroup optgroups[] = {\n";
7451   List.iter (
7452     fun (group, _) ->
7453       pr "  { \"%s\", optgroup_%s_available },\n" group group
7454   ) optgroups;
7455   pr "  { NULL, NULL }\n";
7456   pr "};\n"
7457
7458 and generate_daemon_optgroups_h () =
7459   generate_header CStyle GPLv2plus;
7460
7461   List.iter (
7462     fun (group, _) ->
7463       pr "extern int optgroup_%s_available (void);\n" group
7464   ) optgroups
7465
7466 (* Generate the tests. *)
7467 and generate_tests () =
7468   generate_header CStyle GPLv2plus;
7469
7470   pr "\
7471 #include <stdio.h>
7472 #include <stdlib.h>
7473 #include <string.h>
7474 #include <unistd.h>
7475 #include <sys/types.h>
7476 #include <fcntl.h>
7477
7478 #include \"guestfs.h\"
7479 #include \"guestfs-internal.h\"
7480
7481 static guestfs_h *g;
7482 static int suppress_error = 0;
7483
7484 static void print_error (guestfs_h *g, void *data, const char *msg)
7485 {
7486   if (!suppress_error)
7487     fprintf (stderr, \"%%s\\n\", msg);
7488 }
7489
7490 /* FIXME: nearly identical code appears in fish.c */
7491 static void print_strings (char *const *argv)
7492 {
7493   size_t argc;
7494
7495   for (argc = 0; argv[argc] != NULL; ++argc)
7496     printf (\"\\t%%s\\n\", argv[argc]);
7497 }
7498
7499 /*
7500 static void print_table (char const *const *argv)
7501 {
7502   size_t i;
7503
7504   for (i = 0; argv[i] != NULL; i += 2)
7505     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
7506 }
7507 */
7508
7509 static int
7510 is_available (const char *group)
7511 {
7512   const char *groups[] = { group, NULL };
7513   int r;
7514
7515   suppress_error = 1;
7516   r = guestfs_available (g, (char **) groups);
7517   suppress_error = 0;
7518
7519   return r == 0;
7520 }
7521
7522 static void
7523 incr (guestfs_h *g, void *iv)
7524 {
7525   int *i = (int *) iv;
7526   (*i)++;
7527 }
7528
7529 ";
7530
7531   (* Generate a list of commands which are not tested anywhere. *)
7532   pr "static void no_test_warnings (void)\n";
7533   pr "{\n";
7534
7535   let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
7536   List.iter (
7537     fun (_, _, _, _, tests, _, _) ->
7538       let tests = filter_map (
7539         function
7540         | (_, (Always|If _|Unless _|IfAvailable _), test) -> Some test
7541         | (_, Disabled, _) -> None
7542       ) tests in
7543       let seq = List.concat (List.map seq_of_test tests) in
7544       let cmds_tested = List.map List.hd seq in
7545       List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
7546   ) all_functions;
7547
7548   List.iter (
7549     fun (name, _, _, _, _, _, _) ->
7550       if not (Hashtbl.mem hash name) then
7551         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
7552   ) all_functions;
7553
7554   pr "}\n";
7555   pr "\n";
7556
7557   (* Generate the actual tests.  Note that we generate the tests
7558    * in reverse order, deliberately, so that (in general) the
7559    * newest tests run first.  This makes it quicker and easier to
7560    * debug them.
7561    *)
7562   let test_names =
7563     List.map (
7564       fun (name, _, _, flags, tests, _, _) ->
7565         mapi (generate_one_test name flags) tests
7566     ) (List.rev all_functions) in
7567   let test_names = List.concat test_names in
7568   let nr_tests = List.length test_names in
7569
7570   pr "\
7571 int main (int argc, char *argv[])
7572 {
7573   char c = 0;
7574   unsigned long int n_failed = 0;
7575   const char *filename;
7576   int fd;
7577   int nr_tests, test_num = 0;
7578
7579   setbuf (stdout, NULL);
7580
7581   no_test_warnings ();
7582
7583   g = guestfs_create ();
7584   if (g == NULL) {
7585     printf (\"guestfs_create FAILED\\n\");
7586     exit (EXIT_FAILURE);
7587   }
7588
7589   guestfs_set_error_handler (g, print_error, NULL);
7590
7591   guestfs_set_path (g, \"../appliance\");
7592
7593   filename = \"test1.img\";
7594   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7595   if (fd == -1) {
7596     perror (filename);
7597     exit (EXIT_FAILURE);
7598   }
7599   if (lseek (fd, %d, SEEK_SET) == -1) {
7600     perror (\"lseek\");
7601     close (fd);
7602     unlink (filename);
7603     exit (EXIT_FAILURE);
7604   }
7605   if (write (fd, &c, 1) == -1) {
7606     perror (\"write\");
7607     close (fd);
7608     unlink (filename);
7609     exit (EXIT_FAILURE);
7610   }
7611   if (close (fd) == -1) {
7612     perror (filename);
7613     unlink (filename);
7614     exit (EXIT_FAILURE);
7615   }
7616   if (guestfs_add_drive (g, filename) == -1) {
7617     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7618     exit (EXIT_FAILURE);
7619   }
7620
7621   filename = \"test2.img\";
7622   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7623   if (fd == -1) {
7624     perror (filename);
7625     exit (EXIT_FAILURE);
7626   }
7627   if (lseek (fd, %d, SEEK_SET) == -1) {
7628     perror (\"lseek\");
7629     close (fd);
7630     unlink (filename);
7631     exit (EXIT_FAILURE);
7632   }
7633   if (write (fd, &c, 1) == -1) {
7634     perror (\"write\");
7635     close (fd);
7636     unlink (filename);
7637     exit (EXIT_FAILURE);
7638   }
7639   if (close (fd) == -1) {
7640     perror (filename);
7641     unlink (filename);
7642     exit (EXIT_FAILURE);
7643   }
7644   if (guestfs_add_drive (g, filename) == -1) {
7645     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7646     exit (EXIT_FAILURE);
7647   }
7648
7649   filename = \"test3.img\";
7650   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7651   if (fd == -1) {
7652     perror (filename);
7653     exit (EXIT_FAILURE);
7654   }
7655   if (lseek (fd, %d, SEEK_SET) == -1) {
7656     perror (\"lseek\");
7657     close (fd);
7658     unlink (filename);
7659     exit (EXIT_FAILURE);
7660   }
7661   if (write (fd, &c, 1) == -1) {
7662     perror (\"write\");
7663     close (fd);
7664     unlink (filename);
7665     exit (EXIT_FAILURE);
7666   }
7667   if (close (fd) == -1) {
7668     perror (filename);
7669     unlink (filename);
7670     exit (EXIT_FAILURE);
7671   }
7672   if (guestfs_add_drive (g, filename) == -1) {
7673     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7674     exit (EXIT_FAILURE);
7675   }
7676
7677   if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
7678     printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
7679     exit (EXIT_FAILURE);
7680   }
7681
7682   /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
7683   alarm (600);
7684
7685   if (guestfs_launch (g) == -1) {
7686     printf (\"guestfs_launch FAILED\\n\");
7687     exit (EXIT_FAILURE);
7688   }
7689
7690   /* Cancel previous alarm. */
7691   alarm (0);
7692
7693   nr_tests = %d;
7694
7695 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
7696
7697   iteri (
7698     fun i test_name ->
7699       pr "  test_num++;\n";
7700       pr "  if (guestfs_get_verbose (g))\n";
7701       pr "    printf (\"-------------------------------------------------------------------------------\\n\");\n";
7702       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
7703       pr "  if (%s () == -1) {\n" test_name;
7704       pr "    printf (\"%s FAILED\\n\");\n" test_name;
7705       pr "    n_failed++;\n";
7706       pr "  }\n";
7707   ) test_names;
7708   pr "\n";
7709
7710   pr "  /* Check close callback is called. */
7711   int close_sentinel = 1;
7712   guestfs_set_close_callback (g, incr, &close_sentinel);
7713
7714   guestfs_close (g);
7715
7716   if (close_sentinel != 2) {
7717     fprintf (stderr, \"close callback was not called\\n\");
7718     exit (EXIT_FAILURE);
7719   }
7720
7721   unlink (\"test1.img\");
7722   unlink (\"test2.img\");
7723   unlink (\"test3.img\");
7724
7725 ";
7726
7727   pr "  if (n_failed > 0) {\n";
7728   pr "    printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
7729   pr "    exit (EXIT_FAILURE);\n";
7730   pr "  }\n";
7731   pr "\n";
7732
7733   pr "  exit (EXIT_SUCCESS);\n";
7734   pr "}\n"
7735
7736 and generate_one_test name flags i (init, prereq, test) =
7737   let test_name = sprintf "test_%s_%d" name i in
7738
7739   pr "\
7740 static int %s_skip (void)
7741 {
7742   const char *str;
7743
7744   str = getenv (\"TEST_ONLY\");
7745   if (str)
7746     return strstr (str, \"%s\") == NULL;
7747   str = getenv (\"SKIP_%s\");
7748   if (str && STREQ (str, \"1\")) return 1;
7749   str = getenv (\"SKIP_TEST_%s\");
7750   if (str && STREQ (str, \"1\")) return 1;
7751   return 0;
7752 }
7753
7754 " test_name name (String.uppercase test_name) (String.uppercase name);
7755
7756   (match prereq with
7757    | Disabled | Always | IfAvailable _ -> ()
7758    | If code | Unless code ->
7759        pr "static int %s_prereq (void)\n" test_name;
7760        pr "{\n";
7761        pr "  %s\n" code;
7762        pr "}\n";
7763        pr "\n";
7764   );
7765
7766   pr "\
7767 static int %s (void)
7768 {
7769   if (%s_skip ()) {
7770     printf (\"        %%s skipped (reason: environment variable set)\\n\", \"%s\");
7771     return 0;
7772   }
7773
7774 " test_name test_name test_name;
7775
7776   (* Optional functions should only be tested if the relevant
7777    * support is available in the daemon.
7778    *)
7779   List.iter (
7780     function
7781     | Optional group ->
7782         pr "  if (!is_available (\"%s\")) {\n" group;
7783         pr "    printf (\"        %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", \"%s\");\n" test_name group;
7784         pr "    return 0;\n";
7785         pr "  }\n";
7786     | _ -> ()
7787   ) flags;
7788
7789   (match prereq with
7790    | Disabled ->
7791        pr "  printf (\"        %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
7792    | If _ ->
7793        pr "  if (! %s_prereq ()) {\n" test_name;
7794        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7795        pr "    return 0;\n";
7796        pr "  }\n";
7797        pr "\n";
7798        generate_one_test_body name i test_name init test;
7799    | Unless _ ->
7800        pr "  if (%s_prereq ()) {\n" test_name;
7801        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7802        pr "    return 0;\n";
7803        pr "  }\n";
7804        pr "\n";
7805        generate_one_test_body name i test_name init test;
7806    | IfAvailable group ->
7807        pr "  if (!is_available (\"%s\")) {\n" group;
7808        pr "    printf (\"        %%s skipped (reason: %%s not available)\\n\", \"%s\", \"%s\");\n" test_name group;
7809        pr "    return 0;\n";
7810        pr "  }\n";
7811        pr "\n";
7812        generate_one_test_body name i test_name init test;
7813    | Always ->
7814        generate_one_test_body name i test_name init test
7815   );
7816
7817   pr "  return 0;\n";
7818   pr "}\n";
7819   pr "\n";
7820   test_name
7821
7822 and generate_one_test_body name i test_name init test =
7823   (match init with
7824    | InitNone (* XXX at some point, InitNone and InitEmpty became
7825                * folded together as the same thing.  Really we should
7826                * make InitNone do nothing at all, but the tests may
7827                * need to be checked to make sure this is OK.
7828                *)
7829    | InitEmpty ->
7830        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
7831        List.iter (generate_test_command_call test_name)
7832          [["blockdev_setrw"; "/dev/sda"];
7833           ["umount_all"];
7834           ["lvm_remove_all"]]
7835    | InitPartition ->
7836        pr "  /* InitPartition for %s: create /dev/sda1 */\n" test_name;
7837        List.iter (generate_test_command_call test_name)
7838          [["blockdev_setrw"; "/dev/sda"];
7839           ["umount_all"];
7840           ["lvm_remove_all"];
7841           ["part_disk"; "/dev/sda"; "mbr"]]
7842    | InitBasicFS ->
7843        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
7844        List.iter (generate_test_command_call test_name)
7845          [["blockdev_setrw"; "/dev/sda"];
7846           ["umount_all"];
7847           ["lvm_remove_all"];
7848           ["part_disk"; "/dev/sda"; "mbr"];
7849           ["mkfs"; "ext2"; "/dev/sda1"];
7850           ["mount_options"; ""; "/dev/sda1"; "/"]]
7851    | InitBasicFSonLVM ->
7852        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
7853          test_name;
7854        List.iter (generate_test_command_call test_name)
7855          [["blockdev_setrw"; "/dev/sda"];
7856           ["umount_all"];
7857           ["lvm_remove_all"];
7858           ["part_disk"; "/dev/sda"; "mbr"];
7859           ["pvcreate"; "/dev/sda1"];
7860           ["vgcreate"; "VG"; "/dev/sda1"];
7861           ["lvcreate"; "LV"; "VG"; "8"];
7862           ["mkfs"; "ext2"; "/dev/VG/LV"];
7863           ["mount_options"; ""; "/dev/VG/LV"; "/"]]
7864    | InitISOFS ->
7865        pr "  /* InitISOFS for %s */\n" test_name;
7866        List.iter (generate_test_command_call test_name)
7867          [["blockdev_setrw"; "/dev/sda"];
7868           ["umount_all"];
7869           ["lvm_remove_all"];
7870           ["mount_ro"; "/dev/sdd"; "/"]]
7871   );
7872
7873   let get_seq_last = function
7874     | [] ->
7875         failwithf "%s: you cannot use [] (empty list) when expecting a command"
7876           test_name
7877     | seq ->
7878         let seq = List.rev seq in
7879         List.rev (List.tl seq), List.hd seq
7880   in
7881
7882   match test with
7883   | TestRun seq ->
7884       pr "  /* TestRun for %s (%d) */\n" name i;
7885       List.iter (generate_test_command_call test_name) seq
7886   | TestOutput (seq, expected) ->
7887       pr "  /* TestOutput for %s (%d) */\n" name i;
7888       pr "  const char *expected = \"%s\";\n" (c_quote expected);
7889       let seq, last = get_seq_last seq in
7890       let test () =
7891         pr "    if (STRNEQ (r, expected)) {\n";
7892         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7893         pr "      return -1;\n";
7894         pr "    }\n"
7895       in
7896       List.iter (generate_test_command_call test_name) seq;
7897       generate_test_command_call ~test test_name last
7898   | TestOutputList (seq, expected) ->
7899       pr "  /* TestOutputList for %s (%d) */\n" name i;
7900       let seq, last = get_seq_last seq in
7901       let test () =
7902         iteri (
7903           fun i str ->
7904             pr "    if (!r[%d]) {\n" i;
7905             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7906             pr "      print_strings (r);\n";
7907             pr "      return -1;\n";
7908             pr "    }\n";
7909             pr "    {\n";
7910             pr "      const char *expected = \"%s\";\n" (c_quote str);
7911             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7912             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7913             pr "        return -1;\n";
7914             pr "      }\n";
7915             pr "    }\n"
7916         ) expected;
7917         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7918         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7919           test_name;
7920         pr "      print_strings (r);\n";
7921         pr "      return -1;\n";
7922         pr "    }\n"
7923       in
7924       List.iter (generate_test_command_call test_name) seq;
7925       generate_test_command_call ~test test_name last
7926   | TestOutputListOfDevices (seq, expected) ->
7927       pr "  /* TestOutputListOfDevices for %s (%d) */\n" name i;
7928       let seq, last = get_seq_last seq in
7929       let test () =
7930         iteri (
7931           fun i str ->
7932             pr "    if (!r[%d]) {\n" i;
7933             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7934             pr "      print_strings (r);\n";
7935             pr "      return -1;\n";
7936             pr "    }\n";
7937             pr "    {\n";
7938             pr "      const char *expected = \"%s\";\n" (c_quote str);
7939             pr "      r[%d][5] = 's';\n" i;
7940             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7941             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7942             pr "        return -1;\n";
7943             pr "      }\n";
7944             pr "    }\n"
7945         ) expected;
7946         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7947         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7948           test_name;
7949         pr "      print_strings (r);\n";
7950         pr "      return -1;\n";
7951         pr "    }\n"
7952       in
7953       List.iter (generate_test_command_call test_name) seq;
7954       generate_test_command_call ~test test_name last
7955   | TestOutputInt (seq, expected) ->
7956       pr "  /* TestOutputInt for %s (%d) */\n" name i;
7957       let seq, last = get_seq_last seq in
7958       let test () =
7959         pr "    if (r != %d) {\n" expected;
7960         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
7961           test_name expected;
7962         pr "               (int) r);\n";
7963         pr "      return -1;\n";
7964         pr "    }\n"
7965       in
7966       List.iter (generate_test_command_call test_name) seq;
7967       generate_test_command_call ~test test_name last
7968   | TestOutputIntOp (seq, op, expected) ->
7969       pr "  /* TestOutputIntOp for %s (%d) */\n" name i;
7970       let seq, last = get_seq_last seq in
7971       let test () =
7972         pr "    if (! (r %s %d)) {\n" op expected;
7973         pr "      fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
7974           test_name op expected;
7975         pr "               (int) r);\n";
7976         pr "      return -1;\n";
7977         pr "    }\n"
7978       in
7979       List.iter (generate_test_command_call test_name) seq;
7980       generate_test_command_call ~test test_name last
7981   | TestOutputTrue seq ->
7982       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
7983       let seq, last = get_seq_last seq in
7984       let test () =
7985         pr "    if (!r) {\n";
7986         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
7987           test_name;
7988         pr "      return -1;\n";
7989         pr "    }\n"
7990       in
7991       List.iter (generate_test_command_call test_name) seq;
7992       generate_test_command_call ~test test_name last
7993   | TestOutputFalse seq ->
7994       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
7995       let seq, last = get_seq_last seq in
7996       let test () =
7997         pr "    if (r) {\n";
7998         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
7999           test_name;
8000         pr "      return -1;\n";
8001         pr "    }\n"
8002       in
8003       List.iter (generate_test_command_call test_name) seq;
8004       generate_test_command_call ~test test_name last
8005   | TestOutputLength (seq, expected) ->
8006       pr "  /* TestOutputLength for %s (%d) */\n" name i;
8007       let seq, last = get_seq_last seq in
8008       let test () =
8009         pr "    int j;\n";
8010         pr "    for (j = 0; j < %d; ++j)\n" expected;
8011         pr "      if (r[j] == NULL) {\n";
8012         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
8013           test_name;
8014         pr "        print_strings (r);\n";
8015         pr "        return -1;\n";
8016         pr "      }\n";
8017         pr "    if (r[j] != NULL) {\n";
8018         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
8019           test_name;
8020         pr "      print_strings (r);\n";
8021         pr "      return -1;\n";
8022         pr "    }\n"
8023       in
8024       List.iter (generate_test_command_call test_name) seq;
8025       generate_test_command_call ~test test_name last
8026   | TestOutputBuffer (seq, expected) ->
8027       pr "  /* TestOutputBuffer for %s (%d) */\n" name i;
8028       pr "  const char *expected = \"%s\";\n" (c_quote expected);
8029       let seq, last = get_seq_last seq in
8030       let len = String.length expected in
8031       let test () =
8032         pr "    if (size != %d) {\n" len;
8033         pr "      fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
8034         pr "      return -1;\n";
8035         pr "    }\n";
8036         pr "    if (STRNEQLEN (r, expected, size)) {\n";
8037         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
8038         pr "      return -1;\n";
8039         pr "    }\n"
8040       in
8041       List.iter (generate_test_command_call test_name) seq;
8042       generate_test_command_call ~test test_name last
8043   | TestOutputStruct (seq, checks) ->
8044       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
8045       let seq, last = get_seq_last seq in
8046       let test () =
8047         List.iter (
8048           function
8049           | CompareWithInt (field, expected) ->
8050               pr "    if (r->%s != %d) {\n" field expected;
8051               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
8052                 test_name field expected;
8053               pr "               (int) r->%s);\n" field;
8054               pr "      return -1;\n";
8055               pr "    }\n"
8056           | CompareWithIntOp (field, op, expected) ->
8057               pr "    if (!(r->%s %s %d)) {\n" field op expected;
8058               pr "      fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
8059                 test_name field op expected;
8060               pr "               (int) r->%s);\n" field;
8061               pr "      return -1;\n";
8062               pr "    }\n"
8063           | CompareWithString (field, expected) ->
8064               pr "    if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
8065               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
8066                 test_name field expected;
8067               pr "               r->%s);\n" field;
8068               pr "      return -1;\n";
8069               pr "    }\n"
8070           | CompareFieldsIntEq (field1, field2) ->
8071               pr "    if (r->%s != r->%s) {\n" field1 field2;
8072               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
8073                 test_name field1 field2;
8074               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
8075               pr "      return -1;\n";
8076               pr "    }\n"
8077           | CompareFieldsStrEq (field1, field2) ->
8078               pr "    if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
8079               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
8080                 test_name field1 field2;
8081               pr "               r->%s, r->%s);\n" field1 field2;
8082               pr "      return -1;\n";
8083               pr "    }\n"
8084         ) checks
8085       in
8086       List.iter (generate_test_command_call test_name) seq;
8087       generate_test_command_call ~test test_name last
8088   | TestLastFail seq ->
8089       pr "  /* TestLastFail for %s (%d) */\n" name i;
8090       let seq, last = get_seq_last seq in
8091       List.iter (generate_test_command_call test_name) seq;
8092       generate_test_command_call test_name ~expect_error:true last
8093
8094 (* Generate the code to run a command, leaving the result in 'r'.
8095  * If you expect to get an error then you should set expect_error:true.
8096  *)
8097 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
8098   match cmd with
8099   | [] -> assert false
8100   | name :: args ->
8101       (* Look up the command to find out what args/ret it has. *)
8102       let style =
8103         try
8104           let _, style, _, _, _, _, _ =
8105             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
8106           style
8107         with Not_found ->
8108           failwithf "%s: in test, command %s was not found" test_name name in
8109
8110       if List.length (snd style) <> List.length args then
8111         failwithf "%s: in test, wrong number of args given to %s"
8112           test_name name;
8113
8114       pr "  {\n";
8115
8116       List.iter (
8117         function
8118         | OptString n, "NULL" -> ()
8119         | Pathname n, arg
8120         | Device n, arg
8121         | Dev_or_Path n, arg
8122         | String n, arg
8123         | OptString n, arg
8124         | Key n, arg ->
8125             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8126         | BufferIn n, arg ->
8127             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8128             pr "    size_t %s_size = %d;\n" n (String.length arg)
8129         | Int _, _
8130         | Int64 _, _
8131         | Bool _, _
8132         | FileIn _, _ | FileOut _, _ -> ()
8133         | StringList n, "" | DeviceList n, "" ->
8134             pr "    const char *const %s[1] = { NULL };\n" n
8135         | StringList n, arg | DeviceList n, arg ->
8136             let strs = string_split " " arg in
8137             iteri (
8138               fun i str ->
8139                 pr "    const char *%s_%d = \"%s\";\n" n i (c_quote str);
8140             ) strs;
8141             pr "    const char *const %s[] = {\n" n;
8142             iteri (
8143               fun i _ -> pr "      %s_%d,\n" n i
8144             ) strs;
8145             pr "      NULL\n";
8146             pr "    };\n";
8147       ) (List.combine (snd style) args);
8148
8149       let error_code =
8150         match fst style with
8151         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
8152         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
8153         | RConstString _ | RConstOptString _ ->
8154             pr "    const char *r;\n"; "NULL"
8155         | RString _ -> pr "    char *r;\n"; "NULL"
8156         | RStringList _ | RHashtable _ ->
8157             pr "    char **r;\n";
8158             pr "    size_t i;\n";
8159             "NULL"
8160         | RStruct (_, typ) ->
8161             pr "    struct guestfs_%s *r;\n" typ; "NULL"
8162         | RStructList (_, typ) ->
8163             pr "    struct guestfs_%s_list *r;\n" typ; "NULL"
8164         | RBufferOut _ ->
8165             pr "    char *r;\n";
8166             pr "    size_t size;\n";
8167             "NULL" in
8168
8169       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
8170       pr "    r = guestfs_%s (g" name;
8171
8172       (* Generate the parameters. *)
8173       List.iter (
8174         function
8175         | OptString _, "NULL" -> pr ", NULL"
8176         | Pathname n, _
8177         | Device n, _ | Dev_or_Path n, _
8178         | String n, _
8179         | OptString n, _
8180         | Key n, _ ->
8181             pr ", %s" n
8182         | BufferIn n, _ ->
8183             pr ", %s, %s_size" n n
8184         | FileIn _, arg | FileOut _, arg ->
8185             pr ", \"%s\"" (c_quote arg)
8186         | StringList n, _ | DeviceList n, _ ->
8187             pr ", (char **) %s" n
8188         | Int _, arg ->
8189             let i =
8190               try int_of_string arg
8191               with Failure "int_of_string" ->
8192                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
8193             pr ", %d" i
8194         | Int64 _, arg ->
8195             let i =
8196               try Int64.of_string arg
8197               with Failure "int_of_string" ->
8198                 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
8199             pr ", %Ld" i
8200         | Bool _, arg ->
8201             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
8202       ) (List.combine (snd style) args);
8203
8204       (match fst style with
8205        | RBufferOut _ -> pr ", &size"
8206        | _ -> ()
8207       );
8208
8209       pr ");\n";
8210
8211       if not expect_error then
8212         pr "    if (r == %s)\n" error_code
8213       else
8214         pr "    if (r != %s)\n" error_code;
8215       pr "      return -1;\n";
8216
8217       (* Insert the test code. *)
8218       (match test with
8219        | None -> ()
8220        | Some f -> f ()
8221       );
8222
8223       (match fst style with
8224        | RErr | RInt _ | RInt64 _ | RBool _
8225        | RConstString _ | RConstOptString _ -> ()
8226        | RString _ | RBufferOut _ -> pr "    free (r);\n"
8227        | RStringList _ | RHashtable _ ->
8228            pr "    for (i = 0; r[i] != NULL; ++i)\n";
8229            pr "      free (r[i]);\n";
8230            pr "    free (r);\n"
8231        | RStruct (_, typ) ->
8232            pr "    guestfs_free_%s (r);\n" typ
8233        | RStructList (_, typ) ->
8234            pr "    guestfs_free_%s_list (r);\n" typ
8235       );
8236
8237       pr "  }\n"
8238
8239 and c_quote str =
8240   let str = replace_str str "\r" "\\r" in
8241   let str = replace_str str "\n" "\\n" in
8242   let str = replace_str str "\t" "\\t" in
8243   let str = replace_str str "\000" "\\0" in
8244   str
8245
8246 (* Generate a lot of different functions for guestfish. *)
8247 and generate_fish_cmds () =
8248   generate_header CStyle GPLv2plus;
8249
8250   let all_functions =
8251     List.filter (
8252       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8253     ) all_functions in
8254   let all_functions_sorted =
8255     List.filter (
8256       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8257     ) all_functions_sorted in
8258
8259   pr "#include <config.h>\n";
8260   pr "\n";
8261   pr "#include <stdio.h>\n";
8262   pr "#include <stdlib.h>\n";
8263   pr "#include <string.h>\n";
8264   pr "#include <inttypes.h>\n";
8265   pr "\n";
8266   pr "#include <guestfs.h>\n";
8267   pr "#include \"c-ctype.h\"\n";
8268   pr "#include \"full-write.h\"\n";
8269   pr "#include \"xstrtol.h\"\n";
8270   pr "#include \"fish.h\"\n";
8271   pr "\n";
8272   pr "/* Valid suffixes allowed for numbers.  See Gnulib xstrtol function. */\n";
8273   pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
8274   pr "\n";
8275
8276   (* list_commands function, which implements guestfish -h *)
8277   pr "void list_commands (void)\n";
8278   pr "{\n";
8279   pr "  printf (\"    %%-16s     %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
8280   pr "  list_builtin_commands ();\n";
8281   List.iter (
8282     fun (name, _, _, flags, _, shortdesc, _) ->
8283       let name = replace_char name '_' '-' in
8284       pr "  printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
8285         name shortdesc
8286   ) all_functions_sorted;
8287   pr "  printf (\"    %%s\\n\",";
8288   pr "          _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
8289   pr "}\n";
8290   pr "\n";
8291
8292   (* display_command function, which implements guestfish -h cmd *)
8293   pr "int display_command (const char *cmd)\n";
8294   pr "{\n";
8295   List.iter (
8296     fun (name, style, _, flags, _, shortdesc, longdesc) ->
8297       let name2 = replace_char name '_' '-' in
8298       let alias =
8299         try find_map (function FishAlias n -> Some n | _ -> None) flags
8300         with Not_found -> name in
8301       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
8302       let synopsis =
8303         match snd style with
8304         | [] -> name2
8305         | args ->
8306             let args = List.filter (function Key _ -> false | _ -> true) args in
8307             sprintf "%s %s"
8308               name2 (String.concat " " (List.map name_of_argt args)) in
8309
8310       let warnings =
8311         if List.exists (function Key _ -> true | _ -> false) (snd style) then
8312           "\n\nThis command has one or more key or passphrase parameters.
8313 Guestfish will prompt for these separately."
8314         else "" in
8315
8316       let warnings =
8317         warnings ^
8318           if List.mem ProtocolLimitWarning flags then
8319             ("\n\n" ^ protocol_limit_warning)
8320           else "" in
8321
8322       (* For DangerWillRobinson commands, we should probably have
8323        * guestfish prompt before allowing you to use them (especially
8324        * in interactive mode). XXX
8325        *)
8326       let warnings =
8327         warnings ^
8328           if List.mem DangerWillRobinson flags then
8329             ("\n\n" ^ danger_will_robinson)
8330           else "" in
8331
8332       let warnings =
8333         warnings ^
8334           match deprecation_notice flags with
8335           | None -> ""
8336           | Some txt -> "\n\n" ^ txt in
8337
8338       let describe_alias =
8339         if name <> alias then
8340           sprintf "\n\nYou can use '%s' as an alias for this command." alias
8341         else "" in
8342
8343       pr "  if (";
8344       pr "STRCASEEQ (cmd, \"%s\")" name;
8345       if name <> name2 then
8346         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8347       if name <> alias then
8348         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8349       pr ") {\n";
8350       pr "    pod2text (\"%s\", _(\"%s\"), %S);\n"
8351         name2 shortdesc
8352         ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
8353          "=head1 DESCRIPTION\n\n" ^
8354          longdesc ^ warnings ^ describe_alias);
8355       pr "    return 0;\n";
8356       pr "  }\n";
8357       pr "  else\n"
8358   ) all_functions;
8359   pr "    return display_builtin_command (cmd);\n";
8360   pr "}\n";
8361   pr "\n";
8362
8363   let emit_print_list_function typ =
8364     pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
8365       typ typ typ;
8366     pr "{\n";
8367     pr "  unsigned int i;\n";
8368     pr "\n";
8369     pr "  for (i = 0; i < %ss->len; ++i) {\n" typ;
8370     pr "    printf (\"[%%d] = {\\n\", i);\n";
8371     pr "    print_%s_indent (&%ss->val[i], \"  \");\n" typ typ;
8372     pr "    printf (\"}\\n\");\n";
8373     pr "  }\n";
8374     pr "}\n";
8375     pr "\n";
8376   in
8377
8378   (* print_* functions *)
8379   List.iter (
8380     fun (typ, cols) ->
8381       let needs_i =
8382         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
8383
8384       pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
8385       pr "{\n";
8386       if needs_i then (
8387         pr "  unsigned int i;\n";
8388         pr "\n"
8389       );
8390       List.iter (
8391         function
8392         | name, FString ->
8393             pr "  printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
8394         | name, FUUID ->
8395             pr "  printf (\"%%s%s: \", indent);\n" name;
8396             pr "  for (i = 0; i < 32; ++i)\n";
8397             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
8398             pr "  printf (\"\\n\");\n"
8399         | name, FBuffer ->
8400             pr "  printf (\"%%s%s: \", indent);\n" name;
8401             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
8402             pr "    if (c_isprint (%s->%s[i]))\n" typ name;
8403             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
8404             pr "    else\n";
8405             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
8406             pr "  printf (\"\\n\");\n"
8407         | name, (FUInt64|FBytes) ->
8408             pr "  printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
8409               name typ name
8410         | name, FInt64 ->
8411             pr "  printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
8412               name typ name
8413         | name, FUInt32 ->
8414             pr "  printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
8415               name typ name
8416         | name, FInt32 ->
8417             pr "  printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
8418               name typ name
8419         | name, FChar ->
8420             pr "  printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
8421               name typ name
8422         | name, FOptPercent ->
8423             pr "  if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
8424               typ name name typ name;
8425             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
8426       ) cols;
8427       pr "}\n";
8428       pr "\n";
8429   ) structs;
8430
8431   (* Emit a print_TYPE_list function definition only if that function is used. *)
8432   List.iter (
8433     function
8434     | typ, (RStructListOnly | RStructAndList) ->
8435         (* generate the function for typ *)
8436         emit_print_list_function typ
8437     | typ, _ -> () (* empty *)
8438   ) (rstructs_used_by all_functions);
8439
8440   (* Emit a print_TYPE function definition only if that function is used. *)
8441   List.iter (
8442     function
8443     | typ, (RStructOnly | RStructAndList) ->
8444         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
8445         pr "{\n";
8446         pr "  print_%s_indent (%s, \"\");\n" typ typ;
8447         pr "}\n";
8448         pr "\n";
8449     | typ, _ -> () (* empty *)
8450   ) (rstructs_used_by all_functions);
8451
8452   (* run_<action> actions *)
8453   List.iter (
8454     fun (name, style, _, flags, _, _, _) ->
8455       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
8456       pr "{\n";
8457       (match fst style with
8458        | RErr
8459        | RInt _
8460        | RBool _ -> pr "  int r;\n"
8461        | RInt64 _ -> pr "  int64_t r;\n"
8462        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
8463        | RString _ -> pr "  char *r;\n"
8464        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
8465        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
8466        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
8467        | RBufferOut _ ->
8468            pr "  char *r;\n";
8469            pr "  size_t size;\n";
8470       );
8471       List.iter (
8472         function
8473         | Device n
8474         | String n
8475         | OptString n -> pr "  const char *%s;\n" n
8476         | Pathname n
8477         | Dev_or_Path n
8478         | FileIn n
8479         | FileOut n
8480         | Key n -> pr "  char *%s;\n" n
8481         | BufferIn n ->
8482             pr "  const char *%s;\n" n;
8483             pr "  size_t %s_size;\n" n
8484         | StringList n | DeviceList n -> pr "  char **%s;\n" n
8485         | Bool n -> pr "  int %s;\n" n
8486         | Int n -> pr "  int %s;\n" n
8487         | Int64 n -> pr "  int64_t %s;\n" n
8488       ) (snd style);
8489
8490       (* Check and convert parameters. *)
8491       let argc_expected =
8492         let args_no_keys =
8493           List.filter (function Key _ -> false | _ -> true) (snd style) in
8494         List.length args_no_keys in
8495       pr "  if (argc != %d) {\n" argc_expected;
8496       pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
8497         argc_expected;
8498       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
8499       pr "    return -1;\n";
8500       pr "  }\n";
8501
8502       let parse_integer fn fntyp rtyp range name =
8503         pr "  {\n";
8504         pr "    strtol_error xerr;\n";
8505         pr "    %s r;\n" fntyp;
8506         pr "\n";
8507         pr "    xerr = %s (argv[i++], NULL, 0, &r, xstrtol_suffixes);\n" fn;
8508         pr "    if (xerr != LONGINT_OK) {\n";
8509         pr "      fprintf (stderr,\n";
8510         pr "               _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
8511         pr "               cmd, \"%s\", \"%s\", xerr);\n" name fn;
8512         pr "      return -1;\n";
8513         pr "    }\n";
8514         (match range with
8515          | None -> ()
8516          | Some (min, max, comment) ->
8517              pr "    /* %s */\n" comment;
8518              pr "    if (r < %s || r > %s) {\n" min max;
8519              pr "      fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
8520                name;
8521              pr "      return -1;\n";
8522              pr "    }\n";
8523              pr "    /* The check above should ensure this assignment does not overflow. */\n";
8524         );
8525         pr "    %s = r;\n" name;
8526         pr "  }\n";
8527       in
8528
8529       if snd style <> [] then
8530         pr "  size_t i = 0;\n";
8531
8532       List.iter (
8533         function
8534         | Device name
8535         | String name ->
8536             pr "  %s = argv[i++];\n" name
8537         | Pathname name
8538         | Dev_or_Path name ->
8539             pr "  %s = resolve_win_path (argv[i++]);\n" name;
8540             pr "  if (%s == NULL) return -1;\n" name
8541         | OptString name ->
8542             pr "  %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
8543             pr "  i++;\n"
8544         | BufferIn name ->
8545             pr "  %s = argv[i];\n" name;
8546             pr "  %s_size = strlen (argv[i]);\n" name;
8547             pr "  i++;\n"
8548         | FileIn name ->
8549             pr "  %s = file_in (argv[i++]);\n" name;
8550             pr "  if (%s == NULL) return -1;\n" name
8551         | FileOut name ->
8552             pr "  %s = file_out (argv[i++]);\n" name;
8553             pr "  if (%s == NULL) return -1;\n" name
8554         | StringList name | DeviceList name ->
8555             pr "  %s = parse_string_list (argv[i++]);\n" name;
8556             pr "  if (%s == NULL) return -1;\n" name
8557         | Key name ->
8558             pr "  %s = read_key (\"%s\");\n" name name;
8559             pr "  if (%s == NULL) return -1;\n" name
8560         | Bool name ->
8561             pr "  %s = is_true (argv[i++]) ? 1 : 0;\n" name
8562         | Int name ->
8563             let range =
8564               let min = "(-(2LL<<30))"
8565               and max = "((2LL<<30)-1)"
8566               and comment =
8567                 "The Int type in the generator is a signed 31 bit int." in
8568               Some (min, max, comment) in
8569             parse_integer "xstrtoll" "long long" "int" range name
8570         | Int64 name ->
8571             parse_integer "xstrtoll" "long long" "int64_t" None name
8572       ) (snd style);
8573
8574       (* Call C API function. *)
8575       pr "  r = guestfs_%s " name;
8576       generate_c_call_args ~handle:"g" style;
8577       pr ";\n";
8578
8579       List.iter (
8580         function
8581         | Device _ | String _
8582         | OptString _ | Bool _
8583         | Int _ | Int64 _
8584         | BufferIn _ -> ()
8585         | Pathname name | Dev_or_Path name | FileOut name
8586         | Key name ->
8587             pr "  free (%s);\n" name
8588         | FileIn name ->
8589             pr "  free_file_in (%s);\n" name
8590         | StringList name | DeviceList name ->
8591             pr "  free_strings (%s);\n" name
8592       ) (snd style);
8593
8594       (* Any output flags? *)
8595       let fish_output =
8596         let flags = filter_map (
8597           function FishOutput flag -> Some flag | _ -> None
8598         ) flags in
8599         match flags with
8600         | [] -> None
8601         | [f] -> Some f
8602         | _ ->
8603             failwithf "%s: more than one FishOutput flag is not allowed" name in
8604
8605       (* Check return value for errors and display command results. *)
8606       (match fst style with
8607        | RErr -> pr "  return r;\n"
8608        | RInt _ ->
8609            pr "  if (r == -1) return -1;\n";
8610            (match fish_output with
8611             | None ->
8612                 pr "  printf (\"%%d\\n\", r);\n";
8613             | Some FishOutputOctal ->
8614                 pr "  printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
8615             | Some FishOutputHexadecimal ->
8616                 pr "  printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8617            pr "  return 0;\n"
8618        | RInt64 _ ->
8619            pr "  if (r == -1) return -1;\n";
8620            (match fish_output with
8621             | None ->
8622                 pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
8623             | Some FishOutputOctal ->
8624                 pr "  printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
8625             | Some FishOutputHexadecimal ->
8626                 pr "  printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8627            pr "  return 0;\n"
8628        | RBool _ ->
8629            pr "  if (r == -1) return -1;\n";
8630            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
8631            pr "  return 0;\n"
8632        | RConstString _ ->
8633            pr "  if (r == NULL) return -1;\n";
8634            pr "  printf (\"%%s\\n\", r);\n";
8635            pr "  return 0;\n"
8636        | RConstOptString _ ->
8637            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
8638            pr "  return 0;\n"
8639        | RString _ ->
8640            pr "  if (r == NULL) return -1;\n";
8641            pr "  printf (\"%%s\\n\", r);\n";
8642            pr "  free (r);\n";
8643            pr "  return 0;\n"
8644        | RStringList _ ->
8645            pr "  if (r == NULL) return -1;\n";
8646            pr "  print_strings (r);\n";
8647            pr "  free_strings (r);\n";
8648            pr "  return 0;\n"
8649        | RStruct (_, typ) ->
8650            pr "  if (r == NULL) return -1;\n";
8651            pr "  print_%s (r);\n" typ;
8652            pr "  guestfs_free_%s (r);\n" typ;
8653            pr "  return 0;\n"
8654        | RStructList (_, typ) ->
8655            pr "  if (r == NULL) return -1;\n";
8656            pr "  print_%s_list (r);\n" typ;
8657            pr "  guestfs_free_%s_list (r);\n" typ;
8658            pr "  return 0;\n"
8659        | RHashtable _ ->
8660            pr "  if (r == NULL) return -1;\n";
8661            pr "  print_table (r);\n";
8662            pr "  free_strings (r);\n";
8663            pr "  return 0;\n"
8664        | RBufferOut _ ->
8665            pr "  if (r == NULL) return -1;\n";
8666            pr "  if (full_write (1, r, size) != size) {\n";
8667            pr "    perror (\"write\");\n";
8668            pr "    free (r);\n";
8669            pr "    return -1;\n";
8670            pr "  }\n";
8671            pr "  free (r);\n";
8672            pr "  return 0;\n"
8673       );
8674       pr "}\n";
8675       pr "\n"
8676   ) all_functions;
8677
8678   (* run_action function *)
8679   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
8680   pr "{\n";
8681   List.iter (
8682     fun (name, _, _, flags, _, _, _) ->
8683       let name2 = replace_char name '_' '-' in
8684       let alias =
8685         try find_map (function FishAlias n -> Some n | _ -> None) flags
8686         with Not_found -> name in
8687       pr "  if (";
8688       pr "STRCASEEQ (cmd, \"%s\")" name;
8689       if name <> name2 then
8690         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8691       if name <> alias then
8692         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8693       pr ")\n";
8694       pr "    return run_%s (cmd, argc, argv);\n" name;
8695       pr "  else\n";
8696   ) all_functions;
8697   pr "    {\n";
8698   pr "      fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
8699   pr "      if (command_num == 1)\n";
8700   pr "        extended_help_message ();\n";
8701   pr "      return -1;\n";
8702   pr "    }\n";
8703   pr "  return 0;\n";
8704   pr "}\n";
8705   pr "\n"
8706
8707 (* Readline completion for guestfish. *)
8708 and generate_fish_completion () =
8709   generate_header CStyle GPLv2plus;
8710
8711   let all_functions =
8712     List.filter (
8713       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8714     ) all_functions in
8715
8716   pr "\
8717 #include <config.h>
8718
8719 #include <stdio.h>
8720 #include <stdlib.h>
8721 #include <string.h>
8722
8723 #ifdef HAVE_LIBREADLINE
8724 #include <readline/readline.h>
8725 #endif
8726
8727 #include \"fish.h\"
8728
8729 #ifdef HAVE_LIBREADLINE
8730
8731 static const char *const commands[] = {
8732   BUILTIN_COMMANDS_FOR_COMPLETION,
8733 ";
8734
8735   (* Get the commands, including the aliases.  They don't need to be
8736    * sorted - the generator() function just does a dumb linear search.
8737    *)
8738   let commands =
8739     List.map (
8740       fun (name, _, _, flags, _, _, _) ->
8741         let name2 = replace_char name '_' '-' in
8742         let alias =
8743           try find_map (function FishAlias n -> Some n | _ -> None) flags
8744           with Not_found -> name in
8745
8746         if name <> alias then [name2; alias] else [name2]
8747     ) all_functions in
8748   let commands = List.flatten commands in
8749
8750   List.iter (pr "  \"%s\",\n") commands;
8751
8752   pr "  NULL
8753 };
8754
8755 static char *
8756 generator (const char *text, int state)
8757 {
8758   static size_t index, len;
8759   const char *name;
8760
8761   if (!state) {
8762     index = 0;
8763     len = strlen (text);
8764   }
8765
8766   rl_attempted_completion_over = 1;
8767
8768   while ((name = commands[index]) != NULL) {
8769     index++;
8770     if (STRCASEEQLEN (name, text, len))
8771       return strdup (name);
8772   }
8773
8774   return NULL;
8775 }
8776
8777 #endif /* HAVE_LIBREADLINE */
8778
8779 #ifdef HAVE_RL_COMPLETION_MATCHES
8780 #define RL_COMPLETION_MATCHES rl_completion_matches
8781 #else
8782 #ifdef HAVE_COMPLETION_MATCHES
8783 #define RL_COMPLETION_MATCHES completion_matches
8784 #endif
8785 #endif /* else just fail if we don't have either symbol */
8786
8787 char **
8788 do_completion (const char *text, int start, int end)
8789 {
8790   char **matches = NULL;
8791
8792 #ifdef HAVE_LIBREADLINE
8793   rl_completion_append_character = ' ';
8794
8795   if (start == 0)
8796     matches = RL_COMPLETION_MATCHES (text, generator);
8797   else if (complete_dest_paths)
8798     matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
8799 #endif
8800
8801   return matches;
8802 }
8803 ";
8804
8805 (* Generate the POD documentation for guestfish. *)
8806 and generate_fish_actions_pod () =
8807   let all_functions_sorted =
8808     List.filter (
8809       fun (_, _, _, flags, _, _, _) ->
8810         not (List.mem NotInFish flags || List.mem NotInDocs flags)
8811     ) all_functions_sorted in
8812
8813   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
8814
8815   List.iter (
8816     fun (name, style, _, flags, _, _, longdesc) ->
8817       let longdesc =
8818         Str.global_substitute rex (
8819           fun s ->
8820             let sub =
8821               try Str.matched_group 1 s
8822               with Not_found ->
8823                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
8824             "C<" ^ replace_char sub '_' '-' ^ ">"
8825         ) longdesc in
8826       let name = replace_char name '_' '-' in
8827       let alias =
8828         try find_map (function FishAlias n -> Some n | _ -> None) flags
8829         with Not_found -> name in
8830
8831       pr "=head2 %s" name;
8832       if name <> alias then
8833         pr " | %s" alias;
8834       pr "\n";
8835       pr "\n";
8836       pr " %s" name;
8837       List.iter (
8838         function
8839         | Pathname n | Device n | Dev_or_Path n | String n ->
8840             pr " %s" n
8841         | OptString n -> pr " %s" n
8842         | StringList n | DeviceList n -> pr " '%s ...'" n
8843         | Bool _ -> pr " true|false"
8844         | Int n -> pr " %s" n
8845         | Int64 n -> pr " %s" n
8846         | FileIn n | FileOut n -> pr " (%s|-)" n
8847         | BufferIn n -> pr " %s" n
8848         | Key _ -> () (* keys are entered at a prompt *)
8849       ) (snd style);
8850       pr "\n";
8851       pr "\n";
8852       pr "%s\n\n" longdesc;
8853
8854       if List.exists (function FileIn _ | FileOut _ -> true
8855                       | _ -> false) (snd style) then
8856         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
8857
8858       if List.exists (function Key _ -> true | _ -> false) (snd style) then
8859         pr "This command has one or more key or passphrase parameters.
8860 Guestfish will prompt for these separately.\n\n";
8861
8862       if List.mem ProtocolLimitWarning flags then
8863         pr "%s\n\n" protocol_limit_warning;
8864
8865       if List.mem DangerWillRobinson flags then
8866         pr "%s\n\n" danger_will_robinson;
8867
8868       match deprecation_notice flags with
8869       | None -> ()
8870       | Some txt -> pr "%s\n\n" txt
8871   ) all_functions_sorted
8872
8873 and generate_fish_prep_options_h () =
8874   generate_header CStyle GPLv2plus;
8875
8876   pr "#ifndef PREPOPTS_H\n";
8877   pr "\n";
8878
8879   pr "\
8880 struct prep {
8881   const char *name;             /* eg. \"fs\" */
8882
8883   size_t nr_params;             /* optional parameters */
8884   struct prep_param *params;
8885
8886   const char *shortdesc;        /* short description */
8887   const char *longdesc;         /* long description */
8888
8889                                 /* functions to implement it */
8890   void (*prelaunch) (const char *filename, prep_data *);
8891   void (*postlaunch) (const char *filename, prep_data *, const char *device);
8892 };
8893
8894 struct prep_param {
8895   const char *pname;            /* parameter name */
8896   const char *pdefault;         /* parameter default */
8897   const char *pdesc;            /* parameter description */
8898 };
8899
8900 extern const struct prep preps[];
8901 #define NR_PREPS %d
8902
8903 " (List.length prepopts);
8904
8905   List.iter (
8906     fun (name, shortdesc, args, longdesc) ->
8907       pr "\
8908 extern void prep_prelaunch_%s (const char *filename, prep_data *data);
8909 extern void prep_postlaunch_%s (const char *filename, prep_data *data, const char *device);
8910
8911 " name name;
8912   ) prepopts;
8913
8914   pr "\n";
8915   pr "#endif /* PREPOPTS_H */\n"
8916
8917 and generate_fish_prep_options_c () =
8918   generate_header CStyle GPLv2plus;
8919
8920   pr "\
8921 #include \"fish.h\"
8922 #include \"prepopts.h\"
8923
8924 ";
8925
8926   List.iter (
8927     fun (name, shortdesc, args, longdesc) ->
8928       pr "static struct prep_param %s_args[] = {\n" name;
8929       List.iter (
8930         fun (n, default, desc) ->
8931           pr "  { \"%s\", \"%s\", \"%s\" },\n" n default desc
8932       ) args;
8933       pr "};\n";
8934       pr "\n";
8935   ) prepopts;
8936
8937   pr "const struct prep preps[] = {\n";
8938   List.iter (
8939     fun (name, shortdesc, args, longdesc) ->
8940       pr "  { \"%s\", %d, %s_args,
8941     \"%s\",
8942     \"%s\",
8943     prep_prelaunch_%s, prep_postlaunch_%s },
8944 "
8945         name (List.length args) name
8946         (c_quote shortdesc) (c_quote longdesc)
8947         name name;
8948   ) prepopts;
8949   pr "};\n"
8950
8951 (* Generate a C function prototype. *)
8952 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
8953     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
8954     ?(prefix = "")
8955     ?handle name style =
8956   if extern then pr "extern ";
8957   if static then pr "static ";
8958   (match fst style with
8959    | RErr -> pr "int "
8960    | RInt _ -> pr "int "
8961    | RInt64 _ -> pr "int64_t "
8962    | RBool _ -> pr "int "
8963    | RConstString _ | RConstOptString _ -> pr "const char *"
8964    | RString _ | RBufferOut _ -> pr "char *"
8965    | RStringList _ | RHashtable _ -> pr "char **"
8966    | RStruct (_, typ) ->
8967        if not in_daemon then pr "struct guestfs_%s *" typ
8968        else pr "guestfs_int_%s *" typ
8969    | RStructList (_, typ) ->
8970        if not in_daemon then pr "struct guestfs_%s_list *" typ
8971        else pr "guestfs_int_%s_list *" typ
8972   );
8973   let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
8974   pr "%s%s (" prefix name;
8975   if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
8976     pr "void"
8977   else (
8978     let comma = ref false in
8979     (match handle with
8980      | None -> ()
8981      | Some handle -> pr "guestfs_h *%s" handle; comma := true
8982     );
8983     let next () =
8984       if !comma then (
8985         if single_line then pr ", " else pr ",\n\t\t"
8986       );
8987       comma := true
8988     in
8989     List.iter (
8990       function
8991       | Pathname n
8992       | Device n | Dev_or_Path n
8993       | String n
8994       | OptString n
8995       | Key n ->
8996           next ();
8997           pr "const char *%s" n
8998       | StringList n | DeviceList n ->
8999           next ();
9000           pr "char *const *%s" n
9001       | Bool n -> next (); pr "int %s" n
9002       | Int n -> next (); pr "int %s" n
9003       | Int64 n -> next (); pr "int64_t %s" n
9004       | FileIn n
9005       | FileOut n ->
9006           if not in_daemon then (next (); pr "const char *%s" n)
9007       | BufferIn n ->
9008           next ();
9009           pr "const char *%s" n;
9010           next ();
9011           pr "size_t %s_size" n
9012     ) (snd style);
9013     if is_RBufferOut then (next (); pr "size_t *size_r");
9014   );
9015   pr ")";
9016   if semicolon then pr ";";
9017   if newline then pr "\n"
9018
9019 (* Generate C call arguments, eg "(handle, foo, bar)" *)
9020 and generate_c_call_args ?handle ?(decl = false) style =
9021   pr "(";
9022   let comma = ref false in
9023   let next () =
9024     if !comma then pr ", ";
9025     comma := true
9026   in
9027   (match handle with
9028    | None -> ()
9029    | Some handle -> pr "%s" handle; comma := true
9030   );
9031   List.iter (
9032     function
9033     | BufferIn n ->
9034         next ();
9035         pr "%s, %s_size" n n
9036     | arg ->
9037         next ();
9038         pr "%s" (name_of_argt arg)
9039   ) (snd style);
9040   (* For RBufferOut calls, add implicit &size parameter. *)
9041   if not decl then (
9042     match fst style with
9043     | RBufferOut _ ->
9044         next ();
9045         pr "&size"
9046     | _ -> ()
9047   );
9048   pr ")"
9049
9050 (* Generate the OCaml bindings interface. *)
9051 and generate_ocaml_mli () =
9052   generate_header OCamlStyle LGPLv2plus;
9053
9054   pr "\
9055 (** For API documentation you should refer to the C API
9056     in the guestfs(3) manual page.  The OCaml API uses almost
9057     exactly the same calls. *)
9058
9059 type t
9060 (** A [guestfs_h] handle. *)
9061
9062 exception Error of string
9063 (** This exception is raised when there is an error. *)
9064
9065 exception Handle_closed of string
9066 (** This exception is raised if you use a {!Guestfs.t} handle
9067     after calling {!close} on it.  The string is the name of
9068     the function. *)
9069
9070 val create : unit -> t
9071 (** Create a {!Guestfs.t} handle. *)
9072
9073 val close : t -> unit
9074 (** Close the {!Guestfs.t} handle and free up all resources used
9075     by it immediately.
9076
9077     Handles are closed by the garbage collector when they become
9078     unreferenced, but callers can call this in order to provide
9079     predictable cleanup. *)
9080
9081 type progress_cb = int -> int -> int64 -> int64 -> unit
9082
9083 val set_progress_callback : t -> progress_cb -> unit
9084 (** [set_progress_callback g f] sets [f] as the progress callback function.
9085     For some long-running functions, [f] will be called repeatedly
9086     during the function with progress updates.
9087
9088     The callback is [f proc_nr serial position total].  See
9089     the description of [guestfs_set_progress_callback] in guestfs(3)
9090     for the meaning of these four numbers.
9091
9092     Note that if the closure captures a reference to the handle,
9093     this reference will prevent the handle from being
9094     automatically closed by the garbage collector.  There are
9095     three ways to avoid this: be careful not to capture the handle
9096     in the closure, or use a weak reference, or call
9097     {!Guestfs.clear_progress_callback} to remove the reference. *)
9098
9099 val clear_progress_callback : t -> unit
9100 (** [clear_progress_callback g] removes any progress callback function
9101     associated with the handle.  See {!Guestfs.set_progress_callback}. *)
9102
9103 ";
9104   generate_ocaml_structure_decls ();
9105
9106   (* The actions. *)
9107   List.iter (
9108     fun (name, style, _, _, _, shortdesc, _) ->
9109       generate_ocaml_prototype name style;
9110       pr "(** %s *)\n" shortdesc;
9111       pr "\n"
9112   ) all_functions_sorted
9113
9114 (* Generate the OCaml bindings implementation. *)
9115 and generate_ocaml_ml () =
9116   generate_header OCamlStyle LGPLv2plus;
9117
9118   pr "\
9119 type t
9120
9121 exception Error of string
9122 exception Handle_closed of string
9123
9124 external create : unit -> t = \"ocaml_guestfs_create\"
9125 external close : t -> unit = \"ocaml_guestfs_close\"
9126
9127 type progress_cb = int -> int -> int64 -> int64 -> unit
9128
9129 external set_progress_callback : t -> progress_cb -> unit
9130   = \"ocaml_guestfs_set_progress_callback\"
9131 external clear_progress_callback : t -> unit
9132   = \"ocaml_guestfs_clear_progress_callback\"
9133
9134 (* Give the exceptions names, so they can be raised from the C code. *)
9135 let () =
9136   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
9137   Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
9138
9139 ";
9140
9141   generate_ocaml_structure_decls ();
9142
9143   (* The actions. *)
9144   List.iter (
9145     fun (name, style, _, _, _, shortdesc, _) ->
9146       generate_ocaml_prototype ~is_external:true name style;
9147   ) all_functions_sorted
9148
9149 (* Generate the OCaml bindings C implementation. *)
9150 and generate_ocaml_c () =
9151   generate_header CStyle LGPLv2plus;
9152
9153   pr "\
9154 #include <stdio.h>
9155 #include <stdlib.h>
9156 #include <string.h>
9157
9158 #include <caml/config.h>
9159 #include <caml/alloc.h>
9160 #include <caml/callback.h>
9161 #include <caml/fail.h>
9162 #include <caml/memory.h>
9163 #include <caml/mlvalues.h>
9164 #include <caml/signals.h>
9165
9166 #include \"guestfs.h\"
9167
9168 #include \"guestfs_c.h\"
9169
9170 /* Copy a hashtable of string pairs into an assoc-list.  We return
9171  * the list in reverse order, but hashtables aren't supposed to be
9172  * ordered anyway.
9173  */
9174 static CAMLprim value
9175 copy_table (char * const * argv)
9176 {
9177   CAMLparam0 ();
9178   CAMLlocal5 (rv, pairv, kv, vv, cons);
9179   size_t i;
9180
9181   rv = Val_int (0);
9182   for (i = 0; argv[i] != NULL; i += 2) {
9183     kv = caml_copy_string (argv[i]);
9184     vv = caml_copy_string (argv[i+1]);
9185     pairv = caml_alloc (2, 0);
9186     Store_field (pairv, 0, kv);
9187     Store_field (pairv, 1, vv);
9188     cons = caml_alloc (2, 0);
9189     Store_field (cons, 1, rv);
9190     rv = cons;
9191     Store_field (cons, 0, pairv);
9192   }
9193
9194   CAMLreturn (rv);
9195 }
9196
9197 ";
9198
9199   (* Struct copy functions. *)
9200
9201   let emit_ocaml_copy_list_function typ =
9202     pr "static CAMLprim value\n";
9203     pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
9204     pr "{\n";
9205     pr "  CAMLparam0 ();\n";
9206     pr "  CAMLlocal2 (rv, v);\n";
9207     pr "  unsigned int i;\n";
9208     pr "\n";
9209     pr "  if (%ss->len == 0)\n" typ;
9210     pr "    CAMLreturn (Atom (0));\n";
9211     pr "  else {\n";
9212     pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
9213     pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
9214     pr "      v = copy_%s (&%ss->val[i]);\n" typ typ;
9215     pr "      caml_modify (&Field (rv, i), v);\n";
9216     pr "    }\n";
9217     pr "    CAMLreturn (rv);\n";
9218     pr "  }\n";
9219     pr "}\n";
9220     pr "\n";
9221   in
9222
9223   List.iter (
9224     fun (typ, cols) ->
9225       let has_optpercent_col =
9226         List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
9227
9228       pr "static CAMLprim value\n";
9229       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
9230       pr "{\n";
9231       pr "  CAMLparam0 ();\n";
9232       if has_optpercent_col then
9233         pr "  CAMLlocal3 (rv, v, v2);\n"
9234       else
9235         pr "  CAMLlocal2 (rv, v);\n";
9236       pr "\n";
9237       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
9238       iteri (
9239         fun i col ->
9240           (match col with
9241            | name, FString ->
9242                pr "  v = caml_copy_string (%s->%s);\n" typ name
9243            | name, FBuffer ->
9244                pr "  v = caml_alloc_string (%s->%s_len);\n" typ name;
9245                pr "  memcpy (String_val (v), %s->%s, %s->%s_len);\n"
9246                  typ name typ name
9247            | name, FUUID ->
9248                pr "  v = caml_alloc_string (32);\n";
9249                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
9250            | name, (FBytes|FInt64|FUInt64) ->
9251                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
9252            | name, (FInt32|FUInt32) ->
9253                pr "  v = caml_copy_int32 (%s->%s);\n" typ name
9254            | name, FOptPercent ->
9255                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
9256                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
9257                pr "    v = caml_alloc (1, 0);\n";
9258                pr "    Store_field (v, 0, v2);\n";
9259                pr "  } else /* None */\n";
9260                pr "    v = Val_int (0);\n";
9261            | name, FChar ->
9262                pr "  v = Val_int (%s->%s);\n" typ name
9263           );
9264           pr "  Store_field (rv, %d, v);\n" i
9265       ) cols;
9266       pr "  CAMLreturn (rv);\n";
9267       pr "}\n";
9268       pr "\n";
9269   ) structs;
9270
9271   (* Emit a copy_TYPE_list function definition only if that function is used. *)
9272   List.iter (
9273     function
9274     | typ, (RStructListOnly | RStructAndList) ->
9275         (* generate the function for typ *)
9276         emit_ocaml_copy_list_function typ
9277     | typ, _ -> () (* empty *)
9278   ) (rstructs_used_by all_functions);
9279
9280   (* The wrappers. *)
9281   List.iter (
9282     fun (name, style, _, _, _, _, _) ->
9283       pr "/* Automatically generated wrapper for function\n";
9284       pr " * ";
9285       generate_ocaml_prototype name style;
9286       pr " */\n";
9287       pr "\n";
9288
9289       let params =
9290         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
9291
9292       let needs_extra_vs =
9293         match fst style with RConstOptString _ -> true | _ -> false in
9294
9295       pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9296       pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
9297       List.iter (pr ", value %s") (List.tl params); pr ");\n";
9298       pr "\n";
9299
9300       pr "CAMLprim value\n";
9301       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
9302       List.iter (pr ", value %s") (List.tl params);
9303       pr ")\n";
9304       pr "{\n";
9305
9306       (match params with
9307        | [p1; p2; p3; p4; p5] ->
9308            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
9309        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
9310            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
9311            pr "  CAMLxparam%d (%s);\n"
9312              (List.length rest) (String.concat ", " rest)
9313        | ps ->
9314            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
9315       );
9316       if not needs_extra_vs then
9317         pr "  CAMLlocal1 (rv);\n"
9318       else
9319         pr "  CAMLlocal3 (rv, v, v2);\n";
9320       pr "\n";
9321
9322       pr "  guestfs_h *g = Guestfs_val (gv);\n";
9323       pr "  if (g == NULL)\n";
9324       pr "    ocaml_guestfs_raise_closed (\"%s\");\n" name;
9325       pr "\n";
9326
9327       List.iter (
9328         function
9329         | Pathname n
9330         | Device n | Dev_or_Path n
9331         | String n
9332         | FileIn n
9333         | FileOut n
9334         | Key n ->
9335             (* Copy strings in case the GC moves them: RHBZ#604691 *)
9336             pr "  char *%s = guestfs_safe_strdup (g, String_val (%sv));\n" n n
9337         | OptString n ->
9338             pr "  char *%s =\n" n;
9339             pr "    %sv != Val_int (0) ?" n;
9340             pr "      guestfs_safe_strdup (g, String_val (Field (%sv, 0))) : NULL;\n" n
9341         | BufferIn n ->
9342             pr "  size_t %s_size = caml_string_length (%sv);\n" n n;
9343             pr "  char *%s = guestfs_safe_memdup (g, String_val (%sv), %s_size);\n" n n n
9344         | StringList n | DeviceList n ->
9345             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
9346         | Bool n ->
9347             pr "  int %s = Bool_val (%sv);\n" n n
9348         | Int n ->
9349             pr "  int %s = Int_val (%sv);\n" n n
9350         | Int64 n ->
9351             pr "  int64_t %s = Int64_val (%sv);\n" n n
9352       ) (snd style);
9353       let error_code =
9354         match fst style with
9355         | RErr -> pr "  int r;\n"; "-1"
9356         | RInt _ -> pr "  int r;\n"; "-1"
9357         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
9358         | RBool _ -> pr "  int r;\n"; "-1"
9359         | RConstString _ | RConstOptString _ ->
9360             pr "  const char *r;\n"; "NULL"
9361         | RString _ -> pr "  char *r;\n"; "NULL"
9362         | RStringList _ ->
9363             pr "  size_t i;\n";
9364             pr "  char **r;\n";
9365             "NULL"
9366         | RStruct (_, typ) ->
9367             pr "  struct guestfs_%s *r;\n" typ; "NULL"
9368         | RStructList (_, typ) ->
9369             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
9370         | RHashtable _ ->
9371             pr "  size_t i;\n";
9372             pr "  char **r;\n";
9373             "NULL"
9374         | RBufferOut _ ->
9375             pr "  char *r;\n";
9376             pr "  size_t size;\n";
9377             "NULL" in
9378       pr "\n";
9379
9380       pr "  caml_enter_blocking_section ();\n";
9381       pr "  r = guestfs_%s " name;
9382       generate_c_call_args ~handle:"g" style;
9383       pr ";\n";
9384       pr "  caml_leave_blocking_section ();\n";
9385
9386       (* Free strings if we copied them above. *)
9387       List.iter (
9388         function
9389         | Pathname n | Device n | Dev_or_Path n | String n | OptString n
9390         | FileIn n | FileOut n | BufferIn n | Key n ->
9391             pr "  free (%s);\n" n
9392         | StringList n | DeviceList n ->
9393             pr "  ocaml_guestfs_free_strings (%s);\n" n;
9394         | Bool _ | Int _ | Int64 _ -> ()
9395       ) (snd style);
9396
9397       pr "  if (r == %s)\n" error_code;
9398       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
9399       pr "\n";
9400
9401       (match fst style with
9402        | RErr -> pr "  rv = Val_unit;\n"
9403        | RInt _ -> pr "  rv = Val_int (r);\n"
9404        | RInt64 _ ->
9405            pr "  rv = caml_copy_int64 (r);\n"
9406        | RBool _ -> pr "  rv = Val_bool (r);\n"
9407        | RConstString _ ->
9408            pr "  rv = caml_copy_string (r);\n"
9409        | RConstOptString _ ->
9410            pr "  if (r) { /* Some string */\n";
9411            pr "    v = caml_alloc (1, 0);\n";
9412            pr "    v2 = caml_copy_string (r);\n";
9413            pr "    Store_field (v, 0, v2);\n";
9414            pr "  } else /* None */\n";
9415            pr "    v = Val_int (0);\n";
9416        | RString _ ->
9417            pr "  rv = caml_copy_string (r);\n";
9418            pr "  free (r);\n"
9419        | RStringList _ ->
9420            pr "  rv = caml_copy_string_array ((const char **) r);\n";
9421            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9422            pr "  free (r);\n"
9423        | RStruct (_, typ) ->
9424            pr "  rv = copy_%s (r);\n" typ;
9425            pr "  guestfs_free_%s (r);\n" typ;
9426        | RStructList (_, typ) ->
9427            pr "  rv = copy_%s_list (r);\n" typ;
9428            pr "  guestfs_free_%s_list (r);\n" typ;
9429        | RHashtable _ ->
9430            pr "  rv = copy_table (r);\n";
9431            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9432            pr "  free (r);\n";
9433        | RBufferOut _ ->
9434            pr "  rv = caml_alloc_string (size);\n";
9435            pr "  memcpy (String_val (rv), r, size);\n";
9436       );
9437
9438       pr "  CAMLreturn (rv);\n";
9439       pr "}\n";
9440       pr "\n";
9441
9442       if List.length params > 5 then (
9443         pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9444         pr "CAMLprim value ";
9445         pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
9446         pr "CAMLprim value\n";
9447         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
9448         pr "{\n";
9449         pr "  return ocaml_guestfs_%s (argv[0]" name;
9450         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
9451         pr ");\n";
9452         pr "}\n";
9453         pr "\n"
9454       )
9455   ) all_functions_sorted
9456
9457 and generate_ocaml_structure_decls () =
9458   List.iter (
9459     fun (typ, cols) ->
9460       pr "type %s = {\n" typ;
9461       List.iter (
9462         function
9463         | name, FString -> pr "  %s : string;\n" name
9464         | name, FBuffer -> pr "  %s : string;\n" name
9465         | name, FUUID -> pr "  %s : string;\n" name
9466         | name, (FBytes|FInt64|FUInt64) -> pr "  %s : int64;\n" name
9467         | name, (FInt32|FUInt32) -> pr "  %s : int32;\n" name
9468         | name, FChar -> pr "  %s : char;\n" name
9469         | name, FOptPercent -> pr "  %s : float option;\n" name
9470       ) cols;
9471       pr "}\n";
9472       pr "\n"
9473   ) structs
9474
9475 and generate_ocaml_prototype ?(is_external = false) name style =
9476   if is_external then pr "external " else pr "val ";
9477   pr "%s : t -> " name;
9478   List.iter (
9479     function
9480     | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _
9481     | BufferIn _ | Key _ -> pr "string -> "
9482     | OptString _ -> pr "string option -> "
9483     | StringList _ | DeviceList _ -> pr "string array -> "
9484     | Bool _ -> pr "bool -> "
9485     | Int _ -> pr "int -> "
9486     | Int64 _ -> pr "int64 -> "
9487   ) (snd style);
9488   (match fst style with
9489    | RErr -> pr "unit" (* all errors are turned into exceptions *)
9490    | RInt _ -> pr "int"
9491    | RInt64 _ -> pr "int64"
9492    | RBool _ -> pr "bool"
9493    | RConstString _ -> pr "string"
9494    | RConstOptString _ -> pr "string option"
9495    | RString _ | RBufferOut _ -> pr "string"
9496    | RStringList _ -> pr "string array"
9497    | RStruct (_, typ) -> pr "%s" typ
9498    | RStructList (_, typ) -> pr "%s array" typ
9499    | RHashtable _ -> pr "(string * string) list"
9500   );
9501   if is_external then (
9502     pr " = ";
9503     if List.length (snd style) + 1 > 5 then
9504       pr "\"ocaml_guestfs_%s_byte\" " name;
9505     pr "\"ocaml_guestfs_%s\"" name
9506   );
9507   pr "\n"
9508
9509 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
9510 and generate_perl_xs () =
9511   generate_header CStyle LGPLv2plus;
9512
9513   pr "\
9514 #include \"EXTERN.h\"
9515 #include \"perl.h\"
9516 #include \"XSUB.h\"
9517
9518 #include <guestfs.h>
9519
9520 #ifndef PRId64
9521 #define PRId64 \"lld\"
9522 #endif
9523
9524 static SV *
9525 my_newSVll(long long val) {
9526 #ifdef USE_64_BIT_ALL
9527   return newSViv(val);
9528 #else
9529   char buf[100];
9530   int len;
9531   len = snprintf(buf, 100, \"%%\" PRId64, val);
9532   return newSVpv(buf, len);
9533 #endif
9534 }
9535
9536 #ifndef PRIu64
9537 #define PRIu64 \"llu\"
9538 #endif
9539
9540 static SV *
9541 my_newSVull(unsigned long long val) {
9542 #ifdef USE_64_BIT_ALL
9543   return newSVuv(val);
9544 #else
9545   char buf[100];
9546   int len;
9547   len = snprintf(buf, 100, \"%%\" PRIu64, val);
9548   return newSVpv(buf, len);
9549 #endif
9550 }
9551
9552 /* http://www.perlmonks.org/?node_id=680842 */
9553 static char **
9554 XS_unpack_charPtrPtr (SV *arg) {
9555   char **ret;
9556   AV *av;
9557   I32 i;
9558
9559   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
9560     croak (\"array reference expected\");
9561
9562   av = (AV *)SvRV (arg);
9563   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
9564   if (!ret)
9565     croak (\"malloc failed\");
9566
9567   for (i = 0; i <= av_len (av); i++) {
9568     SV **elem = av_fetch (av, i, 0);
9569
9570     if (!elem || !*elem)
9571       croak (\"missing element in list\");
9572
9573     ret[i] = SvPV_nolen (*elem);
9574   }
9575
9576   ret[i] = NULL;
9577
9578   return ret;
9579 }
9580
9581 #define PROGRESS_KEY \"_perl_progress_cb\"
9582
9583 static void
9584 _clear_progress_callback (guestfs_h *g)
9585 {
9586   guestfs_set_progress_callback (g, NULL, NULL);
9587   SV *cb = guestfs_get_private (g, PROGRESS_KEY);
9588   if (cb) {
9589     guestfs_set_private (g, PROGRESS_KEY, NULL);
9590     SvREFCNT_dec (cb);
9591   }
9592 }
9593
9594 /* http://www.perlmonks.org/?node=338857 */
9595 static void
9596 _progress_callback (guestfs_h *g, void *cb,
9597                     int proc_nr, int serial, uint64_t position, uint64_t total)
9598 {
9599   dSP;
9600   ENTER;
9601   SAVETMPS;
9602   PUSHMARK (SP);
9603   XPUSHs (sv_2mortal (newSViv (proc_nr)));
9604   XPUSHs (sv_2mortal (newSViv (serial)));
9605   XPUSHs (sv_2mortal (my_newSVull (position)));
9606   XPUSHs (sv_2mortal (my_newSVull (total)));
9607   PUTBACK;
9608   call_sv ((SV *) cb, G_VOID | G_DISCARD | G_EVAL);
9609   FREETMPS;
9610   LEAVE;
9611 }
9612
9613 static void
9614 _close_handle (guestfs_h *g)
9615 {
9616   assert (g != NULL);
9617   _clear_progress_callback (g);
9618   guestfs_close (g);
9619 }
9620
9621 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
9622
9623 PROTOTYPES: ENABLE
9624
9625 guestfs_h *
9626 _create ()
9627    CODE:
9628       RETVAL = guestfs_create ();
9629       if (!RETVAL)
9630         croak (\"could not create guestfs handle\");
9631       guestfs_set_error_handler (RETVAL, NULL, NULL);
9632  OUTPUT:
9633       RETVAL
9634
9635 void
9636 DESTROY (sv)
9637       SV *sv;
9638  PPCODE:
9639       /* For the 'g' argument above we do the conversion explicitly and
9640        * don't rely on the typemap, because if the handle has been
9641        * explicitly closed we don't want the typemap conversion to
9642        * display an error.
9643        */
9644       HV *hv = (HV *) SvRV (sv);
9645       SV **svp = hv_fetch (hv, \"_g\", 2, 0);
9646       if (svp != NULL) {
9647         guestfs_h *g = (guestfs_h *) SvIV (*svp);
9648         _close_handle (g);
9649       }
9650
9651 void
9652 close (g)
9653       guestfs_h *g;
9654  PPCODE:
9655       _close_handle (g);
9656       /* Avoid double-free in DESTROY method. */
9657       HV *hv = (HV *) SvRV (ST(0));
9658       (void) hv_delete (hv, \"_g\", 2, G_DISCARD);
9659
9660 void
9661 set_progress_callback (g, cb)
9662       guestfs_h *g;
9663       SV *cb;
9664  PPCODE:
9665       _clear_progress_callback (g);
9666       SvREFCNT_inc (cb);
9667       guestfs_set_private (g, PROGRESS_KEY, cb);
9668       guestfs_set_progress_callback (g, _progress_callback, cb);
9669
9670 void
9671 clear_progress_callback (g)
9672       guestfs_h *g;
9673  PPCODE:
9674       _clear_progress_callback (g);
9675
9676 ";
9677
9678   List.iter (
9679     fun (name, style, _, _, _, _, _) ->
9680       (match fst style with
9681        | RErr -> pr "void\n"
9682        | RInt _ -> pr "SV *\n"
9683        | RInt64 _ -> pr "SV *\n"
9684        | RBool _ -> pr "SV *\n"
9685        | RConstString _ -> pr "SV *\n"
9686        | RConstOptString _ -> pr "SV *\n"
9687        | RString _ -> pr "SV *\n"
9688        | RBufferOut _ -> pr "SV *\n"
9689        | RStringList _
9690        | RStruct _ | RStructList _
9691        | RHashtable _ ->
9692            pr "void\n" (* all lists returned implictly on the stack *)
9693       );
9694       (* Call and arguments. *)
9695       pr "%s (g" name;
9696       List.iter (
9697         fun arg -> pr ", %s" (name_of_argt arg)
9698       ) (snd style);
9699       pr ")\n";
9700       pr "      guestfs_h *g;\n";
9701       iteri (
9702         fun i ->
9703           function
9704           | Pathname n | Device n | Dev_or_Path n | String n
9705           | FileIn n | FileOut n | Key n ->
9706               pr "      char *%s;\n" n
9707           | BufferIn n ->
9708               pr "      char *%s;\n" n;
9709               pr "      size_t %s_size = SvCUR (ST(%d));\n" n (i+1)
9710           | OptString n ->
9711               (* http://www.perlmonks.org/?node_id=554277
9712                * Note that the implicit handle argument means we have
9713                * to add 1 to the ST(x) operator.
9714                *)
9715               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
9716           | StringList n | DeviceList n -> pr "      char **%s;\n" n
9717           | Bool n -> pr "      int %s;\n" n
9718           | Int n -> pr "      int %s;\n" n
9719           | Int64 n -> pr "      int64_t %s;\n" n
9720       ) (snd style);
9721
9722       let do_cleanups () =
9723         List.iter (
9724           function
9725           | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
9726           | Bool _ | Int _ | Int64 _
9727           | FileIn _ | FileOut _
9728           | BufferIn _ | Key _ -> ()
9729           | StringList n | DeviceList n -> pr "      free (%s);\n" n
9730         ) (snd style)
9731       in
9732
9733       (* Code. *)
9734       (match fst style with
9735        | RErr ->
9736            pr "PREINIT:\n";
9737            pr "      int r;\n";
9738            pr " PPCODE:\n";
9739            pr "      r = guestfs_%s " name;
9740            generate_c_call_args ~handle:"g" style;
9741            pr ";\n";
9742            do_cleanups ();
9743            pr "      if (r == -1)\n";
9744            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9745        | RInt n
9746        | RBool n ->
9747            pr "PREINIT:\n";
9748            pr "      int %s;\n" n;
9749            pr "   CODE:\n";
9750            pr "      %s = guestfs_%s " n name;
9751            generate_c_call_args ~handle:"g" style;
9752            pr ";\n";
9753            do_cleanups ();
9754            pr "      if (%s == -1)\n" n;
9755            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9756            pr "      RETVAL = newSViv (%s);\n" n;
9757            pr " OUTPUT:\n";
9758            pr "      RETVAL\n"
9759        | RInt64 n ->
9760            pr "PREINIT:\n";
9761            pr "      int64_t %s;\n" n;
9762            pr "   CODE:\n";
9763            pr "      %s = guestfs_%s " n name;
9764            generate_c_call_args ~handle:"g" style;
9765            pr ";\n";
9766            do_cleanups ();
9767            pr "      if (%s == -1)\n" n;
9768            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9769            pr "      RETVAL = my_newSVll (%s);\n" n;
9770            pr " OUTPUT:\n";
9771            pr "      RETVAL\n"
9772        | RConstString n ->
9773            pr "PREINIT:\n";
9774            pr "      const char *%s;\n" n;
9775            pr "   CODE:\n";
9776            pr "      %s = guestfs_%s " n name;
9777            generate_c_call_args ~handle:"g" style;
9778            pr ";\n";
9779            do_cleanups ();
9780            pr "      if (%s == NULL)\n" n;
9781            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9782            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9783            pr " OUTPUT:\n";
9784            pr "      RETVAL\n"
9785        | RConstOptString n ->
9786            pr "PREINIT:\n";
9787            pr "      const char *%s;\n" n;
9788            pr "   CODE:\n";
9789            pr "      %s = guestfs_%s " n name;
9790            generate_c_call_args ~handle:"g" style;
9791            pr ";\n";
9792            do_cleanups ();
9793            pr "      if (%s == NULL)\n" n;
9794            pr "        RETVAL = &PL_sv_undef;\n";
9795            pr "      else\n";
9796            pr "        RETVAL = newSVpv (%s, 0);\n" n;
9797            pr " OUTPUT:\n";
9798            pr "      RETVAL\n"
9799        | RString n ->
9800            pr "PREINIT:\n";
9801            pr "      char *%s;\n" n;
9802            pr "   CODE:\n";
9803            pr "      %s = guestfs_%s " n name;
9804            generate_c_call_args ~handle:"g" style;
9805            pr ";\n";
9806            do_cleanups ();
9807            pr "      if (%s == NULL)\n" n;
9808            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9809            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9810            pr "      free (%s);\n" n;
9811            pr " OUTPUT:\n";
9812            pr "      RETVAL\n"
9813        | RStringList n | RHashtable n ->
9814            pr "PREINIT:\n";
9815            pr "      char **%s;\n" n;
9816            pr "      size_t i, n;\n";
9817            pr " PPCODE:\n";
9818            pr "      %s = guestfs_%s " n name;
9819            generate_c_call_args ~handle:"g" style;
9820            pr ";\n";
9821            do_cleanups ();
9822            pr "      if (%s == NULL)\n" n;
9823            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9824            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
9825            pr "      EXTEND (SP, n);\n";
9826            pr "      for (i = 0; i < n; ++i) {\n";
9827            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
9828            pr "        free (%s[i]);\n" n;
9829            pr "      }\n";
9830            pr "      free (%s);\n" n;
9831        | RStruct (n, typ) ->
9832            let cols = cols_of_struct typ in
9833            generate_perl_struct_code typ cols name style n do_cleanups
9834        | RStructList (n, typ) ->
9835            let cols = cols_of_struct typ in
9836            generate_perl_struct_list_code typ cols name style n do_cleanups
9837        | RBufferOut n ->
9838            pr "PREINIT:\n";
9839            pr "      char *%s;\n" n;
9840            pr "      size_t size;\n";
9841            pr "   CODE:\n";
9842            pr "      %s = guestfs_%s " n name;
9843            generate_c_call_args ~handle:"g" style;
9844            pr ";\n";
9845            do_cleanups ();
9846            pr "      if (%s == NULL)\n" n;
9847            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9848            pr "      RETVAL = newSVpvn (%s, size);\n" n;
9849            pr "      free (%s);\n" n;
9850            pr " OUTPUT:\n";
9851            pr "      RETVAL\n"
9852       );
9853
9854       pr "\n"
9855   ) all_functions
9856
9857 and generate_perl_struct_list_code typ cols name style n do_cleanups =
9858   pr "PREINIT:\n";
9859   pr "      struct guestfs_%s_list *%s;\n" typ n;
9860   pr "      size_t i;\n";
9861   pr "      HV *hv;\n";
9862   pr " PPCODE:\n";
9863   pr "      %s = guestfs_%s " n name;
9864   generate_c_call_args ~handle:"g" style;
9865   pr ";\n";
9866   do_cleanups ();
9867   pr "      if (%s == NULL)\n" n;
9868   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9869   pr "      EXTEND (SP, %s->len);\n" n;
9870   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
9871   pr "        hv = newHV ();\n";
9872   List.iter (
9873     function
9874     | name, FString ->
9875         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
9876           name (String.length name) n name
9877     | name, FUUID ->
9878         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
9879           name (String.length name) n name
9880     | name, FBuffer ->
9881         pr "        (void) hv_store (hv, \"%s\", %d, newSVpvn (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
9882           name (String.length name) n name n name
9883     | name, (FBytes|FUInt64) ->
9884         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
9885           name (String.length name) n name
9886     | name, FInt64 ->
9887         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
9888           name (String.length name) n name
9889     | name, (FInt32|FUInt32) ->
9890         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9891           name (String.length name) n name
9892     | name, FChar ->
9893         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
9894           name (String.length name) n name
9895     | name, FOptPercent ->
9896         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9897           name (String.length name) n name
9898   ) cols;
9899   pr "        PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
9900   pr "      }\n";
9901   pr "      guestfs_free_%s_list (%s);\n" typ n
9902
9903 and generate_perl_struct_code typ cols name style n do_cleanups =
9904   pr "PREINIT:\n";
9905   pr "      struct guestfs_%s *%s;\n" typ n;
9906   pr " PPCODE:\n";
9907   pr "      %s = guestfs_%s " n name;
9908   generate_c_call_args ~handle:"g" style;
9909   pr ";\n";
9910   do_cleanups ();
9911   pr "      if (%s == NULL)\n" n;
9912   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9913   pr "      EXTEND (SP, 2 * %d);\n" (List.length cols);
9914   List.iter (
9915     fun ((name, _) as col) ->
9916       pr "      PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
9917
9918       match col with
9919       | name, FString ->
9920           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
9921             n name
9922       | name, FBuffer ->
9923           pr "      PUSHs (sv_2mortal (newSVpvn (%s->%s, %s->%s_len)));\n"
9924             n name n name
9925       | name, FUUID ->
9926           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
9927             n name
9928       | name, (FBytes|FUInt64) ->
9929           pr "      PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
9930             n name
9931       | name, FInt64 ->
9932           pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
9933             n name
9934       | name, (FInt32|FUInt32) ->
9935           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9936             n name
9937       | name, FChar ->
9938           pr "      PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
9939             n name
9940       | name, FOptPercent ->
9941           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9942             n name
9943   ) cols;
9944   pr "      free (%s);\n" n
9945
9946 (* Generate Sys/Guestfs.pm. *)
9947 and generate_perl_pm () =
9948   generate_header HashStyle LGPLv2plus;
9949
9950   pr "\
9951 =pod
9952
9953 =head1 NAME
9954
9955 Sys::Guestfs - Perl bindings for libguestfs
9956
9957 =head1 SYNOPSIS
9958
9959  use Sys::Guestfs;
9960
9961  my $h = Sys::Guestfs->new ();
9962  $h->add_drive ('guest.img');
9963  $h->launch ();
9964  $h->mount ('/dev/sda1', '/');
9965  $h->touch ('/hello');
9966  $h->sync ();
9967
9968 =head1 DESCRIPTION
9969
9970 The C<Sys::Guestfs> module provides a Perl XS binding to the
9971 libguestfs API for examining and modifying virtual machine
9972 disk images.
9973
9974 Amongst the things this is good for: making batch configuration
9975 changes to guests, getting disk used/free statistics (see also:
9976 virt-df), migrating between virtualization systems (see also:
9977 virt-p2v), performing partial backups, performing partial guest
9978 clones, cloning guests and changing registry/UUID/hostname info, and
9979 much else besides.
9980
9981 Libguestfs uses Linux kernel and qemu code, and can access any type of
9982 guest filesystem that Linux and qemu can, including but not limited
9983 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
9984 schemes, qcow, qcow2, vmdk.
9985
9986 Libguestfs provides ways to enumerate guest storage (eg. partitions,
9987 LVs, what filesystem is in each LV, etc.).  It can also run commands
9988 in the context of the guest.  Also you can access filesystems over
9989 FUSE.
9990
9991 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
9992 functions for using libguestfs from Perl, including integration
9993 with libvirt.
9994
9995 =head1 ERRORS
9996
9997 All errors turn into calls to C<croak> (see L<Carp(3)>).
9998
9999 =head1 METHODS
10000
10001 =over 4
10002
10003 =cut
10004
10005 package Sys::Guestfs;
10006
10007 use strict;
10008 use warnings;
10009
10010 # This version number changes whenever a new function
10011 # is added to the libguestfs API.  It is not directly
10012 # related to the libguestfs version number.
10013 use vars qw($VERSION);
10014 $VERSION = '0.%d';
10015
10016 require XSLoader;
10017 XSLoader::load ('Sys::Guestfs');
10018
10019 =item $h = Sys::Guestfs->new ();
10020
10021 Create a new guestfs handle.
10022
10023 =cut
10024
10025 sub new {
10026   my $proto = shift;
10027   my $class = ref ($proto) || $proto;
10028
10029   my $g = Sys::Guestfs::_create ();
10030   my $self = { _g => $g };
10031   bless $self, $class;
10032   return $self;
10033 }
10034
10035 =item $h->close ();
10036
10037 Explicitly close the guestfs handle.
10038
10039 B<Note:> You should not usually call this function.  The handle will
10040 be closed implicitly when its reference count goes to zero (eg.
10041 when it goes out of scope or the program ends).  This call is
10042 only required in some exceptional cases, such as where the program
10043 may contain cached references to the handle 'somewhere' and you
10044 really have to have the close happen right away.  After calling
10045 C<close> the program must not call any method (including C<close>)
10046 on the handle (but the implicit call to C<DESTROY> that happens
10047 when the final reference is cleaned up is OK).
10048
10049 =item $h->set_progress_callback (\\&cb);
10050
10051 Set the progress notification callback for this handle
10052 to the Perl closure C<cb>.
10053
10054 C<cb> will be called whenever a long-running operation
10055 generates a progress notification message.  The 4 parameters
10056 to the function are: C<proc_nr>, C<serial>, C<position>
10057 and C<total>.
10058
10059 You should carefully read the documentation for
10060 L<guestfs(3)/guestfs_set_progress_callback> before using
10061 this function.
10062
10063 =item $h->clear_progress_callback ();
10064
10065 This removes any progress callback function associated with
10066 the handle.
10067
10068 =cut
10069
10070 " max_proc_nr;
10071
10072   (* Actions.  We only need to print documentation for these as
10073    * they are pulled in from the XS code automatically.
10074    *)
10075   List.iter (
10076     fun (name, style, _, flags, _, _, longdesc) ->
10077       if not (List.mem NotInDocs flags) then (
10078         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
10079         pr "=item ";
10080         generate_perl_prototype name style;
10081         pr "\n\n";
10082         pr "%s\n\n" longdesc;
10083         if List.mem ProtocolLimitWarning flags then
10084           pr "%s\n\n" protocol_limit_warning;
10085         if List.mem DangerWillRobinson flags then
10086           pr "%s\n\n" danger_will_robinson;
10087         match deprecation_notice flags with
10088         | None -> ()
10089         | Some txt -> pr "%s\n\n" txt
10090       )
10091   ) all_functions_sorted;
10092
10093   (* End of file. *)
10094   pr "\
10095 =cut
10096
10097 1;
10098
10099 =back
10100
10101 =head1 AVAILABILITY
10102
10103 From time to time we add new libguestfs APIs.  Also some libguestfs
10104 APIs won't be available in all builds of libguestfs (the Fedora
10105 build is full-featured, but other builds may disable features).
10106 How do you test whether the APIs that your Perl program needs are
10107 available in the version of C<Sys::Guestfs> that you are using?
10108
10109 To test if a particular function is available in the C<Sys::Guestfs>
10110 class, use the ordinary Perl UNIVERSAL method C<can(METHOD)>
10111 (see L<perlobj(1)>).  For example:
10112
10113  use Sys::Guestfs;
10114  if (defined (Sys::Guestfs->can (\"set_verbose\"))) {
10115    print \"\\$h->set_verbose is available\\n\";
10116  }
10117
10118 To test if particular features are supported by the current
10119 build, use the L</available> method like the example below.  Note
10120 that the appliance must be launched first.
10121
10122  $h->available ( [\"augeas\"] );
10123
10124 Since the L</available> method croaks if the feature is not supported,
10125 you might also want to wrap this in an eval and return a boolean.
10126 In fact this has already been done for you: use
10127 L<Sys::Guestfs::Lib(3)/feature_available>.
10128
10129 For further discussion on this topic, refer to
10130 L<guestfs(3)/AVAILABILITY>.
10131
10132 =head1 STORING DATA IN THE HANDLE
10133
10134 The handle returned from L</new> is a hash reference.  The hash
10135 normally contains a single element:
10136
10137  {
10138    _g => [private data used by libguestfs]
10139  }
10140
10141 Callers can add other elements to this hash to store data for their own
10142 purposes.  The data lasts for the lifetime of the handle.
10143
10144 Any fields whose names begin with an underscore are reserved
10145 for private use by libguestfs.  We may add more in future.
10146
10147 It is recommended that callers prefix the name of their field(s)
10148 with some unique string, to avoid conflicts with other users.
10149
10150 =head1 COPYRIGHT
10151
10152 Copyright (C) %s Red Hat Inc.
10153
10154 =head1 LICENSE
10155
10156 Please see the file COPYING.LIB for the full license.
10157
10158 =head1 SEE ALSO
10159
10160 L<guestfs(3)>,
10161 L<guestfish(1)>,
10162 L<http://libguestfs.org>,
10163 L<Sys::Guestfs::Lib(3)>.
10164
10165 =cut
10166 " copyright_years
10167
10168 and generate_perl_prototype name style =
10169   (match fst style with
10170    | RErr -> ()
10171    | RBool n
10172    | RInt n
10173    | RInt64 n
10174    | RConstString n
10175    | RConstOptString n
10176    | RString n
10177    | RBufferOut n -> pr "$%s = " n
10178    | RStruct (n,_)
10179    | RHashtable n -> pr "%%%s = " n
10180    | RStringList n
10181    | RStructList (n,_) -> pr "@%s = " n
10182   );
10183   pr "$h->%s (" name;
10184   let comma = ref false in
10185   List.iter (
10186     fun arg ->
10187       if !comma then pr ", ";
10188       comma := true;
10189       match arg with
10190       | Pathname n | Device n | Dev_or_Path n | String n
10191       | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n
10192       | BufferIn n | Key n ->
10193           pr "$%s" n
10194       | StringList n | DeviceList n ->
10195           pr "\\@%s" n
10196   ) (snd style);
10197   pr ");"
10198
10199 (* Generate Python C module. *)
10200 and generate_python_c () =
10201   generate_header CStyle LGPLv2plus;
10202
10203   pr "\
10204 #define PY_SSIZE_T_CLEAN 1
10205 #include <Python.h>
10206
10207 #if PY_VERSION_HEX < 0x02050000
10208 typedef int Py_ssize_t;
10209 #define PY_SSIZE_T_MAX INT_MAX
10210 #define PY_SSIZE_T_MIN INT_MIN
10211 #endif
10212
10213 #include <stdio.h>
10214 #include <stdlib.h>
10215 #include <assert.h>
10216
10217 #include \"guestfs.h\"
10218
10219 #ifndef HAVE_PYCAPSULE_NEW
10220 typedef struct {
10221   PyObject_HEAD
10222   guestfs_h *g;
10223 } Pyguestfs_Object;
10224 #endif
10225
10226 static guestfs_h *
10227 get_handle (PyObject *obj)
10228 {
10229   assert (obj);
10230   assert (obj != Py_None);
10231 #ifndef HAVE_PYCAPSULE_NEW
10232   return ((Pyguestfs_Object *) obj)->g;
10233 #else
10234   return (guestfs_h*) PyCapsule_GetPointer(obj, \"guestfs_h\");
10235 #endif
10236 }
10237
10238 static PyObject *
10239 put_handle (guestfs_h *g)
10240 {
10241   assert (g);
10242 #ifndef HAVE_PYCAPSULE_NEW
10243   return
10244     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
10245 #else
10246   return PyCapsule_New ((void *) g, \"guestfs_h\", NULL);
10247 #endif
10248 }
10249
10250 /* This list should be freed (but not the strings) after use. */
10251 static char **
10252 get_string_list (PyObject *obj)
10253 {
10254   size_t i, len;
10255   char **r;
10256
10257   assert (obj);
10258
10259   if (!PyList_Check (obj)) {
10260     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
10261     return NULL;
10262   }
10263
10264   Py_ssize_t slen = PyList_Size (obj);
10265   if (slen == -1) {
10266     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: PyList_Size failure\");
10267     return NULL;
10268   }
10269   len = (size_t) slen;
10270   r = malloc (sizeof (char *) * (len+1));
10271   if (r == NULL) {
10272     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
10273     return NULL;
10274   }
10275
10276   for (i = 0; i < len; ++i)
10277     r[i] = PyString_AsString (PyList_GetItem (obj, i));
10278   r[len] = NULL;
10279
10280   return r;
10281 }
10282
10283 static PyObject *
10284 put_string_list (char * const * const argv)
10285 {
10286   PyObject *list;
10287   int argc, i;
10288
10289   for (argc = 0; argv[argc] != NULL; ++argc)
10290     ;
10291
10292   list = PyList_New (argc);
10293   for (i = 0; i < argc; ++i)
10294     PyList_SetItem (list, i, PyString_FromString (argv[i]));
10295
10296   return list;
10297 }
10298
10299 static PyObject *
10300 put_table (char * const * const argv)
10301 {
10302   PyObject *list, *item;
10303   int argc, i;
10304
10305   for (argc = 0; argv[argc] != NULL; ++argc)
10306     ;
10307
10308   list = PyList_New (argc >> 1);
10309   for (i = 0; i < argc; i += 2) {
10310     item = PyTuple_New (2);
10311     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
10312     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
10313     PyList_SetItem (list, i >> 1, item);
10314   }
10315
10316   return list;
10317 }
10318
10319 static void
10320 free_strings (char **argv)
10321 {
10322   int argc;
10323
10324   for (argc = 0; argv[argc] != NULL; ++argc)
10325     free (argv[argc]);
10326   free (argv);
10327 }
10328
10329 static PyObject *
10330 py_guestfs_create (PyObject *self, PyObject *args)
10331 {
10332   guestfs_h *g;
10333
10334   g = guestfs_create ();
10335   if (g == NULL) {
10336     PyErr_SetString (PyExc_RuntimeError,
10337                      \"guestfs.create: failed to allocate handle\");
10338     return NULL;
10339   }
10340   guestfs_set_error_handler (g, NULL, NULL);
10341   /* This can return NULL, but in that case put_handle will have
10342    * set the Python error string.
10343    */
10344   return put_handle (g);
10345 }
10346
10347 static PyObject *
10348 py_guestfs_close (PyObject *self, PyObject *args)
10349 {
10350   PyObject *py_g;
10351   guestfs_h *g;
10352
10353   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
10354     return NULL;
10355   g = get_handle (py_g);
10356
10357   guestfs_close (g);
10358
10359   Py_INCREF (Py_None);
10360   return Py_None;
10361 }
10362
10363 ";
10364
10365   let emit_put_list_function typ =
10366     pr "static PyObject *\n";
10367     pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
10368     pr "{\n";
10369     pr "  PyObject *list;\n";
10370     pr "  size_t i;\n";
10371     pr "\n";
10372     pr "  list = PyList_New (%ss->len);\n" typ;
10373     pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
10374     pr "    PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
10375     pr "  return list;\n";
10376     pr "};\n";
10377     pr "\n"
10378   in
10379
10380   (* Structures, turned into Python dictionaries. *)
10381   List.iter (
10382     fun (typ, cols) ->
10383       pr "static PyObject *\n";
10384       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
10385       pr "{\n";
10386       pr "  PyObject *dict;\n";
10387       pr "\n";
10388       pr "  dict = PyDict_New ();\n";
10389       List.iter (
10390         function
10391         | name, FString ->
10392             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10393             pr "                        PyString_FromString (%s->%s));\n"
10394               typ name
10395         | name, FBuffer ->
10396             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10397             pr "                        PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
10398               typ name typ name
10399         | name, FUUID ->
10400             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10401             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
10402               typ name
10403         | name, (FBytes|FUInt64) ->
10404             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10405             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
10406               typ name
10407         | name, FInt64 ->
10408             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10409             pr "                        PyLong_FromLongLong (%s->%s));\n"
10410               typ name
10411         | name, FUInt32 ->
10412             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10413             pr "                        PyLong_FromUnsignedLong (%s->%s));\n"
10414               typ name
10415         | name, FInt32 ->
10416             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10417             pr "                        PyLong_FromLong (%s->%s));\n"
10418               typ name
10419         | name, FOptPercent ->
10420             pr "  if (%s->%s >= 0)\n" typ name;
10421             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
10422             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
10423               typ name;
10424             pr "  else {\n";
10425             pr "    Py_INCREF (Py_None);\n";
10426             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
10427             pr "  }\n"
10428         | name, FChar ->
10429             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10430             pr "                        PyString_FromStringAndSize (&dirent->%s, 1));\n" name
10431       ) cols;
10432       pr "  return dict;\n";
10433       pr "};\n";
10434       pr "\n";
10435
10436   ) structs;
10437
10438   (* Emit a put_TYPE_list function definition only if that function is used. *)
10439   List.iter (
10440     function
10441     | typ, (RStructListOnly | RStructAndList) ->
10442         (* generate the function for typ *)
10443         emit_put_list_function typ
10444     | typ, _ -> () (* empty *)
10445   ) (rstructs_used_by all_functions);
10446
10447   (* Python wrapper functions. *)
10448   List.iter (
10449     fun (name, style, _, _, _, _, _) ->
10450       pr "static PyObject *\n";
10451       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
10452       pr "{\n";
10453
10454       pr "  PyObject *py_g;\n";
10455       pr "  guestfs_h *g;\n";
10456       pr "  PyObject *py_r;\n";
10457
10458       let error_code =
10459         match fst style with
10460         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10461         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10462         | RConstString _ | RConstOptString _ ->
10463             pr "  const char *r;\n"; "NULL"
10464         | RString _ -> pr "  char *r;\n"; "NULL"
10465         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10466         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10467         | RStructList (_, typ) ->
10468             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10469         | RBufferOut _ ->
10470             pr "  char *r;\n";
10471             pr "  size_t size;\n";
10472             "NULL" in
10473
10474       List.iter (
10475         function
10476         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10477         | FileIn n | FileOut n ->
10478             pr "  const char *%s;\n" n
10479         | OptString n -> pr "  const char *%s;\n" n
10480         | BufferIn n ->
10481             pr "  const char *%s;\n" n;
10482             pr "  Py_ssize_t %s_size;\n" n
10483         | StringList n | DeviceList n ->
10484             pr "  PyObject *py_%s;\n" n;
10485             pr "  char **%s;\n" n
10486         | Bool n -> pr "  int %s;\n" n
10487         | Int n -> pr "  int %s;\n" n
10488         | Int64 n -> pr "  long long %s;\n" n
10489       ) (snd style);
10490
10491       pr "\n";
10492
10493       (* Convert the parameters. *)
10494       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
10495       List.iter (
10496         function
10497         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10498         | FileIn _ | FileOut _ -> pr "s"
10499         | OptString _ -> pr "z"
10500         | StringList _ | DeviceList _ -> pr "O"
10501         | Bool _ -> pr "i" (* XXX Python has booleans? *)
10502         | Int _ -> pr "i"
10503         | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
10504                              * emulate C's int/long/long long in Python?
10505                              *)
10506         | BufferIn _ -> pr "s#"
10507       ) (snd style);
10508       pr ":guestfs_%s\",\n" name;
10509       pr "                         &py_g";
10510       List.iter (
10511         function
10512         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10513         | FileIn n | FileOut n -> pr ", &%s" n
10514         | OptString n -> pr ", &%s" n
10515         | StringList n | DeviceList n -> pr ", &py_%s" n
10516         | Bool n -> pr ", &%s" n
10517         | Int n -> pr ", &%s" n
10518         | Int64 n -> pr ", &%s" n
10519         | BufferIn n -> pr ", &%s, &%s_size" n n
10520       ) (snd style);
10521
10522       pr "))\n";
10523       pr "    return NULL;\n";
10524
10525       pr "  g = get_handle (py_g);\n";
10526       List.iter (
10527         function
10528         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10529         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10530         | BufferIn _ -> ()
10531         | StringList n | DeviceList n ->
10532             pr "  %s = get_string_list (py_%s);\n" n n;
10533             pr "  if (!%s) return NULL;\n" n
10534       ) (snd style);
10535
10536       pr "\n";
10537
10538       pr "  r = guestfs_%s " name;
10539       generate_c_call_args ~handle:"g" style;
10540       pr ";\n";
10541
10542       List.iter (
10543         function
10544         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10545         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10546         | BufferIn _ -> ()
10547         | StringList n | DeviceList n ->
10548             pr "  free (%s);\n" n
10549       ) (snd style);
10550
10551       pr "  if (r == %s) {\n" error_code;
10552       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
10553       pr "    return NULL;\n";
10554       pr "  }\n";
10555       pr "\n";
10556
10557       (match fst style with
10558        | RErr ->
10559            pr "  Py_INCREF (Py_None);\n";
10560            pr "  py_r = Py_None;\n"
10561        | RInt _
10562        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
10563        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
10564        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
10565        | RConstOptString _ ->
10566            pr "  if (r)\n";
10567            pr "    py_r = PyString_FromString (r);\n";
10568            pr "  else {\n";
10569            pr "    Py_INCREF (Py_None);\n";
10570            pr "    py_r = Py_None;\n";
10571            pr "  }\n"
10572        | RString _ ->
10573            pr "  py_r = PyString_FromString (r);\n";
10574            pr "  free (r);\n"
10575        | RStringList _ ->
10576            pr "  py_r = put_string_list (r);\n";
10577            pr "  free_strings (r);\n"
10578        | RStruct (_, typ) ->
10579            pr "  py_r = put_%s (r);\n" typ;
10580            pr "  guestfs_free_%s (r);\n" typ
10581        | RStructList (_, typ) ->
10582            pr "  py_r = put_%s_list (r);\n" typ;
10583            pr "  guestfs_free_%s_list (r);\n" typ
10584        | RHashtable n ->
10585            pr "  py_r = put_table (r);\n";
10586            pr "  free_strings (r);\n"
10587        | RBufferOut _ ->
10588            pr "  py_r = PyString_FromStringAndSize (r, size);\n";
10589            pr "  free (r);\n"
10590       );
10591
10592       pr "  return py_r;\n";
10593       pr "}\n";
10594       pr "\n"
10595   ) all_functions;
10596
10597   (* Table of functions. *)
10598   pr "static PyMethodDef methods[] = {\n";
10599   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
10600   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
10601   List.iter (
10602     fun (name, _, _, _, _, _, _) ->
10603       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
10604         name name
10605   ) all_functions;
10606   pr "  { NULL, NULL, 0, NULL }\n";
10607   pr "};\n";
10608   pr "\n";
10609
10610   (* Init function. *)
10611   pr "\
10612 void
10613 initlibguestfsmod (void)
10614 {
10615   static int initialized = 0;
10616
10617   if (initialized) return;
10618   Py_InitModule ((char *) \"libguestfsmod\", methods);
10619   initialized = 1;
10620 }
10621 "
10622
10623 (* Generate Python module. *)
10624 and generate_python_py () =
10625   generate_header HashStyle LGPLv2plus;
10626
10627   pr "\
10628 u\"\"\"Python bindings for libguestfs
10629
10630 import guestfs
10631 g = guestfs.GuestFS ()
10632 g.add_drive (\"guest.img\")
10633 g.launch ()
10634 parts = g.list_partitions ()
10635
10636 The guestfs module provides a Python binding to the libguestfs API
10637 for examining and modifying virtual machine disk images.
10638
10639 Amongst the things this is good for: making batch configuration
10640 changes to guests, getting disk used/free statistics (see also:
10641 virt-df), migrating between virtualization systems (see also:
10642 virt-p2v), performing partial backups, performing partial guest
10643 clones, cloning guests and changing registry/UUID/hostname info, and
10644 much else besides.
10645
10646 Libguestfs uses Linux kernel and qemu code, and can access any type of
10647 guest filesystem that Linux and qemu can, including but not limited
10648 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
10649 schemes, qcow, qcow2, vmdk.
10650
10651 Libguestfs provides ways to enumerate guest storage (eg. partitions,
10652 LVs, what filesystem is in each LV, etc.).  It can also run commands
10653 in the context of the guest.  Also you can access filesystems over
10654 FUSE.
10655
10656 Errors which happen while using the API are turned into Python
10657 RuntimeError exceptions.
10658
10659 To create a guestfs handle you usually have to perform the following
10660 sequence of calls:
10661
10662 # Create the handle, call add_drive at least once, and possibly
10663 # several times if the guest has multiple block devices:
10664 g = guestfs.GuestFS ()
10665 g.add_drive (\"guest.img\")
10666
10667 # Launch the qemu subprocess and wait for it to become ready:
10668 g.launch ()
10669
10670 # Now you can issue commands, for example:
10671 logvols = g.lvs ()
10672
10673 \"\"\"
10674
10675 import libguestfsmod
10676
10677 class GuestFS:
10678     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
10679
10680     def __init__ (self):
10681         \"\"\"Create a new libguestfs handle.\"\"\"
10682         self._o = libguestfsmod.create ()
10683
10684     def __del__ (self):
10685         libguestfsmod.close (self._o)
10686
10687 ";
10688
10689   List.iter (
10690     fun (name, style, _, flags, _, _, longdesc) ->
10691       pr "    def %s " name;
10692       generate_py_call_args ~handle:"self" (snd style);
10693       pr ":\n";
10694
10695       if not (List.mem NotInDocs flags) then (
10696         let doc = replace_str longdesc "C<guestfs_" "C<g." in
10697         let doc =
10698           match fst style with
10699           | RErr | RInt _ | RInt64 _ | RBool _
10700           | RConstOptString _ | RConstString _
10701           | RString _ | RBufferOut _ -> doc
10702           | RStringList _ ->
10703               doc ^ "\n\nThis function returns a list of strings."
10704           | RStruct (_, typ) ->
10705               doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
10706           | RStructList (_, typ) ->
10707               doc ^ sprintf "\n\nThis function returns a list of %ss.  Each %s is represented as a dictionary." typ typ
10708           | RHashtable _ ->
10709               doc ^ "\n\nThis function returns a dictionary." in
10710         let doc =
10711           if List.mem ProtocolLimitWarning flags then
10712             doc ^ "\n\n" ^ protocol_limit_warning
10713           else doc in
10714         let doc =
10715           if List.mem DangerWillRobinson flags then
10716             doc ^ "\n\n" ^ danger_will_robinson
10717           else doc in
10718         let doc =
10719           match deprecation_notice flags with
10720           | None -> doc
10721           | Some txt -> doc ^ "\n\n" ^ txt in
10722         let doc = pod2text ~width:60 name doc in
10723         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
10724         let doc = String.concat "\n        " doc in
10725         pr "        u\"\"\"%s\"\"\"\n" doc;
10726       );
10727       pr "        return libguestfsmod.%s " name;
10728       generate_py_call_args ~handle:"self._o" (snd style);
10729       pr "\n";
10730       pr "\n";
10731   ) all_functions
10732
10733 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
10734 and generate_py_call_args ~handle args =
10735   pr "(%s" handle;
10736   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10737   pr ")"
10738
10739 (* Useful if you need the longdesc POD text as plain text.  Returns a
10740  * list of lines.
10741  *
10742  * Because this is very slow (the slowest part of autogeneration),
10743  * we memoize the results.
10744  *)
10745 and pod2text ~width name longdesc =
10746   let key = width, name, longdesc in
10747   try Hashtbl.find pod2text_memo key
10748   with Not_found ->
10749     let filename, chan = Filename.open_temp_file "gen" ".tmp" in
10750     fprintf chan "=head1 %s\n\n%s\n" name longdesc;
10751     close_out chan;
10752     let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
10753     let chan = open_process_in cmd in
10754     let lines = ref [] in
10755     let rec loop i =
10756       let line = input_line chan in
10757       if i = 1 then             (* discard the first line of output *)
10758         loop (i+1)
10759       else (
10760         let line = triml line in
10761         lines := line :: !lines;
10762         loop (i+1)
10763       ) in
10764     let lines = try loop 1 with End_of_file -> List.rev !lines in
10765     unlink filename;
10766     (match close_process_in chan with
10767      | WEXITED 0 -> ()
10768      | WEXITED i ->
10769          failwithf "pod2text: process exited with non-zero status (%d)" i
10770      | WSIGNALED i | WSTOPPED i ->
10771          failwithf "pod2text: process signalled or stopped by signal %d" i
10772     );
10773     Hashtbl.add pod2text_memo key lines;
10774     pod2text_memo_updated ();
10775     lines
10776
10777 (* Generate ruby bindings. *)
10778 and generate_ruby_c () =
10779   generate_header CStyle LGPLv2plus;
10780
10781   pr "\
10782 #include <stdio.h>
10783 #include <stdlib.h>
10784
10785 #include <ruby.h>
10786
10787 #include \"guestfs.h\"
10788
10789 #include \"extconf.h\"
10790
10791 /* For Ruby < 1.9 */
10792 #ifndef RARRAY_LEN
10793 #define RARRAY_LEN(r) (RARRAY((r))->len)
10794 #endif
10795
10796 static VALUE m_guestfs;                 /* guestfs module */
10797 static VALUE c_guestfs;                 /* guestfs_h handle */
10798 static VALUE e_Error;                   /* used for all errors */
10799
10800 static void ruby_guestfs_free (void *p)
10801 {
10802   if (!p) return;
10803   guestfs_close ((guestfs_h *) p);
10804 }
10805
10806 static VALUE ruby_guestfs_create (VALUE m)
10807 {
10808   guestfs_h *g;
10809
10810   g = guestfs_create ();
10811   if (!g)
10812     rb_raise (e_Error, \"failed to create guestfs handle\");
10813
10814   /* Don't print error messages to stderr by default. */
10815   guestfs_set_error_handler (g, NULL, NULL);
10816
10817   /* Wrap it, and make sure the close function is called when the
10818    * handle goes away.
10819    */
10820   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
10821 }
10822
10823 static VALUE ruby_guestfs_close (VALUE gv)
10824 {
10825   guestfs_h *g;
10826   Data_Get_Struct (gv, guestfs_h, g);
10827
10828   ruby_guestfs_free (g);
10829   DATA_PTR (gv) = NULL;
10830
10831   return Qnil;
10832 }
10833
10834 ";
10835
10836   List.iter (
10837     fun (name, style, _, _, _, _, _) ->
10838       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
10839       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
10840       pr ")\n";
10841       pr "{\n";
10842       pr "  guestfs_h *g;\n";
10843       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
10844       pr "  if (!g)\n";
10845       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
10846         name;
10847       pr "\n";
10848
10849       List.iter (
10850         function
10851         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10852         | FileIn n | FileOut n ->
10853             pr "  Check_Type (%sv, T_STRING);\n" n;
10854             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
10855             pr "  if (!%s)\n" n;
10856             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10857             pr "              \"%s\", \"%s\");\n" n name
10858         | BufferIn n ->
10859             pr "  Check_Type (%sv, T_STRING);\n" n;
10860             pr "  const char *%s = RSTRING (%sv)->ptr;\n" n n;
10861             pr "  if (!%s)\n" n;
10862             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10863             pr "              \"%s\", \"%s\");\n" n name;
10864             pr "  size_t %s_size = RSTRING (%sv)->len;\n" n n
10865         | OptString n ->
10866             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
10867         | StringList n | DeviceList n ->
10868             pr "  char **%s;\n" n;
10869             pr "  Check_Type (%sv, T_ARRAY);\n" n;
10870             pr "  {\n";
10871             pr "    size_t i, len;\n";
10872             pr "    len = RARRAY_LEN (%sv);\n" n;
10873             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
10874               n;
10875             pr "    for (i = 0; i < len; ++i) {\n";
10876             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
10877             pr "      %s[i] = StringValueCStr (v);\n" n;
10878             pr "    }\n";
10879             pr "    %s[len] = NULL;\n" n;
10880             pr "  }\n";
10881         | Bool n ->
10882             pr "  int %s = RTEST (%sv);\n" n n
10883         | Int n ->
10884             pr "  int %s = NUM2INT (%sv);\n" n n
10885         | Int64 n ->
10886             pr "  long long %s = NUM2LL (%sv);\n" n n
10887       ) (snd style);
10888       pr "\n";
10889
10890       let error_code =
10891         match fst style with
10892         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10893         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10894         | RConstString _ | RConstOptString _ ->
10895             pr "  const char *r;\n"; "NULL"
10896         | RString _ -> pr "  char *r;\n"; "NULL"
10897         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10898         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10899         | RStructList (_, typ) ->
10900             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10901         | RBufferOut _ ->
10902             pr "  char *r;\n";
10903             pr "  size_t size;\n";
10904             "NULL" in
10905       pr "\n";
10906
10907       pr "  r = guestfs_%s " name;
10908       generate_c_call_args ~handle:"g" style;
10909       pr ";\n";
10910
10911       List.iter (
10912         function
10913         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10914         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10915         | BufferIn _ -> ()
10916         | StringList n | DeviceList n ->
10917             pr "  free (%s);\n" n
10918       ) (snd style);
10919
10920       pr "  if (r == %s)\n" error_code;
10921       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
10922       pr "\n";
10923
10924       (match fst style with
10925        | RErr ->
10926            pr "  return Qnil;\n"
10927        | RInt _ | RBool _ ->
10928            pr "  return INT2NUM (r);\n"
10929        | RInt64 _ ->
10930            pr "  return ULL2NUM (r);\n"
10931        | RConstString _ ->
10932            pr "  return rb_str_new2 (r);\n";
10933        | RConstOptString _ ->
10934            pr "  if (r)\n";
10935            pr "    return rb_str_new2 (r);\n";
10936            pr "  else\n";
10937            pr "    return Qnil;\n";
10938        | RString _ ->
10939            pr "  VALUE rv = rb_str_new2 (r);\n";
10940            pr "  free (r);\n";
10941            pr "  return rv;\n";
10942        | RStringList _ ->
10943            pr "  size_t i, len = 0;\n";
10944            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
10945            pr "  VALUE rv = rb_ary_new2 (len);\n";
10946            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
10947            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
10948            pr "    free (r[i]);\n";
10949            pr "  }\n";
10950            pr "  free (r);\n";
10951            pr "  return rv;\n"
10952        | RStruct (_, typ) ->
10953            let cols = cols_of_struct typ in
10954            generate_ruby_struct_code typ cols
10955        | RStructList (_, typ) ->
10956            let cols = cols_of_struct typ in
10957            generate_ruby_struct_list_code typ cols
10958        | RHashtable _ ->
10959            pr "  VALUE rv = rb_hash_new ();\n";
10960            pr "  size_t i;\n";
10961            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
10962            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
10963            pr "    free (r[i]);\n";
10964            pr "    free (r[i+1]);\n";
10965            pr "  }\n";
10966            pr "  free (r);\n";
10967            pr "  return rv;\n"
10968        | RBufferOut _ ->
10969            pr "  VALUE rv = rb_str_new (r, size);\n";
10970            pr "  free (r);\n";
10971            pr "  return rv;\n";
10972       );
10973
10974       pr "}\n";
10975       pr "\n"
10976   ) all_functions;
10977
10978   pr "\
10979 /* Initialize the module. */
10980 void Init__guestfs ()
10981 {
10982   m_guestfs = rb_define_module (\"Guestfs\");
10983   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
10984   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
10985
10986 #ifdef HAVE_RB_DEFINE_ALLOC_FUNC
10987   rb_define_alloc_func (c_guestfs, ruby_guestfs_create);
10988 #endif
10989
10990   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
10991   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
10992
10993 ";
10994   (* Define the rest of the methods. *)
10995   List.iter (
10996     fun (name, style, _, _, _, _, _) ->
10997       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
10998       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
10999   ) all_functions;
11000
11001   pr "}\n"
11002
11003 (* Ruby code to return a struct. *)
11004 and generate_ruby_struct_code typ cols =
11005   pr "  VALUE rv = rb_hash_new ();\n";
11006   List.iter (
11007     function
11008     | name, FString ->
11009         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
11010     | name, FBuffer ->
11011         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
11012     | name, FUUID ->
11013         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
11014     | name, (FBytes|FUInt64) ->
11015         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
11016     | name, FInt64 ->
11017         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
11018     | name, FUInt32 ->
11019         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
11020     | name, FInt32 ->
11021         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
11022     | name, FOptPercent ->
11023         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
11024     | name, FChar -> (* XXX wrong? *)
11025         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
11026   ) cols;
11027   pr "  guestfs_free_%s (r);\n" typ;
11028   pr "  return rv;\n"
11029
11030 (* Ruby code to return a struct list. *)
11031 and generate_ruby_struct_list_code typ cols =
11032   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
11033   pr "  size_t i;\n";
11034   pr "  for (i = 0; i < r->len; ++i) {\n";
11035   pr "    VALUE hv = rb_hash_new ();\n";
11036   List.iter (
11037     function
11038     | name, FString ->
11039         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
11040     | name, FBuffer ->
11041         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
11042     | name, FUUID ->
11043         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
11044     | name, (FBytes|FUInt64) ->
11045         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
11046     | name, FInt64 ->
11047         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
11048     | name, FUInt32 ->
11049         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
11050     | name, FInt32 ->
11051         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
11052     | name, FOptPercent ->
11053         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
11054     | name, FChar -> (* XXX wrong? *)
11055         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
11056   ) cols;
11057   pr "    rb_ary_push (rv, hv);\n";
11058   pr "  }\n";
11059   pr "  guestfs_free_%s_list (r);\n" typ;
11060   pr "  return rv;\n"
11061
11062 (* Generate Java bindings GuestFS.java file. *)
11063 and generate_java_java () =
11064   generate_header CStyle LGPLv2plus;
11065
11066   pr "\
11067 package com.redhat.et.libguestfs;
11068
11069 import java.util.HashMap;
11070 import com.redhat.et.libguestfs.LibGuestFSException;
11071 import com.redhat.et.libguestfs.PV;
11072 import com.redhat.et.libguestfs.VG;
11073 import com.redhat.et.libguestfs.LV;
11074 import com.redhat.et.libguestfs.Stat;
11075 import com.redhat.et.libguestfs.StatVFS;
11076 import com.redhat.et.libguestfs.IntBool;
11077 import com.redhat.et.libguestfs.Dirent;
11078
11079 /**
11080  * The GuestFS object is a libguestfs handle.
11081  *
11082  * @author rjones
11083  */
11084 public class GuestFS {
11085   // Load the native code.
11086   static {
11087     System.loadLibrary (\"guestfs_jni\");
11088   }
11089
11090   /**
11091    * The native guestfs_h pointer.
11092    */
11093   long g;
11094
11095   /**
11096    * Create a libguestfs handle.
11097    *
11098    * @throws LibGuestFSException
11099    */
11100   public GuestFS () throws LibGuestFSException
11101   {
11102     g = _create ();
11103   }
11104   private native long _create () throws LibGuestFSException;
11105
11106   /**
11107    * Close a libguestfs handle.
11108    *
11109    * You can also leave handles to be collected by the garbage
11110    * collector, but this method ensures that the resources used
11111    * by the handle are freed up immediately.  If you call any
11112    * other methods after closing the handle, you will get an
11113    * exception.
11114    *
11115    * @throws LibGuestFSException
11116    */
11117   public void close () throws LibGuestFSException
11118   {
11119     if (g != 0)
11120       _close (g);
11121     g = 0;
11122   }
11123   private native void _close (long g) throws LibGuestFSException;
11124
11125   public void finalize () throws LibGuestFSException
11126   {
11127     close ();
11128   }
11129
11130 ";
11131
11132   List.iter (
11133     fun (name, style, _, flags, _, shortdesc, longdesc) ->
11134       if not (List.mem NotInDocs flags); then (
11135         let doc = replace_str longdesc "C<guestfs_" "C<g." in
11136         let doc =
11137           if List.mem ProtocolLimitWarning flags then
11138             doc ^ "\n\n" ^ protocol_limit_warning
11139           else doc in
11140         let doc =
11141           if List.mem DangerWillRobinson flags then
11142             doc ^ "\n\n" ^ danger_will_robinson
11143           else doc in
11144         let doc =
11145           match deprecation_notice flags with
11146           | None -> doc
11147           | Some txt -> doc ^ "\n\n" ^ txt in
11148         let doc = pod2text ~width:60 name doc in
11149         let doc = List.map (            (* RHBZ#501883 *)
11150           function
11151           | "" -> "<p>"
11152           | nonempty -> nonempty
11153         ) doc in
11154         let doc = String.concat "\n   * " doc in
11155
11156         pr "  /**\n";
11157         pr "   * %s\n" shortdesc;
11158         pr "   * <p>\n";
11159         pr "   * %s\n" doc;
11160         pr "   * @throws LibGuestFSException\n";
11161         pr "   */\n";
11162         pr "  ";
11163       );
11164       generate_java_prototype ~public:true ~semicolon:false name style;
11165       pr "\n";
11166       pr "  {\n";
11167       pr "    if (g == 0)\n";
11168       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
11169         name;
11170       pr "    ";
11171       if fst style <> RErr then pr "return ";
11172       pr "_%s " name;
11173       generate_java_call_args ~handle:"g" (snd style);
11174       pr ";\n";
11175       pr "  }\n";
11176       pr "  ";
11177       generate_java_prototype ~privat:true ~native:true name style;
11178       pr "\n";
11179       pr "\n";
11180   ) all_functions;
11181
11182   pr "}\n"
11183
11184 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
11185 and generate_java_call_args ~handle args =
11186   pr "(%s" handle;
11187   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
11188   pr ")"
11189
11190 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
11191     ?(semicolon=true) name style =
11192   if privat then pr "private ";
11193   if public then pr "public ";
11194   if native then pr "native ";
11195
11196   (* return type *)
11197   (match fst style with
11198    | RErr -> pr "void ";
11199    | RInt _ -> pr "int ";
11200    | RInt64 _ -> pr "long ";
11201    | RBool _ -> pr "boolean ";
11202    | RConstString _ | RConstOptString _ | RString _
11203    | RBufferOut _ -> pr "String ";
11204    | RStringList _ -> pr "String[] ";
11205    | RStruct (_, typ) ->
11206        let name = java_name_of_struct typ in
11207        pr "%s " name;
11208    | RStructList (_, typ) ->
11209        let name = java_name_of_struct typ in
11210        pr "%s[] " name;
11211    | RHashtable _ -> pr "HashMap<String,String> ";
11212   );
11213
11214   if native then pr "_%s " name else pr "%s " name;
11215   pr "(";
11216   let needs_comma = ref false in
11217   if native then (
11218     pr "long g";
11219     needs_comma := true
11220   );
11221
11222   (* args *)
11223   List.iter (
11224     fun arg ->
11225       if !needs_comma then pr ", ";
11226       needs_comma := true;
11227
11228       match arg with
11229       | Pathname n
11230       | Device n | Dev_or_Path n
11231       | String n
11232       | OptString n
11233       | FileIn n
11234       | FileOut n
11235       | Key n ->
11236           pr "String %s" n
11237       | BufferIn n ->
11238           pr "byte[] %s" n
11239       | StringList n | DeviceList n ->
11240           pr "String[] %s" n
11241       | Bool n ->
11242           pr "boolean %s" n
11243       | Int n ->
11244           pr "int %s" n
11245       | Int64 n ->
11246           pr "long %s" n
11247   ) (snd style);
11248
11249   pr ")\n";
11250   pr "    throws LibGuestFSException";
11251   if semicolon then pr ";"
11252
11253 and generate_java_struct jtyp cols () =
11254   generate_header CStyle LGPLv2plus;
11255
11256   pr "\
11257 package com.redhat.et.libguestfs;
11258
11259 /**
11260  * Libguestfs %s structure.
11261  *
11262  * @author rjones
11263  * @see GuestFS
11264  */
11265 public class %s {
11266 " jtyp jtyp;
11267
11268   List.iter (
11269     function
11270     | name, FString
11271     | name, FUUID
11272     | name, FBuffer -> pr "  public String %s;\n" name
11273     | name, (FBytes|FUInt64|FInt64) -> pr "  public long %s;\n" name
11274     | name, (FUInt32|FInt32) -> pr "  public int %s;\n" name
11275     | name, FChar -> pr "  public char %s;\n" name
11276     | name, FOptPercent ->
11277         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
11278         pr "  public float %s;\n" name
11279   ) cols;
11280
11281   pr "}\n"
11282
11283 and generate_java_c () =
11284   generate_header CStyle LGPLv2plus;
11285
11286   pr "\
11287 #include <stdio.h>
11288 #include <stdlib.h>
11289 #include <string.h>
11290
11291 #include \"com_redhat_et_libguestfs_GuestFS.h\"
11292 #include \"guestfs.h\"
11293
11294 /* Note that this function returns.  The exception is not thrown
11295  * until after the wrapper function returns.
11296  */
11297 static void
11298 throw_exception (JNIEnv *env, const char *msg)
11299 {
11300   jclass cl;
11301   cl = (*env)->FindClass (env,
11302                           \"com/redhat/et/libguestfs/LibGuestFSException\");
11303   (*env)->ThrowNew (env, cl, msg);
11304 }
11305
11306 JNIEXPORT jlong JNICALL
11307 Java_com_redhat_et_libguestfs_GuestFS__1create
11308   (JNIEnv *env, jobject obj)
11309 {
11310   guestfs_h *g;
11311
11312   g = guestfs_create ();
11313   if (g == NULL) {
11314     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
11315     return 0;
11316   }
11317   guestfs_set_error_handler (g, NULL, NULL);
11318   return (jlong) (long) g;
11319 }
11320
11321 JNIEXPORT void JNICALL
11322 Java_com_redhat_et_libguestfs_GuestFS__1close
11323   (JNIEnv *env, jobject obj, jlong jg)
11324 {
11325   guestfs_h *g = (guestfs_h *) (long) jg;
11326   guestfs_close (g);
11327 }
11328
11329 ";
11330
11331   List.iter (
11332     fun (name, style, _, _, _, _, _) ->
11333       pr "JNIEXPORT ";
11334       (match fst style with
11335        | RErr -> pr "void ";
11336        | RInt _ -> pr "jint ";
11337        | RInt64 _ -> pr "jlong ";
11338        | RBool _ -> pr "jboolean ";
11339        | RConstString _ | RConstOptString _ | RString _
11340        | RBufferOut _ -> pr "jstring ";
11341        | RStruct _ | RHashtable _ ->
11342            pr "jobject ";
11343        | RStringList _ | RStructList _ ->
11344            pr "jobjectArray ";
11345       );
11346       pr "JNICALL\n";
11347       pr "Java_com_redhat_et_libguestfs_GuestFS_";
11348       pr "%s" (replace_str ("_" ^ name) "_" "_1");
11349       pr "\n";
11350       pr "  (JNIEnv *env, jobject obj, jlong jg";
11351       List.iter (
11352         function
11353         | Pathname n
11354         | Device n | Dev_or_Path n
11355         | String n
11356         | OptString n
11357         | FileIn n
11358         | FileOut n
11359         | Key n ->
11360             pr ", jstring j%s" n
11361         | BufferIn n ->
11362             pr ", jbyteArray j%s" n
11363         | StringList n | DeviceList n ->
11364             pr ", jobjectArray j%s" n
11365         | Bool n ->
11366             pr ", jboolean j%s" n
11367         | Int n ->
11368             pr ", jint j%s" n
11369         | Int64 n ->
11370             pr ", jlong j%s" n
11371       ) (snd style);
11372       pr ")\n";
11373       pr "{\n";
11374       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
11375       let error_code, no_ret =
11376         match fst style with
11377         | RErr -> pr "  int r;\n"; "-1", ""
11378         | RBool _
11379         | RInt _ -> pr "  int r;\n"; "-1", "0"
11380         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
11381         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11382         | RConstOptString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11383         | RString _ ->
11384             pr "  jstring jr;\n";
11385             pr "  char *r;\n"; "NULL", "NULL"
11386         | RStringList _ ->
11387             pr "  jobjectArray jr;\n";
11388             pr "  int r_len;\n";
11389             pr "  jclass cl;\n";
11390             pr "  jstring jstr;\n";
11391             pr "  char **r;\n"; "NULL", "NULL"
11392         | RStruct (_, typ) ->
11393             pr "  jobject jr;\n";
11394             pr "  jclass cl;\n";
11395             pr "  jfieldID fl;\n";
11396             pr "  struct guestfs_%s *r;\n" typ; "NULL", "NULL"
11397         | RStructList (_, typ) ->
11398             pr "  jobjectArray jr;\n";
11399             pr "  jclass cl;\n";
11400             pr "  jfieldID fl;\n";
11401             pr "  jobject jfl;\n";
11402             pr "  struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
11403         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL"
11404         | RBufferOut _ ->
11405             pr "  jstring jr;\n";
11406             pr "  char *r;\n";
11407             pr "  size_t size;\n";
11408             "NULL", "NULL" in
11409       List.iter (
11410         function
11411         | Pathname n
11412         | Device n | Dev_or_Path n
11413         | String n
11414         | OptString n
11415         | FileIn n
11416         | FileOut n
11417         | Key n ->
11418             pr "  const char *%s;\n" n
11419         | BufferIn n ->
11420             pr "  jbyte *%s;\n" n;
11421             pr "  size_t %s_size;\n" n
11422         | StringList n | DeviceList n ->
11423             pr "  int %s_len;\n" n;
11424             pr "  const char **%s;\n" n
11425         | Bool n
11426         | Int n ->
11427             pr "  int %s;\n" n
11428         | Int64 n ->
11429             pr "  int64_t %s;\n" n
11430       ) (snd style);
11431
11432       let needs_i =
11433         (match fst style with
11434          | RStringList _ | RStructList _ -> true
11435          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
11436          | RConstOptString _
11437          | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
11438           List.exists (function
11439                        | StringList _ -> true
11440                        | DeviceList _ -> true
11441                        | _ -> false) (snd style) in
11442       if needs_i then
11443         pr "  size_t i;\n";
11444
11445       pr "\n";
11446
11447       (* Get the parameters. *)
11448       List.iter (
11449         function
11450         | Pathname n
11451         | Device n | Dev_or_Path n
11452         | String n
11453         | FileIn n
11454         | FileOut n
11455         | Key n ->
11456             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
11457         | OptString n ->
11458             (* This is completely undocumented, but Java null becomes
11459              * a NULL parameter.
11460              *)
11461             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
11462         | BufferIn n ->
11463             pr "  %s = (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n;
11464             pr "  %s_size = (*env)->GetArrayLength (env, j%s);\n" n n
11465         | StringList n | DeviceList n ->
11466             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
11467             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
11468             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11469             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11470               n;
11471             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
11472             pr "  }\n";
11473             pr "  %s[%s_len] = NULL;\n" n n;
11474         | Bool n
11475         | Int n
11476         | Int64 n ->
11477             pr "  %s = j%s;\n" n n
11478       ) (snd style);
11479
11480       (* Make the call. *)
11481       pr "  r = guestfs_%s " name;
11482       generate_c_call_args ~handle:"g" style;
11483       pr ";\n";
11484
11485       (* Release the parameters. *)
11486       List.iter (
11487         function
11488         | Pathname n
11489         | Device n | Dev_or_Path n
11490         | String n
11491         | FileIn n
11492         | FileOut n
11493         | Key n ->
11494             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11495         | OptString n ->
11496             pr "  if (j%s)\n" n;
11497             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11498         | BufferIn n ->
11499             pr "  (*env)->ReleaseByteArrayElements (env, j%s, %s, 0);\n" n n
11500         | StringList n | DeviceList n ->
11501             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11502             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11503               n;
11504             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
11505             pr "  }\n";
11506             pr "  free (%s);\n" n
11507         | Bool n
11508         | Int n
11509         | Int64 n -> ()
11510       ) (snd style);
11511
11512       (* Check for errors. *)
11513       pr "  if (r == %s) {\n" error_code;
11514       pr "    throw_exception (env, guestfs_last_error (g));\n";
11515       pr "    return %s;\n" no_ret;
11516       pr "  }\n";
11517
11518       (* Return value. *)
11519       (match fst style with
11520        | RErr -> ()
11521        | RInt _ -> pr "  return (jint) r;\n"
11522        | RBool _ -> pr "  return (jboolean) r;\n"
11523        | RInt64 _ -> pr "  return (jlong) r;\n"
11524        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
11525        | RConstOptString _ ->
11526            pr "  return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
11527        | RString _ ->
11528            pr "  jr = (*env)->NewStringUTF (env, r);\n";
11529            pr "  free (r);\n";
11530            pr "  return jr;\n"
11531        | RStringList _ ->
11532            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
11533            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
11534            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
11535            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
11536            pr "  for (i = 0; i < r_len; ++i) {\n";
11537            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
11538            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
11539            pr "    free (r[i]);\n";
11540            pr "  }\n";
11541            pr "  free (r);\n";
11542            pr "  return jr;\n"
11543        | RStruct (_, typ) ->
11544            let jtyp = java_name_of_struct typ in
11545            let cols = cols_of_struct typ in
11546            generate_java_struct_return typ jtyp cols
11547        | RStructList (_, typ) ->
11548            let jtyp = java_name_of_struct typ in
11549            let cols = cols_of_struct typ in
11550            generate_java_struct_list_return typ jtyp cols
11551        | RHashtable _ ->
11552            (* XXX *)
11553            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
11554            pr "  return NULL;\n"
11555        | RBufferOut _ ->
11556            pr "  jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
11557            pr "  free (r);\n";
11558            pr "  return jr;\n"
11559       );
11560
11561       pr "}\n";
11562       pr "\n"
11563   ) all_functions
11564
11565 and generate_java_struct_return typ jtyp cols =
11566   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11567   pr "  jr = (*env)->AllocObject (env, cl);\n";
11568   List.iter (
11569     function
11570     | name, FString ->
11571         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11572         pr "  (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
11573     | name, FUUID ->
11574         pr "  {\n";
11575         pr "    char s[33];\n";
11576         pr "    memcpy (s, r->%s, 32);\n" name;
11577         pr "    s[32] = 0;\n";
11578         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11579         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11580         pr "  }\n";
11581     | name, FBuffer ->
11582         pr "  {\n";
11583         pr "    int len = r->%s_len;\n" name;
11584         pr "    char s[len+1];\n";
11585         pr "    memcpy (s, r->%s, len);\n" name;
11586         pr "    s[len] = 0;\n";
11587         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11588         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11589         pr "  }\n";
11590     | name, (FBytes|FUInt64|FInt64) ->
11591         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11592         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11593     | name, (FUInt32|FInt32) ->
11594         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11595         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11596     | name, FOptPercent ->
11597         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11598         pr "  (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
11599     | name, FChar ->
11600         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11601         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11602   ) cols;
11603   pr "  free (r);\n";
11604   pr "  return jr;\n"
11605
11606 and generate_java_struct_list_return typ jtyp cols =
11607   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11608   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
11609   pr "  for (i = 0; i < r->len; ++i) {\n";
11610   pr "    jfl = (*env)->AllocObject (env, cl);\n";
11611   List.iter (
11612     function
11613     | name, FString ->
11614         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11615         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
11616     | name, FUUID ->
11617         pr "    {\n";
11618         pr "      char s[33];\n";
11619         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
11620         pr "      s[32] = 0;\n";
11621         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11622         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11623         pr "    }\n";
11624     | name, FBuffer ->
11625         pr "    {\n";
11626         pr "      int len = r->val[i].%s_len;\n" name;
11627         pr "      char s[len+1];\n";
11628         pr "      memcpy (s, r->val[i].%s, len);\n" name;
11629         pr "      s[len] = 0;\n";
11630         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11631         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11632         pr "    }\n";
11633     | name, (FBytes|FUInt64|FInt64) ->
11634         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11635         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11636     | name, (FUInt32|FInt32) ->
11637         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11638         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11639     | name, FOptPercent ->
11640         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11641         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
11642     | name, FChar ->
11643         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11644         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11645   ) cols;
11646   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
11647   pr "  }\n";
11648   pr "  guestfs_free_%s_list (r);\n" typ;
11649   pr "  return jr;\n"
11650
11651 and generate_java_makefile_inc () =
11652   generate_header HashStyle GPLv2plus;
11653
11654   pr "java_built_sources = \\\n";
11655   List.iter (
11656     fun (typ, jtyp) ->
11657         pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
11658   ) java_structs;
11659   pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
11660
11661 and generate_haskell_hs () =
11662   generate_header HaskellStyle LGPLv2plus;
11663
11664   (* XXX We only know how to generate partial FFI for Haskell
11665    * at the moment.  Please help out!
11666    *)
11667   let can_generate style =
11668     match style with
11669     | RErr, _
11670     | RInt _, _
11671     | RInt64 _, _ -> true
11672     | RBool _, _
11673     | RConstString _, _
11674     | RConstOptString _, _
11675     | RString _, _
11676     | RStringList _, _
11677     | RStruct _, _
11678     | RStructList _, _
11679     | RHashtable _, _
11680     | RBufferOut _, _ -> false in
11681
11682   pr "\
11683 {-# INCLUDE <guestfs.h> #-}
11684 {-# LANGUAGE ForeignFunctionInterface #-}
11685
11686 module Guestfs (
11687   create";
11688
11689   (* List out the names of the actions we want to export. *)
11690   List.iter (
11691     fun (name, style, _, _, _, _, _) ->
11692       if can_generate style then pr ",\n  %s" name
11693   ) all_functions;
11694
11695   pr "
11696   ) where
11697
11698 -- Unfortunately some symbols duplicate ones already present
11699 -- in Prelude.  We don't know which, so we hard-code a list
11700 -- here.
11701 import Prelude hiding (truncate)
11702
11703 import Foreign
11704 import Foreign.C
11705 import Foreign.C.Types
11706 import IO
11707 import Control.Exception
11708 import Data.Typeable
11709
11710 data GuestfsS = GuestfsS            -- represents the opaque C struct
11711 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
11712 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
11713
11714 -- XXX define properly later XXX
11715 data PV = PV
11716 data VG = VG
11717 data LV = LV
11718 data IntBool = IntBool
11719 data Stat = Stat
11720 data StatVFS = StatVFS
11721 data Hashtable = Hashtable
11722
11723 foreign import ccall unsafe \"guestfs_create\" c_create
11724   :: IO GuestfsP
11725 foreign import ccall unsafe \"&guestfs_close\" c_close
11726   :: FunPtr (GuestfsP -> IO ())
11727 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
11728   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
11729
11730 create :: IO GuestfsH
11731 create = do
11732   p <- c_create
11733   c_set_error_handler p nullPtr nullPtr
11734   h <- newForeignPtr c_close p
11735   return h
11736
11737 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
11738   :: GuestfsP -> IO CString
11739
11740 -- last_error :: GuestfsH -> IO (Maybe String)
11741 -- last_error h = do
11742 --   str <- withForeignPtr h (\\p -> c_last_error p)
11743 --   maybePeek peekCString str
11744
11745 last_error :: GuestfsH -> IO (String)
11746 last_error h = do
11747   str <- withForeignPtr h (\\p -> c_last_error p)
11748   if (str == nullPtr)
11749     then return \"no error\"
11750     else peekCString str
11751
11752 ";
11753
11754   (* Generate wrappers for each foreign function. *)
11755   List.iter (
11756     fun (name, style, _, _, _, _, _) ->
11757       if can_generate style then (
11758         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
11759         pr "  :: ";
11760         generate_haskell_prototype ~handle:"GuestfsP" style;
11761         pr "\n";
11762         pr "\n";
11763         pr "%s :: " name;
11764         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
11765         pr "\n";
11766         pr "%s %s = do\n" name
11767           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
11768         pr "  r <- ";
11769         (* Convert pointer arguments using with* functions. *)
11770         List.iter (
11771           function
11772           | FileIn n
11773           | FileOut n
11774           | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
11775               pr "withCString %s $ \\%s -> " n n
11776           | BufferIn n ->
11777               pr "withCStringLen %s $ \\(%s, %s_size) -> " n n n
11778           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
11779           | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
11780           | Bool _ | Int _ | Int64 _ -> ()
11781         ) (snd style);
11782         (* Convert integer arguments. *)
11783         let args =
11784           List.map (
11785             function
11786             | Bool n -> sprintf "(fromBool %s)" n
11787             | Int n -> sprintf "(fromIntegral %s)" n
11788             | Int64 n -> sprintf "(fromIntegral %s)" n
11789             | FileIn n | FileOut n
11790             | Pathname n | Device n | Dev_or_Path n
11791             | String n | OptString n
11792             | StringList n | DeviceList n
11793             | Key n -> n
11794             | BufferIn n -> sprintf "%s (fromIntegral %s_size)" n n
11795           ) (snd style) in
11796         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
11797           (String.concat " " ("p" :: args));
11798         (match fst style with
11799          | RErr | RInt _ | RInt64 _ | RBool _ ->
11800              pr "  if (r == -1)\n";
11801              pr "    then do\n";
11802              pr "      err <- last_error h\n";
11803              pr "      fail err\n";
11804          | RConstString _ | RConstOptString _ | RString _
11805          | RStringList _ | RStruct _
11806          | RStructList _ | RHashtable _ | RBufferOut _ ->
11807              pr "  if (r == nullPtr)\n";
11808              pr "    then do\n";
11809              pr "      err <- last_error h\n";
11810              pr "      fail err\n";
11811         );
11812         (match fst style with
11813          | RErr ->
11814              pr "    else return ()\n"
11815          | RInt _ ->
11816              pr "    else return (fromIntegral r)\n"
11817          | RInt64 _ ->
11818              pr "    else return (fromIntegral r)\n"
11819          | RBool _ ->
11820              pr "    else return (toBool r)\n"
11821          | RConstString _
11822          | RConstOptString _
11823          | RString _
11824          | RStringList _
11825          | RStruct _
11826          | RStructList _
11827          | RHashtable _
11828          | RBufferOut _ ->
11829              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
11830         );
11831         pr "\n";
11832       )
11833   ) all_functions
11834
11835 and generate_haskell_prototype ~handle ?(hs = false) style =
11836   pr "%s -> " handle;
11837   let string = if hs then "String" else "CString" in
11838   let int = if hs then "Int" else "CInt" in
11839   let bool = if hs then "Bool" else "CInt" in
11840   let int64 = if hs then "Integer" else "Int64" in
11841   List.iter (
11842     fun arg ->
11843       (match arg with
11844        | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _ ->
11845            pr "%s" string
11846        | BufferIn _ ->
11847            if hs then pr "String"
11848            else pr "CString -> CInt"
11849        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
11850        | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
11851        | Bool _ -> pr "%s" bool
11852        | Int _ -> pr "%s" int
11853        | Int64 _ -> pr "%s" int
11854        | FileIn _ -> pr "%s" string
11855        | FileOut _ -> pr "%s" string
11856       );
11857       pr " -> ";
11858   ) (snd style);
11859   pr "IO (";
11860   (match fst style with
11861    | RErr -> if not hs then pr "CInt"
11862    | RInt _ -> pr "%s" int
11863    | RInt64 _ -> pr "%s" int64
11864    | RBool _ -> pr "%s" bool
11865    | RConstString _ -> pr "%s" string
11866    | RConstOptString _ -> pr "Maybe %s" string
11867    | RString _ -> pr "%s" string
11868    | RStringList _ -> pr "[%s]" string
11869    | RStruct (_, typ) ->
11870        let name = java_name_of_struct typ in
11871        pr "%s" name
11872    | RStructList (_, typ) ->
11873        let name = java_name_of_struct typ in
11874        pr "[%s]" name
11875    | RHashtable _ -> pr "Hashtable"
11876    | RBufferOut _ -> pr "%s" string
11877   );
11878   pr ")"
11879
11880 and generate_csharp () =
11881   generate_header CPlusPlusStyle LGPLv2plus;
11882
11883   (* XXX Make this configurable by the C# assembly users. *)
11884   let library = "libguestfs.so.0" in
11885
11886   pr "\
11887 // These C# bindings are highly experimental at present.
11888 //
11889 // Firstly they only work on Linux (ie. Mono).  In order to get them
11890 // to work on Windows (ie. .Net) you would need to port the library
11891 // itself to Windows first.
11892 //
11893 // The second issue is that some calls are known to be incorrect and
11894 // can cause Mono to segfault.  Particularly: calls which pass or
11895 // return string[], or return any structure value.  This is because
11896 // we haven't worked out the correct way to do this from C#.
11897 //
11898 // The third issue is that when compiling you get a lot of warnings.
11899 // We are not sure whether the warnings are important or not.
11900 //
11901 // Fourthly we do not routinely build or test these bindings as part
11902 // of the make && make check cycle, which means that regressions might
11903 // go unnoticed.
11904 //
11905 // Suggestions and patches are welcome.
11906
11907 // To compile:
11908 //
11909 // gmcs Libguestfs.cs
11910 // mono Libguestfs.exe
11911 //
11912 // (You'll probably want to add a Test class / static main function
11913 // otherwise this won't do anything useful).
11914
11915 using System;
11916 using System.IO;
11917 using System.Runtime.InteropServices;
11918 using System.Runtime.Serialization;
11919 using System.Collections;
11920
11921 namespace Guestfs
11922 {
11923   class Error : System.ApplicationException
11924   {
11925     public Error (string message) : base (message) {}
11926     protected Error (SerializationInfo info, StreamingContext context) {}
11927   }
11928
11929   class Guestfs
11930   {
11931     IntPtr _handle;
11932
11933     [DllImport (\"%s\")]
11934     static extern IntPtr guestfs_create ();
11935
11936     public Guestfs ()
11937     {
11938       _handle = guestfs_create ();
11939       if (_handle == IntPtr.Zero)
11940         throw new Error (\"could not create guestfs handle\");
11941     }
11942
11943     [DllImport (\"%s\")]
11944     static extern void guestfs_close (IntPtr h);
11945
11946     ~Guestfs ()
11947     {
11948       guestfs_close (_handle);
11949     }
11950
11951     [DllImport (\"%s\")]
11952     static extern string guestfs_last_error (IntPtr h);
11953
11954 " library library library;
11955
11956   (* Generate C# structure bindings.  We prefix struct names with
11957    * underscore because C# cannot have conflicting struct names and
11958    * method names (eg. "class stat" and "stat").
11959    *)
11960   List.iter (
11961     fun (typ, cols) ->
11962       pr "    [StructLayout (LayoutKind.Sequential)]\n";
11963       pr "    public class _%s {\n" typ;
11964       List.iter (
11965         function
11966         | name, FChar -> pr "      char %s;\n" name
11967         | name, FString -> pr "      string %s;\n" name
11968         | name, FBuffer ->
11969             pr "      uint %s_len;\n" name;
11970             pr "      string %s;\n" name
11971         | name, FUUID ->
11972             pr "      [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
11973             pr "      string %s;\n" name
11974         | name, FUInt32 -> pr "      uint %s;\n" name
11975         | name, FInt32 -> pr "      int %s;\n" name
11976         | name, (FUInt64|FBytes) -> pr "      ulong %s;\n" name
11977         | name, FInt64 -> pr "      long %s;\n" name
11978         | name, FOptPercent -> pr "      float %s; /* [0..100] or -1 */\n" name
11979       ) cols;
11980       pr "    }\n";
11981       pr "\n"
11982   ) structs;
11983
11984   (* Generate C# function bindings. *)
11985   List.iter (
11986     fun (name, style, _, _, _, shortdesc, _) ->
11987       let rec csharp_return_type () =
11988         match fst style with
11989         | RErr -> "void"
11990         | RBool n -> "bool"
11991         | RInt n -> "int"
11992         | RInt64 n -> "long"
11993         | RConstString n
11994         | RConstOptString n
11995         | RString n
11996         | RBufferOut n -> "string"
11997         | RStruct (_,n) -> "_" ^ n
11998         | RHashtable n -> "Hashtable"
11999         | RStringList n -> "string[]"
12000         | RStructList (_,n) -> sprintf "_%s[]" n
12001
12002       and c_return_type () =
12003         match fst style with
12004         | RErr
12005         | RBool _
12006         | RInt _ -> "int"
12007         | RInt64 _ -> "long"
12008         | RConstString _
12009         | RConstOptString _
12010         | RString _
12011         | RBufferOut _ -> "string"
12012         | RStruct (_,n) -> "_" ^ n
12013         | RHashtable _
12014         | RStringList _ -> "string[]"
12015         | RStructList (_,n) -> sprintf "_%s[]" n
12016
12017       and c_error_comparison () =
12018         match fst style with
12019         | RErr
12020         | RBool _
12021         | RInt _
12022         | RInt64 _ -> "== -1"
12023         | RConstString _
12024         | RConstOptString _
12025         | RString _
12026         | RBufferOut _
12027         | RStruct (_,_)
12028         | RHashtable _
12029         | RStringList _
12030         | RStructList (_,_) -> "== null"
12031
12032       and generate_extern_prototype () =
12033         pr "    static extern %s guestfs_%s (IntPtr h"
12034           (c_return_type ()) name;
12035         List.iter (
12036           function
12037           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
12038           | FileIn n | FileOut n
12039           | Key n
12040           | BufferIn n ->
12041               pr ", [In] string %s" n
12042           | StringList n | DeviceList n ->
12043               pr ", [In] string[] %s" n
12044           | Bool n ->
12045               pr ", bool %s" n
12046           | Int n ->
12047               pr ", int %s" n
12048           | Int64 n ->
12049               pr ", long %s" n
12050         ) (snd style);
12051         pr ");\n"
12052
12053       and generate_public_prototype () =
12054         pr "    public %s %s (" (csharp_return_type ()) name;
12055         let comma = ref false in
12056         let next () =
12057           if !comma then pr ", ";
12058           comma := true
12059         in
12060         List.iter (
12061           function
12062           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
12063           | FileIn n | FileOut n
12064           | Key n
12065           | BufferIn n ->
12066               next (); pr "string %s" n
12067           | StringList n | DeviceList n ->
12068               next (); pr "string[] %s" n
12069           | Bool n ->
12070               next (); pr "bool %s" n
12071           | Int n ->
12072               next (); pr "int %s" n
12073           | Int64 n ->
12074               next (); pr "long %s" n
12075         ) (snd style);
12076         pr ")\n"
12077
12078       and generate_call () =
12079         pr "guestfs_%s (_handle" name;
12080         List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
12081         pr ");\n";
12082       in
12083
12084       pr "    [DllImport (\"%s\")]\n" library;
12085       generate_extern_prototype ();
12086       pr "\n";
12087       pr "    /// <summary>\n";
12088       pr "    /// %s\n" shortdesc;
12089       pr "    /// </summary>\n";
12090       generate_public_prototype ();
12091       pr "    {\n";
12092       pr "      %s r;\n" (c_return_type ());
12093       pr "      r = ";
12094       generate_call ();
12095       pr "      if (r %s)\n" (c_error_comparison ());
12096       pr "        throw new Error (guestfs_last_error (_handle));\n";
12097       (match fst style with
12098        | RErr -> ()
12099        | RBool _ ->
12100            pr "      return r != 0 ? true : false;\n"
12101        | RHashtable _ ->
12102            pr "      Hashtable rr = new Hashtable ();\n";
12103            pr "      for (size_t i = 0; i < r.Length; i += 2)\n";
12104            pr "        rr.Add (r[i], r[i+1]);\n";
12105            pr "      return rr;\n"
12106        | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
12107        | RString _ | RBufferOut _ | RStruct _ | RStringList _
12108        | RStructList _ ->
12109            pr "      return r;\n"
12110       );
12111       pr "    }\n";
12112       pr "\n";
12113   ) all_functions_sorted;
12114
12115   pr "  }
12116 }
12117 "
12118
12119 and generate_php_h () =
12120   generate_header CStyle LGPLv2plus;
12121
12122   pr "\
12123 #ifndef PHP_GUESTFS_PHP_H
12124 #define PHP_GUESTFS_PHP_H 1
12125
12126 #ifdef ZTS
12127 #include \"TSRM.h\"
12128 #endif
12129
12130 #define PHP_GUESTFS_PHP_EXTNAME \"guestfs_php\"
12131 #define PHP_GUESTFS_PHP_VERSION \"1.0\"
12132
12133 PHP_MINIT_FUNCTION (guestfs_php);
12134
12135 #define PHP_GUESTFS_HANDLE_RES_NAME \"guestfs_h\"
12136
12137 PHP_FUNCTION (guestfs_create);
12138 PHP_FUNCTION (guestfs_last_error);
12139 ";
12140
12141   List.iter (
12142     fun (shortname, style, _, _, _, _, _) ->
12143       pr "PHP_FUNCTION (guestfs_%s);\n" shortname
12144   ) all_functions_sorted;
12145
12146   pr "\
12147
12148 extern zend_module_entry guestfs_php_module_entry;
12149 #define phpext_guestfs_php_ptr &guestfs_php_module_entry
12150
12151 #endif /* PHP_GUESTFS_PHP_H */
12152 "
12153
12154 and generate_php_c () =
12155   generate_header CStyle LGPLv2plus;
12156
12157   pr "\
12158 /* NOTE: Be very careful with all macros in PHP header files.  The
12159  * morons who wrote them aren't good at making them safe for inclusion
12160  * in arbitrary places in C code, eg. not using 'do ... while(0)'
12161  * or parenthesizing any of the arguments.
12162  */
12163
12164 /* NOTE (2): Some parts of the API can't be used on 32 bit platforms.
12165  * Any 64 bit numbers will be truncated.  There's no easy way around
12166  * this in PHP.
12167  */
12168
12169 #include <config.h>
12170
12171 #include <stdio.h>
12172 #include <stdlib.h>
12173
12174 #include <php.h>
12175 #include <php_guestfs_php.h>
12176
12177 #include \"guestfs.h\"
12178
12179 static int res_guestfs_h;
12180
12181 static void
12182 guestfs_php_handle_dtor (zend_rsrc_list_entry *rsrc TSRMLS_DC)
12183 {
12184   guestfs_h *g = (guestfs_h *) rsrc->ptr;
12185   if (g != NULL)
12186     guestfs_close (g);
12187 }
12188
12189 PHP_MINIT_FUNCTION (guestfs_php)
12190 {
12191   res_guestfs_h =
12192     zend_register_list_destructors_ex (guestfs_php_handle_dtor,
12193     NULL, PHP_GUESTFS_HANDLE_RES_NAME, module_number);
12194 }
12195
12196 static function_entry guestfs_php_functions[] = {
12197   PHP_FE (guestfs_create, NULL)
12198   PHP_FE (guestfs_last_error, NULL)
12199 ";
12200
12201   List.iter (
12202     fun (shortname, style, _, _, _, _, _) ->
12203       pr "  PHP_FE (guestfs_%s, NULL)\n" shortname
12204   ) all_functions_sorted;
12205
12206   pr "  { NULL, NULL, NULL }
12207 };
12208
12209 zend_module_entry guestfs_php_module_entry = {
12210 #if ZEND_MODULE_API_NO >= 20010901
12211   STANDARD_MODULE_HEADER,
12212 #endif
12213   PHP_GUESTFS_PHP_EXTNAME,
12214   guestfs_php_functions,
12215   PHP_MINIT (guestfs_php),
12216   NULL,
12217   NULL,
12218   NULL,
12219   NULL,
12220 #if ZEND_MODULE_API_NO >= 20010901
12221   PHP_GUESTFS_PHP_VERSION,
12222 #endif
12223   STANDARD_MODULE_PROPERTIES
12224 };
12225
12226 #ifdef COMPILE_DL_GUESTFS_PHP
12227 ZEND_GET_MODULE (guestfs_php)
12228 #endif
12229
12230 PHP_FUNCTION (guestfs_create)
12231 {
12232   guestfs_h *g = guestfs_create ();
12233   if (g == NULL) {
12234     RETURN_FALSE;
12235   }
12236
12237   guestfs_set_error_handler (g, NULL, NULL);
12238
12239   ZEND_REGISTER_RESOURCE (return_value, g, res_guestfs_h);
12240 }
12241
12242 PHP_FUNCTION (guestfs_last_error)
12243 {
12244   zval *z_g;
12245   guestfs_h *g;
12246
12247   if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, \"r\",
12248                              &z_g) == FAILURE) {
12249     RETURN_FALSE;
12250   }
12251
12252   ZEND_FETCH_RESOURCE (g, guestfs_h *, &z_g, -1, PHP_GUESTFS_HANDLE_RES_NAME,
12253                        res_guestfs_h);
12254   if (g == NULL) {
12255     RETURN_FALSE;
12256   }
12257
12258   const char *err = guestfs_last_error (g);
12259   if (err) {
12260     RETURN_STRING (err, 1);
12261   } else {
12262     RETURN_NULL ();
12263   }
12264 }
12265
12266 ";
12267
12268   (* Now generate the PHP bindings for each action. *)
12269   List.iter (
12270     fun (shortname, style, _, _, _, _, _) ->
12271       pr "PHP_FUNCTION (guestfs_%s)\n" shortname;
12272       pr "{\n";
12273       pr "  zval *z_g;\n";
12274       pr "  guestfs_h *g;\n";
12275
12276       List.iter (
12277         function
12278         | String n | Device n | Pathname n | Dev_or_Path n
12279         | FileIn n | FileOut n | Key n
12280         | OptString n
12281         | BufferIn n ->
12282             pr "  char *%s;\n" n;
12283             pr "  int %s_size;\n" n
12284         | StringList n
12285         | DeviceList n ->
12286             pr "  zval *z_%s;\n" n;
12287             pr "  char **%s;\n" n;
12288         | Bool n ->
12289             pr "  zend_bool %s;\n" n
12290         | Int n | Int64 n ->
12291             pr "  long %s;\n" n
12292         ) (snd style);
12293
12294       pr "\n";
12295
12296       (* Parse the parameters. *)
12297       let param_string = String.concat "" (
12298         List.map (
12299           function
12300           | String n | Device n | Pathname n | Dev_or_Path n
12301           | FileIn n | FileOut n | BufferIn n | Key n -> "s"
12302           | OptString n -> "s!"
12303           | StringList n | DeviceList n -> "a"
12304           | Bool n -> "b"
12305           | Int n | Int64 n -> "l"
12306         ) (snd style)
12307       ) in
12308
12309       pr "  if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, \"r%s\",\n"
12310         param_string;
12311       pr "        &z_g";
12312       List.iter (
12313         function
12314         | String n | Device n | Pathname n | Dev_or_Path n
12315         | FileIn n | FileOut n | BufferIn n | Key n
12316         | OptString n ->
12317             pr ", &%s, &%s_size" n n
12318         | StringList n | DeviceList n ->
12319             pr ", &z_%s" n
12320         | Bool n ->
12321             pr ", &%s" n
12322         | Int n | Int64 n ->
12323             pr ", &%s" n
12324       ) (snd style);
12325       pr ") == FAILURE) {\n";
12326       pr "    RETURN_FALSE;\n";
12327       pr "  }\n";
12328       pr "\n";
12329       pr "  ZEND_FETCH_RESOURCE (g, guestfs_h *, &z_g, -1, PHP_GUESTFS_HANDLE_RES_NAME,\n";
12330       pr "                       res_guestfs_h);\n";
12331       pr "  if (g == NULL) {\n";
12332       pr "    RETURN_FALSE;\n";
12333       pr "  }\n";
12334       pr "\n";
12335
12336       List.iter (
12337         function
12338         | String n | Device n | Pathname n | Dev_or_Path n
12339         | FileIn n | FileOut n | Key n
12340         | OptString n ->
12341             (* Just need to check the string doesn't contain any ASCII
12342              * NUL characters, which won't be supported by the C API.
12343              *)
12344             pr "  if (strlen (%s) != %s_size) {\n" n n;
12345             pr "    fprintf (stderr, \"libguestfs: %s: parameter '%s' contains embedded ASCII NUL.\\n\");\n" shortname n;
12346             pr "    RETURN_FALSE;\n";
12347             pr "  }\n";
12348             pr "\n"
12349         | BufferIn n -> ()
12350         | StringList n
12351         | DeviceList n ->
12352             (* Convert array to list of strings.
12353              * http://marc.info/?l=pecl-dev&m=112205192100631&w=2
12354              *)
12355             pr "  {\n";
12356             pr "    HashTable *a;\n";
12357             pr "    int n;\n";
12358             pr "    HashPosition p;\n";
12359             pr "    zval **d;\n";
12360             pr "    size_t c = 0;\n";
12361             pr "\n";
12362             pr "    a = Z_ARRVAL_P (z_%s);\n" n;
12363             pr "    n = zend_hash_num_elements (a);\n";
12364             pr "    %s = safe_emalloc (n + 1, sizeof (char *), 0);\n" n;
12365             pr "    for (zend_hash_internal_pointer_reset_ex (a, &p);\n";
12366             pr "         zend_hash_get_current_data_ex (a, (void **) &d, &p) == SUCCESS;\n";
12367             pr "         zend_hash_move_forward_ex (a, &p)) {\n";
12368             pr "      zval t = **d;\n";
12369             pr "      zval_copy_ctor (&t);\n";
12370             pr "      convert_to_string (&t);\n";
12371             pr "      %s[c] = Z_STRVAL (t);\n" n;
12372             pr "      c++;\n";
12373             pr "    }\n";
12374             pr "    %s[c] = NULL;\n" n;
12375             pr "  }\n";
12376             pr "\n"
12377         | Bool n | Int n | Int64 n -> ()
12378         ) (snd style);
12379
12380       (* Return value. *)
12381       let error_code =
12382         match fst style with
12383         | RErr -> pr "  int r;\n"; "-1"
12384         | RBool _
12385         | RInt _ -> pr "  int r;\n"; "-1"
12386         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
12387         | RConstString _ -> pr "  const char *r;\n"; "NULL"
12388         | RConstOptString _ -> pr "  const char *r;\n"; "NULL"
12389         | RString _ ->
12390             pr "  char *r;\n"; "NULL"
12391         | RStringList _ ->
12392             pr "  char **r;\n"; "NULL"
12393         | RStruct (_, typ) ->
12394             pr "  struct guestfs_%s *r;\n" typ; "NULL"
12395         | RStructList (_, typ) ->
12396             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
12397         | RHashtable _ ->
12398             pr "  char **r;\n"; "NULL"
12399         | RBufferOut _ ->
12400             pr "  char *r;\n";
12401             pr "  size_t size;\n";
12402             "NULL" in
12403
12404       (* Call the function. *)
12405       pr "  r = guestfs_%s " shortname;
12406       generate_c_call_args ~handle:"g" style;
12407       pr ";\n";
12408       pr "\n";
12409
12410       (* Free up parameters. *)
12411       List.iter (
12412         function
12413         | String n | Device n | Pathname n | Dev_or_Path n
12414         | FileIn n | FileOut n | Key n
12415         | OptString n -> ()
12416         | BufferIn n -> ()
12417         | StringList n
12418         | DeviceList n ->
12419             pr "  {\n";
12420             pr "    size_t c = 0;\n";
12421             pr "\n";
12422             pr "    for (c = 0; %s[c] != NULL; ++c)\n" n;
12423             pr "      efree (%s[c]);\n" n;
12424             pr "    efree (%s);\n" n;
12425             pr "  }\n";
12426             pr "\n"
12427         | Bool n | Int n | Int64 n -> ()
12428         ) (snd style);
12429
12430       (* Check for errors. *)
12431       pr "  if (r == %s) {\n" error_code;
12432       pr "    RETURN_FALSE;\n";
12433       pr "  }\n";
12434       pr "\n";
12435
12436       (* Convert the return value. *)
12437       (match fst style with
12438        | RErr ->
12439            pr "  RETURN_TRUE;\n"
12440        | RBool _ ->
12441            pr "  RETURN_BOOL (r);\n"
12442        | RInt _ ->
12443            pr "  RETURN_LONG (r);\n"
12444        | RInt64 _ ->
12445            pr "  RETURN_LONG (r);\n"
12446        | RConstString _ ->
12447            pr "  RETURN_STRING (r, 1);\n"
12448        | RConstOptString _ ->
12449            pr "  if (r) { RETURN_STRING (r, 1); }\n";
12450            pr "  else { RETURN_NULL (); }\n"
12451        | RString _ ->
12452            pr "  char *r_copy = estrdup (r);\n";
12453            pr "  free (r);\n";
12454            pr "  RETURN_STRING (r_copy, 0);\n"
12455        | RBufferOut _ ->
12456            pr "  char *r_copy = estrndup (r, size);\n";
12457            pr "  free (r);\n";
12458            pr "  RETURN_STRING (r_copy, 0);\n"
12459        | RStringList _ ->
12460            pr "  size_t c = 0;\n";
12461            pr "  array_init (return_value);\n";
12462            pr "  for (c = 0; r[c] != NULL; ++c) {\n";
12463            pr "    add_next_index_string (return_value, r[c], 1);\n";
12464            pr "    free (r[c]);\n";
12465            pr "  }\n";
12466            pr "  free (r);\n";
12467        | RHashtable _ ->
12468            pr "  size_t c = 0;\n";
12469            pr "  array_init (return_value);\n";
12470            pr "  for (c = 0; r[c] != NULL; c += 2) {\n";
12471            pr "    add_assoc_string (return_value, r[c], r[c+1], 1);\n";
12472            pr "    free (r[c]);\n";
12473            pr "    free (r[c+1]);\n";
12474            pr "  }\n";
12475            pr "  free (r);\n";
12476        | RStruct (_, typ) ->
12477            let cols = cols_of_struct typ in
12478            generate_php_struct_code typ cols
12479        | RStructList (_, typ) ->
12480            let cols = cols_of_struct typ in
12481            generate_php_struct_list_code typ cols
12482       );
12483
12484       pr "}\n";
12485       pr "\n"
12486   ) all_functions_sorted
12487
12488 and generate_php_struct_code typ cols =
12489   pr "  array_init (return_value);\n";
12490   List.iter (
12491     function
12492     | name, FString ->
12493         pr "  add_assoc_string (return_value, \"%s\", r->%s, 1);\n" name name
12494     | name, FBuffer ->
12495         pr "  add_assoc_stringl (return_value, \"%s\", r->%s, r->%s_len, 1);\n"
12496           name name name
12497     | name, FUUID ->
12498         pr "  add_assoc_stringl (return_value, \"%s\", r->%s, 32, 1);\n"
12499           name name
12500     | name, (FBytes|FUInt64|FInt64|FInt32|FUInt32) ->
12501         pr "  add_assoc_long (return_value, \"%s\", r->%s);\n"
12502           name name
12503     | name, FChar ->
12504         pr "  add_assoc_stringl (return_value, \"%s\", &r->%s, 1, 1);\n"
12505           name name
12506     | name, FOptPercent ->
12507         pr "  add_assoc_double (return_value, \"%s\", r->%s);\n"
12508           name name
12509   ) cols;
12510   pr "  guestfs_free_%s (r);\n" typ
12511
12512 and generate_php_struct_list_code typ cols =
12513   pr "  array_init (return_value);\n";
12514   pr "  size_t c = 0;\n";
12515   pr "  for (c = 0; c < r->len; ++c) {\n";
12516   pr "    zval *z_elem;\n";
12517   pr "    ALLOC_INIT_ZVAL (z_elem);\n";
12518   pr "    array_init (z_elem);\n";
12519   List.iter (
12520     function
12521     | name, FString ->
12522         pr "    add_assoc_string (z_elem, \"%s\", r->val[c].%s, 1);\n"
12523           name name
12524     | name, FBuffer ->
12525         pr "    add_assoc_stringl (z_elem, \"%s\", r->val[c].%s, r->val[c].%s_len, 1);\n"
12526           name name name
12527     | name, FUUID ->
12528         pr "    add_assoc_stringl (z_elem, \"%s\", r->val[c].%s, 32, 1);\n"
12529           name name
12530     | name, (FBytes|FUInt64|FInt64|FInt32|FUInt32) ->
12531         pr "    add_assoc_long (z_elem, \"%s\", r->val[c].%s);\n"
12532           name name
12533     | name, FChar ->
12534         pr "    add_assoc_stringl (z_elem, \"%s\", &r->val[c].%s, 1, 1);\n"
12535           name name
12536     | name, FOptPercent ->
12537         pr "    add_assoc_double (z_elem, \"%s\", r->val[c].%s);\n"
12538           name name
12539   ) cols;
12540   pr "    add_next_index_zval (return_value, z_elem);\n";
12541   pr "  }\n";
12542   pr "  guestfs_free_%s_list (r);\n" typ
12543
12544 and generate_bindtests () =
12545   generate_header CStyle LGPLv2plus;
12546
12547   pr "\
12548 #include <stdio.h>
12549 #include <stdlib.h>
12550 #include <inttypes.h>
12551 #include <string.h>
12552
12553 #include \"guestfs.h\"
12554 #include \"guestfs-internal.h\"
12555 #include \"guestfs-internal-actions.h\"
12556 #include \"guestfs_protocol.h\"
12557
12558 #define error guestfs_error
12559 #define safe_calloc guestfs_safe_calloc
12560 #define safe_malloc guestfs_safe_malloc
12561
12562 static void
12563 print_strings (char *const *argv)
12564 {
12565   size_t argc;
12566
12567   printf (\"[\");
12568   for (argc = 0; argv[argc] != NULL; ++argc) {
12569     if (argc > 0) printf (\", \");
12570     printf (\"\\\"%%s\\\"\", argv[argc]);
12571   }
12572   printf (\"]\\n\");
12573 }
12574
12575 /* The test0 function prints its parameters to stdout. */
12576 ";
12577
12578   let test0, tests =
12579     match test_functions with
12580     | [] -> assert false
12581     | test0 :: tests -> test0, tests in
12582
12583   let () =
12584     let (name, style, _, _, _, _, _) = test0 in
12585     generate_prototype ~extern:false ~semicolon:false ~newline:true
12586       ~handle:"g" ~prefix:"guestfs__" name style;
12587     pr "{\n";
12588     List.iter (
12589       function
12590       | Pathname n
12591       | Device n | Dev_or_Path n
12592       | String n
12593       | FileIn n
12594       | FileOut n
12595       | Key n -> pr "  printf (\"%%s\\n\", %s);\n" n
12596       | BufferIn n ->
12597           pr "  {\n";
12598           pr "    size_t i;\n";
12599           pr "    for (i = 0; i < %s_size; ++i)\n" n;
12600           pr "      printf (\"<%%02x>\", %s[i]);\n" n;
12601           pr "    printf (\"\\n\");\n";
12602           pr "  }\n";
12603       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
12604       | StringList n | DeviceList n -> pr "  print_strings (%s);\n" n
12605       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
12606       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
12607       | Int64 n -> pr "  printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
12608     ) (snd style);
12609     pr "  /* Java changes stdout line buffering so we need this: */\n";
12610     pr "  fflush (stdout);\n";
12611     pr "  return 0;\n";
12612     pr "}\n";
12613     pr "\n" in
12614
12615   List.iter (
12616     fun (name, style, _, _, _, _, _) ->
12617       if String.sub name (String.length name - 3) 3 <> "err" then (
12618         pr "/* Test normal return. */\n";
12619         generate_prototype ~extern:false ~semicolon:false ~newline:true
12620           ~handle:"g" ~prefix:"guestfs__" name style;
12621         pr "{\n";
12622         (match fst style with
12623          | RErr ->
12624              pr "  return 0;\n"
12625          | RInt _ ->
12626              pr "  int r;\n";
12627              pr "  sscanf (val, \"%%d\", &r);\n";
12628              pr "  return r;\n"
12629          | RInt64 _ ->
12630              pr "  int64_t r;\n";
12631              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
12632              pr "  return r;\n"
12633          | RBool _ ->
12634              pr "  return STREQ (val, \"true\");\n"
12635          | RConstString _
12636          | RConstOptString _ ->
12637              (* Can't return the input string here.  Return a static
12638               * string so we ensure we get a segfault if the caller
12639               * tries to free it.
12640               *)
12641              pr "  return \"static string\";\n"
12642          | RString _ ->
12643              pr "  return strdup (val);\n"
12644          | RStringList _ ->
12645              pr "  char **strs;\n";
12646              pr "  int n, i;\n";
12647              pr "  sscanf (val, \"%%d\", &n);\n";
12648              pr "  strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
12649              pr "  for (i = 0; i < n; ++i) {\n";
12650              pr "    strs[i] = safe_malloc (g, 16);\n";
12651              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
12652              pr "  }\n";
12653              pr "  strs[n] = NULL;\n";
12654              pr "  return strs;\n"
12655          | RStruct (_, typ) ->
12656              pr "  struct guestfs_%s *r;\n" typ;
12657              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
12658              pr "  return r;\n"
12659          | RStructList (_, typ) ->
12660              pr "  struct guestfs_%s_list *r;\n" typ;
12661              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
12662              pr "  sscanf (val, \"%%d\", &r->len);\n";
12663              pr "  r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
12664              pr "  return r;\n"
12665          | RHashtable _ ->
12666              pr "  char **strs;\n";
12667              pr "  int n, i;\n";
12668              pr "  sscanf (val, \"%%d\", &n);\n";
12669              pr "  strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
12670              pr "  for (i = 0; i < n; ++i) {\n";
12671              pr "    strs[i*2] = safe_malloc (g, 16);\n";
12672              pr "    strs[i*2+1] = safe_malloc (g, 16);\n";
12673              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
12674              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
12675              pr "  }\n";
12676              pr "  strs[n*2] = NULL;\n";
12677              pr "  return strs;\n"
12678          | RBufferOut _ ->
12679              pr "  return strdup (val);\n"
12680         );
12681         pr "}\n";
12682         pr "\n"
12683       ) else (
12684         pr "/* Test error return. */\n";
12685         generate_prototype ~extern:false ~semicolon:false ~newline:true
12686           ~handle:"g" ~prefix:"guestfs__" name style;
12687         pr "{\n";
12688         pr "  error (g, \"error\");\n";
12689         (match fst style with
12690          | RErr | RInt _ | RInt64 _ | RBool _ ->
12691              pr "  return -1;\n"
12692          | RConstString _ | RConstOptString _
12693          | RString _ | RStringList _ | RStruct _
12694          | RStructList _
12695          | RHashtable _
12696          | RBufferOut _ ->
12697              pr "  return NULL;\n"
12698         );
12699         pr "}\n";
12700         pr "\n"
12701       )
12702   ) tests
12703
12704 and generate_ocaml_bindtests () =
12705   generate_header OCamlStyle GPLv2plus;
12706
12707   pr "\
12708 let () =
12709   let g = Guestfs.create () in
12710 ";
12711
12712   let mkargs args =
12713     String.concat " " (
12714       List.map (
12715         function
12716         | CallString s -> "\"" ^ s ^ "\""
12717         | CallOptString None -> "None"
12718         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
12719         | CallStringList xs ->
12720             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
12721         | CallInt i when i >= 0 -> string_of_int i
12722         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
12723         | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
12724         | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
12725         | CallBool b -> string_of_bool b
12726         | CallBuffer s -> sprintf "%S" s
12727       ) args
12728     )
12729   in
12730
12731   generate_lang_bindtests (
12732     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
12733   );
12734
12735   pr "print_endline \"EOF\"\n"
12736
12737 and generate_perl_bindtests () =
12738   pr "#!/usr/bin/perl -w\n";
12739   generate_header HashStyle GPLv2plus;
12740
12741   pr "\
12742 use strict;
12743
12744 use Sys::Guestfs;
12745
12746 my $g = Sys::Guestfs->new ();
12747 ";
12748
12749   let mkargs args =
12750     String.concat ", " (
12751       List.map (
12752         function
12753         | CallString s -> "\"" ^ s ^ "\""
12754         | CallOptString None -> "undef"
12755         | CallOptString (Some s) -> sprintf "\"%s\"" s
12756         | CallStringList xs ->
12757             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12758         | CallInt i -> string_of_int i
12759         | CallInt64 i -> Int64.to_string i
12760         | CallBool b -> if b then "1" else "0"
12761         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12762       ) args
12763     )
12764   in
12765
12766   generate_lang_bindtests (
12767     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
12768   );
12769
12770   pr "print \"EOF\\n\"\n"
12771
12772 and generate_python_bindtests () =
12773   generate_header HashStyle GPLv2plus;
12774
12775   pr "\
12776 import guestfs
12777
12778 g = guestfs.GuestFS ()
12779 ";
12780
12781   let mkargs args =
12782     String.concat ", " (
12783       List.map (
12784         function
12785         | CallString s -> "\"" ^ s ^ "\""
12786         | CallOptString None -> "None"
12787         | CallOptString (Some s) -> sprintf "\"%s\"" s
12788         | CallStringList xs ->
12789             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12790         | CallInt i -> string_of_int i
12791         | CallInt64 i -> Int64.to_string i
12792         | CallBool b -> if b then "1" else "0"
12793         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12794       ) args
12795     )
12796   in
12797
12798   generate_lang_bindtests (
12799     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
12800   );
12801
12802   pr "print \"EOF\"\n"
12803
12804 and generate_ruby_bindtests () =
12805   generate_header HashStyle GPLv2plus;
12806
12807   pr "\
12808 require 'guestfs'
12809
12810 g = Guestfs::create()
12811 ";
12812
12813   let mkargs args =
12814     String.concat ", " (
12815       List.map (
12816         function
12817         | CallString s -> "\"" ^ s ^ "\""
12818         | CallOptString None -> "nil"
12819         | CallOptString (Some s) -> sprintf "\"%s\"" s
12820         | CallStringList xs ->
12821             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12822         | CallInt i -> string_of_int i
12823         | CallInt64 i -> Int64.to_string i
12824         | CallBool b -> string_of_bool b
12825         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12826       ) args
12827     )
12828   in
12829
12830   generate_lang_bindtests (
12831     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
12832   );
12833
12834   pr "print \"EOF\\n\"\n"
12835
12836 and generate_java_bindtests () =
12837   generate_header CStyle GPLv2plus;
12838
12839   pr "\
12840 import com.redhat.et.libguestfs.*;
12841
12842 public class Bindtests {
12843     public static void main (String[] argv)
12844     {
12845         try {
12846             GuestFS g = new GuestFS ();
12847 ";
12848
12849   let mkargs args =
12850     String.concat ", " (
12851       List.map (
12852         function
12853         | CallString s -> "\"" ^ s ^ "\""
12854         | CallOptString None -> "null"
12855         | CallOptString (Some s) -> sprintf "\"%s\"" s
12856         | CallStringList xs ->
12857             "new String[]{" ^
12858               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
12859         | CallInt i -> string_of_int i
12860         | CallInt64 i -> Int64.to_string i
12861         | CallBool b -> string_of_bool b
12862         | CallBuffer s ->
12863             "new byte[] { " ^ String.concat "," (
12864               map_chars (fun c -> string_of_int (Char.code c)) s
12865             ) ^ " }"
12866       ) args
12867     )
12868   in
12869
12870   generate_lang_bindtests (
12871     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
12872   );
12873
12874   pr "
12875             System.out.println (\"EOF\");
12876         }
12877         catch (Exception exn) {
12878             System.err.println (exn);
12879             System.exit (1);
12880         }
12881     }
12882 }
12883 "
12884
12885 and generate_haskell_bindtests () =
12886   generate_header HaskellStyle GPLv2plus;
12887
12888   pr "\
12889 module Bindtests where
12890 import qualified Guestfs
12891
12892 main = do
12893   g <- Guestfs.create
12894 ";
12895
12896   let mkargs args =
12897     String.concat " " (
12898       List.map (
12899         function
12900         | CallString s -> "\"" ^ s ^ "\""
12901         | CallOptString None -> "Nothing"
12902         | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
12903         | CallStringList xs ->
12904             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12905         | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
12906         | CallInt i -> string_of_int i
12907         | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
12908         | CallInt64 i -> Int64.to_string i
12909         | CallBool true -> "True"
12910         | CallBool false -> "False"
12911         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12912       ) args
12913     )
12914   in
12915
12916   generate_lang_bindtests (
12917     fun f args -> pr "  Guestfs.%s g %s\n" f (mkargs args)
12918   );
12919
12920   pr "  putStrLn \"EOF\"\n"
12921
12922 (* Language-independent bindings tests - we do it this way to
12923  * ensure there is parity in testing bindings across all languages.
12924  *)
12925 and generate_lang_bindtests call =
12926   call "test0" [CallString "abc"; CallOptString (Some "def");
12927                 CallStringList []; CallBool false;
12928                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12929                 CallBuffer "abc\000abc"];
12930   call "test0" [CallString "abc"; CallOptString None;
12931                 CallStringList []; CallBool false;
12932                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12933                 CallBuffer "abc\000abc"];
12934   call "test0" [CallString ""; CallOptString (Some "def");
12935                 CallStringList []; CallBool false;
12936                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12937                 CallBuffer "abc\000abc"];
12938   call "test0" [CallString ""; CallOptString (Some "");
12939                 CallStringList []; CallBool false;
12940                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12941                 CallBuffer "abc\000abc"];
12942   call "test0" [CallString "abc"; CallOptString (Some "def");
12943                 CallStringList ["1"]; CallBool false;
12944                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12945                 CallBuffer "abc\000abc"];
12946   call "test0" [CallString "abc"; CallOptString (Some "def");
12947                 CallStringList ["1"; "2"]; CallBool false;
12948                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12949                 CallBuffer "abc\000abc"];
12950   call "test0" [CallString "abc"; CallOptString (Some "def");
12951                 CallStringList ["1"]; CallBool true;
12952                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12953                 CallBuffer "abc\000abc"];
12954   call "test0" [CallString "abc"; CallOptString (Some "def");
12955                 CallStringList ["1"]; CallBool false;
12956                 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456";
12957                 CallBuffer "abc\000abc"];
12958   call "test0" [CallString "abc"; CallOptString (Some "def");
12959                 CallStringList ["1"]; CallBool false;
12960                 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456";
12961                 CallBuffer "abc\000abc"];
12962   call "test0" [CallString "abc"; CallOptString (Some "def");
12963                 CallStringList ["1"]; CallBool false;
12964                 CallInt 1; CallInt64 1L; CallString "123"; CallString "456";
12965                 CallBuffer "abc\000abc"];
12966   call "test0" [CallString "abc"; CallOptString (Some "def");
12967                 CallStringList ["1"]; CallBool false;
12968                 CallInt 2; CallInt64 2L; CallString "123"; CallString "456";
12969                 CallBuffer "abc\000abc"];
12970   call "test0" [CallString "abc"; CallOptString (Some "def");
12971                 CallStringList ["1"]; CallBool false;
12972                 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456";
12973                 CallBuffer "abc\000abc"];
12974   call "test0" [CallString "abc"; CallOptString (Some "def");
12975                 CallStringList ["1"]; CallBool false;
12976                 CallInt 0; CallInt64 0L; CallString ""; CallString "";
12977                 CallBuffer "abc\000abc"]
12978
12979 (* XXX Add here tests of the return and error functions. *)
12980
12981 and generate_max_proc_nr () =
12982   pr "%d\n" max_proc_nr
12983
12984 let output_to filename k =
12985   let filename_new = filename ^ ".new" in
12986   chan := open_out filename_new;
12987   k ();
12988   close_out !chan;
12989   chan := Pervasives.stdout;
12990
12991   (* Is the new file different from the current file? *)
12992   if Sys.file_exists filename && files_equal filename filename_new then
12993     unlink filename_new                 (* same, so skip it *)
12994   else (
12995     (* different, overwrite old one *)
12996     (try chmod filename 0o644 with Unix_error _ -> ());
12997     rename filename_new filename;
12998     chmod filename 0o444;
12999     printf "written %s\n%!" filename;
13000   )
13001
13002 let perror msg = function
13003   | Unix_error (err, _, _) ->
13004       eprintf "%s: %s\n" msg (error_message err)
13005   | exn ->
13006       eprintf "%s: %s\n" msg (Printexc.to_string exn)
13007
13008 (* Main program. *)
13009 let () =
13010   let lock_fd =
13011     try openfile "HACKING" [O_RDWR] 0
13012     with
13013     | Unix_error (ENOENT, _, _) ->
13014         eprintf "\
13015 You are probably running this from the wrong directory.
13016 Run it from the top source directory using the command
13017   src/generator.ml
13018 ";
13019         exit 1
13020     | exn ->
13021         perror "open: HACKING" exn;
13022         exit 1 in
13023
13024   (* Acquire a lock so parallel builds won't try to run the generator
13025    * twice at the same time.  Subsequent builds will wait for the first
13026    * one to finish.  Note the lock is released implicitly when the
13027    * program exits.
13028    *)
13029   (try lockf lock_fd F_LOCK 1
13030    with exn ->
13031      perror "lock: HACKING" exn;
13032      exit 1);
13033
13034   check_functions ();
13035
13036   output_to "src/guestfs_protocol.x" generate_xdr;
13037   output_to "src/guestfs-structs.h" generate_structs_h;
13038   output_to "src/guestfs-actions.h" generate_actions_h;
13039   output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
13040   output_to "src/actions.c" generate_client_actions;
13041   output_to "src/bindtests.c" generate_bindtests;
13042   output_to "src/guestfs-structs.pod" generate_structs_pod;
13043   output_to "src/guestfs-actions.pod" generate_actions_pod;
13044   output_to "src/guestfs-availability.pod" generate_availability_pod;
13045   output_to "src/MAX_PROC_NR" generate_max_proc_nr;
13046   output_to "src/libguestfs.syms" generate_linker_script;
13047   output_to "daemon/actions.h" generate_daemon_actions_h;
13048   output_to "daemon/stubs.c" generate_daemon_actions;
13049   output_to "daemon/names.c" generate_daemon_names;
13050   output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
13051   output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
13052   output_to "capitests/tests.c" generate_tests;
13053   output_to "fish/cmds.c" generate_fish_cmds;
13054   output_to "fish/completion.c" generate_fish_completion;
13055   output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
13056   output_to "fish/prepopts.c" generate_fish_prep_options_c;
13057   output_to "fish/prepopts.h" generate_fish_prep_options_h;
13058   output_to "ocaml/guestfs.mli" generate_ocaml_mli;
13059   output_to "ocaml/guestfs.ml" generate_ocaml_ml;
13060   output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
13061   output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
13062   output_to "perl/Guestfs.xs" generate_perl_xs;
13063   output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
13064   output_to "perl/bindtests.pl" generate_perl_bindtests;
13065   output_to "python/guestfs-py.c" generate_python_c;
13066   output_to "python/guestfs.py" generate_python_py;
13067   output_to "python/bindtests.py" generate_python_bindtests;
13068   output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
13069   output_to "ruby/bindtests.rb" generate_ruby_bindtests;
13070   output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
13071
13072   List.iter (
13073     fun (typ, jtyp) ->
13074       let cols = cols_of_struct typ in
13075       let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
13076       output_to filename (generate_java_struct jtyp cols);
13077   ) java_structs;
13078
13079   output_to "java/Makefile.inc" generate_java_makefile_inc;
13080   output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
13081   output_to "java/Bindtests.java" generate_java_bindtests;
13082   output_to "haskell/Guestfs.hs" generate_haskell_hs;
13083   output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
13084   output_to "csharp/Libguestfs.cs" generate_csharp;
13085   output_to "php/extension/php_guestfs_php.h" generate_php_h;
13086   output_to "php/extension/guestfs_php.c" generate_php_c;
13087
13088   (* Always generate this file last, and unconditionally.  It's used
13089    * by the Makefile to know when we must re-run the generator.
13090    *)
13091   let chan = open_out "src/stamp-generator" in
13092   fprintf chan "1\n";
13093   close_out chan;
13094
13095   printf "generated %d lines of code\n" !lines