New APIs: set-network and get-network to enable network support.
[libguestfs.git] / src / generator.ml
1 #!/usr/bin/env ocaml
2 (* libguestfs
3  * Copyright (C) 2009-2010 Red Hat Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  *)
19
20 (* This script generates a large amount of code and documentation for
21  * all the daemon actions.
22  *
23  * To add a new action there are only two files you need to change,
24  * this one to describe the interface (see the big table of
25  * 'daemon_functions' below), and daemon/<somefile>.c to write the
26  * implementation.
27  *
28  * After editing this file, run it (./src/generator.ml) to regenerate
29  * all the output files.  'make' will rerun this automatically when
30  * necessary.  Note that if you are using a separate build directory
31  * you must run generator.ml from the _source_ directory.
32  *
33  * IMPORTANT: This script should NOT print any warnings.  If it prints
34  * warnings, you should treat them as errors.
35  *
36  * OCaml tips:
37  * (1) In emacs, install tuareg-mode to display and format OCaml code
38  * correctly.  'vim' comes with a good OCaml editing mode by default.
39  * (2) Read the resources at http://ocaml-tutorial.org/
40  *)
41
42 #load "unix.cma";;
43 #load "str.cma";;
44 #directory "+xml-light";;
45 #directory "+../pkg-lib/xml-light";; (* for GODI users *)
46 #load "xml-light.cma";;
47
48 open Unix
49 open Printf
50
51 type style = ret * args
52 and ret =
53     (* "RErr" as a return value means an int used as a simple error
54      * indication, ie. 0 or -1.
55      *)
56   | RErr
57
58     (* "RInt" as a return value means an int which is -1 for error
59      * or any value >= 0 on success.  Only use this for smallish
60      * positive ints (0 <= i < 2^30).
61      *)
62   | RInt of string
63
64     (* "RInt64" is the same as RInt, but is guaranteed to be able
65      * to return a full 64 bit value, _except_ that -1 means error
66      * (so -1 cannot be a valid, non-error return value).
67      *)
68   | RInt64 of string
69
70     (* "RBool" is a bool return value which can be true/false or
71      * -1 for error.
72      *)
73   | RBool of string
74
75     (* "RConstString" is a string that refers to a constant value.
76      * The return value must NOT be NULL (since NULL indicates
77      * an error).
78      *
79      * Try to avoid using this.  In particular you cannot use this
80      * for values returned from the daemon, because there is no
81      * thread-safe way to return them in the C API.
82      *)
83   | RConstString of string
84
85     (* "RConstOptString" is an even more broken version of
86      * "RConstString".  The returned string may be NULL and there
87      * is no way to return an error indication.  Avoid using this!
88      *)
89   | RConstOptString of string
90
91     (* "RString" is a returned string.  It must NOT be NULL, since
92      * a NULL return indicates an error.  The caller frees this.
93      *)
94   | RString of string
95
96     (* "RStringList" is a list of strings.  No string in the list
97      * can be NULL.  The caller frees the strings and the array.
98      *)
99   | RStringList of string
100
101     (* "RStruct" is a function which returns a single named structure
102      * or an error indication (in C, a struct, and in other languages
103      * with varying representations, but usually very efficient).  See
104      * after the function list below for the structures.
105      *)
106   | RStruct of string * string          (* name of retval, name of struct *)
107
108     (* "RStructList" is a function which returns either a list/array
109      * of structures (could be zero-length), or an error indication.
110      *)
111   | RStructList of string * string      (* name of retval, name of struct *)
112
113     (* Key-value pairs of untyped strings.  Turns into a hashtable or
114      * dictionary in languages which support it.  DON'T use this as a
115      * general "bucket" for results.  Prefer a stronger typed return
116      * value if one is available, or write a custom struct.  Don't use
117      * this if the list could potentially be very long, since it is
118      * inefficient.  Keys should be unique.  NULLs are not permitted.
119      *)
120   | RHashtable of string
121
122     (* "RBufferOut" is handled almost exactly like RString, but
123      * it allows the string to contain arbitrary 8 bit data including
124      * ASCII NUL.  In the C API this causes an implicit extra parameter
125      * to be added of type <size_t *size_r>.  The extra parameter
126      * returns the actual size of the return buffer in bytes.
127      *
128      * Other programming languages support strings with arbitrary 8 bit
129      * data.
130      *
131      * At the RPC layer we have to use the opaque<> type instead of
132      * string<>.  Returned data is still limited to the max message
133      * size (ie. ~ 2 MB).
134      *)
135   | RBufferOut of string
136
137 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
138
139     (* Note in future we should allow a "variable args" parameter as
140      * the final parameter, to allow commands like
141      *   chmod mode file [file(s)...]
142      * This is not implemented yet, but many commands (such as chmod)
143      * are currently defined with the argument order keeping this future
144      * possibility in mind.
145      *)
146 and argt =
147   | String of string    (* const char *name, cannot be NULL *)
148   | Device of string    (* /dev device name, cannot be NULL *)
149   | Pathname of string  (* file name, cannot be NULL *)
150   | Dev_or_Path of string (* /dev device name or Pathname, cannot be NULL *)
151   | OptString of string (* const char *name, may be NULL *)
152   | StringList of string(* list of strings (each string cannot be NULL) *)
153   | DeviceList of string(* list of Device names (each cannot be NULL) *)
154   | Bool of string      (* boolean *)
155   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
156   | Int64 of string     (* any 64 bit int *)
157     (* These are treated as filenames (simple string parameters) in
158      * the C API and bindings.  But in the RPC protocol, we transfer
159      * the actual file content up to or down from the daemon.
160      * FileIn: local machine -> daemon (in request)
161      * FileOut: daemon -> local machine (in reply)
162      * In guestfish (only), the special name "-" means read from
163      * stdin or write to stdout.
164      *)
165   | FileIn of string
166   | FileOut of string
167     (* Opaque buffer which can contain arbitrary 8 bit data.
168      * In the C API, this is expressed as <const char *, size_t> pair.
169      * Most other languages have a string type which can contain
170      * ASCII NUL.  We use whatever type is appropriate for each
171      * language.
172      * Buffers are limited by the total message size.  To transfer
173      * large blocks of data, use FileIn/FileOut parameters instead.
174      * To return an arbitrary buffer, use RBufferOut.
175      *)
176   | BufferIn of string
177     (* Key material / passphrase.  Eventually we should treat this
178      * as sensitive and mlock it into physical RAM.  However this
179      * is highly complex because of all the places that XDR-encoded
180      * strings can end up.  So currently the only difference from
181      * 'String' is the way that guestfish requests these parameters
182      * from the user.
183      *)
184   | Key of string
185
186 type flags =
187   | ProtocolLimitWarning  (* display warning about protocol size limits *)
188   | DangerWillRobinson    (* flags particularly dangerous commands *)
189   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
190   | FishOutput of fish_output_t (* how to display output in guestfish *)
191   | NotInFish             (* do not export via guestfish *)
192   | NotInDocs             (* do not add this function to documentation *)
193   | DeprecatedBy of string (* function is deprecated, use .. instead *)
194   | Optional of string    (* function is part of an optional group *)
195
196 and fish_output_t =
197   | FishOutputOctal       (* for int return, print in octal *)
198   | FishOutputHexadecimal (* for int return, print in hex *)
199
200 (* You can supply zero or as many tests as you want per API call.
201  *
202  * Note that the test environment has 3 block devices, of size 500MB,
203  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
204  * a fourth ISO block device with some known files on it (/dev/sdd).
205  *
206  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
207  * Number of cylinders was 63 for IDE emulated disks with precisely
208  * the same size.  How exactly this is calculated is a mystery.
209  *
210  * The ISO block device (/dev/sdd) comes from images/test.iso.
211  *
212  * To be able to run the tests in a reasonable amount of time,
213  * the virtual machine and block devices are reused between tests.
214  * So don't try testing kill_subprocess :-x
215  *
216  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
217  *
218  * Don't assume anything about the previous contents of the block
219  * devices.  Use 'Init*' to create some initial scenarios.
220  *
221  * You can add a prerequisite clause to any individual test.  This
222  * is a run-time check, which, if it fails, causes the test to be
223  * skipped.  Useful if testing a command which might not work on
224  * all variations of libguestfs builds.  A test that has prerequisite
225  * of 'Always' is run unconditionally.
226  *
227  * In addition, packagers can skip individual tests by setting the
228  * environment variables:     eg:
229  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
230  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
231  *)
232 type tests = (test_init * test_prereq * test) list
233 and test =
234     (* Run the command sequence and just expect nothing to fail. *)
235   | TestRun of seq
236
237     (* Run the command sequence and expect the output of the final
238      * command to be the string.
239      *)
240   | TestOutput of seq * string
241
242     (* Run the command sequence and expect the output of the final
243      * command to be the list of strings.
244      *)
245   | TestOutputList of seq * string list
246
247     (* Run the command sequence and expect the output of the final
248      * command to be the list of block devices (could be either
249      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
250      * character of each string).
251      *)
252   | TestOutputListOfDevices of seq * string list
253
254     (* Run the command sequence and expect the output of the final
255      * command to be the integer.
256      *)
257   | TestOutputInt of seq * int
258
259     (* Run the command sequence and expect the output of the final
260      * command to be <op> <int>, eg. ">=", "1".
261      *)
262   | TestOutputIntOp of seq * string * int
263
264     (* Run the command sequence and expect the output of the final
265      * command to be a true value (!= 0 or != NULL).
266      *)
267   | TestOutputTrue of seq
268
269     (* Run the command sequence and expect the output of the final
270      * command to be a false value (== 0 or == NULL, but not an error).
271      *)
272   | TestOutputFalse of seq
273
274     (* Run the command sequence and expect the output of the final
275      * command to be a list of the given length (but don't care about
276      * content).
277      *)
278   | TestOutputLength of seq * int
279
280     (* Run the command sequence and expect the output of the final
281      * command to be a buffer (RBufferOut), ie. string + size.
282      *)
283   | TestOutputBuffer of seq * string
284
285     (* Run the command sequence and expect the output of the final
286      * command to be a structure.
287      *)
288   | TestOutputStruct of seq * test_field_compare list
289
290     (* Run the command sequence and expect the final command (only)
291      * to fail.
292      *)
293   | TestLastFail of seq
294
295 and test_field_compare =
296   | CompareWithInt of string * int
297   | CompareWithIntOp of string * string * int
298   | CompareWithString of string * string
299   | CompareFieldsIntEq of string * string
300   | CompareFieldsStrEq of string * string
301
302 (* Test prerequisites. *)
303 and test_prereq =
304     (* Test always runs. *)
305   | Always
306
307     (* Test is currently disabled - eg. it fails, or it tests some
308      * unimplemented feature.
309      *)
310   | Disabled
311
312     (* 'string' is some C code (a function body) that should return
313      * true or false.  The test will run if the code returns true.
314      *)
315   | If of string
316
317     (* As for 'If' but the test runs _unless_ the code returns true. *)
318   | Unless of string
319
320     (* Run the test only if 'string' is available in the daemon. *)
321   | IfAvailable of string
322
323 (* Some initial scenarios for testing. *)
324 and test_init =
325     (* Do nothing, block devices could contain random stuff including
326      * LVM PVs, and some filesystems might be mounted.  This is usually
327      * a bad idea.
328      *)
329   | InitNone
330
331     (* Block devices are empty and no filesystems are mounted. *)
332   | InitEmpty
333
334     (* /dev/sda contains a single partition /dev/sda1, with random
335      * content.  /dev/sdb and /dev/sdc may have random content.
336      * No LVM.
337      *)
338   | InitPartition
339
340     (* /dev/sda contains a single partition /dev/sda1, which is formatted
341      * as ext2, empty [except for lost+found] and mounted on /.
342      * /dev/sdb and /dev/sdc may have random content.
343      * No LVM.
344      *)
345   | InitBasicFS
346
347     (* /dev/sda:
348      *   /dev/sda1 (is a PV):
349      *     /dev/VG/LV (size 8MB):
350      *       formatted as ext2, empty [except for lost+found], mounted on /
351      * /dev/sdb and /dev/sdc may have random content.
352      *)
353   | InitBasicFSonLVM
354
355     (* /dev/sdd (the ISO, see images/ directory in source)
356      * is mounted on /
357      *)
358   | InitISOFS
359
360 (* Sequence of commands for testing. *)
361 and seq = cmd list
362 and cmd = string list
363
364 (* Note about long descriptions: When referring to another
365  * action, use the format C<guestfs_other> (ie. the full name of
366  * the C function).  This will be replaced as appropriate in other
367  * language bindings.
368  *
369  * Apart from that, long descriptions are just perldoc paragraphs.
370  *)
371
372 (* Generate a random UUID (used in tests). *)
373 let uuidgen () =
374   let chan = open_process_in "uuidgen" in
375   let uuid = input_line chan in
376   (match close_process_in chan with
377    | WEXITED 0 -> ()
378    | WEXITED _ ->
379        failwith "uuidgen: process exited with non-zero status"
380    | WSIGNALED _ | WSTOPPED _ ->
381        failwith "uuidgen: process signalled or stopped by signal"
382   );
383   uuid
384
385 (* These test functions are used in the language binding tests. *)
386
387 let test_all_args = [
388   String "str";
389   OptString "optstr";
390   StringList "strlist";
391   Bool "b";
392   Int "integer";
393   Int64 "integer64";
394   FileIn "filein";
395   FileOut "fileout";
396   BufferIn "bufferin";
397 ]
398
399 let test_all_rets = [
400   (* except for RErr, which is tested thoroughly elsewhere *)
401   "test0rint",         RInt "valout";
402   "test0rint64",       RInt64 "valout";
403   "test0rbool",        RBool "valout";
404   "test0rconststring", RConstString "valout";
405   "test0rconstoptstring", RConstOptString "valout";
406   "test0rstring",      RString "valout";
407   "test0rstringlist",  RStringList "valout";
408   "test0rstruct",      RStruct ("valout", "lvm_pv");
409   "test0rstructlist",  RStructList ("valout", "lvm_pv");
410   "test0rhashtable",   RHashtable "valout";
411 ]
412
413 let test_functions = [
414   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
415    [],
416    "internal test function - do not use",
417    "\
418 This is an internal test function which is used to test whether
419 the automatically generated bindings can handle every possible
420 parameter type correctly.
421
422 It echos the contents of each parameter to stdout.
423
424 You probably don't want to call this function.");
425 ] @ List.flatten (
426   List.map (
427     fun (name, ret) ->
428       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
429         [],
430         "internal test function - do not use",
431         "\
432 This is an internal test function which is used to test whether
433 the automatically generated bindings can handle every possible
434 return type correctly.
435
436 It converts string C<val> to the return type.
437
438 You probably don't want to call this function.");
439        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
440         [],
441         "internal test function - do not use",
442         "\
443 This is an internal test function which is used to test whether
444 the automatically generated bindings can handle every possible
445 return type correctly.
446
447 This function always returns an error.
448
449 You probably don't want to call this function.")]
450   ) test_all_rets
451 )
452
453 (* non_daemon_functions are any functions which don't get processed
454  * in the daemon, eg. functions for setting and getting local
455  * configuration values.
456  *)
457
458 let non_daemon_functions = test_functions @ [
459   ("launch", (RErr, []), -1, [FishAlias "run"],
460    [],
461    "launch the qemu subprocess",
462    "\
463 Internally libguestfs is implemented by running a virtual machine
464 using L<qemu(1)>.
465
466 You should call this after configuring the handle
467 (eg. adding drives) but before performing any actions.");
468
469   ("wait_ready", (RErr, []), -1, [NotInFish],
470    [],
471    "wait until the qemu subprocess launches (no op)",
472    "\
473 This function is a no op.
474
475 In versions of the API E<lt> 1.0.71 you had to call this function
476 just after calling C<guestfs_launch> to wait for the launch
477 to complete.  However this is no longer necessary because
478 C<guestfs_launch> now does the waiting.
479
480 If you see any calls to this function in code then you can just
481 remove them, unless you want to retain compatibility with older
482 versions of the API.");
483
484   ("kill_subprocess", (RErr, []), -1, [],
485    [],
486    "kill the qemu subprocess",
487    "\
488 This kills the qemu subprocess.  You should never need to call this.");
489
490   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
491    [],
492    "add an image to examine or modify",
493    "\
494 This function adds a virtual machine disk image C<filename> to the
495 guest.  The first time you call this function, the disk appears as IDE
496 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
497 so on.
498
499 You don't necessarily need to be root when using libguestfs.  However
500 you obviously do need sufficient permissions to access the filename
501 for whatever operations you want to perform (ie. read access if you
502 just want to read the image or write access if you want to modify the
503 image).
504
505 This is equivalent to the qemu parameter
506 C<-drive file=filename,cache=off,if=...>.
507
508 C<cache=off> is omitted in cases where it is not supported by
509 the underlying filesystem.
510
511 C<if=...> is set at compile time by the configuration option
512 C<./configure --with-drive-if=...>.  In the rare case where you
513 might need to change this at run time, use C<guestfs_add_drive_with_if>
514 or C<guestfs_add_drive_ro_with_if>.
515
516 Note that this call checks for the existence of C<filename>.  This
517 stops you from specifying other types of drive which are supported
518 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
519 the general C<guestfs_config> call instead.");
520
521   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
522    [],
523    "add a CD-ROM disk image to examine",
524    "\
525 This function adds a virtual CD-ROM disk image to the guest.
526
527 This is equivalent to the qemu parameter C<-cdrom filename>.
528
529 Notes:
530
531 =over 4
532
533 =item *
534
535 This call checks for the existence of C<filename>.  This
536 stops you from specifying other types of drive which are supported
537 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
538 the general C<guestfs_config> call instead.
539
540 =item *
541
542 If you just want to add an ISO file (often you use this as an
543 efficient way to transfer large files into the guest), then you
544 should probably use C<guestfs_add_drive_ro> instead.
545
546 =back");
547
548   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
549    [],
550    "add a drive in snapshot mode (read-only)",
551    "\
552 This adds a drive in snapshot mode, making it effectively
553 read-only.
554
555 Note that writes to the device are allowed, and will be seen for
556 the duration of the guestfs handle, but they are written
557 to a temporary file which is discarded as soon as the guestfs
558 handle is closed.  We don't currently have any method to enable
559 changes to be committed, although qemu can support this.
560
561 This is equivalent to the qemu parameter
562 C<-drive file=filename,snapshot=on,if=...>.
563
564 C<if=...> is set at compile time by the configuration option
565 C<./configure --with-drive-if=...>.  In the rare case where you
566 might need to change this at run time, use C<guestfs_add_drive_with_if>
567 or C<guestfs_add_drive_ro_with_if>.
568
569 Note that this call checks for the existence of C<filename>.  This
570 stops you from specifying other types of drive which are supported
571 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
572 the general C<guestfs_config> call instead.");
573
574   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
575    [],
576    "add qemu parameters",
577    "\
578 This can be used to add arbitrary qemu command line parameters
579 of the form C<-param value>.  Actually it's not quite arbitrary - we
580 prevent you from setting some parameters which would interfere with
581 parameters that we use.
582
583 The first character of C<param> string must be a C<-> (dash).
584
585 C<value> can be NULL.");
586
587   ("set_qemu", (RErr, [OptString "qemu"]), -1, [FishAlias "qemu"],
588    [],
589    "set the qemu binary",
590    "\
591 Set the qemu binary that we will use.
592
593 The default is chosen when the library was compiled by the
594 configure script.
595
596 You can also override this by setting the C<LIBGUESTFS_QEMU>
597 environment variable.
598
599 Setting C<qemu> to C<NULL> restores the default qemu binary.
600
601 Note that you should call this function as early as possible
602 after creating the handle.  This is because some pre-launch
603 operations depend on testing qemu features (by running C<qemu -help>).
604 If the qemu binary changes, we don't retest features, and
605 so you might see inconsistent results.  Using the environment
606 variable C<LIBGUESTFS_QEMU> is safest of all since that picks
607 the qemu binary at the same time as the handle is created.");
608
609   ("get_qemu", (RConstString "qemu", []), -1, [],
610    [InitNone, Always, TestRun (
611       [["get_qemu"]])],
612    "get the qemu binary",
613    "\
614 Return the current qemu binary.
615
616 This is always non-NULL.  If it wasn't set already, then this will
617 return the default qemu binary name.");
618
619   ("set_path", (RErr, [OptString "searchpath"]), -1, [FishAlias "path"],
620    [],
621    "set the search path",
622    "\
623 Set the path that libguestfs searches for kernel and initrd.img.
624
625 The default is C<$libdir/guestfs> unless overridden by setting
626 C<LIBGUESTFS_PATH> environment variable.
627
628 Setting C<path> to C<NULL> restores the default path.");
629
630   ("get_path", (RConstString "path", []), -1, [],
631    [InitNone, Always, TestRun (
632       [["get_path"]])],
633    "get the search path",
634    "\
635 Return the current search path.
636
637 This is always non-NULL.  If it wasn't set already, then this will
638 return the default path.");
639
640   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
641    [],
642    "add options to kernel command line",
643    "\
644 This function is used to add additional options to the
645 guest kernel command line.
646
647 The default is C<NULL> unless overridden by setting
648 C<LIBGUESTFS_APPEND> environment variable.
649
650 Setting C<append> to C<NULL> means I<no> additional options
651 are passed (libguestfs always adds a few of its own).");
652
653   ("get_append", (RConstOptString "append", []), -1, [],
654    (* This cannot be tested with the current framework.  The
655     * function can return NULL in normal operations, which the
656     * test framework interprets as an error.
657     *)
658    [],
659    "get the additional kernel options",
660    "\
661 Return the additional kernel options which are added to the
662 guest kernel command line.
663
664 If C<NULL> then no options are added.");
665
666   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
667    [],
668    "set autosync mode",
669    "\
670 If C<autosync> is true, this enables autosync.  Libguestfs will make a
671 best effort attempt to run C<guestfs_umount_all> followed by
672 C<guestfs_sync> when the handle is closed
673 (also if the program exits without closing handles).
674
675 This is disabled by default (except in guestfish where it is
676 enabled by default).");
677
678   ("get_autosync", (RBool "autosync", []), -1, [],
679    [InitNone, Always, TestRun (
680       [["get_autosync"]])],
681    "get autosync mode",
682    "\
683 Get the autosync flag.");
684
685   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
686    [],
687    "set verbose mode",
688    "\
689 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
690
691 Verbose messages are disabled unless the environment variable
692 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
693
694   ("get_verbose", (RBool "verbose", []), -1, [],
695    [],
696    "get verbose mode",
697    "\
698 This returns the verbose messages flag.");
699
700   ("is_ready", (RBool "ready", []), -1, [],
701    [InitNone, Always, TestOutputTrue (
702       [["is_ready"]])],
703    "is ready to accept commands",
704    "\
705 This returns true iff this handle is ready to accept commands
706 (in the C<READY> state).
707
708 For more information on states, see L<guestfs(3)>.");
709
710   ("is_config", (RBool "config", []), -1, [],
711    [InitNone, Always, TestOutputFalse (
712       [["is_config"]])],
713    "is in configuration state",
714    "\
715 This returns true iff this handle is being configured
716 (in the C<CONFIG> state).
717
718 For more information on states, see L<guestfs(3)>.");
719
720   ("is_launching", (RBool "launching", []), -1, [],
721    [InitNone, Always, TestOutputFalse (
722       [["is_launching"]])],
723    "is launching subprocess",
724    "\
725 This returns true iff this handle is launching the subprocess
726 (in the C<LAUNCHING> state).
727
728 For more information on states, see L<guestfs(3)>.");
729
730   ("is_busy", (RBool "busy", []), -1, [],
731    [InitNone, Always, TestOutputFalse (
732       [["is_busy"]])],
733    "is busy processing a command",
734    "\
735 This returns true iff this handle is busy processing a command
736 (in the C<BUSY> state).
737
738 For more information on states, see L<guestfs(3)>.");
739
740   ("get_state", (RInt "state", []), -1, [],
741    [],
742    "get the current state",
743    "\
744 This returns the current state as an opaque integer.  This is
745 only useful for printing debug and internal error messages.
746
747 For more information on states, see L<guestfs(3)>.");
748
749   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
750    [InitNone, Always, TestOutputInt (
751       [["set_memsize"; "500"];
752        ["get_memsize"]], 500)],
753    "set memory allocated to the qemu subprocess",
754    "\
755 This sets the memory size in megabytes allocated to the
756 qemu subprocess.  This only has any effect if called before
757 C<guestfs_launch>.
758
759 You can also change this by setting the environment
760 variable C<LIBGUESTFS_MEMSIZE> before the handle is
761 created.
762
763 For more information on the architecture of libguestfs,
764 see L<guestfs(3)>.");
765
766   ("get_memsize", (RInt "memsize", []), -1, [],
767    [InitNone, Always, TestOutputIntOp (
768       [["get_memsize"]], ">=", 256)],
769    "get memory allocated to the qemu subprocess",
770    "\
771 This gets the memory size in megabytes allocated to the
772 qemu subprocess.
773
774 If C<guestfs_set_memsize> was not called
775 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
776 then this returns the compiled-in default value for memsize.
777
778 For more information on the architecture of libguestfs,
779 see L<guestfs(3)>.");
780
781   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
782    [InitNone, Always, TestOutputIntOp (
783       [["get_pid"]], ">=", 1)],
784    "get PID of qemu subprocess",
785    "\
786 Return the process ID of the qemu subprocess.  If there is no
787 qemu subprocess, then this will return an error.
788
789 This is an internal call used for debugging and testing.");
790
791   ("version", (RStruct ("version", "version"), []), -1, [],
792    [InitNone, Always, TestOutputStruct (
793       [["version"]], [CompareWithInt ("major", 1)])],
794    "get the library version number",
795    "\
796 Return the libguestfs version number that the program is linked
797 against.
798
799 Note that because of dynamic linking this is not necessarily
800 the version of libguestfs that you compiled against.  You can
801 compile the program, and then at runtime dynamically link
802 against a completely different C<libguestfs.so> library.
803
804 This call was added in version C<1.0.58>.  In previous
805 versions of libguestfs there was no way to get the version
806 number.  From C code you can use dynamic linker functions
807 to find out if this symbol exists (if it doesn't, then
808 it's an earlier version).
809
810 The call returns a structure with four elements.  The first
811 three (C<major>, C<minor> and C<release>) are numbers and
812 correspond to the usual version triplet.  The fourth element
813 (C<extra>) is a string and is normally empty, but may be
814 used for distro-specific information.
815
816 To construct the original version string:
817 C<$major.$minor.$release$extra>
818
819 See also: L<guestfs(3)/LIBGUESTFS VERSION NUMBERS>.
820
821 I<Note:> Don't use this call to test for availability
822 of features.  In enterprise distributions we backport
823 features from later versions into earlier versions,
824 making this an unreliable way to test for features.
825 Use C<guestfs_available> instead.");
826
827   ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
828    [InitNone, Always, TestOutputTrue (
829       [["set_selinux"; "true"];
830        ["get_selinux"]])],
831    "set SELinux enabled or disabled at appliance boot",
832    "\
833 This sets the selinux flag that is passed to the appliance
834 at boot time.  The default is C<selinux=0> (disabled).
835
836 Note that if SELinux is enabled, it is always in
837 Permissive mode (C<enforcing=0>).
838
839 For more information on the architecture of libguestfs,
840 see L<guestfs(3)>.");
841
842   ("get_selinux", (RBool "selinux", []), -1, [],
843    [],
844    "get SELinux enabled flag",
845    "\
846 This returns the current setting of the selinux flag which
847 is passed to the appliance at boot time.  See C<guestfs_set_selinux>.
848
849 For more information on the architecture of libguestfs,
850 see L<guestfs(3)>.");
851
852   ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
853    [InitNone, Always, TestOutputFalse (
854       [["set_trace"; "false"];
855        ["get_trace"]])],
856    "enable or disable command traces",
857    "\
858 If the command trace flag is set to 1, then commands are
859 printed on stderr before they are executed in a format
860 which is very similar to the one used by guestfish.  In
861 other words, you can run a program with this enabled, and
862 you will get out a script which you can feed to guestfish
863 to perform the same set of actions.
864
865 If you want to trace C API calls into libguestfs (and
866 other libraries) then possibly a better way is to use
867 the external ltrace(1) command.
868
869 Command traces are disabled unless the environment variable
870 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
871
872   ("get_trace", (RBool "trace", []), -1, [],
873    [],
874    "get command trace enabled flag",
875    "\
876 Return the command trace flag.");
877
878   ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
879    [InitNone, Always, TestOutputFalse (
880       [["set_direct"; "false"];
881        ["get_direct"]])],
882    "enable or disable direct appliance mode",
883    "\
884 If the direct appliance mode flag is enabled, then stdin and
885 stdout are passed directly through to the appliance once it
886 is launched.
887
888 One consequence of this is that log messages aren't caught
889 by the library and handled by C<guestfs_set_log_message_callback>,
890 but go straight to stdout.
891
892 You probably don't want to use this unless you know what you
893 are doing.
894
895 The default is disabled.");
896
897   ("get_direct", (RBool "direct", []), -1, [],
898    [],
899    "get direct appliance mode flag",
900    "\
901 Return the direct appliance mode flag.");
902
903   ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
904    [InitNone, Always, TestOutputTrue (
905       [["set_recovery_proc"; "true"];
906        ["get_recovery_proc"]])],
907    "enable or disable the recovery process",
908    "\
909 If this is called with the parameter C<false> then
910 C<guestfs_launch> does not create a recovery process.  The
911 purpose of the recovery process is to stop runaway qemu
912 processes in the case where the main program aborts abruptly.
913
914 This only has any effect if called before C<guestfs_launch>,
915 and the default is true.
916
917 About the only time when you would want to disable this is
918 if the main process will fork itself into the background
919 (\"daemonize\" itself).  In this case the recovery process
920 thinks that the main program has disappeared and so kills
921 qemu, which is not very helpful.");
922
923   ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
924    [],
925    "get recovery process enabled flag",
926    "\
927 Return the recovery process enabled flag.");
928
929   ("add_drive_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
930    [],
931    "add a drive specifying the QEMU block emulation to use",
932    "\
933 This is the same as C<guestfs_add_drive> but it allows you
934 to specify the QEMU interface emulation to use at run time.");
935
936   ("add_drive_ro_with_if", (RErr, [String "filename"; String "iface"]), -1, [],
937    [],
938    "add a drive read-only specifying the QEMU block emulation to use",
939    "\
940 This is the same as C<guestfs_add_drive_ro> but it allows you
941 to specify the QEMU interface emulation to use at run time.");
942
943   ("file_architecture", (RString "arch", [Pathname "filename"]), -1, [],
944    [InitISOFS, Always, TestOutput (
945       [["file_architecture"; "/bin-i586-dynamic"]], "i386");
946     InitISOFS, Always, TestOutput (
947       [["file_architecture"; "/bin-sparc-dynamic"]], "sparc");
948     InitISOFS, Always, TestOutput (
949       [["file_architecture"; "/bin-win32.exe"]], "i386");
950     InitISOFS, Always, TestOutput (
951       [["file_architecture"; "/bin-win64.exe"]], "x86_64");
952     InitISOFS, Always, TestOutput (
953       [["file_architecture"; "/bin-x86_64-dynamic"]], "x86_64");
954     InitISOFS, Always, TestOutput (
955       [["file_architecture"; "/lib-i586.so"]], "i386");
956     InitISOFS, Always, TestOutput (
957       [["file_architecture"; "/lib-sparc.so"]], "sparc");
958     InitISOFS, Always, TestOutput (
959       [["file_architecture"; "/lib-win32.dll"]], "i386");
960     InitISOFS, Always, TestOutput (
961       [["file_architecture"; "/lib-win64.dll"]], "x86_64");
962     InitISOFS, Always, TestOutput (
963       [["file_architecture"; "/lib-x86_64.so"]], "x86_64");
964     InitISOFS, Always, TestOutput (
965       [["file_architecture"; "/initrd-x86_64.img"]], "x86_64");
966     InitISOFS, Always, TestOutput (
967       [["file_architecture"; "/initrd-x86_64.img.gz"]], "x86_64");],
968    "detect the architecture of a binary file",
969    "\
970 This detects the architecture of the binary C<filename>,
971 and returns it if known.
972
973 Currently defined architectures are:
974
975 =over 4
976
977 =item \"i386\"
978
979 This string is returned for all 32 bit i386, i486, i586, i686 binaries
980 irrespective of the precise processor requirements of the binary.
981
982 =item \"x86_64\"
983
984 64 bit x86-64.
985
986 =item \"sparc\"
987
988 32 bit SPARC.
989
990 =item \"sparc64\"
991
992 64 bit SPARC V9 and above.
993
994 =item \"ia64\"
995
996 Intel Itanium.
997
998 =item \"ppc\"
999
1000 32 bit Power PC.
1001
1002 =item \"ppc64\"
1003
1004 64 bit Power PC.
1005
1006 =back
1007
1008 Libguestfs may return other architecture strings in future.
1009
1010 The function works on at least the following types of files:
1011
1012 =over 4
1013
1014 =item *
1015
1016 many types of Un*x and Linux binary
1017
1018 =item *
1019
1020 many types of Un*x and Linux shared library
1021
1022 =item *
1023
1024 Windows Win32 and Win64 binaries
1025
1026 =item *
1027
1028 Windows Win32 and Win64 DLLs
1029
1030 Win32 binaries and DLLs return C<i386>.
1031
1032 Win64 binaries and DLLs return C<x86_64>.
1033
1034 =item *
1035
1036 Linux kernel modules
1037
1038 =item *
1039
1040 Linux new-style initrd images
1041
1042 =item *
1043
1044 some non-x86 Linux vmlinuz kernels
1045
1046 =back
1047
1048 What it can't do currently:
1049
1050 =over 4
1051
1052 =item *
1053
1054 static libraries (libfoo.a)
1055
1056 =item *
1057
1058 Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
1059
1060 =item *
1061
1062 x86 Linux vmlinuz kernels
1063
1064 x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and
1065 compressed code, and are horribly hard to unpack.  If you want to find
1066 the architecture of a kernel, use the architecture of the associated
1067 initrd or kernel module(s) instead.
1068
1069 =back");
1070
1071   ("inspect_os", (RStringList "roots", []), -1, [],
1072    [],
1073    "inspect disk and return list of operating systems found",
1074    "\
1075 This function uses other libguestfs functions and certain
1076 heuristics to inspect the disk(s) (usually disks belonging to
1077 a virtual machine), looking for operating systems.
1078
1079 The list returned is empty if no operating systems were found.
1080
1081 If one operating system was found, then this returns a list with
1082 a single element, which is the name of the root filesystem of
1083 this operating system.  It is also possible for this function
1084 to return a list containing more than one element, indicating
1085 a dual-boot or multi-boot virtual machine, with each element being
1086 the root filesystem of one of the operating systems.
1087
1088 You can pass the root string(s) returned to other
1089 C<guestfs_inspect_get_*> functions in order to query further
1090 information about each operating system, such as the name
1091 and version.
1092
1093 This function uses other libguestfs features such as
1094 C<guestfs_mount_ro> and C<guestfs_umount_all> in order to mount
1095 and unmount filesystems and look at the contents.  This should
1096 be called with no disks currently mounted.  The function may also
1097 use Augeas, so any existing Augeas handle will be closed.
1098
1099 This function cannot decrypt encrypted disks.  The caller
1100 must do that first (supplying the necessary keys) if the
1101 disk is encrypted.
1102
1103 Please read L<guestfs(3)/INSPECTION> for more details.");
1104
1105   ("inspect_get_type", (RString "name", [Device "root"]), -1, [],
1106    [],
1107    "get type of inspected operating system",
1108    "\
1109 This function should only be called with a root device string
1110 as returned by C<guestfs_inspect_os>.
1111
1112 This returns the type of the inspected operating system.
1113 Currently defined types are:
1114
1115 =over 4
1116
1117 =item \"linux\"
1118
1119 Any Linux-based operating system.
1120
1121 =item \"windows\"
1122
1123 Any Microsoft Windows operating system.
1124
1125 =item \"unknown\"
1126
1127 The operating system type could not be determined.
1128
1129 =back
1130
1131 Future versions of libguestfs may return other strings here.
1132 The caller should be prepared to handle any string.
1133
1134 Please read L<guestfs(3)/INSPECTION> for more details.");
1135
1136   ("inspect_get_arch", (RString "arch", [Device "root"]), -1, [],
1137    [],
1138    "get architecture of inspected operating system",
1139    "\
1140 This function should only be called with a root device string
1141 as returned by C<guestfs_inspect_os>.
1142
1143 This returns the architecture of the inspected operating system.
1144 The possible return values are listed under
1145 C<guestfs_file_architecture>.
1146
1147 If the architecture could not be determined, then the
1148 string C<unknown> is returned.
1149
1150 Please read L<guestfs(3)/INSPECTION> for more details.");
1151
1152   ("inspect_get_distro", (RString "distro", [Device "root"]), -1, [],
1153    [],
1154    "get distro of inspected operating system",
1155    "\
1156 This function should only be called with a root device string
1157 as returned by C<guestfs_inspect_os>.
1158
1159 This returns the distro (distribution) of the inspected operating
1160 system.
1161
1162 Currently defined distros are:
1163
1164 =over 4
1165
1166 =item \"debian\"
1167
1168 Debian or a Debian-derived distro such as Ubuntu.
1169
1170 =item \"fedora\"
1171
1172 Fedora.
1173
1174 =item \"redhat-based\"
1175
1176 Some Red Hat-derived distro.
1177
1178 =item \"rhel\"
1179
1180 Red Hat Enterprise Linux and some derivatives.
1181
1182 =item \"windows\"
1183
1184 Windows does not have distributions.  This string is
1185 returned if the OS type is Windows.
1186
1187 =item \"unknown\"
1188
1189 The distro could not be determined.
1190
1191 =back
1192
1193 Future versions of libguestfs may return other strings here.
1194 The caller should be prepared to handle any string.
1195
1196 Please read L<guestfs(3)/INSPECTION> for more details.");
1197
1198   ("inspect_get_major_version", (RInt "major", [Device "root"]), -1, [],
1199    [],
1200    "get major version of inspected operating system",
1201    "\
1202 This function should only be called with a root device string
1203 as returned by C<guestfs_inspect_os>.
1204
1205 This returns the major version number of the inspected operating
1206 system.
1207
1208 Windows uses a consistent versioning scheme which is I<not>
1209 reflected in the popular public names used by the operating system.
1210 Notably the operating system known as \"Windows 7\" is really
1211 version 6.1 (ie. major = 6, minor = 1).  You can find out the
1212 real versions corresponding to releases of Windows by consulting
1213 Wikipedia or MSDN.
1214
1215 If the version could not be determined, then C<0> is returned.
1216
1217 Please read L<guestfs(3)/INSPECTION> for more details.");
1218
1219   ("inspect_get_minor_version", (RInt "minor", [Device "root"]), -1, [],
1220    [],
1221    "get minor version of inspected operating system",
1222    "\
1223 This function should only be called with a root device string
1224 as returned by C<guestfs_inspect_os>.
1225
1226 This returns the minor version number of the inspected operating
1227 system.
1228
1229 If the version could not be determined, then C<0> is returned.
1230
1231 Please read L<guestfs(3)/INSPECTION> for more details.
1232 See also C<guestfs_inspect_get_major_version>.");
1233
1234   ("inspect_get_product_name", (RString "product", [Device "root"]), -1, [],
1235    [],
1236    "get product name of inspected operating system",
1237    "\
1238 This function should only be called with a root device string
1239 as returned by C<guestfs_inspect_os>.
1240
1241 This returns the product name of the inspected operating
1242 system.  The product name is generally some freeform string
1243 which can be displayed to the user, but should not be
1244 parsed by programs.
1245
1246 If the product name could not be determined, then the
1247 string C<unknown> is returned.
1248
1249 Please read L<guestfs(3)/INSPECTION> for more details.");
1250
1251   ("inspect_get_mountpoints", (RHashtable "mountpoints", [Device "root"]), -1, [],
1252    [],
1253    "get mountpoints of inspected operating system",
1254    "\
1255 This function should only be called with a root device string
1256 as returned by C<guestfs_inspect_os>.
1257
1258 This returns a hash of where we think the filesystems
1259 associated with this operating system should be mounted.
1260 Callers should note that this is at best an educated guess
1261 made by reading configuration files such as C</etc/fstab>.
1262
1263 Each element in the returned hashtable has a key which
1264 is the path of the mountpoint (eg. C</boot>) and a value
1265 which is the filesystem that would be mounted there
1266 (eg. C</dev/sda1>).
1267
1268 Non-mounted devices such as swap devices are I<not>
1269 returned in this list.
1270
1271 Please read L<guestfs(3)/INSPECTION> for more details.
1272 See also C<guestfs_inspect_get_filesystems>.");
1273
1274   ("inspect_get_filesystems", (RStringList "filesystems", [Device "root"]), -1, [],
1275    [],
1276    "get filesystems associated with inspected operating system",
1277    "\
1278 This function should only be called with a root device string
1279 as returned by C<guestfs_inspect_os>.
1280
1281 This returns a list of all the filesystems that we think
1282 are associated with this operating system.  This includes
1283 the root filesystem, other ordinary filesystems, and
1284 non-mounted devices like swap partitions.
1285
1286 In the case of a multi-boot virtual machine, it is possible
1287 for a filesystem to be shared between operating systems.
1288
1289 Please read L<guestfs(3)/INSPECTION> for more details.
1290 See also C<guestfs_inspect_get_mountpoints>.");
1291
1292   ("set_network", (RErr, [Bool "network"]), -1, [FishAlias "network"],
1293    [],
1294    "set enable network flag",
1295    "\
1296 If C<network> is true, then the network is enabled in the
1297 libguestfs appliance.  The default is false.
1298
1299 This affects whether commands are able to access the network
1300 (see L<guestfs(3)/RUNNING COMMANDS>).
1301
1302 You must call this before calling C<guestfs_launch>, otherwise
1303 it has no effect.");
1304
1305   ("get_network", (RBool "network", []), -1, [],
1306    [],
1307    "get enable network flag",
1308    "\
1309 This returns the enable network flag.");
1310
1311 ]
1312
1313 (* daemon_functions are any functions which cause some action
1314  * to take place in the daemon.
1315  *)
1316
1317 let daemon_functions = [
1318   ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
1319    [InitEmpty, Always, TestOutput (
1320       [["part_disk"; "/dev/sda"; "mbr"];
1321        ["mkfs"; "ext2"; "/dev/sda1"];
1322        ["mount"; "/dev/sda1"; "/"];
1323        ["write"; "/new"; "new file contents"];
1324        ["cat"; "/new"]], "new file contents")],
1325    "mount a guest disk at a position in the filesystem",
1326    "\
1327 Mount a guest disk at a position in the filesystem.  Block devices
1328 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
1329 the guest.  If those block devices contain partitions, they will have
1330 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
1331 names can be used.
1332
1333 The rules are the same as for L<mount(2)>:  A filesystem must
1334 first be mounted on C</> before others can be mounted.  Other
1335 filesystems can only be mounted on directories which already
1336 exist.
1337
1338 The mounted filesystem is writable, if we have sufficient permissions
1339 on the underlying device.
1340
1341 B<Important note:>
1342 When you use this call, the filesystem options C<sync> and C<noatime>
1343 are set implicitly.  This was originally done because we thought it
1344 would improve reliability, but it turns out that I<-o sync> has a
1345 very large negative performance impact and negligible effect on
1346 reliability.  Therefore we recommend that you avoid using
1347 C<guestfs_mount> in any code that needs performance, and instead
1348 use C<guestfs_mount_options> (use an empty string for the first
1349 parameter if you don't want any options).");
1350
1351   ("sync", (RErr, []), 2, [],
1352    [ InitEmpty, Always, TestRun [["sync"]]],
1353    "sync disks, writes are flushed through to the disk image",
1354    "\
1355 This syncs the disk, so that any writes are flushed through to the
1356 underlying disk image.
1357
1358 You should always call this if you have modified a disk image, before
1359 closing the handle.");
1360
1361   ("touch", (RErr, [Pathname "path"]), 3, [],
1362    [InitBasicFS, Always, TestOutputTrue (
1363       [["touch"; "/new"];
1364        ["exists"; "/new"]])],
1365    "update file timestamps or create a new file",
1366    "\
1367 Touch acts like the L<touch(1)> command.  It can be used to
1368 update the timestamps on a file, or, if the file does not exist,
1369 to create a new zero-length file.
1370
1371 This command only works on regular files, and will fail on other
1372 file types such as directories, symbolic links, block special etc.");
1373
1374   ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
1375    [InitISOFS, Always, TestOutput (
1376       [["cat"; "/known-2"]], "abcdef\n")],
1377    "list the contents of a file",
1378    "\
1379 Return the contents of the file named C<path>.
1380
1381 Note that this function cannot correctly handle binary files
1382 (specifically, files containing C<\\0> character which is treated
1383 as end of string).  For those you need to use the C<guestfs_read_file>
1384 or C<guestfs_download> functions which have a more complex interface.");
1385
1386   ("ll", (RString "listing", [Pathname "directory"]), 5, [],
1387    [], (* XXX Tricky to test because it depends on the exact format
1388         * of the 'ls -l' command, which changes between F10 and F11.
1389         *)
1390    "list the files in a directory (long format)",
1391    "\
1392 List the files in C<directory> (relative to the root directory,
1393 there is no cwd) in the format of 'ls -la'.
1394
1395 This command is mostly useful for interactive sessions.  It
1396 is I<not> intended that you try to parse the output string.");
1397
1398   ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
1399    [InitBasicFS, Always, TestOutputList (
1400       [["touch"; "/new"];
1401        ["touch"; "/newer"];
1402        ["touch"; "/newest"];
1403        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
1404    "list the files in a directory",
1405    "\
1406 List the files in C<directory> (relative to the root directory,
1407 there is no cwd).  The '.' and '..' entries are not returned, but
1408 hidden files are shown.
1409
1410 This command is mostly useful for interactive sessions.  Programs
1411 should probably use C<guestfs_readdir> instead.");
1412
1413   ("list_devices", (RStringList "devices", []), 7, [],
1414    [InitEmpty, Always, TestOutputListOfDevices (
1415       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
1416    "list the block devices",
1417    "\
1418 List all the block devices.
1419
1420 The full block device names are returned, eg. C</dev/sda>");
1421
1422   ("list_partitions", (RStringList "partitions", []), 8, [],
1423    [InitBasicFS, Always, TestOutputListOfDevices (
1424       [["list_partitions"]], ["/dev/sda1"]);
1425     InitEmpty, Always, TestOutputListOfDevices (
1426       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1427        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1428    "list the partitions",
1429    "\
1430 List all the partitions detected on all block devices.
1431
1432 The full partition device names are returned, eg. C</dev/sda1>
1433
1434 This does not return logical volumes.  For that you will need to
1435 call C<guestfs_lvs>.");
1436
1437   ("pvs", (RStringList "physvols", []), 9, [Optional "lvm2"],
1438    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
1439       [["pvs"]], ["/dev/sda1"]);
1440     InitEmpty, Always, TestOutputListOfDevices (
1441       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1442        ["pvcreate"; "/dev/sda1"];
1443        ["pvcreate"; "/dev/sda2"];
1444        ["pvcreate"; "/dev/sda3"];
1445        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1446    "list the LVM physical volumes (PVs)",
1447    "\
1448 List all the physical volumes detected.  This is the equivalent
1449 of the L<pvs(8)> command.
1450
1451 This returns a list of just the device names that contain
1452 PVs (eg. C</dev/sda2>).
1453
1454 See also C<guestfs_pvs_full>.");
1455
1456   ("vgs", (RStringList "volgroups", []), 10, [Optional "lvm2"],
1457    [InitBasicFSonLVM, Always, TestOutputList (
1458       [["vgs"]], ["VG"]);
1459     InitEmpty, Always, TestOutputList (
1460       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1461        ["pvcreate"; "/dev/sda1"];
1462        ["pvcreate"; "/dev/sda2"];
1463        ["pvcreate"; "/dev/sda3"];
1464        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1465        ["vgcreate"; "VG2"; "/dev/sda3"];
1466        ["vgs"]], ["VG1"; "VG2"])],
1467    "list the LVM volume groups (VGs)",
1468    "\
1469 List all the volumes groups detected.  This is the equivalent
1470 of the L<vgs(8)> command.
1471
1472 This returns a list of just the volume group names that were
1473 detected (eg. C<VolGroup00>).
1474
1475 See also C<guestfs_vgs_full>.");
1476
1477   ("lvs", (RStringList "logvols", []), 11, [Optional "lvm2"],
1478    [InitBasicFSonLVM, Always, TestOutputList (
1479       [["lvs"]], ["/dev/VG/LV"]);
1480     InitEmpty, Always, TestOutputList (
1481       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1482        ["pvcreate"; "/dev/sda1"];
1483        ["pvcreate"; "/dev/sda2"];
1484        ["pvcreate"; "/dev/sda3"];
1485        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1486        ["vgcreate"; "VG2"; "/dev/sda3"];
1487        ["lvcreate"; "LV1"; "VG1"; "50"];
1488        ["lvcreate"; "LV2"; "VG1"; "50"];
1489        ["lvcreate"; "LV3"; "VG2"; "50"];
1490        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1491    "list the LVM logical volumes (LVs)",
1492    "\
1493 List all the logical volumes detected.  This is the equivalent
1494 of the L<lvs(8)> command.
1495
1496 This returns a list of the logical volume device names
1497 (eg. C</dev/VolGroup00/LogVol00>).
1498
1499 See also C<guestfs_lvs_full>.");
1500
1501   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [Optional "lvm2"],
1502    [], (* XXX how to test? *)
1503    "list the LVM physical volumes (PVs)",
1504    "\
1505 List all the physical volumes detected.  This is the equivalent
1506 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
1507
1508   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [Optional "lvm2"],
1509    [], (* XXX how to test? *)
1510    "list the LVM volume groups (VGs)",
1511    "\
1512 List all the volumes groups detected.  This is the equivalent
1513 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
1514
1515   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [Optional "lvm2"],
1516    [], (* XXX how to test? *)
1517    "list the LVM logical volumes (LVs)",
1518    "\
1519 List all the logical volumes detected.  This is the equivalent
1520 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
1521
1522   ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1523    [InitISOFS, Always, TestOutputList (
1524       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1525     InitISOFS, Always, TestOutputList (
1526       [["read_lines"; "/empty"]], [])],
1527    "read file as lines",
1528    "\
1529 Return the contents of the file named C<path>.
1530
1531 The file contents are returned as a list of lines.  Trailing
1532 C<LF> and C<CRLF> character sequences are I<not> returned.
1533
1534 Note that this function cannot correctly handle binary files
1535 (specifically, files containing C<\\0> character which is treated
1536 as end of line).  For those you need to use the C<guestfs_read_file>
1537 function which has a more complex interface.");
1538
1539   ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [Optional "augeas"],
1540    [], (* XXX Augeas code needs tests. *)
1541    "create a new Augeas handle",
1542    "\
1543 Create a new Augeas handle for editing configuration files.
1544 If there was any previous Augeas handle associated with this
1545 guestfs session, then it is closed.
1546
1547 You must call this before using any other C<guestfs_aug_*>
1548 commands.
1549
1550 C<root> is the filesystem root.  C<root> must not be NULL,
1551 use C</> instead.
1552
1553 The flags are the same as the flags defined in
1554 E<lt>augeas.hE<gt>, the logical I<or> of the following
1555 integers:
1556
1557 =over 4
1558
1559 =item C<AUG_SAVE_BACKUP> = 1
1560
1561 Keep the original file with a C<.augsave> extension.
1562
1563 =item C<AUG_SAVE_NEWFILE> = 2
1564
1565 Save changes into a file with extension C<.augnew>, and
1566 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
1567
1568 =item C<AUG_TYPE_CHECK> = 4
1569
1570 Typecheck lenses (can be expensive).
1571
1572 =item C<AUG_NO_STDINC> = 8
1573
1574 Do not use standard load path for modules.
1575
1576 =item C<AUG_SAVE_NOOP> = 16
1577
1578 Make save a no-op, just record what would have been changed.
1579
1580 =item C<AUG_NO_LOAD> = 32
1581
1582 Do not load the tree in C<guestfs_aug_init>.
1583
1584 =back
1585
1586 To close the handle, you can call C<guestfs_aug_close>.
1587
1588 To find out more about Augeas, see L<http://augeas.net/>.");
1589
1590   ("aug_close", (RErr, []), 26, [Optional "augeas"],
1591    [], (* XXX Augeas code needs tests. *)
1592    "close the current Augeas handle",
1593    "\
1594 Close the current Augeas handle and free up any resources
1595 used by it.  After calling this, you have to call
1596 C<guestfs_aug_init> again before you can use any other
1597 Augeas functions.");
1598
1599   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [Optional "augeas"],
1600    [], (* XXX Augeas code needs tests. *)
1601    "define an Augeas variable",
1602    "\
1603 Defines an Augeas variable C<name> whose value is the result
1604 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1605 undefined.
1606
1607 On success this returns the number of nodes in C<expr>, or
1608 C<0> if C<expr> evaluates to something which is not a nodeset.");
1609
1610   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [Optional "augeas"],
1611    [], (* XXX Augeas code needs tests. *)
1612    "define an Augeas node",
1613    "\
1614 Defines a variable C<name> whose value is the result of
1615 evaluating C<expr>.
1616
1617 If C<expr> evaluates to an empty nodeset, a node is created,
1618 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1619 C<name> will be the nodeset containing that single node.
1620
1621 On success this returns a pair containing the
1622 number of nodes in the nodeset, and a boolean flag
1623 if a node was created.");
1624
1625   ("aug_get", (RString "val", [String "augpath"]), 19, [Optional "augeas"],
1626    [], (* XXX Augeas code needs tests. *)
1627    "look up the value of an Augeas path",
1628    "\
1629 Look up the value associated with C<path>.  If C<path>
1630 matches exactly one node, the C<value> is returned.");
1631
1632   ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [Optional "augeas"],
1633    [], (* XXX Augeas code needs tests. *)
1634    "set Augeas path to value",
1635    "\
1636 Set the value associated with C<path> to C<val>.
1637
1638 In the Augeas API, it is possible to clear a node by setting
1639 the value to NULL.  Due to an oversight in the libguestfs API
1640 you cannot do that with this call.  Instead you must use the
1641 C<guestfs_aug_clear> call.");
1642
1643   ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [Optional "augeas"],
1644    [], (* XXX Augeas code needs tests. *)
1645    "insert a sibling Augeas node",
1646    "\
1647 Create a new sibling C<label> for C<path>, inserting it into
1648 the tree before or after C<path> (depending on the boolean
1649 flag C<before>).
1650
1651 C<path> must match exactly one existing node in the tree, and
1652 C<label> must be a label, ie. not contain C</>, C<*> or end
1653 with a bracketed index C<[N]>.");
1654
1655   ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [Optional "augeas"],
1656    [], (* XXX Augeas code needs tests. *)
1657    "remove an Augeas path",
1658    "\
1659 Remove C<path> and all of its children.
1660
1661 On success this returns the number of entries which were removed.");
1662
1663   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [Optional "augeas"],
1664    [], (* XXX Augeas code needs tests. *)
1665    "move Augeas node",
1666    "\
1667 Move the node C<src> to C<dest>.  C<src> must match exactly
1668 one node.  C<dest> is overwritten if it exists.");
1669
1670   ("aug_match", (RStringList "matches", [String "augpath"]), 24, [Optional "augeas"],
1671    [], (* XXX Augeas code needs tests. *)
1672    "return Augeas nodes which match augpath",
1673    "\
1674 Returns a list of paths which match the path expression C<path>.
1675 The returned paths are sufficiently qualified so that they match
1676 exactly one node in the current tree.");
1677
1678   ("aug_save", (RErr, []), 25, [Optional "augeas"],
1679    [], (* XXX Augeas code needs tests. *)
1680    "write all pending Augeas changes to disk",
1681    "\
1682 This writes all pending changes to disk.
1683
1684 The flags which were passed to C<guestfs_aug_init> affect exactly
1685 how files are saved.");
1686
1687   ("aug_load", (RErr, []), 27, [Optional "augeas"],
1688    [], (* XXX Augeas code needs tests. *)
1689    "load files into the tree",
1690    "\
1691 Load files into the tree.
1692
1693 See C<aug_load> in the Augeas documentation for the full gory
1694 details.");
1695
1696   ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [Optional "augeas"],
1697    [], (* XXX Augeas code needs tests. *)
1698    "list Augeas nodes under augpath",
1699    "\
1700 This is just a shortcut for listing C<guestfs_aug_match>
1701 C<path/*> and sorting the resulting nodes into alphabetical order.");
1702
1703   ("rm", (RErr, [Pathname "path"]), 29, [],
1704    [InitBasicFS, Always, TestRun
1705       [["touch"; "/new"];
1706        ["rm"; "/new"]];
1707     InitBasicFS, Always, TestLastFail
1708       [["rm"; "/new"]];
1709     InitBasicFS, Always, TestLastFail
1710       [["mkdir"; "/new"];
1711        ["rm"; "/new"]]],
1712    "remove a file",
1713    "\
1714 Remove the single file C<path>.");
1715
1716   ("rmdir", (RErr, [Pathname "path"]), 30, [],
1717    [InitBasicFS, Always, TestRun
1718       [["mkdir"; "/new"];
1719        ["rmdir"; "/new"]];
1720     InitBasicFS, Always, TestLastFail
1721       [["rmdir"; "/new"]];
1722     InitBasicFS, Always, TestLastFail
1723       [["touch"; "/new"];
1724        ["rmdir"; "/new"]]],
1725    "remove a directory",
1726    "\
1727 Remove the single directory C<path>.");
1728
1729   ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1730    [InitBasicFS, Always, TestOutputFalse
1731       [["mkdir"; "/new"];
1732        ["mkdir"; "/new/foo"];
1733        ["touch"; "/new/foo/bar"];
1734        ["rm_rf"; "/new"];
1735        ["exists"; "/new"]]],
1736    "remove a file or directory recursively",
1737    "\
1738 Remove the file or directory C<path>, recursively removing the
1739 contents if its a directory.  This is like the C<rm -rf> shell
1740 command.");
1741
1742   ("mkdir", (RErr, [Pathname "path"]), 32, [],
1743    [InitBasicFS, Always, TestOutputTrue
1744       [["mkdir"; "/new"];
1745        ["is_dir"; "/new"]];
1746     InitBasicFS, Always, TestLastFail
1747       [["mkdir"; "/new/foo/bar"]]],
1748    "create a directory",
1749    "\
1750 Create a directory named C<path>.");
1751
1752   ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1753    [InitBasicFS, Always, TestOutputTrue
1754       [["mkdir_p"; "/new/foo/bar"];
1755        ["is_dir"; "/new/foo/bar"]];
1756     InitBasicFS, Always, TestOutputTrue
1757       [["mkdir_p"; "/new/foo/bar"];
1758        ["is_dir"; "/new/foo"]];
1759     InitBasicFS, Always, TestOutputTrue
1760       [["mkdir_p"; "/new/foo/bar"];
1761        ["is_dir"; "/new"]];
1762     (* Regression tests for RHBZ#503133: *)
1763     InitBasicFS, Always, TestRun
1764       [["mkdir"; "/new"];
1765        ["mkdir_p"; "/new"]];
1766     InitBasicFS, Always, TestLastFail
1767       [["touch"; "/new"];
1768        ["mkdir_p"; "/new"]]],
1769    "create a directory and parents",
1770    "\
1771 Create a directory named C<path>, creating any parent directories
1772 as necessary.  This is like the C<mkdir -p> shell command.");
1773
1774   ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1775    [], (* XXX Need stat command to test *)
1776    "change file mode",
1777    "\
1778 Change the mode (permissions) of C<path> to C<mode>.  Only
1779 numeric modes are supported.
1780
1781 I<Note>: When using this command from guestfish, C<mode>
1782 by default would be decimal, unless you prefix it with
1783 C<0> to get octal, ie. use C<0700> not C<700>.
1784
1785 The mode actually set is affected by the umask.");
1786
1787   ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1788    [], (* XXX Need stat command to test *)
1789    "change file owner and group",
1790    "\
1791 Change the file owner to C<owner> and group to C<group>.
1792
1793 Only numeric uid and gid are supported.  If you want to use
1794 names, you will need to locate and parse the password file
1795 yourself (Augeas support makes this relatively easy).");
1796
1797   ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1798    [InitISOFS, Always, TestOutputTrue (
1799       [["exists"; "/empty"]]);
1800     InitISOFS, Always, TestOutputTrue (
1801       [["exists"; "/directory"]])],
1802    "test if file or directory exists",
1803    "\
1804 This returns C<true> if and only if there is a file, directory
1805 (or anything) with the given C<path> name.
1806
1807 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1808
1809   ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1810    [InitISOFS, Always, TestOutputTrue (
1811       [["is_file"; "/known-1"]]);
1812     InitISOFS, Always, TestOutputFalse (
1813       [["is_file"; "/directory"]])],
1814    "test if file exists",
1815    "\
1816 This returns C<true> if and only if there is a file
1817 with the given C<path> name.  Note that it returns false for
1818 other objects like directories.
1819
1820 See also C<guestfs_stat>.");
1821
1822   ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1823    [InitISOFS, Always, TestOutputFalse (
1824       [["is_dir"; "/known-3"]]);
1825     InitISOFS, Always, TestOutputTrue (
1826       [["is_dir"; "/directory"]])],
1827    "test if file exists",
1828    "\
1829 This returns C<true> if and only if there is a directory
1830 with the given C<path> name.  Note that it returns false for
1831 other objects like files.
1832
1833 See also C<guestfs_stat>.");
1834
1835   ("pvcreate", (RErr, [Device "device"]), 39, [Optional "lvm2"],
1836    [InitEmpty, Always, TestOutputListOfDevices (
1837       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1838        ["pvcreate"; "/dev/sda1"];
1839        ["pvcreate"; "/dev/sda2"];
1840        ["pvcreate"; "/dev/sda3"];
1841        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1842    "create an LVM physical volume",
1843    "\
1844 This creates an LVM physical volume on the named C<device>,
1845 where C<device> should usually be a partition name such
1846 as C</dev/sda1>.");
1847
1848   ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [Optional "lvm2"],
1849    [InitEmpty, Always, TestOutputList (
1850       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1851        ["pvcreate"; "/dev/sda1"];
1852        ["pvcreate"; "/dev/sda2"];
1853        ["pvcreate"; "/dev/sda3"];
1854        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1855        ["vgcreate"; "VG2"; "/dev/sda3"];
1856        ["vgs"]], ["VG1"; "VG2"])],
1857    "create an LVM volume group",
1858    "\
1859 This creates an LVM volume group called C<volgroup>
1860 from the non-empty list of physical volumes C<physvols>.");
1861
1862   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [Optional "lvm2"],
1863    [InitEmpty, Always, TestOutputList (
1864       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1865        ["pvcreate"; "/dev/sda1"];
1866        ["pvcreate"; "/dev/sda2"];
1867        ["pvcreate"; "/dev/sda3"];
1868        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1869        ["vgcreate"; "VG2"; "/dev/sda3"];
1870        ["lvcreate"; "LV1"; "VG1"; "50"];
1871        ["lvcreate"; "LV2"; "VG1"; "50"];
1872        ["lvcreate"; "LV3"; "VG2"; "50"];
1873        ["lvcreate"; "LV4"; "VG2"; "50"];
1874        ["lvcreate"; "LV5"; "VG2"; "50"];
1875        ["lvs"]],
1876       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1877        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1878    "create an LVM logical volume",
1879    "\
1880 This creates an LVM logical volume called C<logvol>
1881 on the volume group C<volgroup>, with C<size> megabytes.");
1882
1883   ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1884    [InitEmpty, Always, TestOutput (
1885       [["part_disk"; "/dev/sda"; "mbr"];
1886        ["mkfs"; "ext2"; "/dev/sda1"];
1887        ["mount_options"; ""; "/dev/sda1"; "/"];
1888        ["write"; "/new"; "new file contents"];
1889        ["cat"; "/new"]], "new file contents")],
1890    "make a filesystem",
1891    "\
1892 This creates a filesystem on C<device> (usually a partition
1893 or LVM logical volume).  The filesystem type is C<fstype>, for
1894 example C<ext3>.");
1895
1896   ("sfdisk", (RErr, [Device "device";
1897                      Int "cyls"; Int "heads"; Int "sectors";
1898                      StringList "lines"]), 43, [DangerWillRobinson],
1899    [],
1900    "create partitions on a block device",
1901    "\
1902 This is a direct interface to the L<sfdisk(8)> program for creating
1903 partitions on block devices.
1904
1905 C<device> should be a block device, for example C</dev/sda>.
1906
1907 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1908 and sectors on the device, which are passed directly to sfdisk as
1909 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1910 of these, then the corresponding parameter is omitted.  Usually for
1911 'large' disks, you can just pass C<0> for these, but for small
1912 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1913 out the right geometry and you will need to tell it.
1914
1915 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1916 information refer to the L<sfdisk(8)> manpage.
1917
1918 To create a single partition occupying the whole disk, you would
1919 pass C<lines> as a single element list, when the single element being
1920 the string C<,> (comma).
1921
1922 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>,
1923 C<guestfs_part_init>");
1924
1925   ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning; DeprecatedBy "write"],
1926    (* Regression test for RHBZ#597135. *)
1927    [InitBasicFS, Always, TestLastFail
1928       [["write_file"; "/new"; "abc"; "10000"]]],
1929    "create a file",
1930    "\
1931 This call creates a file called C<path>.  The contents of the
1932 file is the string C<content> (which can contain any 8 bit data),
1933 with length C<size>.
1934
1935 As a special case, if C<size> is C<0>
1936 then the length is calculated using C<strlen> (so in this case
1937 the content cannot contain embedded ASCII NULs).
1938
1939 I<NB.> Owing to a bug, writing content containing ASCII NUL
1940 characters does I<not> work, even if the length is specified.");
1941
1942   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1943    [InitEmpty, Always, TestOutputListOfDevices (
1944       [["part_disk"; "/dev/sda"; "mbr"];
1945        ["mkfs"; "ext2"; "/dev/sda1"];
1946        ["mount_options"; ""; "/dev/sda1"; "/"];
1947        ["mounts"]], ["/dev/sda1"]);
1948     InitEmpty, Always, TestOutputList (
1949       [["part_disk"; "/dev/sda"; "mbr"];
1950        ["mkfs"; "ext2"; "/dev/sda1"];
1951        ["mount_options"; ""; "/dev/sda1"; "/"];
1952        ["umount"; "/"];
1953        ["mounts"]], [])],
1954    "unmount a filesystem",
1955    "\
1956 This unmounts the given filesystem.  The filesystem may be
1957 specified either by its mountpoint (path) or the device which
1958 contains the filesystem.");
1959
1960   ("mounts", (RStringList "devices", []), 46, [],
1961    [InitBasicFS, Always, TestOutputListOfDevices (
1962       [["mounts"]], ["/dev/sda1"])],
1963    "show mounted filesystems",
1964    "\
1965 This returns the list of currently mounted filesystems.  It returns
1966 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1967
1968 Some internal mounts are not shown.
1969
1970 See also: C<guestfs_mountpoints>");
1971
1972   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1973    [InitBasicFS, Always, TestOutputList (
1974       [["umount_all"];
1975        ["mounts"]], []);
1976     (* check that umount_all can unmount nested mounts correctly: *)
1977     InitEmpty, Always, TestOutputList (
1978       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1979        ["mkfs"; "ext2"; "/dev/sda1"];
1980        ["mkfs"; "ext2"; "/dev/sda2"];
1981        ["mkfs"; "ext2"; "/dev/sda3"];
1982        ["mount_options"; ""; "/dev/sda1"; "/"];
1983        ["mkdir"; "/mp1"];
1984        ["mount_options"; ""; "/dev/sda2"; "/mp1"];
1985        ["mkdir"; "/mp1/mp2"];
1986        ["mount_options"; ""; "/dev/sda3"; "/mp1/mp2"];
1987        ["mkdir"; "/mp1/mp2/mp3"];
1988        ["umount_all"];
1989        ["mounts"]], [])],
1990    "unmount all filesystems",
1991    "\
1992 This unmounts all mounted filesystems.
1993
1994 Some internal mounts are not unmounted by this call.");
1995
1996   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson; Optional "lvm2"],
1997    [],
1998    "remove all LVM LVs, VGs and PVs",
1999    "\
2000 This command removes all LVM logical volumes, volume groups
2001 and physical volumes.");
2002
2003   ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
2004    [InitISOFS, Always, TestOutput (
2005       [["file"; "/empty"]], "empty");
2006     InitISOFS, Always, TestOutput (
2007       [["file"; "/known-1"]], "ASCII text");
2008     InitISOFS, Always, TestLastFail (
2009       [["file"; "/notexists"]]);
2010     InitISOFS, Always, TestOutput (
2011       [["file"; "/abssymlink"]], "symbolic link");
2012     InitISOFS, Always, TestOutput (
2013       [["file"; "/directory"]], "directory")],
2014    "determine file type",
2015    "\
2016 This call uses the standard L<file(1)> command to determine
2017 the type or contents of the file.
2018
2019 This call will also transparently look inside various types
2020 of compressed file.
2021
2022 The exact command which runs is C<file -zb path>.  Note in
2023 particular that the filename is not prepended to the output
2024 (the C<-b> option).
2025
2026 This command can also be used on C</dev/> devices
2027 (and partitions, LV names).  You can for example use this
2028 to determine if a device contains a filesystem, although
2029 it's usually better to use C<guestfs_vfs_type>.
2030
2031 If the C<path> does not begin with C</dev/> then
2032 this command only works for the content of regular files.
2033 For other file types (directory, symbolic link etc) it
2034 will just return the string C<directory> etc.");
2035
2036   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
2037    [InitBasicFS, Always, TestOutput (
2038       [["upload"; "test-command"; "/test-command"];
2039        ["chmod"; "0o755"; "/test-command"];
2040        ["command"; "/test-command 1"]], "Result1");
2041     InitBasicFS, Always, TestOutput (
2042       [["upload"; "test-command"; "/test-command"];
2043        ["chmod"; "0o755"; "/test-command"];
2044        ["command"; "/test-command 2"]], "Result2\n");
2045     InitBasicFS, Always, TestOutput (
2046       [["upload"; "test-command"; "/test-command"];
2047        ["chmod"; "0o755"; "/test-command"];
2048        ["command"; "/test-command 3"]], "\nResult3");
2049     InitBasicFS, Always, TestOutput (
2050       [["upload"; "test-command"; "/test-command"];
2051        ["chmod"; "0o755"; "/test-command"];
2052        ["command"; "/test-command 4"]], "\nResult4\n");
2053     InitBasicFS, Always, TestOutput (
2054       [["upload"; "test-command"; "/test-command"];
2055        ["chmod"; "0o755"; "/test-command"];
2056        ["command"; "/test-command 5"]], "\nResult5\n\n");
2057     InitBasicFS, Always, TestOutput (
2058       [["upload"; "test-command"; "/test-command"];
2059        ["chmod"; "0o755"; "/test-command"];
2060        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
2061     InitBasicFS, Always, TestOutput (
2062       [["upload"; "test-command"; "/test-command"];
2063        ["chmod"; "0o755"; "/test-command"];
2064        ["command"; "/test-command 7"]], "");
2065     InitBasicFS, Always, TestOutput (
2066       [["upload"; "test-command"; "/test-command"];
2067        ["chmod"; "0o755"; "/test-command"];
2068        ["command"; "/test-command 8"]], "\n");
2069     InitBasicFS, Always, TestOutput (
2070       [["upload"; "test-command"; "/test-command"];
2071        ["chmod"; "0o755"; "/test-command"];
2072        ["command"; "/test-command 9"]], "\n\n");
2073     InitBasicFS, Always, TestOutput (
2074       [["upload"; "test-command"; "/test-command"];
2075        ["chmod"; "0o755"; "/test-command"];
2076        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
2077     InitBasicFS, Always, TestOutput (
2078       [["upload"; "test-command"; "/test-command"];
2079        ["chmod"; "0o755"; "/test-command"];
2080        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
2081     InitBasicFS, Always, TestLastFail (
2082       [["upload"; "test-command"; "/test-command"];
2083        ["chmod"; "0o755"; "/test-command"];
2084        ["command"; "/test-command"]])],
2085    "run a command from the guest filesystem",
2086    "\
2087 This call runs a command from the guest filesystem.  The
2088 filesystem must be mounted, and must contain a compatible
2089 operating system (ie. something Linux, with the same
2090 or compatible processor architecture).
2091
2092 The single parameter is an argv-style list of arguments.
2093 The first element is the name of the program to run.
2094 Subsequent elements are parameters.  The list must be
2095 non-empty (ie. must contain a program name).  Note that
2096 the command runs directly, and is I<not> invoked via
2097 the shell (see C<guestfs_sh>).
2098
2099 The return value is anything printed to I<stdout> by
2100 the command.
2101
2102 If the command returns a non-zero exit status, then
2103 this function returns an error message.  The error message
2104 string is the content of I<stderr> from the command.
2105
2106 The C<$PATH> environment variable will contain at least
2107 C</usr/bin> and C</bin>.  If you require a program from
2108 another location, you should provide the full path in the
2109 first parameter.
2110
2111 Shared libraries and data files required by the program
2112 must be available on filesystems which are mounted in the
2113 correct places.  It is the caller's responsibility to ensure
2114 all filesystems that are needed are mounted at the right
2115 locations.");
2116
2117   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
2118    [InitBasicFS, Always, TestOutputList (
2119       [["upload"; "test-command"; "/test-command"];
2120        ["chmod"; "0o755"; "/test-command"];
2121        ["command_lines"; "/test-command 1"]], ["Result1"]);
2122     InitBasicFS, Always, TestOutputList (
2123       [["upload"; "test-command"; "/test-command"];
2124        ["chmod"; "0o755"; "/test-command"];
2125        ["command_lines"; "/test-command 2"]], ["Result2"]);
2126     InitBasicFS, Always, TestOutputList (
2127       [["upload"; "test-command"; "/test-command"];
2128        ["chmod"; "0o755"; "/test-command"];
2129        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
2130     InitBasicFS, Always, TestOutputList (
2131       [["upload"; "test-command"; "/test-command"];
2132        ["chmod"; "0o755"; "/test-command"];
2133        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
2134     InitBasicFS, Always, TestOutputList (
2135       [["upload"; "test-command"; "/test-command"];
2136        ["chmod"; "0o755"; "/test-command"];
2137        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
2138     InitBasicFS, Always, TestOutputList (
2139       [["upload"; "test-command"; "/test-command"];
2140        ["chmod"; "0o755"; "/test-command"];
2141        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
2142     InitBasicFS, Always, TestOutputList (
2143       [["upload"; "test-command"; "/test-command"];
2144        ["chmod"; "0o755"; "/test-command"];
2145        ["command_lines"; "/test-command 7"]], []);
2146     InitBasicFS, Always, TestOutputList (
2147       [["upload"; "test-command"; "/test-command"];
2148        ["chmod"; "0o755"; "/test-command"];
2149        ["command_lines"; "/test-command 8"]], [""]);
2150     InitBasicFS, Always, TestOutputList (
2151       [["upload"; "test-command"; "/test-command"];
2152        ["chmod"; "0o755"; "/test-command"];
2153        ["command_lines"; "/test-command 9"]], ["";""]);
2154     InitBasicFS, Always, TestOutputList (
2155       [["upload"; "test-command"; "/test-command"];
2156        ["chmod"; "0o755"; "/test-command"];
2157        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
2158     InitBasicFS, Always, TestOutputList (
2159       [["upload"; "test-command"; "/test-command"];
2160        ["chmod"; "0o755"; "/test-command"];
2161        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
2162    "run a command, returning lines",
2163    "\
2164 This is the same as C<guestfs_command>, but splits the
2165 result into a list of lines.
2166
2167 See also: C<guestfs_sh_lines>");
2168
2169   ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
2170    [InitISOFS, Always, TestOutputStruct (
2171       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
2172    "get file information",
2173    "\
2174 Returns file information for the given C<path>.
2175
2176 This is the same as the C<stat(2)> system call.");
2177
2178   ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
2179    [InitISOFS, Always, TestOutputStruct (
2180       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
2181    "get file information for a symbolic link",
2182    "\
2183 Returns file information for the given C<path>.
2184
2185 This is the same as C<guestfs_stat> except that if C<path>
2186 is a symbolic link, then the link is stat-ed, not the file it
2187 refers to.
2188
2189 This is the same as the C<lstat(2)> system call.");
2190
2191   ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
2192    [InitISOFS, Always, TestOutputStruct (
2193       [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
2194    "get file system statistics",
2195    "\
2196 Returns file system statistics for any mounted file system.
2197 C<path> should be a file or directory in the mounted file system
2198 (typically it is the mount point itself, but it doesn't need to be).
2199
2200 This is the same as the C<statvfs(2)> system call.");
2201
2202   ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
2203    [], (* XXX test *)
2204    "get ext2/ext3/ext4 superblock details",
2205    "\
2206 This returns the contents of the ext2, ext3 or ext4 filesystem
2207 superblock on C<device>.
2208
2209 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
2210 manpage for more details.  The list of fields returned isn't
2211 clearly defined, and depends on both the version of C<tune2fs>
2212 that libguestfs was built against, and the filesystem itself.");
2213
2214   ("blockdev_setro", (RErr, [Device "device"]), 56, [],
2215    [InitEmpty, Always, TestOutputTrue (
2216       [["blockdev_setro"; "/dev/sda"];
2217        ["blockdev_getro"; "/dev/sda"]])],
2218    "set block device to read-only",
2219    "\
2220 Sets the block device named C<device> to read-only.
2221
2222 This uses the L<blockdev(8)> command.");
2223
2224   ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
2225    [InitEmpty, Always, TestOutputFalse (
2226       [["blockdev_setrw"; "/dev/sda"];
2227        ["blockdev_getro"; "/dev/sda"]])],
2228    "set block device to read-write",
2229    "\
2230 Sets the block device named C<device> to read-write.
2231
2232 This uses the L<blockdev(8)> command.");
2233
2234   ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
2235    [InitEmpty, Always, TestOutputTrue (
2236       [["blockdev_setro"; "/dev/sda"];
2237        ["blockdev_getro"; "/dev/sda"]])],
2238    "is block device set to read-only",
2239    "\
2240 Returns a boolean indicating if the block device is read-only
2241 (true if read-only, false if not).
2242
2243 This uses the L<blockdev(8)> command.");
2244
2245   ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
2246    [InitEmpty, Always, TestOutputInt (
2247       [["blockdev_getss"; "/dev/sda"]], 512)],
2248    "get sectorsize of block device",
2249    "\
2250 This returns the size of sectors on a block device.
2251 Usually 512, but can be larger for modern devices.
2252
2253 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
2254 for that).
2255
2256 This uses the L<blockdev(8)> command.");
2257
2258   ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
2259    [InitEmpty, Always, TestOutputInt (
2260       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
2261    "get blocksize of block device",
2262    "\
2263 This returns the block size of a device.
2264
2265 (Note this is different from both I<size in blocks> and
2266 I<filesystem block size>).
2267
2268 This uses the L<blockdev(8)> command.");
2269
2270   ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
2271    [], (* XXX test *)
2272    "set blocksize of block device",
2273    "\
2274 This sets the block size of a device.
2275
2276 (Note this is different from both I<size in blocks> and
2277 I<filesystem block size>).
2278
2279 This uses the L<blockdev(8)> command.");
2280
2281   ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
2282    [InitEmpty, Always, TestOutputInt (
2283       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
2284    "get total size of device in 512-byte sectors",
2285    "\
2286 This returns the size of the device in units of 512-byte sectors
2287 (even if the sectorsize isn't 512 bytes ... weird).
2288
2289 See also C<guestfs_blockdev_getss> for the real sector size of
2290 the device, and C<guestfs_blockdev_getsize64> for the more
2291 useful I<size in bytes>.
2292
2293 This uses the L<blockdev(8)> command.");
2294
2295   ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
2296    [InitEmpty, Always, TestOutputInt (
2297       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
2298    "get total size of device in bytes",
2299    "\
2300 This returns the size of the device in bytes.
2301
2302 See also C<guestfs_blockdev_getsz>.
2303
2304 This uses the L<blockdev(8)> command.");
2305
2306   ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
2307    [InitEmpty, Always, TestRun
2308       [["blockdev_flushbufs"; "/dev/sda"]]],
2309    "flush device buffers",
2310    "\
2311 This tells the kernel to flush internal buffers associated
2312 with C<device>.
2313
2314 This uses the L<blockdev(8)> command.");
2315
2316   ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
2317    [InitEmpty, Always, TestRun
2318       [["blockdev_rereadpt"; "/dev/sda"]]],
2319    "reread partition table",
2320    "\
2321 Reread the partition table on C<device>.
2322
2323 This uses the L<blockdev(8)> command.");
2324
2325   ("upload", (RErr, [FileIn "filename"; Dev_or_Path "remotefilename"]), 66, [],
2326    [InitBasicFS, Always, TestOutput (
2327       (* Pick a file from cwd which isn't likely to change. *)
2328       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2329        ["checksum"; "md5"; "/COPYING.LIB"]],
2330       Digest.to_hex (Digest.file "COPYING.LIB"))],
2331    "upload a file from the local machine",
2332    "\
2333 Upload local file C<filename> to C<remotefilename> on the
2334 filesystem.
2335
2336 C<filename> can also be a named pipe.
2337
2338 See also C<guestfs_download>.");
2339
2340   ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [],
2341    [InitBasicFS, Always, TestOutput (
2342       (* Pick a file from cwd which isn't likely to change. *)
2343       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
2344        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
2345        ["upload"; "testdownload.tmp"; "/upload"];
2346        ["checksum"; "md5"; "/upload"]],
2347       Digest.to_hex (Digest.file "COPYING.LIB"))],
2348    "download a file to the local machine",
2349    "\
2350 Download file C<remotefilename> and save it as C<filename>
2351 on the local machine.
2352
2353 C<filename> can also be a named pipe.
2354
2355 See also C<guestfs_upload>, C<guestfs_cat>.");
2356
2357   ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
2358    [InitISOFS, Always, TestOutput (
2359       [["checksum"; "crc"; "/known-3"]], "2891671662");
2360     InitISOFS, Always, TestLastFail (
2361       [["checksum"; "crc"; "/notexists"]]);
2362     InitISOFS, Always, TestOutput (
2363       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
2364     InitISOFS, Always, TestOutput (
2365       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
2366     InitISOFS, Always, TestOutput (
2367       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
2368     InitISOFS, Always, TestOutput (
2369       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
2370     InitISOFS, Always, TestOutput (
2371       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
2372     InitISOFS, Always, TestOutput (
2373       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6");
2374     (* Test for RHBZ#579608, absolute symbolic links. *)
2375     InitISOFS, Always, TestOutput (
2376       [["checksum"; "sha512"; "/abssymlink"]], "5f57d0639bc95081c53afc63a449403883818edc64da48930ad6b1a4fb49be90404686877743fbcd7c99811f3def7df7bc22635c885c6a8cf79c806b43451c1a")],
2377    "compute MD5, SHAx or CRC checksum of file",
2378    "\
2379 This call computes the MD5, SHAx or CRC checksum of the
2380 file named C<path>.
2381
2382 The type of checksum to compute is given by the C<csumtype>
2383 parameter which must have one of the following values:
2384
2385 =over 4
2386
2387 =item C<crc>
2388
2389 Compute the cyclic redundancy check (CRC) specified by POSIX
2390 for the C<cksum> command.
2391
2392 =item C<md5>
2393
2394 Compute the MD5 hash (using the C<md5sum> program).
2395
2396 =item C<sha1>
2397
2398 Compute the SHA1 hash (using the C<sha1sum> program).
2399
2400 =item C<sha224>
2401
2402 Compute the SHA224 hash (using the C<sha224sum> program).
2403
2404 =item C<sha256>
2405
2406 Compute the SHA256 hash (using the C<sha256sum> program).
2407
2408 =item C<sha384>
2409
2410 Compute the SHA384 hash (using the C<sha384sum> program).
2411
2412 =item C<sha512>
2413
2414 Compute the SHA512 hash (using the C<sha512sum> program).
2415
2416 =back
2417
2418 The checksum is returned as a printable string.
2419
2420 To get the checksum for a device, use C<guestfs_checksum_device>.
2421
2422 To get the checksums for many files, use C<guestfs_checksums_out>.");
2423
2424   ("tar_in", (RErr, [FileIn "tarfile"; Pathname "directory"]), 69, [],
2425    [InitBasicFS, Always, TestOutput (
2426       [["tar_in"; "../images/helloworld.tar"; "/"];
2427        ["cat"; "/hello"]], "hello\n")],
2428    "unpack tarfile to directory",
2429    "\
2430 This command uploads and unpacks local file C<tarfile> (an
2431 I<uncompressed> tar file) into C<directory>.
2432
2433 To upload a compressed tarball, use C<guestfs_tgz_in>
2434 or C<guestfs_txz_in>.");
2435
2436   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
2437    [],
2438    "pack directory into tarfile",
2439    "\
2440 This command packs the contents of C<directory> and downloads
2441 it to local file C<tarfile>.
2442
2443 To download a compressed tarball, use C<guestfs_tgz_out>
2444 or C<guestfs_txz_out>.");
2445
2446   ("tgz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 71, [],
2447    [InitBasicFS, Always, TestOutput (
2448       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
2449        ["cat"; "/hello"]], "hello\n")],
2450    "unpack compressed tarball to directory",
2451    "\
2452 This command uploads and unpacks local file C<tarball> (a
2453 I<gzip compressed> tar file) into C<directory>.
2454
2455 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
2456
2457   ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
2458    [],
2459    "pack directory into compressed tarball",
2460    "\
2461 This command packs the contents of C<directory> and downloads
2462 it to local file C<tarball>.
2463
2464 To download an uncompressed tarball, use C<guestfs_tar_out>.");
2465
2466   ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
2467    [InitBasicFS, Always, TestLastFail (
2468       [["umount"; "/"];
2469        ["mount_ro"; "/dev/sda1"; "/"];
2470        ["touch"; "/new"]]);
2471     InitBasicFS, Always, TestOutput (
2472       [["write"; "/new"; "data"];
2473        ["umount"; "/"];
2474        ["mount_ro"; "/dev/sda1"; "/"];
2475        ["cat"; "/new"]], "data")],
2476    "mount a guest disk, read-only",
2477    "\
2478 This is the same as the C<guestfs_mount> command, but it
2479 mounts the filesystem with the read-only (I<-o ro>) flag.");
2480
2481   ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2482    [],
2483    "mount a guest disk with mount options",
2484    "\
2485 This is the same as the C<guestfs_mount> command, but it
2486 allows you to set the mount options as for the
2487 L<mount(8)> I<-o> flag.
2488
2489 If the C<options> parameter is an empty string, then
2490 no options are passed (all options default to whatever
2491 the filesystem uses).");
2492
2493   ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2494    [],
2495    "mount a guest disk with mount options and vfstype",
2496    "\
2497 This is the same as the C<guestfs_mount> command, but it
2498 allows you to set both the mount options and the vfstype
2499 as for the L<mount(8)> I<-o> and I<-t> flags.");
2500
2501   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2502    [],
2503    "debugging and internals",
2504    "\
2505 The C<guestfs_debug> command exposes some internals of
2506 C<guestfsd> (the guestfs daemon) that runs inside the
2507 qemu subprocess.
2508
2509 There is no comprehensive help for this command.  You have
2510 to look at the file C<daemon/debug.c> in the libguestfs source
2511 to find out what you can do.");
2512
2513   ("lvremove", (RErr, [Device "device"]), 77, [Optional "lvm2"],
2514    [InitEmpty, Always, TestOutputList (
2515       [["part_disk"; "/dev/sda"; "mbr"];
2516        ["pvcreate"; "/dev/sda1"];
2517        ["vgcreate"; "VG"; "/dev/sda1"];
2518        ["lvcreate"; "LV1"; "VG"; "50"];
2519        ["lvcreate"; "LV2"; "VG"; "50"];
2520        ["lvremove"; "/dev/VG/LV1"];
2521        ["lvs"]], ["/dev/VG/LV2"]);
2522     InitEmpty, Always, TestOutputList (
2523       [["part_disk"; "/dev/sda"; "mbr"];
2524        ["pvcreate"; "/dev/sda1"];
2525        ["vgcreate"; "VG"; "/dev/sda1"];
2526        ["lvcreate"; "LV1"; "VG"; "50"];
2527        ["lvcreate"; "LV2"; "VG"; "50"];
2528        ["lvremove"; "/dev/VG"];
2529        ["lvs"]], []);
2530     InitEmpty, Always, TestOutputList (
2531       [["part_disk"; "/dev/sda"; "mbr"];
2532        ["pvcreate"; "/dev/sda1"];
2533        ["vgcreate"; "VG"; "/dev/sda1"];
2534        ["lvcreate"; "LV1"; "VG"; "50"];
2535        ["lvcreate"; "LV2"; "VG"; "50"];
2536        ["lvremove"; "/dev/VG"];
2537        ["vgs"]], ["VG"])],
2538    "remove an LVM logical volume",
2539    "\
2540 Remove an LVM logical volume C<device>, where C<device> is
2541 the path to the LV, such as C</dev/VG/LV>.
2542
2543 You can also remove all LVs in a volume group by specifying
2544 the VG name, C</dev/VG>.");
2545
2546   ("vgremove", (RErr, [String "vgname"]), 78, [Optional "lvm2"],
2547    [InitEmpty, Always, TestOutputList (
2548       [["part_disk"; "/dev/sda"; "mbr"];
2549        ["pvcreate"; "/dev/sda1"];
2550        ["vgcreate"; "VG"; "/dev/sda1"];
2551        ["lvcreate"; "LV1"; "VG"; "50"];
2552        ["lvcreate"; "LV2"; "VG"; "50"];
2553        ["vgremove"; "VG"];
2554        ["lvs"]], []);
2555     InitEmpty, Always, TestOutputList (
2556       [["part_disk"; "/dev/sda"; "mbr"];
2557        ["pvcreate"; "/dev/sda1"];
2558        ["vgcreate"; "VG"; "/dev/sda1"];
2559        ["lvcreate"; "LV1"; "VG"; "50"];
2560        ["lvcreate"; "LV2"; "VG"; "50"];
2561        ["vgremove"; "VG"];
2562        ["vgs"]], [])],
2563    "remove an LVM volume group",
2564    "\
2565 Remove an LVM volume group C<vgname>, (for example C<VG>).
2566
2567 This also forcibly removes all logical volumes in the volume
2568 group (if any).");
2569
2570   ("pvremove", (RErr, [Device "device"]), 79, [Optional "lvm2"],
2571    [InitEmpty, Always, TestOutputListOfDevices (
2572       [["part_disk"; "/dev/sda"; "mbr"];
2573        ["pvcreate"; "/dev/sda1"];
2574        ["vgcreate"; "VG"; "/dev/sda1"];
2575        ["lvcreate"; "LV1"; "VG"; "50"];
2576        ["lvcreate"; "LV2"; "VG"; "50"];
2577        ["vgremove"; "VG"];
2578        ["pvremove"; "/dev/sda1"];
2579        ["lvs"]], []);
2580     InitEmpty, Always, TestOutputListOfDevices (
2581       [["part_disk"; "/dev/sda"; "mbr"];
2582        ["pvcreate"; "/dev/sda1"];
2583        ["vgcreate"; "VG"; "/dev/sda1"];
2584        ["lvcreate"; "LV1"; "VG"; "50"];
2585        ["lvcreate"; "LV2"; "VG"; "50"];
2586        ["vgremove"; "VG"];
2587        ["pvremove"; "/dev/sda1"];
2588        ["vgs"]], []);
2589     InitEmpty, Always, TestOutputListOfDevices (
2590       [["part_disk"; "/dev/sda"; "mbr"];
2591        ["pvcreate"; "/dev/sda1"];
2592        ["vgcreate"; "VG"; "/dev/sda1"];
2593        ["lvcreate"; "LV1"; "VG"; "50"];
2594        ["lvcreate"; "LV2"; "VG"; "50"];
2595        ["vgremove"; "VG"];
2596        ["pvremove"; "/dev/sda1"];
2597        ["pvs"]], [])],
2598    "remove an LVM physical volume",
2599    "\
2600 This wipes a physical volume C<device> so that LVM will no longer
2601 recognise it.
2602
2603 The implementation uses the C<pvremove> command which refuses to
2604 wipe physical volumes that contain any volume groups, so you have
2605 to remove those first.");
2606
2607   ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2608    [InitBasicFS, Always, TestOutput (
2609       [["set_e2label"; "/dev/sda1"; "testlabel"];
2610        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2611    "set the ext2/3/4 filesystem label",
2612    "\
2613 This sets the ext2/3/4 filesystem label of the filesystem on
2614 C<device> to C<label>.  Filesystem labels are limited to
2615 16 characters.
2616
2617 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2618 to return the existing label on a filesystem.");
2619
2620   ("get_e2label", (RString "label", [Device "device"]), 81, [DeprecatedBy "vfs_label"],
2621    [],
2622    "get the ext2/3/4 filesystem label",
2623    "\
2624 This returns the ext2/3/4 filesystem label of the filesystem on
2625 C<device>.");
2626
2627   ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2628    (let uuid = uuidgen () in
2629     [InitBasicFS, Always, TestOutput (
2630        [["set_e2uuid"; "/dev/sda1"; uuid];
2631         ["get_e2uuid"; "/dev/sda1"]], uuid);
2632      InitBasicFS, Always, TestOutput (
2633        [["set_e2uuid"; "/dev/sda1"; "clear"];
2634         ["get_e2uuid"; "/dev/sda1"]], "");
2635      (* We can't predict what UUIDs will be, so just check the commands run. *)
2636      InitBasicFS, Always, TestRun (
2637        [["set_e2uuid"; "/dev/sda1"; "random"]]);
2638      InitBasicFS, Always, TestRun (
2639        [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2640    "set the ext2/3/4 filesystem UUID",
2641    "\
2642 This sets the ext2/3/4 filesystem UUID of the filesystem on
2643 C<device> to C<uuid>.  The format of the UUID and alternatives
2644 such as C<clear>, C<random> and C<time> are described in the
2645 L<tune2fs(8)> manpage.
2646
2647 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2648 to return the existing UUID of a filesystem.");
2649
2650   ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [DeprecatedBy "vfs_uuid"],
2651    (* Regression test for RHBZ#597112. *)
2652    (let uuid = uuidgen () in
2653     [InitBasicFS, Always, TestOutput (
2654        [["mke2journal"; "1024"; "/dev/sdb"];
2655         ["set_e2uuid"; "/dev/sdb"; uuid];
2656         ["get_e2uuid"; "/dev/sdb"]], uuid)]),
2657    "get the ext2/3/4 filesystem UUID",
2658    "\
2659 This returns the ext2/3/4 filesystem UUID of the filesystem on
2660 C<device>.");
2661
2662   ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [FishOutput FishOutputHexadecimal],
2663    [InitBasicFS, Always, TestOutputInt (
2664       [["umount"; "/dev/sda1"];
2665        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2666     InitBasicFS, Always, TestOutputInt (
2667       [["umount"; "/dev/sda1"];
2668        ["zero"; "/dev/sda1"];
2669        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2670    "run the filesystem checker",
2671    "\
2672 This runs the filesystem checker (fsck) on C<device> which
2673 should have filesystem type C<fstype>.
2674
2675 The returned integer is the status.  See L<fsck(8)> for the
2676 list of status codes from C<fsck>.
2677
2678 Notes:
2679
2680 =over 4
2681
2682 =item *
2683
2684 Multiple status codes can be summed together.
2685
2686 =item *
2687
2688 A non-zero return code can mean \"success\", for example if
2689 errors have been corrected on the filesystem.
2690
2691 =item *
2692
2693 Checking or repairing NTFS volumes is not supported
2694 (by linux-ntfs).
2695
2696 =back
2697
2698 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2699
2700   ("zero", (RErr, [Device "device"]), 85, [],
2701    [InitBasicFS, Always, TestOutput (
2702       [["umount"; "/dev/sda1"];
2703        ["zero"; "/dev/sda1"];
2704        ["file"; "/dev/sda1"]], "data")],
2705    "write zeroes to the device",
2706    "\
2707 This command writes zeroes over the first few blocks of C<device>.
2708
2709 How many blocks are zeroed isn't specified (but it's I<not> enough
2710 to securely wipe the device).  It should be sufficient to remove
2711 any partition tables, filesystem superblocks and so on.
2712
2713 See also: C<guestfs_zero_device>, C<guestfs_scrub_device>.");
2714
2715   ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2716    (* See:
2717     * https://bugzilla.redhat.com/show_bug.cgi?id=484986
2718     * https://bugzilla.redhat.com/show_bug.cgi?id=479760
2719     *)
2720    [InitBasicFS, Always, TestOutputTrue (
2721       [["mkdir_p"; "/boot/grub"];
2722        ["write"; "/boot/grub/device.map"; "(hd0) /dev/vda"];
2723        ["grub_install"; "/"; "/dev/vda"];
2724        ["is_dir"; "/boot"]])],
2725    "install GRUB",
2726    "\
2727 This command installs GRUB (the Grand Unified Bootloader) on
2728 C<device>, with the root directory being C<root>.
2729
2730 Note: If grub-install reports the error
2731 \"No suitable drive was found in the generated device map.\"
2732 it may be that you need to create a C</boot/grub/device.map>
2733 file first that contains the mapping between grub device names
2734 and Linux device names.  It is usually sufficient to create
2735 a file containing:
2736
2737  (hd0) /dev/vda
2738
2739 replacing C</dev/vda> with the name of the installation device.");
2740
2741   ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2742    [InitBasicFS, Always, TestOutput (
2743       [["write"; "/old"; "file content"];
2744        ["cp"; "/old"; "/new"];
2745        ["cat"; "/new"]], "file content");
2746     InitBasicFS, Always, TestOutputTrue (
2747       [["write"; "/old"; "file content"];
2748        ["cp"; "/old"; "/new"];
2749        ["is_file"; "/old"]]);
2750     InitBasicFS, Always, TestOutput (
2751       [["write"; "/old"; "file content"];
2752        ["mkdir"; "/dir"];
2753        ["cp"; "/old"; "/dir/new"];
2754        ["cat"; "/dir/new"]], "file content")],
2755    "copy a file",
2756    "\
2757 This copies a file from C<src> to C<dest> where C<dest> is
2758 either a destination filename or destination directory.");
2759
2760   ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2761    [InitBasicFS, Always, TestOutput (
2762       [["mkdir"; "/olddir"];
2763        ["mkdir"; "/newdir"];
2764        ["write"; "/olddir/file"; "file content"];
2765        ["cp_a"; "/olddir"; "/newdir"];
2766        ["cat"; "/newdir/olddir/file"]], "file content")],
2767    "copy a file or directory recursively",
2768    "\
2769 This copies a file or directory from C<src> to C<dest>
2770 recursively using the C<cp -a> command.");
2771
2772   ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2773    [InitBasicFS, Always, TestOutput (
2774       [["write"; "/old"; "file content"];
2775        ["mv"; "/old"; "/new"];
2776        ["cat"; "/new"]], "file content");
2777     InitBasicFS, Always, TestOutputFalse (
2778       [["write"; "/old"; "file content"];
2779        ["mv"; "/old"; "/new"];
2780        ["is_file"; "/old"]])],
2781    "move a file",
2782    "\
2783 This moves a file from C<src> to C<dest> where C<dest> is
2784 either a destination filename or destination directory.");
2785
2786   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2787    [InitEmpty, Always, TestRun (
2788       [["drop_caches"; "3"]])],
2789    "drop kernel page cache, dentries and inodes",
2790    "\
2791 This instructs the guest kernel to drop its page cache,
2792 and/or dentries and inode caches.  The parameter C<whattodrop>
2793 tells the kernel what precisely to drop, see
2794 L<http://linux-mm.org/Drop_Caches>
2795
2796 Setting C<whattodrop> to 3 should drop everything.
2797
2798 This automatically calls L<sync(2)> before the operation,
2799 so that the maximum guest memory is freed.");
2800
2801   ("dmesg", (RString "kmsgs", []), 91, [],
2802    [InitEmpty, Always, TestRun (
2803       [["dmesg"]])],
2804    "return kernel messages",
2805    "\
2806 This returns the kernel messages (C<dmesg> output) from
2807 the guest kernel.  This is sometimes useful for extended
2808 debugging of problems.
2809
2810 Another way to get the same information is to enable
2811 verbose messages with C<guestfs_set_verbose> or by setting
2812 the environment variable C<LIBGUESTFS_DEBUG=1> before
2813 running the program.");
2814
2815   ("ping_daemon", (RErr, []), 92, [],
2816    [InitEmpty, Always, TestRun (
2817       [["ping_daemon"]])],
2818    "ping the guest daemon",
2819    "\
2820 This is a test probe into the guestfs daemon running inside
2821 the qemu subprocess.  Calling this function checks that the
2822 daemon responds to the ping message, without affecting the daemon
2823 or attached block device(s) in any other way.");
2824
2825   ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2826    [InitBasicFS, Always, TestOutputTrue (
2827       [["write"; "/file1"; "contents of a file"];
2828        ["cp"; "/file1"; "/file2"];
2829        ["equal"; "/file1"; "/file2"]]);
2830     InitBasicFS, Always, TestOutputFalse (
2831       [["write"; "/file1"; "contents of a file"];
2832        ["write"; "/file2"; "contents of another file"];
2833        ["equal"; "/file1"; "/file2"]]);
2834     InitBasicFS, Always, TestLastFail (
2835       [["equal"; "/file1"; "/file2"]])],
2836    "test if two files have equal contents",
2837    "\
2838 This compares the two files C<file1> and C<file2> and returns
2839 true if their content is exactly equal, or false otherwise.
2840
2841 The external L<cmp(1)> program is used for the comparison.");
2842
2843   ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2844    [InitISOFS, Always, TestOutputList (
2845       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2846     InitISOFS, Always, TestOutputList (
2847       [["strings"; "/empty"]], []);
2848     (* Test for RHBZ#579608, absolute symbolic links. *)
2849     InitISOFS, Always, TestRun (
2850       [["strings"; "/abssymlink"]])],
2851    "print the printable strings in a file",
2852    "\
2853 This runs the L<strings(1)> command on a file and returns
2854 the list of printable strings found.");
2855
2856   ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2857    [InitISOFS, Always, TestOutputList (
2858       [["strings_e"; "b"; "/known-5"]], []);
2859     InitBasicFS, Always, TestOutputList (
2860       [["write"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"];
2861        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2862    "print the printable strings in a file",
2863    "\
2864 This is like the C<guestfs_strings> command, but allows you to
2865 specify the encoding of strings that are looked for in
2866 the source file C<path>.
2867
2868 Allowed encodings are:
2869
2870 =over 4
2871
2872 =item s
2873
2874 Single 7-bit-byte characters like ASCII and the ASCII-compatible
2875 parts of ISO-8859-X (this is what C<guestfs_strings> uses).
2876
2877 =item S
2878
2879 Single 8-bit-byte characters.
2880
2881 =item b
2882
2883 16-bit big endian strings such as those encoded in
2884 UTF-16BE or UCS-2BE.
2885
2886 =item l (lower case letter L)
2887
2888 16-bit little endian such as UTF-16LE and UCS-2LE.
2889 This is useful for examining binaries in Windows guests.
2890
2891 =item B
2892
2893 32-bit big endian such as UCS-4BE.
2894
2895 =item L
2896
2897 32-bit little endian such as UCS-4LE.
2898
2899 =back
2900
2901 The returned strings are transcoded to UTF-8.");
2902
2903   ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2904    [InitISOFS, Always, TestOutput (
2905       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2906     (* Test for RHBZ#501888c2 regression which caused large hexdump
2907      * commands to segfault.
2908      *)
2909     InitISOFS, Always, TestRun (
2910       [["hexdump"; "/100krandom"]]);
2911     (* Test for RHBZ#579608, absolute symbolic links. *)
2912     InitISOFS, Always, TestRun (
2913       [["hexdump"; "/abssymlink"]])],
2914    "dump a file in hexadecimal",
2915    "\
2916 This runs C<hexdump -C> on the given C<path>.  The result is
2917 the human-readable, canonical hex dump of the file.");
2918
2919   ("zerofree", (RErr, [Device "device"]), 97, [Optional "zerofree"],
2920    [InitNone, Always, TestOutput (
2921       [["part_disk"; "/dev/sda"; "mbr"];
2922        ["mkfs"; "ext3"; "/dev/sda1"];
2923        ["mount_options"; ""; "/dev/sda1"; "/"];
2924        ["write"; "/new"; "test file"];
2925        ["umount"; "/dev/sda1"];
2926        ["zerofree"; "/dev/sda1"];
2927        ["mount_options"; ""; "/dev/sda1"; "/"];
2928        ["cat"; "/new"]], "test file")],
2929    "zero unused inodes and disk blocks on ext2/3 filesystem",
2930    "\
2931 This runs the I<zerofree> program on C<device>.  This program
2932 claims to zero unused inodes and disk blocks on an ext2/3
2933 filesystem, thus making it possible to compress the filesystem
2934 more effectively.
2935
2936 You should B<not> run this program if the filesystem is
2937 mounted.
2938
2939 It is possible that using this program can damage the filesystem
2940 or data on the filesystem.");
2941
2942   ("pvresize", (RErr, [Device "device"]), 98, [Optional "lvm2"],
2943    [],
2944    "resize an LVM physical volume",
2945    "\
2946 This resizes (expands or shrinks) an existing LVM physical
2947 volume to match the new size of the underlying device.");
2948
2949   ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2950                        Int "cyls"; Int "heads"; Int "sectors";
2951                        String "line"]), 99, [DangerWillRobinson],
2952    [],
2953    "modify a single partition on a block device",
2954    "\
2955 This runs L<sfdisk(8)> option to modify just the single
2956 partition C<n> (note: C<n> counts from 1).
2957
2958 For other parameters, see C<guestfs_sfdisk>.  You should usually
2959 pass C<0> for the cyls/heads/sectors parameters.
2960
2961 See also: C<guestfs_part_add>");
2962
2963   ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2964    [],
2965    "display the partition table",
2966    "\
2967 This displays the partition table on C<device>, in the
2968 human-readable output of the L<sfdisk(8)> command.  It is
2969 not intended to be parsed.
2970
2971 See also: C<guestfs_part_list>");
2972
2973   ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2974    [],
2975    "display the kernel geometry",
2976    "\
2977 This displays the kernel's idea of the geometry of C<device>.
2978
2979 The result is in human-readable format, and not designed to
2980 be parsed.");
2981
2982   ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2983    [],
2984    "display the disk geometry from the partition table",
2985    "\
2986 This displays the disk geometry of C<device> read from the
2987 partition table.  Especially in the case where the underlying
2988 block device has been resized, this can be different from the
2989 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2990
2991 The result is in human-readable format, and not designed to
2992 be parsed.");
2993
2994   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [Optional "lvm2"],
2995    [],
2996    "activate or deactivate all volume groups",
2997    "\
2998 This command activates or (if C<activate> is false) deactivates
2999 all logical volumes in all volume groups.
3000 If activated, then they are made known to the
3001 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3002 then those devices disappear.
3003
3004 This command is the same as running C<vgchange -a y|n>");
3005
3006   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [Optional "lvm2"],
3007    [],
3008    "activate or deactivate some volume groups",
3009    "\
3010 This command activates or (if C<activate> is false) deactivates
3011 all logical volumes in the listed volume groups C<volgroups>.
3012 If activated, then they are made known to the
3013 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
3014 then those devices disappear.
3015
3016 This command is the same as running C<vgchange -a y|n volgroups...>
3017
3018 Note that if C<volgroups> is an empty list then B<all> volume groups
3019 are activated or deactivated.");
3020
3021   ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [Optional "lvm2"],
3022    [InitNone, Always, TestOutput (
3023       [["part_disk"; "/dev/sda"; "mbr"];
3024        ["pvcreate"; "/dev/sda1"];
3025        ["vgcreate"; "VG"; "/dev/sda1"];
3026        ["lvcreate"; "LV"; "VG"; "10"];
3027        ["mkfs"; "ext2"; "/dev/VG/LV"];
3028        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3029        ["write"; "/new"; "test content"];
3030        ["umount"; "/"];
3031        ["lvresize"; "/dev/VG/LV"; "20"];
3032        ["e2fsck_f"; "/dev/VG/LV"];
3033        ["resize2fs"; "/dev/VG/LV"];
3034        ["mount_options"; ""; "/dev/VG/LV"; "/"];
3035        ["cat"; "/new"]], "test content");
3036     InitNone, Always, TestRun (
3037       (* Make an LV smaller to test RHBZ#587484. *)
3038       [["part_disk"; "/dev/sda"; "mbr"];
3039        ["pvcreate"; "/dev/sda1"];
3040        ["vgcreate"; "VG"; "/dev/sda1"];
3041        ["lvcreate"; "LV"; "VG"; "20"];
3042        ["lvresize"; "/dev/VG/LV"; "10"]])],
3043    "resize an LVM logical volume",
3044    "\
3045 This resizes (expands or shrinks) an existing LVM logical
3046 volume to C<mbytes>.  When reducing, data in the reduced part
3047 is lost.");
3048
3049   ("resize2fs", (RErr, [Device "device"]), 106, [],
3050    [], (* lvresize tests this *)
3051    "resize an ext2, ext3 or ext4 filesystem",
3052    "\
3053 This resizes an ext2, ext3 or ext4 filesystem to match the size of
3054 the underlying device.
3055
3056 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
3057 on the C<device> before calling this command.  For unknown reasons
3058 C<resize2fs> sometimes gives an error about this and sometimes not.
3059 In any case, it is always safe to call C<guestfs_e2fsck_f> before
3060 calling this function.");
3061
3062   ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
3063    [InitBasicFS, Always, TestOutputList (
3064       [["find"; "/"]], ["lost+found"]);
3065     InitBasicFS, Always, TestOutputList (
3066       [["touch"; "/a"];
3067        ["mkdir"; "/b"];
3068        ["touch"; "/b/c"];
3069        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
3070     InitBasicFS, Always, TestOutputList (
3071       [["mkdir_p"; "/a/b/c"];
3072        ["touch"; "/a/b/c/d"];
3073        ["find"; "/a/b/"]], ["c"; "c/d"])],
3074    "find all files and directories",
3075    "\
3076 This command lists out all files and directories, recursively,
3077 starting at C<directory>.  It is essentially equivalent to
3078 running the shell command C<find directory -print> but some
3079 post-processing happens on the output, described below.
3080
3081 This returns a list of strings I<without any prefix>.  Thus
3082 if the directory structure was:
3083
3084  /tmp/a
3085  /tmp/b
3086  /tmp/c/d
3087
3088 then the returned list from C<guestfs_find> C</tmp> would be
3089 4 elements:
3090
3091  a
3092  b
3093  c
3094  c/d
3095
3096 If C<directory> is not a directory, then this command returns
3097 an error.
3098
3099 The returned list is sorted.
3100
3101 See also C<guestfs_find0>.");
3102
3103   ("e2fsck_f", (RErr, [Device "device"]), 108, [],
3104    [], (* lvresize tests this *)
3105    "check an ext2/ext3 filesystem",
3106    "\
3107 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
3108 filesystem checker on C<device>, noninteractively (C<-p>),
3109 even if the filesystem appears to be clean (C<-f>).
3110
3111 This command is only needed because of C<guestfs_resize2fs>
3112 (q.v.).  Normally you should use C<guestfs_fsck>.");
3113
3114   ("sleep", (RErr, [Int "secs"]), 109, [],
3115    [InitNone, Always, TestRun (
3116       [["sleep"; "1"]])],
3117    "sleep for some seconds",
3118    "\
3119 Sleep for C<secs> seconds.");
3120
3121   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [Optional "ntfs3g"],
3122    [InitNone, Always, TestOutputInt (
3123       [["part_disk"; "/dev/sda"; "mbr"];
3124        ["mkfs"; "ntfs"; "/dev/sda1"];
3125        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
3126     InitNone, Always, TestOutputInt (
3127       [["part_disk"; "/dev/sda"; "mbr"];
3128        ["mkfs"; "ext2"; "/dev/sda1"];
3129        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
3130    "probe NTFS volume",
3131    "\
3132 This command runs the L<ntfs-3g.probe(8)> command which probes
3133 an NTFS C<device> for mountability.  (Not all NTFS volumes can
3134 be mounted read-write, and some cannot be mounted at all).
3135
3136 C<rw> is a boolean flag.  Set it to true if you want to test
3137 if the volume can be mounted read-write.  Set it to false if
3138 you want to test if the volume can be mounted read-only.
3139
3140 The return value is an integer which C<0> if the operation
3141 would succeed, or some non-zero value documented in the
3142 L<ntfs-3g.probe(8)> manual page.");
3143
3144   ("sh", (RString "output", [String "command"]), 111, [],
3145    [], (* XXX needs tests *)
3146    "run a command via the shell",
3147    "\
3148 This call runs a command from the guest filesystem via the
3149 guest's C</bin/sh>.
3150
3151 This is like C<guestfs_command>, but passes the command to:
3152
3153  /bin/sh -c \"command\"
3154
3155 Depending on the guest's shell, this usually results in
3156 wildcards being expanded, shell expressions being interpolated
3157 and so on.
3158
3159 All the provisos about C<guestfs_command> apply to this call.");
3160
3161   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
3162    [], (* XXX needs tests *)
3163    "run a command via the shell returning lines",
3164    "\
3165 This is the same as C<guestfs_sh>, but splits the result
3166 into a list of lines.
3167
3168 See also: C<guestfs_command_lines>");
3169
3170   ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
3171    (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
3172     * code in stubs.c, since all valid glob patterns must start with "/".
3173     * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
3174     *)
3175    [InitBasicFS, Always, TestOutputList (
3176       [["mkdir_p"; "/a/b/c"];
3177        ["touch"; "/a/b/c/d"];
3178        ["touch"; "/a/b/c/e"];
3179        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3180     InitBasicFS, Always, TestOutputList (
3181       [["mkdir_p"; "/a/b/c"];
3182        ["touch"; "/a/b/c/d"];
3183        ["touch"; "/a/b/c/e"];
3184        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
3185     InitBasicFS, Always, TestOutputList (
3186       [["mkdir_p"; "/a/b/c"];
3187        ["touch"; "/a/b/c/d"];
3188        ["touch"; "/a/b/c/e"];
3189        ["glob_expand"; "/a/*/x/*"]], [])],
3190    "expand a wildcard path",
3191    "\
3192 This command searches for all the pathnames matching
3193 C<pattern> according to the wildcard expansion rules
3194 used by the shell.
3195
3196 If no paths match, then this returns an empty list
3197 (note: not an error).
3198
3199 It is just a wrapper around the C L<glob(3)> function
3200 with flags C<GLOB_MARK|GLOB_BRACE>.
3201 See that manual page for more details.");
3202
3203   ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson; Optional "scrub"],
3204    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
3205       [["scrub_device"; "/dev/sdc"]])],
3206    "scrub (securely wipe) a device",
3207    "\
3208 This command writes patterns over C<device> to make data retrieval
3209 more difficult.
3210
3211 It is an interface to the L<scrub(1)> program.  See that
3212 manual page for more details.");
3213
3214   ("scrub_file", (RErr, [Pathname "file"]), 115, [Optional "scrub"],
3215    [InitBasicFS, Always, TestRun (
3216       [["write"; "/file"; "content"];
3217        ["scrub_file"; "/file"]])],
3218    "scrub (securely wipe) a file",
3219    "\
3220 This command writes patterns over a file to make data retrieval
3221 more difficult.
3222
3223 The file is I<removed> after scrubbing.
3224
3225 It is an interface to the L<scrub(1)> program.  See that
3226 manual page for more details.");
3227
3228   ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [Optional "scrub"],
3229    [], (* XXX needs testing *)
3230    "scrub (securely wipe) free space",
3231    "\
3232 This command creates the directory C<dir> and then fills it
3233 with files until the filesystem is full, and scrubs the files
3234 as for C<guestfs_scrub_file>, and deletes them.
3235 The intention is to scrub any free space on the partition
3236 containing C<dir>.
3237
3238 It is an interface to the L<scrub(1)> program.  See that
3239 manual page for more details.");
3240
3241   ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
3242    [InitBasicFS, Always, TestRun (
3243       [["mkdir"; "/tmp"];
3244        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
3245    "create a temporary directory",
3246    "\
3247 This command creates a temporary directory.  The
3248 C<template> parameter should be a full pathname for the
3249 temporary directory name with the final six characters being
3250 \"XXXXXX\".
3251
3252 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
3253 the second one being suitable for Windows filesystems.
3254
3255 The name of the temporary directory that was created
3256 is returned.
3257
3258 The temporary directory is created with mode 0700
3259 and is owned by root.
3260
3261 The caller is responsible for deleting the temporary
3262 directory and its contents after use.
3263
3264 See also: L<mkdtemp(3)>");
3265
3266   ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
3267    [InitISOFS, Always, TestOutputInt (
3268       [["wc_l"; "/10klines"]], 10000);
3269     (* Test for RHBZ#579608, absolute symbolic links. *)
3270     InitISOFS, Always, TestOutputInt (
3271       [["wc_l"; "/abssymlink"]], 10000)],
3272    "count lines in a file",
3273    "\
3274 This command counts the lines in a file, using the
3275 C<wc -l> external command.");
3276
3277   ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
3278    [InitISOFS, Always, TestOutputInt (
3279       [["wc_w"; "/10klines"]], 10000)],
3280    "count words in a file",
3281    "\
3282 This command counts the words in a file, using the
3283 C<wc -w> external command.");
3284
3285   ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
3286    [InitISOFS, Always, TestOutputInt (
3287       [["wc_c"; "/100kallspaces"]], 102400)],
3288    "count characters in a file",
3289    "\
3290 This command counts the characters in a file, using the
3291 C<wc -c> external command.");
3292
3293   ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
3294    [InitISOFS, Always, TestOutputList (
3295       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"]);
3296     (* Test for RHBZ#579608, absolute symbolic links. *)
3297     InitISOFS, Always, TestOutputList (
3298       [["head"; "/abssymlink"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
3299    "return first 10 lines of a file",
3300    "\
3301 This command returns up to the first 10 lines of a file as
3302 a list of strings.");
3303
3304   ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
3305    [InitISOFS, Always, TestOutputList (
3306       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3307     InitISOFS, Always, TestOutputList (
3308       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
3309     InitISOFS, Always, TestOutputList (
3310       [["head_n"; "0"; "/10klines"]], [])],
3311    "return first N lines of a file",
3312    "\
3313 If the parameter C<nrlines> is a positive number, this returns the first
3314 C<nrlines> lines of the file C<path>.
3315
3316 If the parameter C<nrlines> is a negative number, this returns lines
3317 from the file C<path>, excluding the last C<nrlines> lines.
3318
3319 If the parameter C<nrlines> is zero, this returns an empty list.");
3320
3321   ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
3322    [InitISOFS, Always, TestOutputList (
3323       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
3324    "return last 10 lines of a file",
3325    "\
3326 This command returns up to the last 10 lines of a file as
3327 a list of strings.");
3328
3329   ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
3330    [InitISOFS, Always, TestOutputList (
3331       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3332     InitISOFS, Always, TestOutputList (
3333       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
3334     InitISOFS, Always, TestOutputList (
3335       [["tail_n"; "0"; "/10klines"]], [])],
3336    "return last N lines of a file",
3337    "\
3338 If the parameter C<nrlines> is a positive number, this returns the last
3339 C<nrlines> lines of the file C<path>.
3340
3341 If the parameter C<nrlines> is a negative number, this returns lines
3342 from the file C<path>, starting with the C<-nrlines>th line.
3343
3344 If the parameter C<nrlines> is zero, this returns an empty list.");
3345
3346   ("df", (RString "output", []), 125, [],
3347    [], (* XXX Tricky to test because it depends on the exact format
3348         * of the 'df' command and other imponderables.
3349         *)
3350    "report file system disk space usage",
3351    "\
3352 This command runs the C<df> command to report disk space used.
3353
3354 This command is mostly useful for interactive sessions.  It
3355 is I<not> intended that you try to parse the output string.
3356 Use C<statvfs> from programs.");
3357
3358   ("df_h", (RString "output", []), 126, [],
3359    [], (* XXX Tricky to test because it depends on the exact format
3360         * of the 'df' command and other imponderables.
3361         *)
3362    "report file system disk space usage (human readable)",
3363    "\
3364 This command runs the C<df -h> command to report disk space used
3365 in human-readable format.
3366
3367 This command is mostly useful for interactive sessions.  It
3368 is I<not> intended that you try to parse the output string.
3369 Use C<statvfs> from programs.");
3370
3371   ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
3372    [InitISOFS, Always, TestOutputInt (
3373       [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
3374    "estimate file space usage",
3375    "\
3376 This command runs the C<du -s> command to estimate file space
3377 usage for C<path>.
3378
3379 C<path> can be a file or a directory.  If C<path> is a directory
3380 then the estimate includes the contents of the directory and all
3381 subdirectories (recursively).
3382
3383 The result is the estimated size in I<kilobytes>
3384 (ie. units of 1024 bytes).");
3385
3386   ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
3387    [InitISOFS, Always, TestOutputList (
3388       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
3389    "list files in an initrd",
3390    "\
3391 This command lists out files contained in an initrd.
3392
3393 The files are listed without any initial C</> character.  The
3394 files are listed in the order they appear (not necessarily
3395 alphabetical).  Directory names are listed as separate items.
3396
3397 Old Linux kernels (2.4 and earlier) used a compressed ext2
3398 filesystem as initrd.  We I<only> support the newer initramfs
3399 format (compressed cpio files).");
3400
3401   ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
3402    [],
3403    "mount a file using the loop device",
3404    "\
3405 This command lets you mount C<file> (a filesystem image
3406 in a file) on a mount point.  It is entirely equivalent to
3407 the command C<mount -o loop file mountpoint>.");
3408
3409   ("mkswap", (RErr, [Device "device"]), 130, [],
3410    [InitEmpty, Always, TestRun (
3411       [["part_disk"; "/dev/sda"; "mbr"];
3412        ["mkswap"; "/dev/sda1"]])],
3413    "create a swap partition",
3414    "\
3415 Create a swap partition on C<device>.");
3416
3417   ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
3418    [InitEmpty, Always, TestRun (
3419       [["part_disk"; "/dev/sda"; "mbr"];
3420        ["mkswap_L"; "hello"; "/dev/sda1"]])],
3421    "create a swap partition with a label",
3422    "\
3423 Create a swap partition on C<device> with label C<label>.
3424
3425 Note that you cannot attach a swap label to a block device
3426 (eg. C</dev/sda>), just to a partition.  This appears to be
3427 a limitation of the kernel or swap tools.");
3428
3429   ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [Optional "linuxfsuuid"],
3430    (let uuid = uuidgen () in
3431     [InitEmpty, Always, TestRun (
3432        [["part_disk"; "/dev/sda"; "mbr"];
3433         ["mkswap_U"; uuid; "/dev/sda1"]])]),
3434    "create a swap partition with an explicit UUID",
3435    "\
3436 Create a swap partition on C<device> with UUID C<uuid>.");
3437
3438   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [Optional "mknod"],
3439    [InitBasicFS, Always, TestOutputStruct (
3440       [["mknod"; "0o10777"; "0"; "0"; "/node"];
3441        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
3442        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
3443     InitBasicFS, Always, TestOutputStruct (
3444       [["mknod"; "0o60777"; "66"; "99"; "/node"];
3445        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3446    "make block, character or FIFO devices",
3447    "\
3448 This call creates block or character special devices, or
3449 named pipes (FIFOs).
3450
3451 The C<mode> parameter should be the mode, using the standard
3452 constants.  C<devmajor> and C<devminor> are the
3453 device major and minor numbers, only used when creating block
3454 and character special devices.
3455
3456 Note that, just like L<mknod(2)>, the mode must be bitwise
3457 OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK (otherwise this call
3458 just creates a regular file).  These constants are
3459 available in the standard Linux header files, or you can use
3460 C<guestfs_mknod_b>, C<guestfs_mknod_c> or C<guestfs_mkfifo>
3461 which are wrappers around this command which bitwise OR
3462 in the appropriate constant for you.
3463
3464 The mode actually set is affected by the umask.");
3465
3466   ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [Optional "mknod"],
3467    [InitBasicFS, Always, TestOutputStruct (
3468       [["mkfifo"; "0o777"; "/node"];
3469        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
3470    "make FIFO (named pipe)",
3471    "\
3472 This call creates a FIFO (named pipe) called C<path> with
3473 mode C<mode>.  It is just a convenient wrapper around
3474 C<guestfs_mknod>.
3475
3476 The mode actually set is affected by the umask.");
3477
3478   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [Optional "mknod"],
3479    [InitBasicFS, Always, TestOutputStruct (
3480       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
3481        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
3482    "make block device node",
3483    "\
3484 This call creates a block device node called C<path> with
3485 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3486 It is just a convenient wrapper around C<guestfs_mknod>.
3487
3488 The mode actually set is affected by the umask.");
3489
3490   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [Optional "mknod"],
3491    [InitBasicFS, Always, TestOutputStruct (
3492       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
3493        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
3494    "make char device node",
3495    "\
3496 This call creates a char device node called C<path> with
3497 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
3498 It is just a convenient wrapper around C<guestfs_mknod>.
3499
3500 The mode actually set is affected by the umask.");
3501
3502   ("umask", (RInt "oldmask", [Int "mask"]), 137, [FishOutput FishOutputOctal],
3503    [InitEmpty, Always, TestOutputInt (
3504       [["umask"; "0o22"]], 0o22)],
3505    "set file mode creation mask (umask)",
3506    "\
3507 This function sets the mask used for creating new files and
3508 device nodes to C<mask & 0777>.
3509
3510 Typical umask values would be C<022> which creates new files
3511 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
3512 C<002> which creates new files with permissions like
3513 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
3514
3515 The default umask is C<022>.  This is important because it
3516 means that directories and device nodes will be created with
3517 C<0644> or C<0755> mode even if you specify C<0777>.
3518
3519 See also C<guestfs_get_umask>,
3520 L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
3521
3522 This call returns the previous umask.");
3523
3524   ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
3525    [],
3526    "read directories entries",
3527    "\
3528 This returns the list of directory entries in directory C<dir>.
3529
3530 All entries in the directory are returned, including C<.> and
3531 C<..>.  The entries are I<not> sorted, but returned in the same
3532 order as the underlying filesystem.
3533
3534 Also this call returns basic file type information about each
3535 file.  The C<ftyp> field will contain one of the following characters:
3536
3537 =over 4
3538
3539 =item 'b'
3540
3541 Block special
3542
3543 =item 'c'
3544
3545 Char special
3546
3547 =item 'd'
3548
3549 Directory
3550
3551 =item 'f'
3552
3553 FIFO (named pipe)
3554
3555 =item 'l'
3556
3557 Symbolic link
3558
3559 =item 'r'
3560
3561 Regular file
3562
3563 =item 's'
3564
3565 Socket
3566
3567 =item 'u'
3568
3569 Unknown file type
3570
3571 =item '?'
3572
3573 The L<readdir(3)> call returned a C<d_type> field with an
3574 unexpected value
3575
3576 =back
3577
3578 This function is primarily intended for use by programs.  To
3579 get a simple list of names, use C<guestfs_ls>.  To get a printable
3580 directory for human consumption, use C<guestfs_ll>.");
3581
3582   ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3583    [],
3584    "create partitions on a block device",
3585    "\
3586 This is a simplified interface to the C<guestfs_sfdisk>
3587 command, where partition sizes are specified in megabytes
3588 only (rounded to the nearest cylinder) and you don't need
3589 to specify the cyls, heads and sectors parameters which
3590 were rarely if ever used anyway.
3591
3592 See also: C<guestfs_sfdisk>, the L<sfdisk(8)> manpage
3593 and C<guestfs_part_disk>");
3594
3595   ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3596    [],
3597    "determine file type inside a compressed file",
3598    "\
3599 This command runs C<file> after first decompressing C<path>
3600 using C<method>.
3601
3602 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3603
3604 Since 1.0.63, use C<guestfs_file> instead which can now
3605 process compressed files.");
3606
3607   ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [Optional "linuxxattrs"],
3608    [],
3609    "list extended attributes of a file or directory",
3610    "\
3611 This call lists the extended attributes of the file or directory
3612 C<path>.
3613
3614 At the system call level, this is a combination of the
3615 L<listxattr(2)> and L<getxattr(2)> calls.
3616
3617 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3618
3619   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [Optional "linuxxattrs"],
3620    [],
3621    "list extended attributes of a file or directory",
3622    "\
3623 This is the same as C<guestfs_getxattrs>, but if C<path>
3624 is a symbolic link, then it returns the extended attributes
3625 of the link itself.");
3626
3627   ("setxattr", (RErr, [String "xattr";
3628                        String "val"; Int "vallen"; (* will be BufferIn *)
3629                        Pathname "path"]), 143, [Optional "linuxxattrs"],
3630    [],
3631    "set extended attribute of a file or directory",
3632    "\
3633 This call sets the extended attribute named C<xattr>
3634 of the file C<path> to the value C<val> (of length C<vallen>).
3635 The value is arbitrary 8 bit data.
3636
3637 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3638
3639   ("lsetxattr", (RErr, [String "xattr";
3640                         String "val"; Int "vallen"; (* will be BufferIn *)
3641                         Pathname "path"]), 144, [Optional "linuxxattrs"],
3642    [],
3643    "set extended attribute of a file or directory",
3644    "\
3645 This is the same as C<guestfs_setxattr>, but if C<path>
3646 is a symbolic link, then it sets an extended attribute
3647 of the link itself.");
3648
3649   ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [Optional "linuxxattrs"],
3650    [],
3651    "remove extended attribute of a file or directory",
3652    "\
3653 This call removes the extended attribute named C<xattr>
3654 of the file C<path>.
3655
3656 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3657
3658   ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [Optional "linuxxattrs"],
3659    [],
3660    "remove extended attribute of a file or directory",
3661    "\
3662 This is the same as C<guestfs_removexattr>, but if C<path>
3663 is a symbolic link, then it removes an extended attribute
3664 of the link itself.");
3665
3666   ("mountpoints", (RHashtable "mps", []), 147, [],
3667    [],
3668    "show mountpoints",
3669    "\
3670 This call is similar to C<guestfs_mounts>.  That call returns
3671 a list of devices.  This one returns a hash table (map) of
3672 device name to directory where the device is mounted.");
3673
3674   ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3675    (* This is a special case: while you would expect a parameter
3676     * of type "Pathname", that doesn't work, because it implies
3677     * NEED_ROOT in the generated calling code in stubs.c, and
3678     * this function cannot use NEED_ROOT.
3679     *)
3680    [],
3681    "create a mountpoint",
3682    "\
3683 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3684 specialized calls that can be used to create extra mountpoints
3685 before mounting the first filesystem.
3686
3687 These calls are I<only> necessary in some very limited circumstances,
3688 mainly the case where you want to mount a mix of unrelated and/or
3689 read-only filesystems together.
3690
3691 For example, live CDs often contain a \"Russian doll\" nest of
3692 filesystems, an ISO outer layer, with a squashfs image inside, with
3693 an ext2/3 image inside that.  You can unpack this as follows
3694 in guestfish:
3695
3696  add-ro Fedora-11-i686-Live.iso
3697  run
3698  mkmountpoint /cd
3699  mkmountpoint /squash
3700  mkmountpoint /ext3
3701  mount /dev/sda /cd
3702  mount-loop /cd/LiveOS/squashfs.img /squash
3703  mount-loop /squash/LiveOS/ext3fs.img /ext3
3704
3705 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3706
3707   ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3708    [],
3709    "remove a mountpoint",
3710    "\
3711 This calls removes a mountpoint that was previously created
3712 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3713 for full details.");
3714
3715   ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3716    [InitISOFS, Always, TestOutputBuffer (
3717       [["read_file"; "/known-4"]], "abc\ndef\nghi");
3718     (* Test various near large, large and too large files (RHBZ#589039). *)
3719     InitBasicFS, Always, TestLastFail (
3720       [["touch"; "/a"];
3721        ["truncate_size"; "/a"; "4194303"]; (* GUESTFS_MESSAGE_MAX - 1 *)
3722        ["read_file"; "/a"]]);
3723     InitBasicFS, Always, TestLastFail (
3724       [["touch"; "/a"];
3725        ["truncate_size"; "/a"; "4194304"]; (* GUESTFS_MESSAGE_MAX *)
3726        ["read_file"; "/a"]]);
3727     InitBasicFS, Always, TestLastFail (
3728       [["touch"; "/a"];
3729        ["truncate_size"; "/a"; "41943040"]; (* GUESTFS_MESSAGE_MAX * 10 *)
3730        ["read_file"; "/a"]])],
3731    "read a file",
3732    "\
3733 This calls returns the contents of the file C<path> as a
3734 buffer.
3735
3736 Unlike C<guestfs_cat>, this function can correctly
3737 handle files that contain embedded ASCII NUL characters.
3738 However unlike C<guestfs_download>, this function is limited
3739 in the total size of file that can be handled.");
3740
3741   ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3742    [InitISOFS, Always, TestOutputList (
3743       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3744     InitISOFS, Always, TestOutputList (
3745       [["grep"; "nomatch"; "/test-grep.txt"]], []);
3746     (* Test for RHBZ#579608, absolute symbolic links. *)
3747     InitISOFS, Always, TestOutputList (
3748       [["grep"; "nomatch"; "/abssymlink"]], [])],
3749    "return lines matching a pattern",
3750    "\
3751 This calls the external C<grep> program and returns the
3752 matching lines.");
3753
3754   ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3755    [InitISOFS, Always, TestOutputList (
3756       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3757    "return lines matching a pattern",
3758    "\
3759 This calls the external C<egrep> program and returns the
3760 matching lines.");
3761
3762   ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3763    [InitISOFS, Always, TestOutputList (
3764       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3765    "return lines matching a pattern",
3766    "\
3767 This calls the external C<fgrep> program and returns the
3768 matching lines.");
3769
3770   ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3771    [InitISOFS, Always, TestOutputList (
3772       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3773    "return lines matching a pattern",
3774    "\
3775 This calls the external C<grep -i> program and returns the
3776 matching lines.");
3777
3778   ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3779    [InitISOFS, Always, TestOutputList (
3780       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3781    "return lines matching a pattern",
3782    "\
3783 This calls the external C<egrep -i> program and returns the
3784 matching lines.");
3785
3786   ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3787    [InitISOFS, Always, TestOutputList (
3788       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3789    "return lines matching a pattern",
3790    "\
3791 This calls the external C<fgrep -i> program and returns the
3792 matching lines.");
3793
3794   ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3795    [InitISOFS, Always, TestOutputList (
3796       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3797    "return lines matching a pattern",
3798    "\
3799 This calls the external C<zgrep> program and returns the
3800 matching lines.");
3801
3802   ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3803    [InitISOFS, Always, TestOutputList (
3804       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3805    "return lines matching a pattern",
3806    "\
3807 This calls the external C<zegrep> program and returns the
3808 matching lines.");
3809
3810   ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3811    [InitISOFS, Always, TestOutputList (
3812       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3813    "return lines matching a pattern",
3814    "\
3815 This calls the external C<zfgrep> program and returns the
3816 matching lines.");
3817
3818   ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3819    [InitISOFS, Always, TestOutputList (
3820       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3821    "return lines matching a pattern",
3822    "\
3823 This calls the external C<zgrep -i> program and returns the
3824 matching lines.");
3825
3826   ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3827    [InitISOFS, Always, TestOutputList (
3828       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3829    "return lines matching a pattern",
3830    "\
3831 This calls the external C<zegrep -i> program and returns the
3832 matching lines.");
3833
3834   ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3835    [InitISOFS, Always, TestOutputList (
3836       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3837    "return lines matching a pattern",
3838    "\
3839 This calls the external C<zfgrep -i> program and returns the
3840 matching lines.");
3841
3842   ("realpath", (RString "rpath", [Pathname "path"]), 163, [Optional "realpath"],
3843    [InitISOFS, Always, TestOutput (
3844       [["realpath"; "/../directory"]], "/directory")],
3845    "canonicalized absolute pathname",
3846    "\
3847 Return the canonicalized absolute pathname of C<path>.  The
3848 returned path has no C<.>, C<..> or symbolic link path elements.");
3849
3850   ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3851    [InitBasicFS, Always, TestOutputStruct (
3852       [["touch"; "/a"];
3853        ["ln"; "/a"; "/b"];
3854        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3855    "create a hard link",
3856    "\
3857 This command creates a hard link using the C<ln> command.");
3858
3859   ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3860    [InitBasicFS, Always, TestOutputStruct (
3861       [["touch"; "/a"];
3862        ["touch"; "/b"];
3863        ["ln_f"; "/a"; "/b"];
3864        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3865    "create a hard link",
3866    "\
3867 This command creates a hard link using the C<ln -f> command.
3868 The C<-f> option removes the link (C<linkname>) if it exists already.");
3869
3870   ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3871    [InitBasicFS, Always, TestOutputStruct (
3872       [["touch"; "/a"];
3873        ["ln_s"; "a"; "/b"];
3874        ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3875    "create a symbolic link",
3876    "\
3877 This command creates a symbolic link using the C<ln -s> command.");
3878
3879   ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3880    [InitBasicFS, Always, TestOutput (
3881       [["mkdir_p"; "/a/b"];
3882        ["touch"; "/a/b/c"];
3883        ["ln_sf"; "../d"; "/a/b/c"];
3884        ["readlink"; "/a/b/c"]], "../d")],
3885    "create a symbolic link",
3886    "\
3887 This command creates a symbolic link using the C<ln -sf> command,
3888 The C<-f> option removes the link (C<linkname>) if it exists already.");
3889
3890   ("readlink", (RString "link", [Pathname "path"]), 168, [],
3891    [] (* XXX tested above *),
3892    "read the target of a symbolic link",
3893    "\
3894 This command reads the target of a symbolic link.");
3895
3896   ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [DeprecatedBy "fallocate64"],
3897    [InitBasicFS, Always, TestOutputStruct (
3898       [["fallocate"; "/a"; "1000000"];
3899        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3900    "preallocate a file in the guest filesystem",
3901    "\
3902 This command preallocates a file (containing zero bytes) named
3903 C<path> of size C<len> bytes.  If the file exists already, it
3904 is overwritten.
3905
3906 Do not confuse this with the guestfish-specific
3907 C<alloc> command which allocates a file in the host and
3908 attaches it as a device.");
3909
3910   ("swapon_device", (RErr, [Device "device"]), 170, [],
3911    [InitPartition, Always, TestRun (
3912       [["mkswap"; "/dev/sda1"];
3913        ["swapon_device"; "/dev/sda1"];
3914        ["swapoff_device"; "/dev/sda1"]])],
3915    "enable swap on device",
3916    "\
3917 This command enables the libguestfs appliance to use the
3918 swap device or partition named C<device>.  The increased
3919 memory is made available for all commands, for example
3920 those run using C<guestfs_command> or C<guestfs_sh>.
3921
3922 Note that you should not swap to existing guest swap
3923 partitions unless you know what you are doing.  They may
3924 contain hibernation information, or other information that
3925 the guest doesn't want you to trash.  You also risk leaking
3926 information about the host to the guest this way.  Instead,
3927 attach a new host device to the guest and swap on that.");
3928
3929   ("swapoff_device", (RErr, [Device "device"]), 171, [],
3930    [], (* XXX tested by swapon_device *)
3931    "disable swap on device",
3932    "\
3933 This command disables the libguestfs appliance swap
3934 device or partition named C<device>.
3935 See C<guestfs_swapon_device>.");
3936
3937   ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3938    [InitBasicFS, Always, TestRun (
3939       [["fallocate"; "/swap"; "8388608"];
3940        ["mkswap_file"; "/swap"];
3941        ["swapon_file"; "/swap"];
3942        ["swapoff_file"; "/swap"]])],
3943    "enable swap on file",
3944    "\
3945 This command enables swap to a file.
3946 See C<guestfs_swapon_device> for other notes.");
3947
3948   ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3949    [], (* XXX tested by swapon_file *)
3950    "disable swap on file",
3951    "\
3952 This command disables the libguestfs appliance swap on file.");
3953
3954   ("swapon_label", (RErr, [String "label"]), 174, [],
3955    [InitEmpty, Always, TestRun (
3956       [["part_disk"; "/dev/sdb"; "mbr"];
3957        ["mkswap_L"; "swapit"; "/dev/sdb1"];
3958        ["swapon_label"; "swapit"];
3959        ["swapoff_label"; "swapit"];
3960        ["zero"; "/dev/sdb"];
3961        ["blockdev_rereadpt"; "/dev/sdb"]])],
3962    "enable swap on labeled swap partition",
3963    "\
3964 This command enables swap to a labeled swap partition.
3965 See C<guestfs_swapon_device> for other notes.");
3966
3967   ("swapoff_label", (RErr, [String "label"]), 175, [],
3968    [], (* XXX tested by swapon_label *)
3969    "disable swap on labeled swap partition",
3970    "\
3971 This command disables the libguestfs appliance swap on
3972 labeled swap partition.");
3973
3974   ("swapon_uuid", (RErr, [String "uuid"]), 176, [Optional "linuxfsuuid"],
3975    (let uuid = uuidgen () in
3976     [InitEmpty, Always, TestRun (
3977        [["mkswap_U"; uuid; "/dev/sdb"];
3978         ["swapon_uuid"; uuid];
3979         ["swapoff_uuid"; uuid]])]),
3980    "enable swap on swap partition by UUID",
3981    "\
3982 This command enables swap to a swap partition with the given UUID.
3983 See C<guestfs_swapon_device> for other notes.");
3984
3985   ("swapoff_uuid", (RErr, [String "uuid"]), 177, [Optional "linuxfsuuid"],
3986    [], (* XXX tested by swapon_uuid *)
3987    "disable swap on swap partition by UUID",
3988    "\
3989 This command disables the libguestfs appliance swap partition
3990 with the given UUID.");
3991
3992   ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3993    [InitBasicFS, Always, TestRun (
3994       [["fallocate"; "/swap"; "8388608"];
3995        ["mkswap_file"; "/swap"]])],
3996    "create a swap file",
3997    "\
3998 Create a swap file.
3999
4000 This command just writes a swap file signature to an existing
4001 file.  To create the file itself, use something like C<guestfs_fallocate>.");
4002
4003   ("inotify_init", (RErr, [Int "maxevents"]), 179, [Optional "inotify"],
4004    [InitISOFS, Always, TestRun (
4005       [["inotify_init"; "0"]])],
4006    "create an inotify handle",
4007    "\
4008 This command creates a new inotify handle.
4009 The inotify subsystem can be used to notify events which happen to
4010 objects in the guest filesystem.
4011
4012 C<maxevents> is the maximum number of events which will be
4013 queued up between calls to C<guestfs_inotify_read> or
4014 C<guestfs_inotify_files>.
4015 If this is passed as C<0>, then the kernel (or previously set)
4016 default is used.  For Linux 2.6.29 the default was 16384 events.
4017 Beyond this limit, the kernel throws away events, but records
4018 the fact that it threw them away by setting a flag
4019 C<IN_Q_OVERFLOW> in the returned structure list (see
4020 C<guestfs_inotify_read>).
4021
4022 Before any events are generated, you have to add some
4023 watches to the internal watch list.  See:
4024 C<guestfs_inotify_add_watch>,
4025 C<guestfs_inotify_rm_watch> and
4026 C<guestfs_inotify_watch_all>.
4027
4028 Queued up events should be read periodically by calling
4029 C<guestfs_inotify_read>
4030 (or C<guestfs_inotify_files> which is just a helpful
4031 wrapper around C<guestfs_inotify_read>).  If you don't
4032 read the events out often enough then you risk the internal
4033 queue overflowing.
4034
4035 The handle should be closed after use by calling
4036 C<guestfs_inotify_close>.  This also removes any
4037 watches automatically.
4038
4039 See also L<inotify(7)> for an overview of the inotify interface
4040 as exposed by the Linux kernel, which is roughly what we expose
4041 via libguestfs.  Note that there is one global inotify handle
4042 per libguestfs instance.");
4043
4044   ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [Optional "inotify"],
4045    [InitBasicFS, Always, TestOutputList (
4046       [["inotify_init"; "0"];
4047        ["inotify_add_watch"; "/"; "1073741823"];
4048        ["touch"; "/a"];
4049        ["touch"; "/b"];
4050        ["inotify_files"]], ["a"; "b"])],
4051    "add an inotify watch",
4052    "\
4053 Watch C<path> for the events listed in C<mask>.
4054
4055 Note that if C<path> is a directory then events within that
4056 directory are watched, but this does I<not> happen recursively
4057 (in subdirectories).
4058
4059 Note for non-C or non-Linux callers: the inotify events are
4060 defined by the Linux kernel ABI and are listed in
4061 C</usr/include/sys/inotify.h>.");
4062
4063   ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [Optional "inotify"],
4064    [],
4065    "remove an inotify watch",
4066    "\
4067 Remove a previously defined inotify watch.
4068 See C<guestfs_inotify_add_watch>.");
4069
4070   ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [Optional "inotify"],
4071    [],
4072    "return list of inotify events",
4073    "\
4074 Return the complete queue of events that have happened
4075 since the previous read call.
4076
4077 If no events have happened, this returns an empty list.
4078
4079 I<Note>: In order to make sure that all events have been
4080 read, you must call this function repeatedly until it
4081 returns an empty list.  The reason is that the call will
4082 read events up to the maximum appliance-to-host message
4083 size and leave remaining events in the queue.");
4084
4085   ("inotify_files", (RStringList "paths", []), 183, [Optional "inotify"],
4086    [],
4087    "return list of watched files that had events",
4088    "\
4089 This function is a helpful wrapper around C<guestfs_inotify_read>
4090 which just returns a list of pathnames of objects that were
4091 touched.  The returned pathnames are sorted and deduplicated.");
4092
4093   ("inotify_close", (RErr, []), 184, [Optional "inotify"],
4094    [],
4095    "close the inotify handle",
4096    "\
4097 This closes the inotify handle which was previously
4098 opened by inotify_init.  It removes all watches, throws
4099 away any pending events, and deallocates all resources.");
4100
4101   ("setcon", (RErr, [String "context"]), 185, [Optional "selinux"],
4102    [],
4103    "set SELinux security context",
4104    "\
4105 This sets the SELinux security context of the daemon
4106 to the string C<context>.
4107
4108 See the documentation about SELINUX in L<guestfs(3)>.");
4109
4110   ("getcon", (RString "context", []), 186, [Optional "selinux"],
4111    [],
4112    "get SELinux security context",
4113    "\
4114 This gets the SELinux security context of the daemon.
4115
4116 See the documentation about SELINUX in L<guestfs(3)>,
4117 and C<guestfs_setcon>");
4118
4119   ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
4120    [InitEmpty, Always, TestOutput (
4121       [["part_disk"; "/dev/sda"; "mbr"];
4122        ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
4123        ["mount_options"; ""; "/dev/sda1"; "/"];
4124        ["write"; "/new"; "new file contents"];
4125        ["cat"; "/new"]], "new file contents");
4126     InitEmpty, Always, TestRun (
4127       [["part_disk"; "/dev/sda"; "mbr"];
4128        ["mkfs_b"; "vfat"; "32768"; "/dev/sda1"]]);
4129     InitEmpty, Always, TestLastFail (
4130       [["part_disk"; "/dev/sda"; "mbr"];
4131        ["mkfs_b"; "vfat"; "32769"; "/dev/sda1"]]);
4132     InitEmpty, Always, TestLastFail (
4133       [["part_disk"; "/dev/sda"; "mbr"];
4134        ["mkfs_b"; "vfat"; "33280"; "/dev/sda1"]]);
4135     InitEmpty, IfAvailable "ntfsprogs", TestRun (
4136       [["part_disk"; "/dev/sda"; "mbr"];
4137        ["mkfs_b"; "ntfs"; "32768"; "/dev/sda1"]])],
4138    "make a filesystem with block size",
4139    "\
4140 This call is similar to C<guestfs_mkfs>, but it allows you to
4141 control the block size of the resulting filesystem.  Supported
4142 block sizes depend on the filesystem type, but typically they
4143 are C<1024>, C<2048> or C<4096> only.
4144
4145 For VFAT and NTFS the C<blocksize> parameter is treated as
4146 the requested cluster size.");
4147
4148   ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
4149    [InitEmpty, Always, TestOutput (
4150       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4151        ["mke2journal"; "4096"; "/dev/sda1"];
4152        ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
4153        ["mount_options"; ""; "/dev/sda2"; "/"];
4154        ["write"; "/new"; "new file contents"];
4155        ["cat"; "/new"]], "new file contents")],
4156    "make ext2/3/4 external journal",
4157    "\
4158 This creates an ext2 external journal on C<device>.  It is equivalent
4159 to the command:
4160
4161  mke2fs -O journal_dev -b blocksize device");
4162
4163   ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
4164    [InitEmpty, Always, TestOutput (
4165       [["sfdiskM"; "/dev/sda"; ",100 ,"];
4166        ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
4167        ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
4168        ["mount_options"; ""; "/dev/sda2"; "/"];
4169        ["write"; "/new"; "new file contents"];
4170        ["cat"; "/new"]], "new file contents")],
4171    "make ext2/3/4 external journal with label",
4172    "\
4173 This creates an ext2 external journal on C<device> with label C<label>.");
4174
4175   ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [Optional "linuxfsuuid"],
4176    (let uuid = uuidgen () in
4177     [InitEmpty, Always, TestOutput (
4178        [["sfdiskM"; "/dev/sda"; ",100 ,"];
4179         ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
4180         ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
4181         ["mount_options"; ""; "/dev/sda2"; "/"];
4182         ["write"; "/new"; "new file contents"];
4183         ["cat"; "/new"]], "new file contents")]),
4184    "make ext2/3/4 external journal with UUID",
4185    "\
4186 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
4187
4188   ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
4189    [],
4190    "make ext2/3/4 filesystem with external journal",
4191    "\
4192 This creates an ext2/3/4 filesystem on C<device> with
4193 an external journal on C<journal>.  It is equivalent
4194 to the command:
4195
4196  mke2fs -t fstype -b blocksize -J device=<journal> <device>
4197
4198 See also C<guestfs_mke2journal>.");
4199
4200   ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
4201    [],
4202    "make ext2/3/4 filesystem with external journal",
4203    "\
4204 This creates an ext2/3/4 filesystem on C<device> with
4205 an external journal on the journal labeled C<label>.
4206
4207 See also C<guestfs_mke2journal_L>.");
4208
4209   ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [Optional "linuxfsuuid"],
4210    [],
4211    "make ext2/3/4 filesystem with external journal",
4212    "\
4213 This creates an ext2/3/4 filesystem on C<device> with
4214 an external journal on the journal with UUID C<uuid>.
4215
4216 See also C<guestfs_mke2journal_U>.");
4217
4218   ("modprobe", (RErr, [String "modulename"]), 194, [Optional "linuxmodules"],
4219    [InitNone, Always, TestRun [["modprobe"; "fat"]]],
4220    "load a kernel module",
4221    "\
4222 This loads a kernel module in the appliance.
4223
4224 The kernel module must have been whitelisted when libguestfs
4225 was built (see C<appliance/kmod.whitelist.in> in the source).");
4226
4227   ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
4228    [InitNone, Always, TestOutput (
4229       [["echo_daemon"; "This is a test"]], "This is a test"
4230     )],
4231    "echo arguments back to the client",
4232    "\
4233 This command concatenates the list of C<words> passed with single spaces
4234 between them and returns the resulting string.
4235
4236 You can use this command to test the connection through to the daemon.
4237
4238 See also C<guestfs_ping_daemon>.");
4239
4240   ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
4241    [], (* There is a regression test for this. *)
4242    "find all files and directories, returning NUL-separated list",
4243    "\
4244 This command lists out all files and directories, recursively,
4245 starting at C<directory>, placing the resulting list in the
4246 external file called C<files>.
4247
4248 This command works the same way as C<guestfs_find> with the
4249 following exceptions:
4250
4251 =over 4
4252
4253 =item *
4254
4255 The resulting list is written to an external file.
4256
4257 =item *
4258
4259 Items (filenames) in the result are separated
4260 by C<\\0> characters.  See L<find(1)> option I<-print0>.
4261
4262 =item *
4263
4264 This command is not limited in the number of names that it
4265 can return.
4266
4267 =item *
4268
4269 The result list is not sorted.
4270
4271 =back");
4272
4273   ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
4274    [InitISOFS, Always, TestOutput (
4275       [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
4276     InitISOFS, Always, TestOutput (
4277       [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
4278     InitISOFS, Always, TestOutput (
4279       [["case_sensitive_path"; "/Known-1"]], "/known-1");
4280     InitISOFS, Always, TestLastFail (
4281       [["case_sensitive_path"; "/Known-1/"]]);
4282     InitBasicFS, Always, TestOutput (
4283       [["mkdir"; "/a"];
4284        ["mkdir"; "/a/bbb"];
4285        ["touch"; "/a/bbb/c"];
4286        ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
4287     InitBasicFS, Always, TestOutput (
4288       [["mkdir"; "/a"];
4289        ["mkdir"; "/a/bbb"];
4290        ["touch"; "/a/bbb/c"];
4291        ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
4292     InitBasicFS, Always, TestLastFail (
4293       [["mkdir"; "/a"];
4294        ["mkdir"; "/a/bbb"];
4295        ["touch"; "/a/bbb/c"];
4296        ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
4297    "return true path on case-insensitive filesystem",
4298    "\
4299 This can be used to resolve case insensitive paths on
4300 a filesystem which is case sensitive.  The use case is
4301 to resolve paths which you have read from Windows configuration
4302 files or the Windows Registry, to the true path.
4303
4304 The command handles a peculiarity of the Linux ntfs-3g
4305 filesystem driver (and probably others), which is that although
4306 the underlying filesystem is case-insensitive, the driver
4307 exports the filesystem to Linux as case-sensitive.
4308
4309 One consequence of this is that special directories such
4310 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
4311 (or other things) depending on the precise details of how
4312 they were created.  In Windows itself this would not be
4313 a problem.
4314
4315 Bug or feature?  You decide:
4316 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
4317
4318 This function resolves the true case of each element in the
4319 path and returns the case-sensitive path.
4320
4321 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
4322 might return C<\"/WINDOWS/system32\"> (the exact return value
4323 would depend on details of how the directories were originally
4324 created under Windows).
4325
4326 I<Note>:
4327 This function does not handle drive names, backslashes etc.
4328
4329 See also C<guestfs_realpath>.");
4330
4331   ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
4332    [InitBasicFS, Always, TestOutput (
4333       [["vfs_type"; "/dev/sda1"]], "ext2")],
4334    "get the Linux VFS type corresponding to a mounted device",
4335    "\
4336 This command gets the filesystem type corresponding to
4337 the filesystem on C<device>.
4338
4339 For most filesystems, the result is the name of the Linux
4340 VFS module which would be used to mount this filesystem
4341 if you mounted it without specifying the filesystem type.
4342 For example a string such as C<ext3> or C<ntfs>.");
4343
4344   ("truncate", (RErr, [Pathname "path"]), 199, [],
4345    [InitBasicFS, Always, TestOutputStruct (
4346       [["write"; "/test"; "some stuff so size is not zero"];
4347        ["truncate"; "/test"];
4348        ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
4349    "truncate a file to zero size",
4350    "\
4351 This command truncates C<path> to a zero-length file.  The
4352 file must exist already.");
4353
4354   ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
4355    [InitBasicFS, Always, TestOutputStruct (
4356       [["touch"; "/test"];
4357        ["truncate_size"; "/test"; "1000"];
4358        ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
4359    "truncate a file to a particular size",
4360    "\
4361 This command truncates C<path> to size C<size> bytes.  The file
4362 must exist already.
4363
4364 If the current file size is less than C<size> then
4365 the file is extended to the required size with zero bytes.
4366 This creates a sparse file (ie. disk blocks are not allocated
4367 for the file until you write to it).  To create a non-sparse
4368 file of zeroes, use C<guestfs_fallocate64> instead.");
4369
4370   ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
4371    [InitBasicFS, Always, TestOutputStruct (
4372       [["touch"; "/test"];
4373        ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
4374        ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
4375    "set timestamp of a file with nanosecond precision",
4376    "\
4377 This command sets the timestamps of a file with nanosecond
4378 precision.
4379
4380 C<atsecs, atnsecs> are the last access time (atime) in secs and
4381 nanoseconds from the epoch.
4382
4383 C<mtsecs, mtnsecs> are the last modification time (mtime) in
4384 secs and nanoseconds from the epoch.
4385
4386 If the C<*nsecs> field contains the special value C<-1> then
4387 the corresponding timestamp is set to the current time.  (The
4388 C<*secs> field is ignored in this case).
4389
4390 If the C<*nsecs> field contains the special value C<-2> then
4391 the corresponding timestamp is left unchanged.  (The
4392 C<*secs> field is ignored in this case).");
4393
4394   ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
4395    [InitBasicFS, Always, TestOutputStruct (
4396       [["mkdir_mode"; "/test"; "0o111"];
4397        ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
4398    "create a directory with a particular mode",
4399    "\
4400 This command creates a directory, setting the initial permissions
4401 of the directory to C<mode>.
4402
4403 For common Linux filesystems, the actual mode which is set will
4404 be C<mode & ~umask & 01777>.  Non-native-Linux filesystems may
4405 interpret the mode in other ways.
4406
4407 See also C<guestfs_mkdir>, C<guestfs_umask>");
4408
4409   ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
4410    [], (* XXX *)
4411    "change file owner and group",
4412    "\
4413 Change the file owner to C<owner> and group to C<group>.
4414 This is like C<guestfs_chown> but if C<path> is a symlink then
4415 the link itself is changed, not the target.
4416
4417 Only numeric uid and gid are supported.  If you want to use
4418 names, you will need to locate and parse the password file
4419 yourself (Augeas support makes this relatively easy).");
4420
4421   ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
4422    [], (* XXX *)
4423    "lstat on multiple files",
4424    "\
4425 This call allows you to perform the C<guestfs_lstat> operation
4426 on multiple files, where all files are in the directory C<path>.
4427 C<names> is the list of files from this directory.
4428
4429 On return you get a list of stat structs, with a one-to-one
4430 correspondence to the C<names> list.  If any name did not exist
4431 or could not be lstat'd, then the C<ino> field of that structure
4432 is set to C<-1>.
4433
4434 This call is intended for programs that want to efficiently
4435 list a directory contents without making many round-trips.
4436 See also C<guestfs_lxattrlist> for a similarly efficient call
4437 for getting extended attributes.  Very long directory listings
4438 might cause the protocol message size to be exceeded, causing
4439 this call to fail.  The caller must split up such requests
4440 into smaller groups of names.");
4441
4442   ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [Optional "linuxxattrs"],
4443    [], (* XXX *)
4444    "lgetxattr on multiple files",
4445    "\
4446 This call allows you to get the extended attributes
4447 of multiple files, where all files are in the directory C<path>.
4448 C<names> is the list of files from this directory.
4449
4450 On return you get a flat list of xattr structs which must be
4451 interpreted sequentially.  The first xattr struct always has a zero-length
4452 C<attrname>.  C<attrval> in this struct is zero-length
4453 to indicate there was an error doing C<lgetxattr> for this
4454 file, I<or> is a C string which is a decimal number
4455 (the number of following attributes for this file, which could
4456 be C<\"0\">).  Then after the first xattr struct are the
4457 zero or more attributes for the first named file.
4458 This repeats for the second and subsequent files.
4459
4460 This call is intended for programs that want to efficiently
4461 list a directory contents without making many round-trips.
4462 See also C<guestfs_lstatlist> for a similarly efficient call
4463 for getting standard stats.  Very long directory listings
4464 might cause the protocol message size to be exceeded, causing
4465 this call to fail.  The caller must split up such requests
4466 into smaller groups of names.");
4467
4468   ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
4469    [], (* XXX *)
4470    "readlink on multiple files",
4471    "\
4472 This call allows you to do a C<readlink> operation
4473 on multiple files, where all files are in the directory C<path>.
4474 C<names> is the list of files from this directory.
4475
4476 On return you get a list of strings, with a one-to-one
4477 correspondence to the C<names> list.  Each string is the
4478 value of the symbolic link.
4479
4480 If the C<readlink(2)> operation fails on any name, then
4481 the corresponding result string is the empty string C<\"\">.
4482 However the whole operation is completed even if there
4483 were C<readlink(2)> errors, and so you can call this
4484 function with names where you don't know if they are
4485 symbolic links already (albeit slightly less efficient).
4486
4487 This call is intended for programs that want to efficiently
4488 list a directory contents without making many round-trips.
4489 Very long directory listings might cause the protocol
4490 message size to be exceeded, causing
4491 this call to fail.  The caller must split up such requests
4492 into smaller groups of names.");
4493
4494   ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
4495    [InitISOFS, Always, TestOutputBuffer (
4496       [["pread"; "/known-4"; "1"; "3"]], "\n");
4497     InitISOFS, Always, TestOutputBuffer (
4498       [["pread"; "/empty"; "0"; "100"]], "")],
4499    "read part of a file",
4500    "\
4501 This command lets you read part of a file.  It reads C<count>
4502 bytes of the file, starting at C<offset>, from file C<path>.
4503
4504 This may read fewer bytes than requested.  For further details
4505 see the L<pread(2)> system call.
4506
4507 See also C<guestfs_pwrite>.");
4508
4509   ("part_init", (RErr, [Device "device"; String "parttype"]), 208, [],
4510    [InitEmpty, Always, TestRun (
4511       [["part_init"; "/dev/sda"; "gpt"]])],
4512    "create an empty partition table",
4513    "\
4514 This creates an empty partition table on C<device> of one of the
4515 partition types listed below.  Usually C<parttype> should be
4516 either C<msdos> or C<gpt> (for large disks).
4517
4518 Initially there are no partitions.  Following this, you should
4519 call C<guestfs_part_add> for each partition required.
4520
4521 Possible values for C<parttype> are:
4522
4523 =over 4
4524
4525 =item B<efi> | B<gpt>
4526
4527 Intel EFI / GPT partition table.
4528
4529 This is recommended for >= 2 TB partitions that will be accessed
4530 from Linux and Intel-based Mac OS X.  It also has limited backwards
4531 compatibility with the C<mbr> format.
4532
4533 =item B<mbr> | B<msdos>
4534
4535 The standard PC \"Master Boot Record\" (MBR) format used
4536 by MS-DOS and Windows.  This partition type will B<only> work
4537 for device sizes up to 2 TB.  For large disks we recommend
4538 using C<gpt>.
4539
4540 =back
4541
4542 Other partition table types that may work but are not
4543 supported include:
4544
4545 =over 4
4546
4547 =item B<aix>
4548
4549 AIX disk labels.
4550
4551 =item B<amiga> | B<rdb>
4552
4553 Amiga \"Rigid Disk Block\" format.
4554
4555 =item B<bsd>
4556
4557 BSD disk labels.
4558
4559 =item B<dasd>
4560
4561 DASD, used on IBM mainframes.
4562
4563 =item B<dvh>
4564
4565 MIPS/SGI volumes.
4566
4567 =item B<mac>
4568
4569 Old Mac partition format.  Modern Macs use C<gpt>.
4570
4571 =item B<pc98>
4572
4573 NEC PC-98 format, common in Japan apparently.
4574
4575 =item B<sun>
4576
4577 Sun disk labels.
4578
4579 =back");
4580
4581   ("part_add", (RErr, [Device "device"; String "prlogex"; Int64 "startsect"; Int64 "endsect"]), 209, [],
4582    [InitEmpty, Always, TestRun (
4583       [["part_init"; "/dev/sda"; "mbr"];
4584        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"]]);
4585     InitEmpty, Always, TestRun (
4586       [["part_init"; "/dev/sda"; "gpt"];
4587        ["part_add"; "/dev/sda"; "primary"; "34"; "127"];
4588        ["part_add"; "/dev/sda"; "primary"; "128"; "-34"]]);
4589     InitEmpty, Always, TestRun (
4590       [["part_init"; "/dev/sda"; "mbr"];
4591        ["part_add"; "/dev/sda"; "primary"; "32"; "127"];
4592        ["part_add"; "/dev/sda"; "primary"; "128"; "255"];
4593        ["part_add"; "/dev/sda"; "primary"; "256"; "511"];
4594        ["part_add"; "/dev/sda"; "primary"; "512"; "-1"]])],
4595    "add a partition to the device",
4596    "\
4597 This command adds a partition to C<device>.  If there is no partition
4598 table on the device, call C<guestfs_part_init> first.
4599
4600 The C<prlogex> parameter is the type of partition.  Normally you
4601 should pass C<p> or C<primary> here, but MBR partition tables also
4602 support C<l> (or C<logical>) and C<e> (or C<extended>) partition
4603 types.
4604
4605 C<startsect> and C<endsect> are the start and end of the partition
4606 in I<sectors>.  C<endsect> may be negative, which means it counts
4607 backwards from the end of the disk (C<-1> is the last sector).
4608
4609 Creating a partition which covers the whole disk is not so easy.
4610 Use C<guestfs_part_disk> to do that.");
4611
4612   ("part_disk", (RErr, [Device "device"; String "parttype"]), 210, [DangerWillRobinson],
4613    [InitEmpty, Always, TestRun (
4614       [["part_disk"; "/dev/sda"; "mbr"]]);
4615     InitEmpty, Always, TestRun (
4616       [["part_disk"; "/dev/sda"; "gpt"]])],
4617    "partition whole disk with a single primary partition",
4618    "\
4619 This command is simply a combination of C<guestfs_part_init>
4620 followed by C<guestfs_part_add> to create a single primary partition
4621 covering the whole disk.
4622
4623 C<parttype> is the partition table type, usually C<mbr> or C<gpt>,
4624 but other possible values are described in C<guestfs_part_init>.");
4625
4626   ("part_set_bootable", (RErr, [Device "device"; Int "partnum"; Bool "bootable"]), 211, [],
4627    [InitEmpty, Always, TestRun (
4628       [["part_disk"; "/dev/sda"; "mbr"];
4629        ["part_set_bootable"; "/dev/sda"; "1"; "true"]])],
4630    "make a partition bootable",
4631    "\
4632 This sets the bootable flag on partition numbered C<partnum> on
4633 device C<device>.  Note that partitions are numbered from 1.
4634
4635 The bootable flag is used by some operating systems (notably
4636 Windows) to determine which partition to boot from.  It is by
4637 no means universally recognized.");
4638
4639   ("part_set_name", (RErr, [Device "device"; Int "partnum"; String "name"]), 212, [],
4640    [InitEmpty, Always, TestRun (
4641       [["part_disk"; "/dev/sda"; "gpt"];
4642        ["part_set_name"; "/dev/sda"; "1"; "thepartname"]])],
4643    "set partition name",
4644    "\
4645 This sets the partition name on partition numbered C<partnum> on
4646 device C<device>.  Note that partitions are numbered from 1.
4647
4648 The partition name can only be set on certain types of partition
4649 table.  This works on C<gpt> but not on C<mbr> partitions.");
4650
4651   ("part_list", (RStructList ("partitions", "partition"), [Device "device"]), 213, [],
4652    [], (* XXX Add a regression test for this. *)
4653    "list partitions on a device",
4654    "\
4655 This command parses the partition table on C<device> and
4656 returns the list of partitions found.
4657
4658 The fields in the returned structure are:
4659
4660 =over 4
4661
4662 =item B<part_num>
4663
4664 Partition number, counting from 1.
4665
4666 =item B<part_start>
4667
4668 Start of the partition I<in bytes>.  To get sectors you have to
4669 divide by the device's sector size, see C<guestfs_blockdev_getss>.
4670
4671 =item B<part_end>
4672
4673 End of the partition in bytes.
4674
4675 =item B<part_size>
4676
4677 Size of the partition in bytes.
4678
4679 =back");
4680
4681   ("part_get_parttype", (RString "parttype", [Device "device"]), 214, [],
4682    [InitEmpty, Always, TestOutput (
4683       [["part_disk"; "/dev/sda"; "gpt"];
4684        ["part_get_parttype"; "/dev/sda"]], "gpt")],
4685    "get the partition table type",
4686    "\
4687 This command examines the partition table on C<device> and
4688 returns the partition table type (format) being used.
4689
4690 Common return values include: C<msdos> (a DOS/Windows style MBR
4691 partition table), C<gpt> (a GPT/EFI-style partition table).  Other
4692 values are possible, although unusual.  See C<guestfs_part_init>
4693 for a full list.");
4694
4695   ("fill", (RErr, [Int "c"; Int "len"; Pathname "path"]), 215, [],
4696    [InitBasicFS, Always, TestOutputBuffer (
4697       [["fill"; "0x63"; "10"; "/test"];
4698        ["read_file"; "/test"]], "cccccccccc")],
4699    "fill a file with octets",
4700    "\
4701 This command creates a new file called C<path>.  The initial
4702 content of the file is C<len> octets of C<c>, where C<c>
4703 must be a number in the range C<[0..255]>.
4704
4705 To fill a file with zero bytes (sparsely), it is
4706 much more efficient to use C<guestfs_truncate_size>.
4707 To create a file with a pattern of repeating bytes
4708 use C<guestfs_fill_pattern>.");
4709
4710   ("available", (RErr, [StringList "groups"]), 216, [],
4711    [InitNone, Always, TestRun [["available"; ""]]],
4712    "test availability of some parts of the API",
4713    "\
4714 This command is used to check the availability of some
4715 groups of functionality in the appliance, which not all builds of
4716 the libguestfs appliance will be able to provide.
4717
4718 The libguestfs groups, and the functions that those
4719 groups correspond to, are listed in L<guestfs(3)/AVAILABILITY>.
4720 You can also fetch this list at runtime by calling
4721 C<guestfs_available_all_groups>.
4722
4723 The argument C<groups> is a list of group names, eg:
4724 C<[\"inotify\", \"augeas\"]> would check for the availability of
4725 the Linux inotify functions and Augeas (configuration file
4726 editing) functions.
4727
4728 The command returns no error if I<all> requested groups are available.
4729
4730 It fails with an error if one or more of the requested
4731 groups is unavailable in the appliance.
4732
4733 If an unknown group name is included in the
4734 list of groups then an error is always returned.
4735
4736 I<Notes:>
4737
4738 =over 4
4739
4740 =item *
4741
4742 You must call C<guestfs_launch> before calling this function.
4743
4744 The reason is because we don't know what groups are
4745 supported by the appliance/daemon until it is running and can
4746 be queried.
4747
4748 =item *
4749
4750 If a group of functions is available, this does not necessarily
4751 mean that they will work.  You still have to check for errors
4752 when calling individual API functions even if they are
4753 available.
4754
4755 =item *
4756
4757 It is usually the job of distro packagers to build
4758 complete functionality into the libguestfs appliance.
4759 Upstream libguestfs, if built from source with all
4760 requirements satisfied, will support everything.
4761
4762 =item *
4763
4764 This call was added in version C<1.0.80>.  In previous
4765 versions of libguestfs all you could do would be to speculatively
4766 execute a command to find out if the daemon implemented it.
4767 See also C<guestfs_version>.
4768
4769 =back");
4770
4771   ("dd", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"]), 217, [],
4772    [InitBasicFS, Always, TestOutputBuffer (
4773       [["write"; "/src"; "hello, world"];
4774        ["dd"; "/src"; "/dest"];
4775        ["read_file"; "/dest"]], "hello, world")],
4776    "copy from source to destination using dd",
4777    "\
4778 This command copies from one source device or file C<src>
4779 to another destination device or file C<dest>.  Normally you
4780 would use this to copy to or from a device or partition, for
4781 example to duplicate a filesystem.
4782
4783 If the destination is a device, it must be as large or larger
4784 than the source file or device, otherwise the copy will fail.
4785 This command cannot do partial copies (see C<guestfs_copy_size>).");
4786
4787   ("filesize", (RInt64 "size", [Pathname "file"]), 218, [],
4788    [InitBasicFS, Always, TestOutputInt (
4789       [["write"; "/file"; "hello, world"];
4790        ["filesize"; "/file"]], 12)],
4791    "return the size of the file in bytes",
4792    "\
4793 This command returns the size of C<file> in bytes.
4794
4795 To get other stats about a file, use C<guestfs_stat>, C<guestfs_lstat>,
4796 C<guestfs_is_dir>, C<guestfs_is_file> etc.
4797 To get the size of block devices, use C<guestfs_blockdev_getsize64>.");
4798
4799   ("lvrename", (RErr, [String "logvol"; String "newlogvol"]), 219, [],
4800    [InitBasicFSonLVM, Always, TestOutputList (
4801       [["lvrename"; "/dev/VG/LV"; "/dev/VG/LV2"];
4802        ["lvs"]], ["/dev/VG/LV2"])],
4803    "rename an LVM logical volume",
4804    "\
4805 Rename a logical volume C<logvol> with the new name C<newlogvol>.");
4806
4807   ("vgrename", (RErr, [String "volgroup"; String "newvolgroup"]), 220, [],
4808    [InitBasicFSonLVM, Always, TestOutputList (
4809       [["umount"; "/"];
4810        ["vg_activate"; "false"; "VG"];
4811        ["vgrename"; "VG"; "VG2"];
4812        ["vg_activate"; "true"; "VG2"];
4813        ["mount_options"; ""; "/dev/VG2/LV"; "/"];
4814        ["vgs"]], ["VG2"])],
4815    "rename an LVM volume group",
4816    "\
4817 Rename a volume group C<volgroup> with the new name C<newvolgroup>.");
4818
4819   ("initrd_cat", (RBufferOut "content", [Pathname "initrdpath"; String "filename"]), 221, [ProtocolLimitWarning],
4820    [InitISOFS, Always, TestOutputBuffer (
4821       [["initrd_cat"; "/initrd"; "known-4"]], "abc\ndef\nghi")],
4822    "list the contents of a single file in an initrd",
4823    "\
4824 This command unpacks the file C<filename> from the initrd file
4825 called C<initrdpath>.  The filename must be given I<without> the
4826 initial C</> character.
4827
4828 For example, in guestfish you could use the following command
4829 to examine the boot script (usually called C</init>)
4830 contained in a Linux initrd or initramfs image:
4831
4832  initrd-cat /boot/initrd-<version>.img init
4833
4834 See also C<guestfs_initrd_list>.");
4835
4836   ("pvuuid", (RString "uuid", [Device "device"]), 222, [],
4837    [],
4838    "get the UUID of a physical volume",
4839    "\
4840 This command returns the UUID of the LVM PV C<device>.");
4841
4842   ("vguuid", (RString "uuid", [String "vgname"]), 223, [],
4843    [],
4844    "get the UUID of a volume group",
4845    "\
4846 This command returns the UUID of the LVM VG named C<vgname>.");
4847
4848   ("lvuuid", (RString "uuid", [Device "device"]), 224, [],
4849    [],
4850    "get the UUID of a logical volume",
4851    "\
4852 This command returns the UUID of the LVM LV C<device>.");
4853
4854   ("vgpvuuids", (RStringList "uuids", [String "vgname"]), 225, [],
4855    [],
4856    "get the PV UUIDs containing the volume group",
4857    "\
4858 Given a VG called C<vgname>, this returns the UUIDs of all
4859 the physical volumes that this volume group resides on.
4860
4861 You can use this along with C<guestfs_pvs> and C<guestfs_pvuuid>
4862 calls to associate physical volumes and volume groups.
4863
4864 See also C<guestfs_vglvuuids>.");
4865
4866   ("vglvuuids", (RStringList "uuids", [String "vgname"]), 226, [],
4867    [],
4868    "get the LV UUIDs of all LVs in the volume group",
4869    "\
4870 Given a VG called C<vgname>, this returns the UUIDs of all
4871 the logical volumes created in this volume group.
4872
4873 You can use this along with C<guestfs_lvs> and C<guestfs_lvuuid>
4874 calls to associate logical volumes and volume groups.
4875
4876 See also C<guestfs_vgpvuuids>.");
4877
4878   ("copy_size", (RErr, [Dev_or_Path "src"; Dev_or_Path "dest"; Int64 "size"]), 227, [],
4879    [InitBasicFS, Always, TestOutputBuffer (
4880       [["write"; "/src"; "hello, world"];
4881        ["copy_size"; "/src"; "/dest"; "5"];
4882        ["read_file"; "/dest"]], "hello")],
4883    "copy size bytes from source to destination using dd",
4884    "\
4885 This command copies exactly C<size> bytes from one source device
4886 or file C<src> to another destination device or file C<dest>.
4887
4888 Note this will fail if the source is too short or if the destination
4889 is not large enough.");
4890
4891   ("zero_device", (RErr, [Device "device"]), 228, [DangerWillRobinson],
4892    [InitBasicFSonLVM, Always, TestRun (
4893       [["zero_device"; "/dev/VG/LV"]])],
4894    "write zeroes to an entire device",
4895    "\
4896 This command writes zeroes over the entire C<device>.  Compare
4897 with C<guestfs_zero> which just zeroes the first few blocks of
4898 a device.");
4899
4900   ("txz_in", (RErr, [FileIn "tarball"; Pathname "directory"]), 229, [Optional "xz"],
4901    [InitBasicFS, Always, TestOutput (
4902       [["txz_in"; "../images/helloworld.tar.xz"; "/"];
4903        ["cat"; "/hello"]], "hello\n")],
4904    "unpack compressed tarball to directory",
4905    "\
4906 This command uploads and unpacks local file C<tarball> (an
4907 I<xz compressed> tar file) into C<directory>.");
4908
4909   ("txz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 230, [Optional "xz"],
4910    [],
4911    "pack directory into compressed tarball",
4912    "\
4913 This command packs the contents of C<directory> and downloads
4914 it to local file C<tarball> (as an xz compressed tar archive).");
4915
4916   ("ntfsresize", (RErr, [Device "device"]), 231, [Optional "ntfsprogs"],
4917    [],
4918    "resize an NTFS filesystem",
4919    "\
4920 This command resizes an NTFS filesystem, expanding or
4921 shrinking it to the size of the underlying device.
4922 See also L<ntfsresize(8)>.");
4923
4924   ("vgscan", (RErr, []), 232, [],
4925    [InitEmpty, Always, TestRun (
4926       [["vgscan"]])],
4927    "rescan for LVM physical volumes, volume groups and logical volumes",
4928    "\
4929 This rescans all block devices and rebuilds the list of LVM
4930 physical volumes, volume groups and logical volumes.");
4931
4932   ("part_del", (RErr, [Device "device"; Int "partnum"]), 233, [],
4933    [InitEmpty, Always, TestRun (
4934       [["part_init"; "/dev/sda"; "mbr"];
4935        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4936        ["part_del"; "/dev/sda"; "1"]])],
4937    "delete a partition",
4938    "\
4939 This command deletes the partition numbered C<partnum> on C<device>.
4940
4941 Note that in the case of MBR partitioning, deleting an
4942 extended partition also deletes any logical partitions
4943 it contains.");
4944
4945   ("part_get_bootable", (RBool "bootable", [Device "device"; Int "partnum"]), 234, [],
4946    [InitEmpty, Always, TestOutputTrue (
4947       [["part_init"; "/dev/sda"; "mbr"];
4948        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4949        ["part_set_bootable"; "/dev/sda"; "1"; "true"];
4950        ["part_get_bootable"; "/dev/sda"; "1"]])],
4951    "return true if a partition is bootable",
4952    "\
4953 This command returns true if the partition C<partnum> on
4954 C<device> has the bootable flag set.
4955
4956 See also C<guestfs_part_set_bootable>.");
4957
4958   ("part_get_mbr_id", (RInt "idbyte", [Device "device"; Int "partnum"]), 235, [FishOutput FishOutputHexadecimal],
4959    [InitEmpty, Always, TestOutputInt (
4960       [["part_init"; "/dev/sda"; "mbr"];
4961        ["part_add"; "/dev/sda"; "primary"; "1"; "-1"];
4962        ["part_set_mbr_id"; "/dev/sda"; "1"; "0x7f"];
4963        ["part_get_mbr_id"; "/dev/sda"; "1"]], 0x7f)],
4964    "get the MBR type byte (ID byte) from a partition",
4965    "\
4966 Returns the MBR type byte (also known as the ID byte) from
4967 the numbered partition C<partnum>.
4968
4969 Note that only MBR (old DOS-style) partitions have type bytes.
4970 You will get undefined results for other partition table
4971 types (see C<guestfs_part_get_parttype>).");
4972
4973   ("part_set_mbr_id", (RErr, [Device "device"; Int "partnum"; Int "idbyte"]), 236, [],
4974    [], (* tested by part_get_mbr_id *)
4975    "set the MBR type byte (ID byte) of a partition",
4976    "\
4977 Sets the MBR type byte (also known as the ID byte) of
4978 the numbered partition C<partnum> to C<idbyte>.  Note
4979 that the type bytes quoted in most documentation are
4980 in fact hexadecimal numbers, but usually documented
4981 without any leading \"0x\" which might be confusing.
4982
4983 Note that only MBR (old DOS-style) partitions have type bytes.
4984 You will get undefined results for other partition table
4985 types (see C<guestfs_part_get_parttype>).");
4986
4987   ("checksum_device", (RString "checksum", [String "csumtype"; Device "device"]), 237, [],
4988    [InitISOFS, Always, TestOutput (
4989       [["checksum_device"; "md5"; "/dev/sdd"]],
4990       (Digest.to_hex (Digest.file "images/test.iso")))],
4991    "compute MD5, SHAx or CRC checksum of the contents of a device",
4992    "\
4993 This call computes the MD5, SHAx or CRC checksum of the
4994 contents of the device named C<device>.  For the types of
4995 checksums supported see the C<guestfs_checksum> command.");
4996
4997   ("lvresize_free", (RErr, [Device "lv"; Int "percent"]), 238, [Optional "lvm2"],
4998    [InitNone, Always, TestRun (
4999       [["part_disk"; "/dev/sda"; "mbr"];
5000        ["pvcreate"; "/dev/sda1"];
5001        ["vgcreate"; "VG"; "/dev/sda1"];
5002        ["lvcreate"; "LV"; "VG"; "10"];
5003        ["lvresize_free"; "/dev/VG/LV"; "100"]])],
5004    "expand an LV to fill free space",
5005    "\
5006 This expands an existing logical volume C<lv> so that it fills
5007 C<pc>% of the remaining free space in the volume group.  Commonly
5008 you would call this with pc = 100 which expands the logical volume
5009 as much as possible, using all remaining free space in the volume
5010 group.");
5011
5012   ("aug_clear", (RErr, [String "augpath"]), 239, [Optional "augeas"],
5013    [], (* XXX Augeas code needs tests. *)
5014    "clear Augeas path",
5015    "\
5016 Set the value associated with C<path> to C<NULL>.  This
5017 is the same as the L<augtool(1)> C<clear> command.");
5018
5019   ("get_umask", (RInt "mask", []), 240, [FishOutput FishOutputOctal],
5020    [InitEmpty, Always, TestOutputInt (
5021       [["get_umask"]], 0o22)],
5022    "get the current umask",
5023    "\
5024 Return the current umask.  By default the umask is C<022>
5025 unless it has been set by calling C<guestfs_umask>.");
5026
5027   ("debug_upload", (RErr, [FileIn "filename"; String "tmpname"; Int "mode"]), 241, [],
5028    [],
5029    "upload a file to the appliance (internal use only)",
5030    "\
5031 The C<guestfs_debug_upload> command uploads a file to
5032 the libguestfs appliance.
5033
5034 There is no comprehensive help for this command.  You have
5035 to look at the file C<daemon/debug.c> in the libguestfs source
5036 to find out what it is for.");
5037
5038   ("base64_in", (RErr, [FileIn "base64file"; Pathname "filename"]), 242, [],
5039    [InitBasicFS, Always, TestOutput (
5040       [["base64_in"; "../images/hello.b64"; "/hello"];
5041        ["cat"; "/hello"]], "hello\n")],
5042    "upload base64-encoded data to file",
5043    "\
5044 This command uploads base64-encoded data from C<base64file>
5045 to C<filename>.");
5046
5047   ("base64_out", (RErr, [Pathname "filename"; FileOut "base64file"]), 243, [],
5048    [],
5049    "download file and encode as base64",
5050    "\
5051 This command downloads the contents of C<filename>, writing
5052 it out to local file C<base64file> encoded as base64.");
5053
5054   ("checksums_out", (RErr, [String "csumtype"; Pathname "directory"; FileOut "sumsfile"]), 244, [],
5055    [],
5056    "compute MD5, SHAx or CRC checksum of files in a directory",
5057    "\
5058 This command computes the checksums of all regular files in
5059 C<directory> and then emits a list of those checksums to
5060 the local output file C<sumsfile>.
5061
5062 This can be used for verifying the integrity of a virtual
5063 machine.  However to be properly secure you should pay
5064 attention to the output of the checksum command (it uses
5065 the ones from GNU coreutils).  In particular when the
5066 filename is not printable, coreutils uses a special
5067 backslash syntax.  For more information, see the GNU
5068 coreutils info file.");
5069
5070   ("fill_pattern", (RErr, [String "pattern"; Int "len"; Pathname "path"]), 245, [],
5071    [InitBasicFS, Always, TestOutputBuffer (
5072       [["fill_pattern"; "abcdefghijklmnopqrstuvwxyz"; "28"; "/test"];
5073        ["read_file"; "/test"]], "abcdefghijklmnopqrstuvwxyzab")],
5074    "fill a file with a repeating pattern of bytes",
5075    "\
5076 This function is like C<guestfs_fill> except that it creates
5077 a new file of length C<len> containing the repeating pattern
5078 of bytes in C<pattern>.  The pattern is truncated if necessary
5079 to ensure the length of the file is exactly C<len> bytes.");
5080
5081   ("write", (RErr, [Pathname "path"; BufferIn "content"]), 246, [ProtocolLimitWarning],
5082    [InitBasicFS, Always, TestOutput (
5083       [["write"; "/new"; "new file contents"];
5084        ["cat"; "/new"]], "new file contents");
5085     InitBasicFS, Always, TestOutput (
5086       [["write"; "/new"; "\nnew file contents\n"];
5087        ["cat"; "/new"]], "\nnew file contents\n");
5088     InitBasicFS, Always, TestOutput (
5089       [["write"; "/new"; "\n\n"];
5090        ["cat"; "/new"]], "\n\n");
5091     InitBasicFS, Always, TestOutput (
5092       [["write"; "/new"; ""];
5093        ["cat"; "/new"]], "");
5094     InitBasicFS, Always, TestOutput (
5095       [["write"; "/new"; "\n\n\n"];
5096        ["cat"; "/new"]], "\n\n\n");
5097     InitBasicFS, Always, TestOutput (
5098       [["write"; "/new"; "\n"];
5099        ["cat"; "/new"]], "\n")],
5100    "create a new file",
5101    "\
5102 This call creates a file called C<path>.  The content of the
5103 file is the string C<content> (which can contain any 8 bit data).");
5104
5105   ("pwrite", (RInt "nbytes", [Pathname "path"; BufferIn "content"; Int64 "offset"]), 247, [ProtocolLimitWarning],
5106    [InitBasicFS, Always, TestOutput (
5107       [["write"; "/new"; "new file contents"];
5108        ["pwrite"; "/new"; "data"; "4"];
5109        ["cat"; "/new"]], "new data contents");
5110     InitBasicFS, Always, TestOutput (
5111       [["write"; "/new"; "new file contents"];
5112        ["pwrite"; "/new"; "is extended"; "9"];
5113        ["cat"; "/new"]], "new file is extended");
5114     InitBasicFS, Always, TestOutput (
5115       [["write"; "/new"; "new file contents"];
5116        ["pwrite"; "/new"; ""; "4"];
5117        ["cat"; "/new"]], "new file contents")],
5118    "write to part of a file",
5119    "\
5120 This command writes to part of a file.  It writes the data
5121 buffer C<content> to the file C<path> starting at offset C<offset>.
5122
5123 This command implements the L<pwrite(2)> system call, and like
5124 that system call it may not write the full data requested.  The
5125 return value is the number of bytes that were actually written
5126 to the file.  This could even be 0, although short writes are
5127 unlikely for regular files in ordinary circumstances.
5128
5129 See also C<guestfs_pread>.");
5130
5131   ("resize2fs_size", (RErr, [Device "device"; Int64 "size"]), 248, [],
5132    [],
5133    "resize an ext2, ext3 or ext4 filesystem (with size)",
5134    "\
5135 This command is the same as C<guestfs_resize2fs> except that it
5136 allows you to specify the new size (in bytes) explicitly.");
5137
5138   ("pvresize_size", (RErr, [Device "device"; Int64 "size"]), 249, [Optional "lvm2"],
5139    [],
5140    "resize an LVM physical volume (with size)",
5141    "\
5142 This command is the same as C<guestfs_pvresize> except that it
5143 allows you to specify the new size (in bytes) explicitly.");
5144
5145   ("ntfsresize_size", (RErr, [Device "device"; Int64 "size"]), 250, [Optional "ntfsprogs"],
5146    [],
5147    "resize an NTFS filesystem (with size)",
5148    "\
5149 This command is the same as C<guestfs_ntfsresize> except that it
5150 allows you to specify the new size (in bytes) explicitly.");
5151
5152   ("available_all_groups", (RStringList "groups", []), 251, [],
5153    [InitNone, Always, TestRun [["available_all_groups"]]],
5154    "return a list of all optional groups",
5155    "\
5156 This command returns a list of all optional groups that this
5157 daemon knows about.  Note this returns both supported and unsupported
5158 groups.  To find out which ones the daemon can actually support
5159 you have to call C<guestfs_available> on each member of the
5160 returned list.
5161
5162 See also C<guestfs_available> and L<guestfs(3)/AVAILABILITY>.");
5163
5164   ("fallocate64", (RErr, [Pathname "path"; Int64 "len"]), 252, [],
5165    [InitBasicFS, Always, TestOutputStruct (
5166       [["fallocate64"; "/a"; "1000000"];
5167        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
5168    "preallocate a file in the guest filesystem",
5169    "\
5170 This command preallocates a file (containing zero bytes) named
5171 C<path> of size C<len> bytes.  If the file exists already, it
5172 is overwritten.
5173
5174 Note that this call allocates disk blocks for the file.
5175 To create a sparse file use C<guestfs_truncate_size> instead.
5176
5177 The deprecated call C<guestfs_fallocate> does the same,
5178 but owing to an oversight it only allowed 30 bit lengths
5179 to be specified, effectively limiting the maximum size
5180 of files created through that call to 1GB.
5181
5182 Do not confuse this with the guestfish-specific
5183 C<alloc> and C<sparse> commands which create
5184 a file in the host and attach it as a device.");
5185
5186   ("vfs_label", (RString "label", [Device "device"]), 253, [],
5187    [InitBasicFS, Always, TestOutput (
5188        [["set_e2label"; "/dev/sda1"; "LTEST"];
5189         ["vfs_label"; "/dev/sda1"]], "LTEST")],
5190    "get the filesystem label",
5191    "\
5192 This returns the filesystem label of the filesystem on
5193 C<device>.
5194
5195 If the filesystem is unlabeled, this returns the empty string.
5196
5197 To find a filesystem from the label, use C<guestfs_findfs_label>.");
5198
5199   ("vfs_uuid", (RString "uuid", [Device "device"]), 254, [],
5200    (let uuid = uuidgen () in
5201     [InitBasicFS, Always, TestOutput (
5202        [["set_e2uuid"; "/dev/sda1"; uuid];
5203         ["vfs_uuid"; "/dev/sda1"]], uuid)]),
5204    "get the filesystem UUID",
5205    "\
5206 This returns the filesystem UUID of the filesystem on
5207 C<device>.
5208
5209 If the filesystem does not have a UUID, this returns the empty string.
5210
5211 To find a filesystem from the UUID, use C<guestfs_findfs_uuid>.");
5212
5213   ("lvm_set_filter", (RErr, [DeviceList "devices"]), 255, [Optional "lvm2"],
5214    (* Can't be tested with the current framework because
5215     * the VG is being used by the mounted filesystem, so
5216     * the vgchange -an command we do first will fail.
5217     *)
5218     [],
5219    "set LVM device filter",
5220    "\
5221 This sets the LVM device filter so that LVM will only be
5222 able to \"see\" the block devices in the list C<devices>,
5223 and will ignore all other attached block devices.
5224
5225 Where disk image(s) contain duplicate PVs or VGs, this
5226 command is useful to get LVM to ignore the duplicates, otherwise
5227 LVM can get confused.  Note also there are two types
5228 of duplication possible: either cloned PVs/VGs which have
5229 identical UUIDs; or VGs that are not cloned but just happen
5230 to have the same name.  In normal operation you cannot
5231 create this situation, but you can do it outside LVM, eg.
5232 by cloning disk images or by bit twiddling inside the LVM
5233 metadata.
5234
5235 This command also clears the LVM cache and performs a volume
5236 group scan.
5237
5238 You can filter whole block devices or individual partitions.
5239
5240 You cannot use this if any VG is currently in use (eg.
5241 contains a mounted filesystem), even if you are not
5242 filtering out that VG.");
5243
5244   ("lvm_clear_filter", (RErr, []), 256, [],
5245    [], (* see note on lvm_set_filter *)
5246    "clear LVM device filter",
5247    "\
5248 This undoes the effect of C<guestfs_lvm_set_filter>.  LVM
5249 will be able to see every block device.
5250
5251 This command also clears the LVM cache and performs a volume
5252 group scan.");
5253
5254   ("luks_open", (RErr, [Device "device"; Key "key"; String "mapname"]), 257, [Optional "luks"],
5255    [],
5256    "open a LUKS-encrypted block device",
5257    "\
5258 This command opens a block device which has been encrypted
5259 according to the Linux Unified Key Setup (LUKS) standard.
5260
5261 C<device> is the encrypted block device or partition.
5262
5263 The caller must supply one of the keys associated with the
5264 LUKS block device, in the C<key> parameter.
5265
5266 This creates a new block device called C</dev/mapper/mapname>.
5267 Reads and writes to this block device are decrypted from and
5268 encrypted to the underlying C<device> respectively.
5269
5270 If this block device contains LVM volume groups, then
5271 calling C<guestfs_vgscan> followed by C<guestfs_vg_activate_all>
5272 will make them visible.");
5273
5274   ("luks_open_ro", (RErr, [Device "device"; Key "key"; String "mapname"]), 258, [Optional "luks"],
5275    [],
5276    "open a LUKS-encrypted block device read-only",
5277    "\
5278 This is the same as C<guestfs_luks_open> except that a read-only
5279 mapping is created.");
5280
5281   ("luks_close", (RErr, [Device "device"]), 259, [Optional "luks"],
5282    [],
5283    "close a LUKS device",
5284    "\
5285 This closes a LUKS device that was created earlier by
5286 C<guestfs_luks_open> or C<guestfs_luks_open_ro>.  The
5287 C<device> parameter must be the name of the LUKS mapping
5288 device (ie. C</dev/mapper/mapname>) and I<not> the name
5289 of the underlying block device.");
5290
5291   ("luks_format", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 260, [Optional "luks"; DangerWillRobinson],
5292    [],
5293    "format a block device as a LUKS encrypted device",
5294    "\
5295 This command erases existing data on C<device> and formats
5296 the device as a LUKS encrypted device.  C<key> is the
5297 initial key, which is added to key slot C<slot>.  (LUKS
5298 supports 8 key slots, numbered 0-7).");
5299
5300   ("luks_format_cipher", (RErr, [Device "device"; Key "key"; Int "keyslot"; String "cipher"]), 261, [Optional "luks"; DangerWillRobinson],
5301    [],
5302    "format a block device as a LUKS encrypted device",
5303    "\
5304 This command is the same as C<guestfs_luks_format> but
5305 it also allows you to set the C<cipher> used.");
5306
5307   ("luks_add_key", (RErr, [Device "device"; Key "key"; Key "newkey"; Int "keyslot"]), 262, [Optional "luks"],
5308    [],
5309    "add a key on a LUKS encrypted device",
5310    "\
5311 This command adds a new key on LUKS device C<device>.
5312 C<key> is any existing key, and is used to access the device.
5313 C<newkey> is the new key to add.  C<keyslot> is the key slot
5314 that will be replaced.
5315
5316 Note that if C<keyslot> already contains a key, then this
5317 command will fail.  You have to use C<guestfs_luks_kill_slot>
5318 first to remove that key.");
5319
5320   ("luks_kill_slot", (RErr, [Device "device"; Key "key"; Int "keyslot"]), 263, [Optional "luks"],
5321    [],
5322    "remove a key from a LUKS encrypted device",
5323    "\
5324 This command deletes the key in key slot C<keyslot> from the
5325 encrypted LUKS device C<device>.  C<key> must be one of the
5326 I<other> keys.");
5327
5328   ("is_lv", (RBool "lvflag", [Device "device"]), 264, [Optional "lvm2"],
5329    [InitBasicFSonLVM, IfAvailable "lvm2", TestOutputTrue (
5330       [["is_lv"; "/dev/VG/LV"]]);
5331     InitBasicFSonLVM, IfAvailable "lvm2", TestOutputFalse (
5332       [["is_lv"; "/dev/sda1"]])],
5333    "test if device is a logical volume",
5334    "\
5335 This command tests whether C<device> is a logical volume, and
5336 returns true iff this is the case.");
5337
5338   ("findfs_uuid", (RString "device", [String "uuid"]), 265, [],
5339    [],
5340    "find a filesystem by UUID",
5341    "\
5342 This command searches the filesystems and returns the one
5343 which has the given UUID.  An error is returned if no such
5344 filesystem can be found.
5345
5346 To find the UUID of a filesystem, use C<guestfs_vfs_uuid>.");
5347
5348   ("findfs_label", (RString "device", [String "label"]), 266, [],
5349    [],
5350    "find a filesystem by label",
5351    "\
5352 This command searches the filesystems and returns the one
5353 which has the given label.  An error is returned if no such
5354 filesystem can be found.
5355
5356 To find the label of a filesystem, use C<guestfs_vfs_label>.");
5357
5358 ]
5359
5360 let all_functions = non_daemon_functions @ daemon_functions
5361
5362 (* In some places we want the functions to be displayed sorted
5363  * alphabetically, so this is useful:
5364  *)
5365 let all_functions_sorted =
5366   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
5367                compare n1 n2) all_functions
5368
5369 (* This is used to generate the src/MAX_PROC_NR file which
5370  * contains the maximum procedure number, a surrogate for the
5371  * ABI version number.  See src/Makefile.am for the details.
5372  *)
5373 let max_proc_nr =
5374   let proc_nrs = List.map (
5375     fun (_, _, proc_nr, _, _, _, _) -> proc_nr
5376   ) daemon_functions in
5377   List.fold_left max 0 proc_nrs
5378
5379 (* Field types for structures. *)
5380 type field =
5381   | FChar                       (* C 'char' (really, a 7 bit byte). *)
5382   | FString                     (* nul-terminated ASCII string, NOT NULL. *)
5383   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
5384   | FUInt32
5385   | FInt32
5386   | FUInt64
5387   | FInt64
5388   | FBytes                      (* Any int measure that counts bytes. *)
5389   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
5390   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
5391
5392 (* Because we generate extra parsing code for LVM command line tools,
5393  * we have to pull out the LVM columns separately here.
5394  *)
5395 let lvm_pv_cols = [
5396   "pv_name", FString;
5397   "pv_uuid", FUUID;
5398   "pv_fmt", FString;
5399   "pv_size", FBytes;
5400   "dev_size", FBytes;
5401   "pv_free", FBytes;
5402   "pv_used", FBytes;
5403   "pv_attr", FString (* XXX *);
5404   "pv_pe_count", FInt64;
5405   "pv_pe_alloc_count", FInt64;
5406   "pv_tags", FString;
5407   "pe_start", FBytes;
5408   "pv_mda_count", FInt64;
5409   "pv_mda_free", FBytes;
5410   (* Not in Fedora 10:
5411      "pv_mda_size", FBytes;
5412   *)
5413 ]
5414 let lvm_vg_cols = [
5415   "vg_name", FString;
5416   "vg_uuid", FUUID;
5417   "vg_fmt", FString;
5418   "vg_attr", FString (* XXX *);
5419   "vg_size", FBytes;
5420   "vg_free", FBytes;
5421   "vg_sysid", FString;
5422   "vg_extent_size", FBytes;
5423   "vg_extent_count", FInt64;
5424   "vg_free_count", FInt64;
5425   "max_lv", FInt64;
5426   "max_pv", FInt64;
5427   "pv_count", FInt64;
5428   "lv_count", FInt64;
5429   "snap_count", FInt64;
5430   "vg_seqno", FInt64;
5431   "vg_tags", FString;
5432   "vg_mda_count", FInt64;
5433   "vg_mda_free", FBytes;
5434   (* Not in Fedora 10:
5435      "vg_mda_size", FBytes;
5436   *)
5437 ]
5438 let lvm_lv_cols = [
5439   "lv_name", FString;
5440   "lv_uuid", FUUID;
5441   "lv_attr", FString (* XXX *);
5442   "lv_major", FInt64;
5443   "lv_minor", FInt64;
5444   "lv_kernel_major", FInt64;
5445   "lv_kernel_minor", FInt64;
5446   "lv_size", FBytes;
5447   "seg_count", FInt64;
5448   "origin", FString;
5449   "snap_percent", FOptPercent;
5450   "copy_percent", FOptPercent;
5451   "move_pv", FString;
5452   "lv_tags", FString;
5453   "mirror_log", FString;
5454   "modules", FString;
5455 ]
5456
5457 (* Names and fields in all structures (in RStruct and RStructList)
5458  * that we support.
5459  *)
5460 let structs = [
5461   (* The old RIntBool return type, only ever used for aug_defnode.  Do
5462    * not use this struct in any new code.
5463    *)
5464   "int_bool", [
5465     "i", FInt32;                (* for historical compatibility *)
5466     "b", FInt32;                (* for historical compatibility *)
5467   ];
5468
5469   (* LVM PVs, VGs, LVs. *)
5470   "lvm_pv", lvm_pv_cols;
5471   "lvm_vg", lvm_vg_cols;
5472   "lvm_lv", lvm_lv_cols;
5473
5474   (* Column names and types from stat structures.
5475    * NB. Can't use things like 'st_atime' because glibc header files
5476    * define some of these as macros.  Ugh.
5477    *)
5478   "stat", [
5479     "dev", FInt64;
5480     "ino", FInt64;
5481     "mode", FInt64;
5482     "nlink", FInt64;
5483     "uid", FInt64;
5484     "gid", FInt64;
5485     "rdev", FInt64;
5486     "size", FInt64;
5487     "blksize", FInt64;
5488     "blocks", FInt64;
5489     "atime", FInt64;
5490     "mtime", FInt64;
5491     "ctime", FInt64;
5492   ];
5493   "statvfs", [
5494     "bsize", FInt64;
5495     "frsize", FInt64;
5496     "blocks", FInt64;
5497     "bfree", FInt64;
5498     "bavail", FInt64;
5499     "files", FInt64;
5500     "ffree", FInt64;
5501     "favail", FInt64;
5502     "fsid", FInt64;
5503     "flag", FInt64;
5504     "namemax", FInt64;
5505   ];
5506
5507   (* Column names in dirent structure. *)
5508   "dirent", [
5509     "ino", FInt64;
5510     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
5511     "ftyp", FChar;
5512     "name", FString;
5513   ];
5514
5515   (* Version numbers. *)
5516   "version", [
5517     "major", FInt64;
5518     "minor", FInt64;
5519     "release", FInt64;
5520     "extra", FString;
5521   ];
5522
5523   (* Extended attribute. *)
5524   "xattr", [
5525     "attrname", FString;
5526     "attrval", FBuffer;
5527   ];
5528
5529   (* Inotify events. *)
5530   "inotify_event", [
5531     "in_wd", FInt64;
5532     "in_mask", FUInt32;
5533     "in_cookie", FUInt32;
5534     "in_name", FString;
5535   ];
5536
5537   (* Partition table entry. *)
5538   "partition", [
5539     "part_num", FInt32;
5540     "part_start", FBytes;
5541     "part_end", FBytes;
5542     "part_size", FBytes;
5543   ];
5544 ] (* end of structs *)
5545
5546 (* Ugh, Java has to be different ..
5547  * These names are also used by the Haskell bindings.
5548  *)
5549 let java_structs = [
5550   "int_bool", "IntBool";
5551   "lvm_pv", "PV";
5552   "lvm_vg", "VG";
5553   "lvm_lv", "LV";
5554   "stat", "Stat";
5555   "statvfs", "StatVFS";
5556   "dirent", "Dirent";
5557   "version", "Version";
5558   "xattr", "XAttr";
5559   "inotify_event", "INotifyEvent";
5560   "partition", "Partition";
5561 ]
5562
5563 (* What structs are actually returned. *)
5564 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
5565
5566 (* Returns a list of RStruct/RStructList structs that are returned
5567  * by any function.  Each element of returned list is a pair:
5568  *
5569  * (structname, RStructOnly)
5570  *    == there exists function which returns RStruct (_, structname)
5571  * (structname, RStructListOnly)
5572  *    == there exists function which returns RStructList (_, structname)
5573  * (structname, RStructAndList)
5574  *    == there are functions returning both RStruct (_, structname)
5575  *                                      and RStructList (_, structname)
5576  *)
5577 let rstructs_used_by functions =
5578   (* ||| is a "logical OR" for rstructs_used_t *)
5579   let (|||) a b =
5580     match a, b with
5581     | RStructAndList, _
5582     | _, RStructAndList -> RStructAndList
5583     | RStructOnly, RStructListOnly
5584     | RStructListOnly, RStructOnly -> RStructAndList
5585     | RStructOnly, RStructOnly -> RStructOnly
5586     | RStructListOnly, RStructListOnly -> RStructListOnly
5587   in
5588
5589   let h = Hashtbl.create 13 in
5590
5591   (* if elem->oldv exists, update entry using ||| operator,
5592    * else just add elem->newv to the hash
5593    *)
5594   let update elem newv =
5595     try  let oldv = Hashtbl.find h elem in
5596          Hashtbl.replace h elem (newv ||| oldv)
5597     with Not_found -> Hashtbl.add h elem newv
5598   in
5599
5600   List.iter (
5601     fun (_, style, _, _, _, _, _) ->
5602       match fst style with
5603       | RStruct (_, structname) -> update structname RStructOnly
5604       | RStructList (_, structname) -> update structname RStructListOnly
5605       | _ -> ()
5606   ) functions;
5607
5608   (* return key->values as a list of (key,value) *)
5609   Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
5610
5611 (* Used for testing language bindings. *)
5612 type callt =
5613   | CallString of string
5614   | CallOptString of string option
5615   | CallStringList of string list
5616   | CallInt of int
5617   | CallInt64 of int64
5618   | CallBool of bool
5619   | CallBuffer of string
5620
5621 (* Used to memoize the result of pod2text. *)
5622 let pod2text_memo_filename = "src/.pod2text.data"
5623 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
5624   try
5625     let chan = open_in pod2text_memo_filename in
5626     let v = input_value chan in
5627     close_in chan;
5628     v
5629   with
5630     _ -> Hashtbl.create 13
5631 let pod2text_memo_updated () =
5632   let chan = open_out pod2text_memo_filename in
5633   output_value chan pod2text_memo;
5634   close_out chan
5635
5636 (* Useful functions.
5637  * Note we don't want to use any external OCaml libraries which
5638  * makes this a bit harder than it should be.
5639  *)
5640 module StringMap = Map.Make (String)
5641
5642 let failwithf fs = ksprintf failwith fs
5643
5644 let unique = let i = ref 0 in fun () -> incr i; !i
5645
5646 let replace_char s c1 c2 =
5647   let s2 = String.copy s in
5648   let r = ref false in
5649   for i = 0 to String.length s2 - 1 do
5650     if String.unsafe_get s2 i = c1 then (
5651       String.unsafe_set s2 i c2;
5652       r := true
5653     )
5654   done;
5655   if not !r then s else s2
5656
5657 let isspace c =
5658   c = ' '
5659   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
5660
5661 let triml ?(test = isspace) str =
5662   let i = ref 0 in
5663   let n = ref (String.length str) in
5664   while !n > 0 && test str.[!i]; do
5665     decr n;
5666     incr i
5667   done;
5668   if !i = 0 then str
5669   else String.sub str !i !n
5670
5671 let trimr ?(test = isspace) str =
5672   let n = ref (String.length str) in
5673   while !n > 0 && test str.[!n-1]; do
5674     decr n
5675   done;
5676   if !n = String.length str then str
5677   else String.sub str 0 !n
5678
5679 let trim ?(test = isspace) str =
5680   trimr ~test (triml ~test str)
5681
5682 let rec find s sub =
5683   let len = String.length s in
5684   let sublen = String.length sub in
5685   let rec loop i =
5686     if i <= len-sublen then (
5687       let rec loop2 j =
5688         if j < sublen then (
5689           if s.[i+j] = sub.[j] then loop2 (j+1)
5690           else -1
5691         ) else
5692           i (* found *)
5693       in
5694       let r = loop2 0 in
5695       if r = -1 then loop (i+1) else r
5696     ) else
5697       -1 (* not found *)
5698   in
5699   loop 0
5700
5701 let rec replace_str s s1 s2 =
5702   let len = String.length s in
5703   let sublen = String.length s1 in
5704   let i = find s s1 in
5705   if i = -1 then s
5706   else (
5707     let s' = String.sub s 0 i in
5708     let s'' = String.sub s (i+sublen) (len-i-sublen) in
5709     s' ^ s2 ^ replace_str s'' s1 s2
5710   )
5711
5712 let rec string_split sep str =
5713   let len = String.length str in
5714   let seplen = String.length sep in
5715   let i = find str sep in
5716   if i = -1 then [str]
5717   else (
5718     let s' = String.sub str 0 i in
5719     let s'' = String.sub str (i+seplen) (len-i-seplen) in
5720     s' :: string_split sep s''
5721   )
5722
5723 let files_equal n1 n2 =
5724   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
5725   match Sys.command cmd with
5726   | 0 -> true
5727   | 1 -> false
5728   | i -> failwithf "%s: failed with error code %d" cmd i
5729
5730 let rec filter_map f = function
5731   | [] -> []
5732   | x :: xs ->
5733       match f x with
5734       | Some y -> y :: filter_map f xs
5735       | None -> filter_map f xs
5736
5737 let rec find_map f = function
5738   | [] -> raise Not_found
5739   | x :: xs ->
5740       match f x with
5741       | Some y -> y
5742       | None -> find_map f xs
5743
5744 let iteri f xs =
5745   let rec loop i = function
5746     | [] -> ()
5747     | x :: xs -> f i x; loop (i+1) xs
5748   in
5749   loop 0 xs
5750
5751 let mapi f xs =
5752   let rec loop i = function
5753     | [] -> []
5754     | x :: xs -> let r = f i x in r :: loop (i+1) xs
5755   in
5756   loop 0 xs
5757
5758 let count_chars c str =
5759   let count = ref 0 in
5760   for i = 0 to String.length str - 1 do
5761     if c = String.unsafe_get str i then incr count
5762   done;
5763   !count
5764
5765 let explode str =
5766   let r = ref [] in
5767   for i = 0 to String.length str - 1 do
5768     let c = String.unsafe_get str i in
5769     r := c :: !r;
5770   done;
5771   List.rev !r
5772
5773 let map_chars f str =
5774   List.map f (explode str)
5775
5776 let name_of_argt = function
5777   | Pathname n | Device n | Dev_or_Path n | String n | OptString n
5778   | StringList n | DeviceList n | Bool n | Int n | Int64 n
5779   | FileIn n | FileOut n | BufferIn n | Key n -> n
5780
5781 let java_name_of_struct typ =
5782   try List.assoc typ java_structs
5783   with Not_found ->
5784     failwithf
5785       "java_name_of_struct: no java_structs entry corresponding to %s" typ
5786
5787 let cols_of_struct typ =
5788   try List.assoc typ structs
5789   with Not_found ->
5790     failwithf "cols_of_struct: unknown struct %s" typ
5791
5792 let seq_of_test = function
5793   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
5794   | TestOutputListOfDevices (s, _)
5795   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
5796   | TestOutputTrue s | TestOutputFalse s
5797   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
5798   | TestOutputStruct (s, _)
5799   | TestLastFail s -> s
5800
5801 (* Handling for function flags. *)
5802 let protocol_limit_warning =
5803   "Because of the message protocol, there is a transfer limit
5804 of somewhere between 2MB and 4MB.  See L<guestfs(3)/PROTOCOL LIMITS>."
5805
5806 let danger_will_robinson =
5807   "B<This command is dangerous.  Without careful use you
5808 can easily destroy all your data>."
5809
5810 let deprecation_notice flags =
5811   try
5812     let alt =
5813       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
5814     let txt =
5815       sprintf "This function is deprecated.
5816 In new code, use the C<%s> call instead.
5817
5818 Deprecated functions will not be removed from the API, but the
5819 fact that they are deprecated indicates that there are problems
5820 with correct use of these functions." alt in
5821     Some txt
5822   with
5823     Not_found -> None
5824
5825 (* Create list of optional groups. *)
5826 let optgroups =
5827   let h = Hashtbl.create 13 in
5828   List.iter (
5829     fun (name, _, _, flags, _, _, _) ->
5830       List.iter (
5831         function
5832         | Optional group ->
5833             let names = try Hashtbl.find h group with Not_found -> [] in
5834             Hashtbl.replace h group (name :: names)
5835         | _ -> ()
5836       ) flags
5837   ) daemon_functions;
5838   let groups = Hashtbl.fold (fun k _ ks -> k :: ks) h [] in
5839   let groups =
5840     List.map (
5841       fun group -> group, List.sort compare (Hashtbl.find h group)
5842     ) groups in
5843   List.sort (fun x y -> compare (fst x) (fst y)) groups
5844
5845 (* Check function names etc. for consistency. *)
5846 let check_functions () =
5847   let contains_uppercase str =
5848     let len = String.length str in
5849     let rec loop i =
5850       if i >= len then false
5851       else (
5852         let c = str.[i] in
5853         if c >= 'A' && c <= 'Z' then true
5854         else loop (i+1)
5855       )
5856     in
5857     loop 0
5858   in
5859
5860   (* Check function names. *)
5861   List.iter (
5862     fun (name, _, _, _, _, _, _) ->
5863       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
5864         failwithf "function name %s does not need 'guestfs' prefix" name;
5865       if name = "" then
5866         failwithf "function name is empty";
5867       if name.[0] < 'a' || name.[0] > 'z' then
5868         failwithf "function name %s must start with lowercase a-z" name;
5869       if String.contains name '-' then
5870         failwithf "function name %s should not contain '-', use '_' instead."
5871           name
5872   ) all_functions;
5873
5874   (* Check function parameter/return names. *)
5875   List.iter (
5876     fun (name, style, _, _, _, _, _) ->
5877       let check_arg_ret_name n =
5878         if contains_uppercase n then
5879           failwithf "%s param/ret %s should not contain uppercase chars"
5880             name n;
5881         if String.contains n '-' || String.contains n '_' then
5882           failwithf "%s param/ret %s should not contain '-' or '_'"
5883             name n;
5884         if n = "value" then
5885           failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
5886         if n = "int" || n = "char" || n = "short" || n = "long" then
5887           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
5888         if n = "i" || n = "n" then
5889           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
5890         if n = "argv" || n = "args" then
5891           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
5892
5893         (* List Haskell, OCaml and C keywords here.
5894          * http://www.haskell.org/haskellwiki/Keywords
5895          * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
5896          * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
5897          * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
5898          *   |perl -pe 's/(.+)/"$1";/'|fmt -70
5899          * Omitting _-containing words, since they're handled above.
5900          * Omitting the OCaml reserved word, "val", is ok,
5901          * and saves us from renaming several parameters.
5902          *)
5903         let reserved = [
5904           "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
5905           "char"; "class"; "const"; "constraint"; "continue"; "data";
5906           "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
5907           "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
5908           "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
5909           "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
5910           "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
5911           "interface";
5912           "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
5913           "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
5914           "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
5915           "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
5916           "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
5917           "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
5918           "volatile"; "when"; "where"; "while";
5919           ] in
5920         if List.mem n reserved then
5921           failwithf "%s has param/ret using reserved word %s" name n;
5922       in
5923
5924       (match fst style with
5925        | RErr -> ()
5926        | RInt n | RInt64 n | RBool n
5927        | RConstString n | RConstOptString n | RString n
5928        | RStringList n | RStruct (n, _) | RStructList (n, _)
5929        | RHashtable n | RBufferOut n ->
5930            check_arg_ret_name n
5931       );
5932       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
5933   ) all_functions;
5934
5935   (* Check short descriptions. *)
5936   List.iter (
5937     fun (name, _, _, _, _, shortdesc, _) ->
5938       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
5939         failwithf "short description of %s should begin with lowercase." name;
5940       let c = shortdesc.[String.length shortdesc-1] in
5941       if c = '\n' || c = '.' then
5942         failwithf "short description of %s should not end with . or \\n." name
5943   ) all_functions;
5944
5945   (* Check long descriptions. *)
5946   List.iter (
5947     fun (name, _, _, _, _, _, longdesc) ->
5948       if longdesc.[String.length longdesc-1] = '\n' then
5949         failwithf "long description of %s should not end with \\n." name
5950   ) all_functions;
5951
5952   (* Check proc_nrs. *)
5953   List.iter (
5954     fun (name, _, proc_nr, _, _, _, _) ->
5955       if proc_nr <= 0 then
5956         failwithf "daemon function %s should have proc_nr > 0" name
5957   ) daemon_functions;
5958
5959   List.iter (
5960     fun (name, _, proc_nr, _, _, _, _) ->
5961       if proc_nr <> -1 then
5962         failwithf "non-daemon function %s should have proc_nr -1" name
5963   ) non_daemon_functions;
5964
5965   let proc_nrs =
5966     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
5967       daemon_functions in
5968   let proc_nrs =
5969     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
5970   let rec loop = function
5971     | [] -> ()
5972     | [_] -> ()
5973     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
5974         loop rest
5975     | (name1,nr1) :: (name2,nr2) :: _ ->
5976         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
5977           name1 name2 nr1 nr2
5978   in
5979   loop proc_nrs;
5980
5981   (* Check tests. *)
5982   List.iter (
5983     function
5984       (* Ignore functions that have no tests.  We generate a
5985        * warning when the user does 'make check' instead.
5986        *)
5987     | name, _, _, _, [], _, _ -> ()
5988     | name, _, _, _, tests, _, _ ->
5989         let funcs =
5990           List.map (
5991             fun (_, _, test) ->
5992               match seq_of_test test with
5993               | [] ->
5994                   failwithf "%s has a test containing an empty sequence" name
5995               | cmds -> List.map List.hd cmds
5996           ) tests in
5997         let funcs = List.flatten funcs in
5998
5999         let tested = List.mem name funcs in
6000
6001         if not tested then
6002           failwithf "function %s has tests but does not test itself" name
6003   ) all_functions
6004
6005 (* 'pr' prints to the current output file. *)
6006 let chan = ref Pervasives.stdout
6007 let lines = ref 0
6008 let pr fs =
6009   ksprintf
6010     (fun str ->
6011        let i = count_chars '\n' str in
6012        lines := !lines + i;
6013        output_string !chan str
6014     ) fs
6015
6016 let copyright_years =
6017   let this_year = 1900 + (localtime (time ())).tm_year in
6018   if this_year > 2009 then sprintf "2009-%04d" this_year else "2009"
6019
6020 (* Generate a header block in a number of standard styles. *)
6021 type comment_style =
6022     CStyle | CPlusPlusStyle | HashStyle | OCamlStyle | HaskellStyle
6023 type license = GPLv2plus | LGPLv2plus
6024
6025 let generate_header ?(extra_inputs = []) comment license =
6026   let inputs = "src/generator.ml" :: extra_inputs in
6027   let c = match comment with
6028     | CStyle ->         pr "/* "; " *"
6029     | CPlusPlusStyle -> pr "// "; "//"
6030     | HashStyle ->      pr "# ";  "#"
6031     | OCamlStyle ->     pr "(* "; " *"
6032     | HaskellStyle ->   pr "{- "; "  " in
6033   pr "libguestfs generated file\n";
6034   pr "%s WARNING: THIS FILE IS GENERATED FROM:\n" c;
6035   List.iter (pr "%s   %s\n" c) inputs;
6036   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
6037   pr "%s\n" c;
6038   pr "%s Copyright (C) %s Red Hat Inc.\n" c copyright_years;
6039   pr "%s\n" c;
6040   (match license with
6041    | GPLv2plus ->
6042        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
6043        pr "%s it under the terms of the GNU General Public License as published by\n" c;
6044        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
6045        pr "%s (at your option) any later version.\n" c;
6046        pr "%s\n" c;
6047        pr "%s This program is distributed in the hope that it will be useful,\n" c;
6048        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6049        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
6050        pr "%s GNU General Public License for more details.\n" c;
6051        pr "%s\n" c;
6052        pr "%s You should have received a copy of the GNU General Public License along\n" c;
6053        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
6054        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
6055
6056    | LGPLv2plus ->
6057        pr "%s This library is free software; you can redistribute it and/or\n" c;
6058        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
6059        pr "%s License as published by the Free Software Foundation; either\n" c;
6060        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
6061        pr "%s\n" c;
6062        pr "%s This library is distributed in the hope that it will be useful,\n" c;
6063        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
6064        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
6065        pr "%s Lesser General Public License for more details.\n" c;
6066        pr "%s\n" c;
6067        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
6068        pr "%s License along with this library; if not, write to the Free Software\n" c;
6069        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
6070   );
6071   (match comment with
6072    | CStyle -> pr " */\n"
6073    | CPlusPlusStyle
6074    | HashStyle -> ()
6075    | OCamlStyle -> pr " *)\n"
6076    | HaskellStyle -> pr "-}\n"
6077   );
6078   pr "\n"
6079
6080 (* Start of main code generation functions below this line. *)
6081
6082 (* Generate the pod documentation for the C API. *)
6083 let rec generate_actions_pod () =
6084   List.iter (
6085     fun (shortname, style, _, flags, _, _, longdesc) ->
6086       if not (List.mem NotInDocs flags) then (
6087         let name = "guestfs_" ^ shortname in
6088         pr "=head2 %s\n\n" name;
6089         pr " ";
6090         generate_prototype ~extern:false ~handle:"g" name style;
6091         pr "\n\n";
6092         pr "%s\n\n" longdesc;
6093         (match fst style with
6094          | RErr ->
6095              pr "This function returns 0 on success or -1 on error.\n\n"
6096          | RInt _ ->
6097              pr "On error this function returns -1.\n\n"
6098          | RInt64 _ ->
6099              pr "On error this function returns -1.\n\n"
6100          | RBool _ ->
6101              pr "This function returns a C truth value on success or -1 on error.\n\n"
6102          | RConstString _ ->
6103              pr "This function returns a string, or NULL on error.
6104 The string is owned by the guest handle and must I<not> be freed.\n\n"
6105          | RConstOptString _ ->
6106              pr "This function returns a string which may be NULL.
6107 There is no way to return an error from this function.
6108 The string is owned by the guest handle and must I<not> be freed.\n\n"
6109          | RString _ ->
6110              pr "This function returns a string, or NULL on error.
6111 I<The caller must free the returned string after use>.\n\n"
6112          | RStringList _ ->
6113              pr "This function returns a NULL-terminated array of strings
6114 (like L<environ(3)>), or NULL if there was an error.
6115 I<The caller must free the strings and the array after use>.\n\n"
6116          | RStruct (_, typ) ->
6117              pr "This function returns a C<struct guestfs_%s *>,
6118 or NULL if there was an error.
6119 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
6120          | RStructList (_, typ) ->
6121              pr "This function returns a C<struct guestfs_%s_list *>
6122 (see E<lt>guestfs-structs.hE<gt>),
6123 or NULL if there was an error.
6124 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
6125          | RHashtable _ ->
6126              pr "This function returns a NULL-terminated array of
6127 strings, or NULL if there was an error.
6128 The array of strings will always have length C<2n+1>, where
6129 C<n> keys and values alternate, followed by the trailing NULL entry.
6130 I<The caller must free the strings and the array after use>.\n\n"
6131          | RBufferOut _ ->
6132              pr "This function returns a buffer, or NULL on error.
6133 The size of the returned buffer is written to C<*size_r>.
6134 I<The caller must free the returned buffer after use>.\n\n"
6135         );
6136         if List.mem ProtocolLimitWarning flags then
6137           pr "%s\n\n" protocol_limit_warning;
6138         if List.mem DangerWillRobinson flags then
6139           pr "%s\n\n" danger_will_robinson;
6140         if List.exists (function Key _ -> true | _ -> false) (snd style) then
6141           pr "This function takes a key or passphrase parameter which
6142 could contain sensitive material.  Read the section
6143 L</KEYS AND PASSPHRASES> for more information.\n\n";
6144         match deprecation_notice flags with
6145         | None -> ()
6146         | Some txt -> pr "%s\n\n" txt
6147       )
6148   ) all_functions_sorted
6149
6150 and generate_structs_pod () =
6151   (* Structs documentation. *)
6152   List.iter (
6153     fun (typ, cols) ->
6154       pr "=head2 guestfs_%s\n" typ;
6155       pr "\n";
6156       pr " struct guestfs_%s {\n" typ;
6157       List.iter (
6158         function
6159         | name, FChar -> pr "   char %s;\n" name
6160         | name, FUInt32 -> pr "   uint32_t %s;\n" name
6161         | name, FInt32 -> pr "   int32_t %s;\n" name
6162         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
6163         | name, FInt64 -> pr "   int64_t %s;\n" name
6164         | name, FString -> pr "   char *%s;\n" name
6165         | name, FBuffer ->
6166             pr "   /* The next two fields describe a byte array. */\n";
6167             pr "   uint32_t %s_len;\n" name;
6168             pr "   char *%s;\n" name
6169         | name, FUUID ->
6170             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
6171             pr "   char %s[32];\n" name
6172         | name, FOptPercent ->
6173             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
6174             pr "   float %s;\n" name
6175       ) cols;
6176       pr " };\n";
6177       pr " \n";
6178       pr " struct guestfs_%s_list {\n" typ;
6179       pr "   uint32_t len; /* Number of elements in list. */\n";
6180       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
6181       pr " };\n";
6182       pr " \n";
6183       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
6184       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
6185         typ typ;
6186       pr "\n"
6187   ) structs
6188
6189 and generate_availability_pod () =
6190   (* Availability documentation. *)
6191   pr "=over 4\n";
6192   pr "\n";
6193   List.iter (
6194     fun (group, functions) ->
6195       pr "=item B<%s>\n" group;
6196       pr "\n";
6197       pr "The following functions:\n";
6198       List.iter (pr "L</guestfs_%s>\n") functions;
6199       pr "\n"
6200   ) optgroups;
6201   pr "=back\n";
6202   pr "\n"
6203
6204 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
6205  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
6206  *
6207  * We have to use an underscore instead of a dash because otherwise
6208  * rpcgen generates incorrect code.
6209  *
6210  * This header is NOT exported to clients, but see also generate_structs_h.
6211  *)
6212 and generate_xdr () =
6213   generate_header CStyle LGPLv2plus;
6214
6215   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
6216   pr "typedef string str<>;\n";
6217   pr "\n";
6218
6219   (* Internal structures. *)
6220   List.iter (
6221     function
6222     | typ, cols ->
6223         pr "struct guestfs_int_%s {\n" typ;
6224         List.iter (function
6225                    | name, FChar -> pr "  char %s;\n" name
6226                    | name, FString -> pr "  string %s<>;\n" name
6227                    | name, FBuffer -> pr "  opaque %s<>;\n" name
6228                    | name, FUUID -> pr "  opaque %s[32];\n" name
6229                    | name, (FInt32|FUInt32) -> pr "  int %s;\n" name
6230                    | name, (FInt64|FUInt64|FBytes) -> pr "  hyper %s;\n" name
6231                    | name, FOptPercent -> pr "  float %s;\n" name
6232                   ) cols;
6233         pr "};\n";
6234         pr "\n";
6235         pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
6236         pr "\n";
6237   ) structs;
6238
6239   List.iter (
6240     fun (shortname, style, _, _, _, _, _) ->
6241       let name = "guestfs_" ^ shortname in
6242
6243       (match snd style with
6244        | [] -> ()
6245        | args ->
6246            pr "struct %s_args {\n" name;
6247            List.iter (
6248              function
6249              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6250                  pr "  string %s<>;\n" n
6251              | OptString n -> pr "  str *%s;\n" n
6252              | StringList n | DeviceList n -> pr "  str %s<>;\n" n
6253              | Bool n -> pr "  bool %s;\n" n
6254              | Int n -> pr "  int %s;\n" n
6255              | Int64 n -> pr "  hyper %s;\n" n
6256              | BufferIn n ->
6257                  pr "  opaque %s<>;\n" n
6258              | FileIn _ | FileOut _ -> ()
6259            ) args;
6260            pr "};\n\n"
6261       );
6262       (match fst style with
6263        | RErr -> ()
6264        | RInt n ->
6265            pr "struct %s_ret {\n" name;
6266            pr "  int %s;\n" n;
6267            pr "};\n\n"
6268        | RInt64 n ->
6269            pr "struct %s_ret {\n" name;
6270            pr "  hyper %s;\n" n;
6271            pr "};\n\n"
6272        | RBool n ->
6273            pr "struct %s_ret {\n" name;
6274            pr "  bool %s;\n" n;
6275            pr "};\n\n"
6276        | RConstString _ | RConstOptString _ ->
6277            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6278        | RString n ->
6279            pr "struct %s_ret {\n" name;
6280            pr "  string %s<>;\n" n;
6281            pr "};\n\n"
6282        | RStringList n ->
6283            pr "struct %s_ret {\n" name;
6284            pr "  str %s<>;\n" n;
6285            pr "};\n\n"
6286        | RStruct (n, typ) ->
6287            pr "struct %s_ret {\n" name;
6288            pr "  guestfs_int_%s %s;\n" typ n;
6289            pr "};\n\n"
6290        | RStructList (n, typ) ->
6291            pr "struct %s_ret {\n" name;
6292            pr "  guestfs_int_%s_list %s;\n" typ n;
6293            pr "};\n\n"
6294        | RHashtable n ->
6295            pr "struct %s_ret {\n" name;
6296            pr "  str %s<>;\n" n;
6297            pr "};\n\n"
6298        | RBufferOut n ->
6299            pr "struct %s_ret {\n" name;
6300            pr "  opaque %s<>;\n" n;
6301            pr "};\n\n"
6302       );
6303   ) daemon_functions;
6304
6305   (* Table of procedure numbers. *)
6306   pr "enum guestfs_procedure {\n";
6307   List.iter (
6308     fun (shortname, _, proc_nr, _, _, _, _) ->
6309       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
6310   ) daemon_functions;
6311   pr "  GUESTFS_PROC_NR_PROCS\n";
6312   pr "};\n";
6313   pr "\n";
6314
6315   (* Having to choose a maximum message size is annoying for several
6316    * reasons (it limits what we can do in the API), but it (a) makes
6317    * the protocol a lot simpler, and (b) provides a bound on the size
6318    * of the daemon which operates in limited memory space.
6319    *)
6320   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
6321   pr "\n";
6322
6323   (* Message header, etc. *)
6324   pr "\
6325 /* The communication protocol is now documented in the guestfs(3)
6326  * manpage.
6327  */
6328
6329 const GUESTFS_PROGRAM = 0x2000F5F5;
6330 const GUESTFS_PROTOCOL_VERSION = 1;
6331
6332 /* These constants must be larger than any possible message length. */
6333 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
6334 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
6335
6336 enum guestfs_message_direction {
6337   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
6338   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
6339 };
6340
6341 enum guestfs_message_status {
6342   GUESTFS_STATUS_OK = 0,
6343   GUESTFS_STATUS_ERROR = 1
6344 };
6345
6346 ";
6347
6348   pr "const GUESTFS_ERROR_LEN = %d;\n" (64 * 1024);
6349   pr "\n";
6350
6351   pr "\
6352 struct guestfs_message_error {
6353   int linux_errno;                   /* Linux errno if available. */
6354   string error_message<GUESTFS_ERROR_LEN>;
6355 };
6356
6357 struct guestfs_message_header {
6358   unsigned prog;                     /* GUESTFS_PROGRAM */
6359   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
6360   guestfs_procedure proc;            /* GUESTFS_PROC_x */
6361   guestfs_message_direction direction;
6362   unsigned serial;                   /* message serial number */
6363   guestfs_message_status status;
6364 };
6365
6366 const GUESTFS_MAX_CHUNK_SIZE = 8192;
6367
6368 struct guestfs_chunk {
6369   int cancel;                        /* if non-zero, transfer is cancelled */
6370   /* data size is 0 bytes if the transfer has finished successfully */
6371   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
6372 };
6373 "
6374
6375 (* Generate the guestfs-structs.h file. *)
6376 and generate_structs_h () =
6377   generate_header CStyle LGPLv2plus;
6378
6379   (* This is a public exported header file containing various
6380    * structures.  The structures are carefully written to have
6381    * exactly the same in-memory format as the XDR structures that
6382    * we use on the wire to the daemon.  The reason for creating
6383    * copies of these structures here is just so we don't have to
6384    * export the whole of guestfs_protocol.h (which includes much
6385    * unrelated and XDR-dependent stuff that we don't want to be
6386    * public, or required by clients).
6387    *
6388    * To reiterate, we will pass these structures to and from the
6389    * client with a simple assignment or memcpy, so the format
6390    * must be identical to what rpcgen / the RFC defines.
6391    *)
6392
6393   (* Public structures. *)
6394   List.iter (
6395     fun (typ, cols) ->
6396       pr "struct guestfs_%s {\n" typ;
6397       List.iter (
6398         function
6399         | name, FChar -> pr "  char %s;\n" name
6400         | name, FString -> pr "  char *%s;\n" name
6401         | name, FBuffer ->
6402             pr "  uint32_t %s_len;\n" name;
6403             pr "  char *%s;\n" name
6404         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
6405         | name, FUInt32 -> pr "  uint32_t %s;\n" name
6406         | name, FInt32 -> pr "  int32_t %s;\n" name
6407         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
6408         | name, FInt64 -> pr "  int64_t %s;\n" name
6409         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
6410       ) cols;
6411       pr "};\n";
6412       pr "\n";
6413       pr "struct guestfs_%s_list {\n" typ;
6414       pr "  uint32_t len;\n";
6415       pr "  struct guestfs_%s *val;\n" typ;
6416       pr "};\n";
6417       pr "\n";
6418       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
6419       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
6420       pr "\n"
6421   ) structs
6422
6423 (* Generate the guestfs-actions.h file. *)
6424 and generate_actions_h () =
6425   generate_header CStyle LGPLv2plus;
6426   List.iter (
6427     fun (shortname, style, _, _, _, _, _) ->
6428       let name = "guestfs_" ^ shortname in
6429       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6430         name style
6431   ) all_functions
6432
6433 (* Generate the guestfs-internal-actions.h file. *)
6434 and generate_internal_actions_h () =
6435   generate_header CStyle LGPLv2plus;
6436   List.iter (
6437     fun (shortname, style, _, _, _, _, _) ->
6438       let name = "guestfs__" ^ shortname in
6439       generate_prototype ~single_line:true ~newline:true ~handle:"g"
6440         name style
6441   ) non_daemon_functions
6442
6443 (* Generate the client-side dispatch stubs. *)
6444 and generate_client_actions () =
6445   generate_header CStyle LGPLv2plus;
6446
6447   pr "\
6448 #include <stdio.h>
6449 #include <stdlib.h>
6450 #include <stdint.h>
6451 #include <string.h>
6452 #include <inttypes.h>
6453
6454 #include \"guestfs.h\"
6455 #include \"guestfs-internal.h\"
6456 #include \"guestfs-internal-actions.h\"
6457 #include \"guestfs_protocol.h\"
6458
6459 /* Check the return message from a call for validity. */
6460 static int
6461 check_reply_header (guestfs_h *g,
6462                     const struct guestfs_message_header *hdr,
6463                     unsigned int proc_nr, unsigned int serial)
6464 {
6465   if (hdr->prog != GUESTFS_PROGRAM) {
6466     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
6467     return -1;
6468   }
6469   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
6470     error (g, \"wrong protocol version (%%d/%%d)\",
6471            hdr->vers, GUESTFS_PROTOCOL_VERSION);
6472     return -1;
6473   }
6474   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
6475     error (g, \"unexpected message direction (%%d/%%d)\",
6476            hdr->direction, GUESTFS_DIRECTION_REPLY);
6477     return -1;
6478   }
6479   if (hdr->proc != proc_nr) {
6480     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
6481     return -1;
6482   }
6483   if (hdr->serial != serial) {
6484     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
6485     return -1;
6486   }
6487
6488   return 0;
6489 }
6490
6491 /* Check we are in the right state to run a high-level action. */
6492 static int
6493 check_state (guestfs_h *g, const char *caller)
6494 {
6495   if (!guestfs__is_ready (g)) {
6496     if (guestfs__is_config (g) || guestfs__is_launching (g))
6497       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
6498         caller);
6499     else
6500       error (g, \"%%s called from the wrong state, %%d != READY\",
6501         caller, guestfs__get_state (g));
6502     return -1;
6503   }
6504   return 0;
6505 }
6506
6507 ";
6508
6509   let error_code_of = function
6510     | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
6511     | RConstString _ | RConstOptString _
6512     | RString _ | RStringList _
6513     | RStruct _ | RStructList _
6514     | RHashtable _ | RBufferOut _ -> "NULL"
6515   in
6516
6517   (* Generate code to check String-like parameters are not passed in
6518    * as NULL (returning an error if they are).
6519    *)
6520   let check_null_strings shortname style =
6521     let pr_newline = ref false in
6522     List.iter (
6523       function
6524       (* parameters which should not be NULL *)
6525       | String n
6526       | Device n
6527       | Pathname n
6528       | Dev_or_Path n
6529       | FileIn n
6530       | FileOut n
6531       | BufferIn n
6532       | StringList n
6533       | DeviceList n
6534       | Key n ->
6535           pr "  if (%s == NULL) {\n" n;
6536           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
6537           pr "           \"%s\", \"%s\");\n" shortname n;
6538           pr "    return %s;\n" (error_code_of (fst style));
6539           pr "  }\n";
6540           pr_newline := true
6541
6542       (* can be NULL *)
6543       | OptString _
6544
6545       (* not applicable *)
6546       | Bool _
6547       | Int _
6548       | Int64 _ -> ()
6549     ) (snd style);
6550
6551     if !pr_newline then pr "\n";
6552   in
6553
6554   (* Generate code to generate guestfish call traces. *)
6555   let trace_call shortname style =
6556     pr "  if (guestfs__get_trace (g)) {\n";
6557
6558     let needs_i =
6559       List.exists (function
6560                    | StringList _ | DeviceList _ -> true
6561                    | _ -> false) (snd style) in
6562     if needs_i then (
6563       pr "    size_t i;\n";
6564       pr "\n"
6565     );
6566
6567     pr "    fprintf (stderr, \"%s\");\n" shortname;
6568     List.iter (
6569       function
6570       | String n                        (* strings *)
6571       | Device n
6572       | Pathname n
6573       | Dev_or_Path n
6574       | FileIn n
6575       | FileOut n
6576       | BufferIn n
6577       | Key n ->
6578           (* guestfish doesn't support string escaping, so neither do we *)
6579           pr "    fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
6580       | OptString n ->                  (* string option *)
6581           pr "    if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
6582           pr "    else fprintf (stderr, \" null\");\n"
6583       | StringList n
6584       | DeviceList n ->                 (* string list *)
6585           pr "    fputc (' ', stderr);\n";
6586           pr "    fputc ('\"', stderr);\n";
6587           pr "    for (i = 0; %s[i]; ++i) {\n" n;
6588           pr "      if (i > 0) fputc (' ', stderr);\n";
6589           pr "      fputs (%s[i], stderr);\n" n;
6590           pr "    }\n";
6591           pr "    fputc ('\"', stderr);\n";
6592       | Bool n ->                       (* boolean *)
6593           pr "    fputs (%s ? \" true\" : \" false\", stderr);\n" n
6594       | Int n ->                        (* int *)
6595           pr "    fprintf (stderr, \" %%d\", %s);\n" n
6596       | Int64 n ->
6597           pr "    fprintf (stderr, \" %%\" PRIi64, %s);\n" n
6598     ) (snd style);
6599     pr "    fputc ('\\n', stderr);\n";
6600     pr "  }\n";
6601     pr "\n";
6602   in
6603
6604   (* For non-daemon functions, generate a wrapper around each function. *)
6605   List.iter (
6606     fun (shortname, style, _, _, _, _, _) ->
6607       let name = "guestfs_" ^ shortname in
6608
6609       generate_prototype ~extern:false ~semicolon:false ~newline:true
6610         ~handle:"g" name style;
6611       pr "{\n";
6612       check_null_strings shortname style;
6613       trace_call shortname style;
6614       pr "  return guestfs__%s " shortname;
6615       generate_c_call_args ~handle:"g" style;
6616       pr ";\n";
6617       pr "}\n";
6618       pr "\n"
6619   ) non_daemon_functions;
6620
6621   (* Client-side stubs for each function. *)
6622   List.iter (
6623     fun (shortname, style, _, _, _, _, _) ->
6624       let name = "guestfs_" ^ shortname in
6625       let error_code = error_code_of (fst style) in
6626
6627       (* Generate the action stub. *)
6628       generate_prototype ~extern:false ~semicolon:false ~newline:true
6629         ~handle:"g" name style;
6630
6631       pr "{\n";
6632
6633       (match snd style with
6634        | [] -> ()
6635        | _ -> pr "  struct %s_args args;\n" name
6636       );
6637
6638       pr "  guestfs_message_header hdr;\n";
6639       pr "  guestfs_message_error err;\n";
6640       let has_ret =
6641         match fst style with
6642         | RErr -> false
6643         | RConstString _ | RConstOptString _ ->
6644             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6645         | RInt _ | RInt64 _
6646         | RBool _ | RString _ | RStringList _
6647         | RStruct _ | RStructList _
6648         | RHashtable _ | RBufferOut _ ->
6649             pr "  struct %s_ret ret;\n" name;
6650             true in
6651
6652       pr "  int serial;\n";
6653       pr "  int r;\n";
6654       pr "\n";
6655       check_null_strings shortname style;
6656       trace_call shortname style;
6657       pr "  if (check_state (g, \"%s\") == -1) return %s;\n"
6658         shortname error_code;
6659       pr "  guestfs___set_busy (g);\n";
6660       pr "\n";
6661
6662       (* Send the main header and arguments. *)
6663       (match snd style with
6664        | [] ->
6665            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
6666              (String.uppercase shortname)
6667        | args ->
6668            List.iter (
6669              function
6670              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
6671                  pr "  args.%s = (char *) %s;\n" n n
6672              | OptString n ->
6673                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
6674              | StringList n | DeviceList n ->
6675                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
6676                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
6677              | Bool n ->
6678                  pr "  args.%s = %s;\n" n n
6679              | Int n ->
6680                  pr "  args.%s = %s;\n" n n
6681              | Int64 n ->
6682                  pr "  args.%s = %s;\n" n n
6683              | FileIn _ | FileOut _ -> ()
6684              | BufferIn n ->
6685                  pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
6686                  pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
6687                  pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
6688                    shortname;
6689                  pr "    guestfs___end_busy (g);\n";
6690                  pr "    return %s;\n" error_code;
6691                  pr "  }\n";
6692                  pr "  args.%s.%s_val = (char *) %s;\n" n n n;
6693                  pr "  args.%s.%s_len = %s_size;\n" n n n
6694            ) args;
6695            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
6696              (String.uppercase shortname);
6697            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
6698              name;
6699       );
6700       pr "  if (serial == -1) {\n";
6701       pr "    guestfs___end_busy (g);\n";
6702       pr "    return %s;\n" error_code;
6703       pr "  }\n";
6704       pr "\n";
6705
6706       (* Send any additional files (FileIn) requested. *)
6707       let need_read_reply_label = ref false in
6708       List.iter (
6709         function
6710         | FileIn n ->
6711             pr "  r = guestfs___send_file (g, %s);\n" n;
6712             pr "  if (r == -1) {\n";
6713             pr "    guestfs___end_busy (g);\n";
6714             pr "    return %s;\n" error_code;
6715             pr "  }\n";
6716             pr "  if (r == -2) /* daemon cancelled */\n";
6717             pr "    goto read_reply;\n";
6718             need_read_reply_label := true;
6719             pr "\n";
6720         | _ -> ()
6721       ) (snd style);
6722
6723       (* Wait for the reply from the remote end. *)
6724       if !need_read_reply_label then pr " read_reply:\n";
6725       pr "  memset (&hdr, 0, sizeof hdr);\n";
6726       pr "  memset (&err, 0, sizeof err);\n";
6727       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
6728       pr "\n";
6729       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
6730       if not has_ret then
6731         pr "NULL, NULL"
6732       else
6733         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
6734       pr ");\n";
6735
6736       pr "  if (r == -1) {\n";
6737       pr "    guestfs___end_busy (g);\n";
6738       pr "    return %s;\n" error_code;
6739       pr "  }\n";
6740       pr "\n";
6741
6742       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
6743         (String.uppercase shortname);
6744       pr "    guestfs___end_busy (g);\n";
6745       pr "    return %s;\n" error_code;
6746       pr "  }\n";
6747       pr "\n";
6748
6749       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
6750       pr "    error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
6751       pr "    free (err.error_message);\n";
6752       pr "    guestfs___end_busy (g);\n";
6753       pr "    return %s;\n" error_code;
6754       pr "  }\n";
6755       pr "\n";
6756
6757       (* Expecting to receive further files (FileOut)? *)
6758       List.iter (
6759         function
6760         | FileOut n ->
6761             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
6762             pr "    guestfs___end_busy (g);\n";
6763             pr "    return %s;\n" error_code;
6764             pr "  }\n";
6765             pr "\n";
6766         | _ -> ()
6767       ) (snd style);
6768
6769       pr "  guestfs___end_busy (g);\n";
6770
6771       (match fst style with
6772        | RErr -> pr "  return 0;\n"
6773        | RInt n | RInt64 n | RBool n ->
6774            pr "  return ret.%s;\n" n
6775        | RConstString _ | RConstOptString _ ->
6776            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6777        | RString n ->
6778            pr "  return ret.%s; /* caller will free */\n" n
6779        | RStringList n | RHashtable n ->
6780            pr "  /* caller will free this, but we need to add a NULL entry */\n";
6781            pr "  ret.%s.%s_val =\n" n n;
6782            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
6783            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
6784              n n;
6785            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
6786            pr "  return ret.%s.%s_val;\n" n n
6787        | RStruct (n, _) ->
6788            pr "  /* caller will free this */\n";
6789            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6790        | RStructList (n, _) ->
6791            pr "  /* caller will free this */\n";
6792            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
6793        | RBufferOut n ->
6794            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
6795            pr "   * _val might be NULL here.  To make the API saner for\n";
6796            pr "   * callers, we turn this case into a unique pointer (using\n";
6797            pr "   * malloc(1)).\n";
6798            pr "   */\n";
6799            pr "  if (ret.%s.%s_len > 0) {\n" n n;
6800            pr "    *size_r = ret.%s.%s_len;\n" n n;
6801            pr "    return ret.%s.%s_val; /* caller will free */\n" n n;
6802            pr "  } else {\n";
6803            pr "    free (ret.%s.%s_val);\n" n n;
6804            pr "    char *p = safe_malloc (g, 1);\n";
6805            pr "    *size_r = ret.%s.%s_len;\n" n n;
6806            pr "    return p;\n";
6807            pr "  }\n";
6808       );
6809
6810       pr "}\n\n"
6811   ) daemon_functions;
6812
6813   (* Functions to free structures. *)
6814   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
6815   pr " * structure format is identical to the XDR format.  See note in\n";
6816   pr " * generator.ml.\n";
6817   pr " */\n";
6818   pr "\n";
6819
6820   List.iter (
6821     fun (typ, _) ->
6822       pr "void\n";
6823       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
6824       pr "{\n";
6825       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
6826       pr "  free (x);\n";
6827       pr "}\n";
6828       pr "\n";
6829
6830       pr "void\n";
6831       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
6832       pr "{\n";
6833       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
6834       pr "  free (x);\n";
6835       pr "}\n";
6836       pr "\n";
6837
6838   ) structs;
6839
6840 (* Generate daemon/actions.h. *)
6841 and generate_daemon_actions_h () =
6842   generate_header CStyle GPLv2plus;
6843
6844   pr "#include \"../src/guestfs_protocol.h\"\n";
6845   pr "\n";
6846
6847   List.iter (
6848     fun (name, style, _, _, _, _, _) ->
6849       generate_prototype
6850         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
6851         name style;
6852   ) daemon_functions
6853
6854 (* Generate the linker script which controls the visibility of
6855  * symbols in the public ABI and ensures no other symbols get
6856  * exported accidentally.
6857  *)
6858 and generate_linker_script () =
6859   generate_header HashStyle GPLv2plus;
6860
6861   let globals = [
6862     "guestfs_create";
6863     "guestfs_close";
6864     "guestfs_get_error_handler";
6865     "guestfs_get_out_of_memory_handler";
6866     "guestfs_last_error";
6867     "guestfs_set_close_callback";
6868     "guestfs_set_error_handler";
6869     "guestfs_set_launch_done_callback";
6870     "guestfs_set_log_message_callback";
6871     "guestfs_set_out_of_memory_handler";
6872     "guestfs_set_subprocess_quit_callback";
6873
6874     (* Unofficial parts of the API: the bindings code use these
6875      * functions, so it is useful to export them.
6876      *)
6877     "guestfs_safe_calloc";
6878     "guestfs_safe_malloc";
6879     "guestfs_safe_strdup";
6880     "guestfs_safe_memdup";
6881   ] in
6882   let functions =
6883     List.map (fun (name, _, _, _, _, _, _) -> "guestfs_" ^ name)
6884       all_functions in
6885   let structs =
6886     List.concat (
6887       List.map (fun (typ, _) ->
6888                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
6889         structs
6890     ) in
6891   let globals = List.sort compare (globals @ functions @ structs) in
6892
6893   pr "{\n";
6894   pr "    global:\n";
6895   List.iter (pr "        %s;\n") globals;
6896   pr "\n";
6897
6898   pr "    local:\n";
6899   pr "        *;\n";
6900   pr "};\n"
6901
6902 (* Generate the server-side stubs. *)
6903 and generate_daemon_actions () =
6904   generate_header CStyle GPLv2plus;
6905
6906   pr "#include <config.h>\n";
6907   pr "\n";
6908   pr "#include <stdio.h>\n";
6909   pr "#include <stdlib.h>\n";
6910   pr "#include <string.h>\n";
6911   pr "#include <inttypes.h>\n";
6912   pr "#include <rpc/types.h>\n";
6913   pr "#include <rpc/xdr.h>\n";
6914   pr "\n";
6915   pr "#include \"daemon.h\"\n";
6916   pr "#include \"c-ctype.h\"\n";
6917   pr "#include \"../src/guestfs_protocol.h\"\n";
6918   pr "#include \"actions.h\"\n";
6919   pr "\n";
6920
6921   List.iter (
6922     fun (name, style, _, _, _, _, _) ->
6923       (* Generate server-side stubs. *)
6924       pr "static void %s_stub (XDR *xdr_in)\n" name;
6925       pr "{\n";
6926       let error_code =
6927         match fst style with
6928         | RErr | RInt _ -> pr "  int r;\n"; "-1"
6929         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
6930         | RBool _ -> pr "  int r;\n"; "-1"
6931         | RConstString _ | RConstOptString _ ->
6932             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
6933         | RString _ -> pr "  char *r;\n"; "NULL"
6934         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
6935         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
6936         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
6937         | RBufferOut _ ->
6938             pr "  size_t size = 1;\n";
6939             pr "  char *r;\n";
6940             "NULL" in
6941
6942       (match snd style with
6943        | [] -> ()
6944        | args ->
6945            pr "  struct guestfs_%s_args args;\n" name;
6946            List.iter (
6947              function
6948              | Device n | Dev_or_Path n
6949              | Pathname n
6950              | String n
6951              | Key n -> ()
6952              | OptString n -> pr "  char *%s;\n" n
6953              | StringList n | DeviceList n -> pr "  char **%s;\n" n
6954              | Bool n -> pr "  int %s;\n" n
6955              | Int n -> pr "  int %s;\n" n
6956              | Int64 n -> pr "  int64_t %s;\n" n
6957              | FileIn _ | FileOut _ -> ()
6958              | BufferIn n ->
6959                  pr "  const char *%s;\n" n;
6960                  pr "  size_t %s_size;\n" n
6961            ) args
6962       );
6963       pr "\n";
6964
6965       let is_filein =
6966         List.exists (function FileIn _ -> true | _ -> false) (snd style) in
6967
6968       (match snd style with
6969        | [] -> ()
6970        | args ->
6971            pr "  memset (&args, 0, sizeof args);\n";
6972            pr "\n";
6973            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
6974            if is_filein then
6975              pr "    if (cancel_receive () != -2)\n";
6976            pr "      reply_with_error (\"daemon failed to decode procedure arguments\");\n";
6977            pr "    goto done;\n";
6978            pr "  }\n";
6979            let pr_args n =
6980              pr "  char *%s = args.%s;\n" n n
6981            in
6982            let pr_list_handling_code n =
6983              pr "  %s = realloc (args.%s.%s_val,\n" n n n;
6984              pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
6985              pr "  if (%s == NULL) {\n" n;
6986              if is_filein then
6987                pr "    if (cancel_receive () != -2)\n";
6988              pr "      reply_with_perror (\"realloc\");\n";
6989              pr "    goto done;\n";
6990              pr "  }\n";
6991              pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
6992              pr "  args.%s.%s_val = %s;\n" n n n;
6993            in
6994            List.iter (
6995              function
6996              | Pathname n ->
6997                  pr_args n;
6998                  pr "  ABS_PATH (%s, %s, goto done);\n"
6999                    n (if is_filein then "cancel_receive ()" else "0");
7000              | Device n ->
7001                  pr_args n;
7002                  pr "  RESOLVE_DEVICE (%s, %s, goto done);\n"
7003                    n (if is_filein then "cancel_receive ()" else "0");
7004              | Dev_or_Path n ->
7005                  pr_args n;
7006                  pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
7007                    n (if is_filein then "cancel_receive ()" else "0");
7008              | String n | Key n -> pr_args n
7009              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
7010              | StringList n ->
7011                  pr_list_handling_code n;
7012              | DeviceList n ->
7013                  pr_list_handling_code n;
7014                  pr "  /* Ensure that each is a device,\n";
7015                  pr "   * and perform device name translation.\n";
7016                  pr "   */\n";
7017                  pr "  {\n";
7018                  pr "    size_t i;\n";
7019                  pr "    for (i = 0; %s[i] != NULL; ++i)\n" n;
7020                  pr "      RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
7021                    (if is_filein then "cancel_receive ()" else "0");
7022                  pr "  }\n";
7023              | Bool n -> pr "  %s = args.%s;\n" n n
7024              | Int n -> pr "  %s = args.%s;\n" n n
7025              | Int64 n -> pr "  %s = args.%s;\n" n n
7026              | FileIn _ | FileOut _ -> ()
7027              | BufferIn n ->
7028                  pr "  %s = args.%s.%s_val;\n" n n n;
7029                  pr "  %s_size = args.%s.%s_len;\n" n n n
7030            ) args;
7031            pr "\n"
7032       );
7033
7034       (* this is used at least for do_equal *)
7035       if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
7036         (* Emit NEED_ROOT just once, even when there are two or
7037            more Pathname args *)
7038         pr "  NEED_ROOT (%s, goto done);\n"
7039           (if is_filein then "cancel_receive ()" else "0");
7040       );
7041
7042       (* Don't want to call the impl with any FileIn or FileOut
7043        * parameters, since these go "outside" the RPC protocol.
7044        *)
7045       let args' =
7046         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
7047           (snd style) in
7048       pr "  r = do_%s " name;
7049       generate_c_call_args (fst style, args');
7050       pr ";\n";
7051
7052       (match fst style with
7053        | RErr | RInt _ | RInt64 _ | RBool _
7054        | RConstString _ | RConstOptString _
7055        | RString _ | RStringList _ | RHashtable _
7056        | RStruct (_, _) | RStructList (_, _) ->
7057            pr "  if (r == %s)\n" error_code;
7058            pr "    /* do_%s has already called reply_with_error */\n" name;
7059            pr "    goto done;\n";
7060            pr "\n"
7061        | RBufferOut _ ->
7062            pr "  /* size == 0 && r == NULL could be a non-error case (just\n";
7063            pr "   * an ordinary zero-length buffer), so be careful ...\n";
7064            pr "   */\n";
7065            pr "  if (size == 1 && r == %s)\n" error_code;
7066            pr "    /* do_%s has already called reply_with_error */\n" name;
7067            pr "    goto done;\n";
7068            pr "\n"
7069       );
7070
7071       (* If there are any FileOut parameters, then the impl must
7072        * send its own reply.
7073        *)
7074       let no_reply =
7075         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
7076       if no_reply then
7077         pr "  /* do_%s has already sent a reply */\n" name
7078       else (
7079         match fst style with
7080         | RErr -> pr "  reply (NULL, NULL);\n"
7081         | RInt n | RInt64 n | RBool n ->
7082             pr "  struct guestfs_%s_ret ret;\n" name;
7083             pr "  ret.%s = r;\n" n;
7084             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7085               name
7086         | RConstString _ | RConstOptString _ ->
7087             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
7088         | RString n ->
7089             pr "  struct guestfs_%s_ret ret;\n" name;
7090             pr "  ret.%s = r;\n" n;
7091             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7092               name;
7093             pr "  free (r);\n"
7094         | RStringList n | RHashtable n ->
7095             pr "  struct guestfs_%s_ret ret;\n" name;
7096             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
7097             pr "  ret.%s.%s_val = r;\n" n n;
7098             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7099               name;
7100             pr "  free_strings (r);\n"
7101         | RStruct (n, _) ->
7102             pr "  struct guestfs_%s_ret ret;\n" name;
7103             pr "  ret.%s = *r;\n" n;
7104             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7105               name;
7106             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7107               name
7108         | RStructList (n, _) ->
7109             pr "  struct guestfs_%s_ret ret;\n" name;
7110             pr "  ret.%s = *r;\n" n;
7111             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7112               name;
7113             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
7114               name
7115         | RBufferOut n ->
7116             pr "  struct guestfs_%s_ret ret;\n" name;
7117             pr "  ret.%s.%s_val = r;\n" n n;
7118             pr "  ret.%s.%s_len = size;\n" n n;
7119             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
7120               name;
7121             pr "  free (r);\n"
7122       );
7123
7124       (* Free the args. *)
7125       pr "done:\n";
7126       (match snd style with
7127        | [] -> ()
7128        | _ ->
7129            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
7130              name
7131       );
7132       pr "  return;\n";
7133       pr "}\n\n";
7134   ) daemon_functions;
7135
7136   (* Dispatch function. *)
7137   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
7138   pr "{\n";
7139   pr "  switch (proc_nr) {\n";
7140
7141   List.iter (
7142     fun (name, style, _, _, _, _, _) ->
7143       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
7144       pr "      %s_stub (xdr_in);\n" name;
7145       pr "      break;\n"
7146   ) daemon_functions;
7147
7148   pr "    default:\n";
7149   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";
7150   pr "  }\n";
7151   pr "}\n";
7152   pr "\n";
7153
7154   (* LVM columns and tokenization functions. *)
7155   (* XXX This generates crap code.  We should rethink how we
7156    * do this parsing.
7157    *)
7158   List.iter (
7159     function
7160     | typ, cols ->
7161         pr "static const char *lvm_%s_cols = \"%s\";\n"
7162           typ (String.concat "," (List.map fst cols));
7163         pr "\n";
7164
7165         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
7166         pr "{\n";
7167         pr "  char *tok, *p, *next;\n";
7168         pr "  size_t i, j;\n";
7169         pr "\n";
7170         (*
7171           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
7172           pr "\n";
7173         *)
7174         pr "  if (!str) {\n";
7175         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
7176         pr "    return -1;\n";
7177         pr "  }\n";
7178         pr "  if (!*str || c_isspace (*str)) {\n";
7179         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
7180         pr "    return -1;\n";
7181         pr "  }\n";
7182         pr "  tok = str;\n";
7183         List.iter (
7184           fun (name, coltype) ->
7185             pr "  if (!tok) {\n";
7186             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
7187             pr "    return -1;\n";
7188             pr "  }\n";
7189             pr "  p = strchrnul (tok, ',');\n";
7190             pr "  if (*p) next = p+1; else next = NULL;\n";
7191             pr "  *p = '\\0';\n";
7192             (match coltype with
7193              | FString ->
7194                  pr "  r->%s = strdup (tok);\n" name;
7195                  pr "  if (r->%s == NULL) {\n" name;
7196                  pr "    perror (\"strdup\");\n";
7197                  pr "    return -1;\n";
7198                  pr "  }\n"
7199              | FUUID ->
7200                  pr "  for (i = j = 0; i < 32; ++j) {\n";
7201                  pr "    if (tok[j] == '\\0') {\n";
7202                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
7203                  pr "      return -1;\n";
7204                  pr "    } else if (tok[j] != '-')\n";
7205                  pr "      r->%s[i++] = tok[j];\n" name;
7206                  pr "  }\n";
7207              | FBytes ->
7208                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
7209                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7210                  pr "    return -1;\n";
7211                  pr "  }\n";
7212              | FInt64 ->
7213                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
7214                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7215                  pr "    return -1;\n";
7216                  pr "  }\n";
7217              | FOptPercent ->
7218                  pr "  if (tok[0] == '\\0')\n";
7219                  pr "    r->%s = -1;\n" name;
7220                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
7221                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
7222                  pr "    return -1;\n";
7223                  pr "  }\n";
7224              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
7225                  assert false (* can never be an LVM column *)
7226             );
7227             pr "  tok = next;\n";
7228         ) cols;
7229
7230         pr "  if (tok != NULL) {\n";
7231         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
7232         pr "    return -1;\n";
7233         pr "  }\n";
7234         pr "  return 0;\n";
7235         pr "}\n";
7236         pr "\n";
7237
7238         pr "guestfs_int_lvm_%s_list *\n" typ;
7239         pr "parse_command_line_%ss (void)\n" typ;
7240         pr "{\n";
7241         pr "  char *out, *err;\n";
7242         pr "  char *p, *pend;\n";
7243         pr "  int r, i;\n";
7244         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
7245         pr "  void *newp;\n";
7246         pr "\n";
7247         pr "  ret = malloc (sizeof *ret);\n";
7248         pr "  if (!ret) {\n";
7249         pr "    reply_with_perror (\"malloc\");\n";
7250         pr "    return NULL;\n";
7251         pr "  }\n";
7252         pr "\n";
7253         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
7254         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
7255         pr "\n";
7256         pr "  r = command (&out, &err,\n";
7257         pr "           \"lvm\", \"%ss\",\n" typ;
7258         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
7259         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
7260         pr "  if (r == -1) {\n";
7261         pr "    reply_with_error (\"%%s\", err);\n";
7262         pr "    free (out);\n";
7263         pr "    free (err);\n";
7264         pr "    free (ret);\n";
7265         pr "    return NULL;\n";
7266         pr "  }\n";
7267         pr "\n";
7268         pr "  free (err);\n";
7269         pr "\n";
7270         pr "  /* Tokenize each line of the output. */\n";
7271         pr "  p = out;\n";
7272         pr "  i = 0;\n";
7273         pr "  while (p) {\n";
7274         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
7275         pr "    if (pend) {\n";
7276         pr "      *pend = '\\0';\n";
7277         pr "      pend++;\n";
7278         pr "    }\n";
7279         pr "\n";
7280         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
7281         pr "      p++;\n";
7282         pr "\n";
7283         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
7284         pr "      p = pend;\n";
7285         pr "      continue;\n";
7286         pr "    }\n";
7287         pr "\n";
7288         pr "    /* Allocate some space to store this next entry. */\n";
7289         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
7290         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
7291         pr "    if (newp == NULL) {\n";
7292         pr "      reply_with_perror (\"realloc\");\n";
7293         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7294         pr "      free (ret);\n";
7295         pr "      free (out);\n";
7296         pr "      return NULL;\n";
7297         pr "    }\n";
7298         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
7299         pr "\n";
7300         pr "    /* Tokenize the next entry. */\n";
7301         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
7302         pr "    if (r == -1) {\n";
7303         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
7304         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
7305         pr "      free (ret);\n";
7306         pr "      free (out);\n";
7307         pr "      return NULL;\n";
7308         pr "    }\n";
7309         pr "\n";
7310         pr "    ++i;\n";
7311         pr "    p = pend;\n";
7312         pr "  }\n";
7313         pr "\n";
7314         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
7315         pr "\n";
7316         pr "  free (out);\n";
7317         pr "  return ret;\n";
7318         pr "}\n"
7319
7320   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
7321
7322 (* Generate a list of function names, for debugging in the daemon.. *)
7323 and generate_daemon_names () =
7324   generate_header CStyle GPLv2plus;
7325
7326   pr "#include <config.h>\n";
7327   pr "\n";
7328   pr "#include \"daemon.h\"\n";
7329   pr "\n";
7330
7331   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
7332   pr "const char *function_names[] = {\n";
7333   List.iter (
7334     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
7335   ) daemon_functions;
7336   pr "};\n";
7337
7338 (* Generate the optional groups for the daemon to implement
7339  * guestfs_available.
7340  *)
7341 and generate_daemon_optgroups_c () =
7342   generate_header CStyle GPLv2plus;
7343
7344   pr "#include <config.h>\n";
7345   pr "\n";
7346   pr "#include \"daemon.h\"\n";
7347   pr "#include \"optgroups.h\"\n";
7348   pr "\n";
7349
7350   pr "struct optgroup optgroups[] = {\n";
7351   List.iter (
7352     fun (group, _) ->
7353       pr "  { \"%s\", optgroup_%s_available },\n" group group
7354   ) optgroups;
7355   pr "  { NULL, NULL }\n";
7356   pr "};\n"
7357
7358 and generate_daemon_optgroups_h () =
7359   generate_header CStyle GPLv2plus;
7360
7361   List.iter (
7362     fun (group, _) ->
7363       pr "extern int optgroup_%s_available (void);\n" group
7364   ) optgroups
7365
7366 (* Generate the tests. *)
7367 and generate_tests () =
7368   generate_header CStyle GPLv2plus;
7369
7370   pr "\
7371 #include <stdio.h>
7372 #include <stdlib.h>
7373 #include <string.h>
7374 #include <unistd.h>
7375 #include <sys/types.h>
7376 #include <fcntl.h>
7377
7378 #include \"guestfs.h\"
7379 #include \"guestfs-internal.h\"
7380
7381 static guestfs_h *g;
7382 static int suppress_error = 0;
7383
7384 static void print_error (guestfs_h *g, void *data, const char *msg)
7385 {
7386   if (!suppress_error)
7387     fprintf (stderr, \"%%s\\n\", msg);
7388 }
7389
7390 /* FIXME: nearly identical code appears in fish.c */
7391 static void print_strings (char *const *argv)
7392 {
7393   size_t argc;
7394
7395   for (argc = 0; argv[argc] != NULL; ++argc)
7396     printf (\"\\t%%s\\n\", argv[argc]);
7397 }
7398
7399 /*
7400 static void print_table (char const *const *argv)
7401 {
7402   size_t i;
7403
7404   for (i = 0; argv[i] != NULL; i += 2)
7405     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
7406 }
7407 */
7408
7409 static int
7410 is_available (const char *group)
7411 {
7412   const char *groups[] = { group, NULL };
7413   int r;
7414
7415   suppress_error = 1;
7416   r = guestfs_available (g, (char **) groups);
7417   suppress_error = 0;
7418
7419   return r == 0;
7420 }
7421
7422 static void
7423 incr (guestfs_h *g, void *iv)
7424 {
7425   int *i = (int *) iv;
7426   (*i)++;
7427 }
7428
7429 ";
7430
7431   (* Generate a list of commands which are not tested anywhere. *)
7432   pr "static void no_test_warnings (void)\n";
7433   pr "{\n";
7434
7435   let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
7436   List.iter (
7437     fun (_, _, _, _, tests, _, _) ->
7438       let tests = filter_map (
7439         function
7440         | (_, (Always|If _|Unless _|IfAvailable _), test) -> Some test
7441         | (_, Disabled, _) -> None
7442       ) tests in
7443       let seq = List.concat (List.map seq_of_test tests) in
7444       let cmds_tested = List.map List.hd seq in
7445       List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
7446   ) all_functions;
7447
7448   List.iter (
7449     fun (name, _, _, _, _, _, _) ->
7450       if not (Hashtbl.mem hash name) then
7451         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
7452   ) all_functions;
7453
7454   pr "}\n";
7455   pr "\n";
7456
7457   (* Generate the actual tests.  Note that we generate the tests
7458    * in reverse order, deliberately, so that (in general) the
7459    * newest tests run first.  This makes it quicker and easier to
7460    * debug them.
7461    *)
7462   let test_names =
7463     List.map (
7464       fun (name, _, _, flags, tests, _, _) ->
7465         mapi (generate_one_test name flags) tests
7466     ) (List.rev all_functions) in
7467   let test_names = List.concat test_names in
7468   let nr_tests = List.length test_names in
7469
7470   pr "\
7471 int main (int argc, char *argv[])
7472 {
7473   char c = 0;
7474   unsigned long int n_failed = 0;
7475   const char *filename;
7476   int fd;
7477   int nr_tests, test_num = 0;
7478
7479   setbuf (stdout, NULL);
7480
7481   no_test_warnings ();
7482
7483   g = guestfs_create ();
7484   if (g == NULL) {
7485     printf (\"guestfs_create FAILED\\n\");
7486     exit (EXIT_FAILURE);
7487   }
7488
7489   guestfs_set_error_handler (g, print_error, NULL);
7490
7491   guestfs_set_path (g, \"../appliance\");
7492
7493   filename = \"test1.img\";
7494   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7495   if (fd == -1) {
7496     perror (filename);
7497     exit (EXIT_FAILURE);
7498   }
7499   if (lseek (fd, %d, SEEK_SET) == -1) {
7500     perror (\"lseek\");
7501     close (fd);
7502     unlink (filename);
7503     exit (EXIT_FAILURE);
7504   }
7505   if (write (fd, &c, 1) == -1) {
7506     perror (\"write\");
7507     close (fd);
7508     unlink (filename);
7509     exit (EXIT_FAILURE);
7510   }
7511   if (close (fd) == -1) {
7512     perror (filename);
7513     unlink (filename);
7514     exit (EXIT_FAILURE);
7515   }
7516   if (guestfs_add_drive (g, filename) == -1) {
7517     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7518     exit (EXIT_FAILURE);
7519   }
7520
7521   filename = \"test2.img\";
7522   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7523   if (fd == -1) {
7524     perror (filename);
7525     exit (EXIT_FAILURE);
7526   }
7527   if (lseek (fd, %d, SEEK_SET) == -1) {
7528     perror (\"lseek\");
7529     close (fd);
7530     unlink (filename);
7531     exit (EXIT_FAILURE);
7532   }
7533   if (write (fd, &c, 1) == -1) {
7534     perror (\"write\");
7535     close (fd);
7536     unlink (filename);
7537     exit (EXIT_FAILURE);
7538   }
7539   if (close (fd) == -1) {
7540     perror (filename);
7541     unlink (filename);
7542     exit (EXIT_FAILURE);
7543   }
7544   if (guestfs_add_drive (g, filename) == -1) {
7545     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7546     exit (EXIT_FAILURE);
7547   }
7548
7549   filename = \"test3.img\";
7550   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
7551   if (fd == -1) {
7552     perror (filename);
7553     exit (EXIT_FAILURE);
7554   }
7555   if (lseek (fd, %d, SEEK_SET) == -1) {
7556     perror (\"lseek\");
7557     close (fd);
7558     unlink (filename);
7559     exit (EXIT_FAILURE);
7560   }
7561   if (write (fd, &c, 1) == -1) {
7562     perror (\"write\");
7563     close (fd);
7564     unlink (filename);
7565     exit (EXIT_FAILURE);
7566   }
7567   if (close (fd) == -1) {
7568     perror (filename);
7569     unlink (filename);
7570     exit (EXIT_FAILURE);
7571   }
7572   if (guestfs_add_drive (g, filename) == -1) {
7573     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
7574     exit (EXIT_FAILURE);
7575   }
7576
7577   if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
7578     printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
7579     exit (EXIT_FAILURE);
7580   }
7581
7582   /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
7583   alarm (600);
7584
7585   if (guestfs_launch (g) == -1) {
7586     printf (\"guestfs_launch FAILED\\n\");
7587     exit (EXIT_FAILURE);
7588   }
7589
7590   /* Cancel previous alarm. */
7591   alarm (0);
7592
7593   nr_tests = %d;
7594
7595 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
7596
7597   iteri (
7598     fun i test_name ->
7599       pr "  test_num++;\n";
7600       pr "  if (guestfs_get_verbose (g))\n";
7601       pr "    printf (\"-------------------------------------------------------------------------------\\n\");\n";
7602       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
7603       pr "  if (%s () == -1) {\n" test_name;
7604       pr "    printf (\"%s FAILED\\n\");\n" test_name;
7605       pr "    n_failed++;\n";
7606       pr "  }\n";
7607   ) test_names;
7608   pr "\n";
7609
7610   pr "  /* Check close callback is called. */
7611   int close_sentinel = 1;
7612   guestfs_set_close_callback (g, incr, &close_sentinel);
7613
7614   guestfs_close (g);
7615
7616   if (close_sentinel != 2) {
7617     fprintf (stderr, \"close callback was not called\\n\");
7618     exit (EXIT_FAILURE);
7619   }
7620
7621   unlink (\"test1.img\");
7622   unlink (\"test2.img\");
7623   unlink (\"test3.img\");
7624
7625 ";
7626
7627   pr "  if (n_failed > 0) {\n";
7628   pr "    printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
7629   pr "    exit (EXIT_FAILURE);\n";
7630   pr "  }\n";
7631   pr "\n";
7632
7633   pr "  exit (EXIT_SUCCESS);\n";
7634   pr "}\n"
7635
7636 and generate_one_test name flags i (init, prereq, test) =
7637   let test_name = sprintf "test_%s_%d" name i in
7638
7639   pr "\
7640 static int %s_skip (void)
7641 {
7642   const char *str;
7643
7644   str = getenv (\"TEST_ONLY\");
7645   if (str)
7646     return strstr (str, \"%s\") == NULL;
7647   str = getenv (\"SKIP_%s\");
7648   if (str && STREQ (str, \"1\")) return 1;
7649   str = getenv (\"SKIP_TEST_%s\");
7650   if (str && STREQ (str, \"1\")) return 1;
7651   return 0;
7652 }
7653
7654 " test_name name (String.uppercase test_name) (String.uppercase name);
7655
7656   (match prereq with
7657    | Disabled | Always | IfAvailable _ -> ()
7658    | If code | Unless code ->
7659        pr "static int %s_prereq (void)\n" test_name;
7660        pr "{\n";
7661        pr "  %s\n" code;
7662        pr "}\n";
7663        pr "\n";
7664   );
7665
7666   pr "\
7667 static int %s (void)
7668 {
7669   if (%s_skip ()) {
7670     printf (\"        %%s skipped (reason: environment variable set)\\n\", \"%s\");
7671     return 0;
7672   }
7673
7674 " test_name test_name test_name;
7675
7676   (* Optional functions should only be tested if the relevant
7677    * support is available in the daemon.
7678    *)
7679   List.iter (
7680     function
7681     | Optional group ->
7682         pr "  if (!is_available (\"%s\")) {\n" group;
7683         pr "    printf (\"        %%s skipped (reason: group %%s not available in daemon)\\n\", \"%s\", \"%s\");\n" test_name group;
7684         pr "    return 0;\n";
7685         pr "  }\n";
7686     | _ -> ()
7687   ) flags;
7688
7689   (match prereq with
7690    | Disabled ->
7691        pr "  printf (\"        %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
7692    | If _ ->
7693        pr "  if (! %s_prereq ()) {\n" test_name;
7694        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7695        pr "    return 0;\n";
7696        pr "  }\n";
7697        pr "\n";
7698        generate_one_test_body name i test_name init test;
7699    | Unless _ ->
7700        pr "  if (%s_prereq ()) {\n" test_name;
7701        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
7702        pr "    return 0;\n";
7703        pr "  }\n";
7704        pr "\n";
7705        generate_one_test_body name i test_name init test;
7706    | IfAvailable group ->
7707        pr "  if (!is_available (\"%s\")) {\n" group;
7708        pr "    printf (\"        %%s skipped (reason: %%s not available)\\n\", \"%s\", \"%s\");\n" test_name group;
7709        pr "    return 0;\n";
7710        pr "  }\n";
7711        pr "\n";
7712        generate_one_test_body name i test_name init test;
7713    | Always ->
7714        generate_one_test_body name i test_name init test
7715   );
7716
7717   pr "  return 0;\n";
7718   pr "}\n";
7719   pr "\n";
7720   test_name
7721
7722 and generate_one_test_body name i test_name init test =
7723   (match init with
7724    | InitNone (* XXX at some point, InitNone and InitEmpty became
7725                * folded together as the same thing.  Really we should
7726                * make InitNone do nothing at all, but the tests may
7727                * need to be checked to make sure this is OK.
7728                *)
7729    | InitEmpty ->
7730        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
7731        List.iter (generate_test_command_call test_name)
7732          [["blockdev_setrw"; "/dev/sda"];
7733           ["umount_all"];
7734           ["lvm_remove_all"]]
7735    | InitPartition ->
7736        pr "  /* InitPartition for %s: create /dev/sda1 */\n" test_name;
7737        List.iter (generate_test_command_call test_name)
7738          [["blockdev_setrw"; "/dev/sda"];
7739           ["umount_all"];
7740           ["lvm_remove_all"];
7741           ["part_disk"; "/dev/sda"; "mbr"]]
7742    | InitBasicFS ->
7743        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
7744        List.iter (generate_test_command_call test_name)
7745          [["blockdev_setrw"; "/dev/sda"];
7746           ["umount_all"];
7747           ["lvm_remove_all"];
7748           ["part_disk"; "/dev/sda"; "mbr"];
7749           ["mkfs"; "ext2"; "/dev/sda1"];
7750           ["mount_options"; ""; "/dev/sda1"; "/"]]
7751    | InitBasicFSonLVM ->
7752        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
7753          test_name;
7754        List.iter (generate_test_command_call test_name)
7755          [["blockdev_setrw"; "/dev/sda"];
7756           ["umount_all"];
7757           ["lvm_remove_all"];
7758           ["part_disk"; "/dev/sda"; "mbr"];
7759           ["pvcreate"; "/dev/sda1"];
7760           ["vgcreate"; "VG"; "/dev/sda1"];
7761           ["lvcreate"; "LV"; "VG"; "8"];
7762           ["mkfs"; "ext2"; "/dev/VG/LV"];
7763           ["mount_options"; ""; "/dev/VG/LV"; "/"]]
7764    | InitISOFS ->
7765        pr "  /* InitISOFS for %s */\n" test_name;
7766        List.iter (generate_test_command_call test_name)
7767          [["blockdev_setrw"; "/dev/sda"];
7768           ["umount_all"];
7769           ["lvm_remove_all"];
7770           ["mount_ro"; "/dev/sdd"; "/"]]
7771   );
7772
7773   let get_seq_last = function
7774     | [] ->
7775         failwithf "%s: you cannot use [] (empty list) when expecting a command"
7776           test_name
7777     | seq ->
7778         let seq = List.rev seq in
7779         List.rev (List.tl seq), List.hd seq
7780   in
7781
7782   match test with
7783   | TestRun seq ->
7784       pr "  /* TestRun for %s (%d) */\n" name i;
7785       List.iter (generate_test_command_call test_name) seq
7786   | TestOutput (seq, expected) ->
7787       pr "  /* TestOutput for %s (%d) */\n" name i;
7788       pr "  const char *expected = \"%s\";\n" (c_quote expected);
7789       let seq, last = get_seq_last seq in
7790       let test () =
7791         pr "    if (STRNEQ (r, expected)) {\n";
7792         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7793         pr "      return -1;\n";
7794         pr "    }\n"
7795       in
7796       List.iter (generate_test_command_call test_name) seq;
7797       generate_test_command_call ~test test_name last
7798   | TestOutputList (seq, expected) ->
7799       pr "  /* TestOutputList for %s (%d) */\n" name i;
7800       let seq, last = get_seq_last seq in
7801       let test () =
7802         iteri (
7803           fun i str ->
7804             pr "    if (!r[%d]) {\n" i;
7805             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7806             pr "      print_strings (r);\n";
7807             pr "      return -1;\n";
7808             pr "    }\n";
7809             pr "    {\n";
7810             pr "      const char *expected = \"%s\";\n" (c_quote str);
7811             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7812             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7813             pr "        return -1;\n";
7814             pr "      }\n";
7815             pr "    }\n"
7816         ) expected;
7817         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7818         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7819           test_name;
7820         pr "      print_strings (r);\n";
7821         pr "      return -1;\n";
7822         pr "    }\n"
7823       in
7824       List.iter (generate_test_command_call test_name) seq;
7825       generate_test_command_call ~test test_name last
7826   | TestOutputListOfDevices (seq, expected) ->
7827       pr "  /* TestOutputListOfDevices for %s (%d) */\n" name i;
7828       let seq, last = get_seq_last seq in
7829       let test () =
7830         iteri (
7831           fun i str ->
7832             pr "    if (!r[%d]) {\n" i;
7833             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
7834             pr "      print_strings (r);\n";
7835             pr "      return -1;\n";
7836             pr "    }\n";
7837             pr "    {\n";
7838             pr "      const char *expected = \"%s\";\n" (c_quote str);
7839             pr "      r[%d][5] = 's';\n" i;
7840             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
7841             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
7842             pr "        return -1;\n";
7843             pr "      }\n";
7844             pr "    }\n"
7845         ) expected;
7846         pr "    if (r[%d] != NULL) {\n" (List.length expected);
7847         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
7848           test_name;
7849         pr "      print_strings (r);\n";
7850         pr "      return -1;\n";
7851         pr "    }\n"
7852       in
7853       List.iter (generate_test_command_call test_name) seq;
7854       generate_test_command_call ~test test_name last
7855   | TestOutputInt (seq, expected) ->
7856       pr "  /* TestOutputInt for %s (%d) */\n" name i;
7857       let seq, last = get_seq_last seq in
7858       let test () =
7859         pr "    if (r != %d) {\n" expected;
7860         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
7861           test_name expected;
7862         pr "               (int) r);\n";
7863         pr "      return -1;\n";
7864         pr "    }\n"
7865       in
7866       List.iter (generate_test_command_call test_name) seq;
7867       generate_test_command_call ~test test_name last
7868   | TestOutputIntOp (seq, op, expected) ->
7869       pr "  /* TestOutputIntOp for %s (%d) */\n" name i;
7870       let seq, last = get_seq_last seq in
7871       let test () =
7872         pr "    if (! (r %s %d)) {\n" op expected;
7873         pr "      fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
7874           test_name op expected;
7875         pr "               (int) r);\n";
7876         pr "      return -1;\n";
7877         pr "    }\n"
7878       in
7879       List.iter (generate_test_command_call test_name) seq;
7880       generate_test_command_call ~test test_name last
7881   | TestOutputTrue seq ->
7882       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
7883       let seq, last = get_seq_last seq in
7884       let test () =
7885         pr "    if (!r) {\n";
7886         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
7887           test_name;
7888         pr "      return -1;\n";
7889         pr "    }\n"
7890       in
7891       List.iter (generate_test_command_call test_name) seq;
7892       generate_test_command_call ~test test_name last
7893   | TestOutputFalse seq ->
7894       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
7895       let seq, last = get_seq_last seq in
7896       let test () =
7897         pr "    if (r) {\n";
7898         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
7899           test_name;
7900         pr "      return -1;\n";
7901         pr "    }\n"
7902       in
7903       List.iter (generate_test_command_call test_name) seq;
7904       generate_test_command_call ~test test_name last
7905   | TestOutputLength (seq, expected) ->
7906       pr "  /* TestOutputLength for %s (%d) */\n" name i;
7907       let seq, last = get_seq_last seq in
7908       let test () =
7909         pr "    int j;\n";
7910         pr "    for (j = 0; j < %d; ++j)\n" expected;
7911         pr "      if (r[j] == NULL) {\n";
7912         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
7913           test_name;
7914         pr "        print_strings (r);\n";
7915         pr "        return -1;\n";
7916         pr "      }\n";
7917         pr "    if (r[j] != NULL) {\n";
7918         pr "      fprintf (stderr, \"%s: long list returned\\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   | TestOutputBuffer (seq, expected) ->
7927       pr "  /* TestOutputBuffer for %s (%d) */\n" name i;
7928       pr "  const char *expected = \"%s\";\n" (c_quote expected);
7929       let seq, last = get_seq_last seq in
7930       let len = String.length expected in
7931       let test () =
7932         pr "    if (size != %d) {\n" len;
7933         pr "      fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
7934         pr "      return -1;\n";
7935         pr "    }\n";
7936         pr "    if (STRNEQLEN (r, expected, size)) {\n";
7937         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
7938         pr "      return -1;\n";
7939         pr "    }\n"
7940       in
7941       List.iter (generate_test_command_call test_name) seq;
7942       generate_test_command_call ~test test_name last
7943   | TestOutputStruct (seq, checks) ->
7944       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
7945       let seq, last = get_seq_last seq in
7946       let test () =
7947         List.iter (
7948           function
7949           | CompareWithInt (field, expected) ->
7950               pr "    if (r->%s != %d) {\n" field expected;
7951               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
7952                 test_name field expected;
7953               pr "               (int) r->%s);\n" field;
7954               pr "      return -1;\n";
7955               pr "    }\n"
7956           | CompareWithIntOp (field, op, expected) ->
7957               pr "    if (!(r->%s %s %d)) {\n" field op expected;
7958               pr "      fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
7959                 test_name field op expected;
7960               pr "               (int) r->%s);\n" field;
7961               pr "      return -1;\n";
7962               pr "    }\n"
7963           | CompareWithString (field, expected) ->
7964               pr "    if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
7965               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
7966                 test_name field expected;
7967               pr "               r->%s);\n" field;
7968               pr "      return -1;\n";
7969               pr "    }\n"
7970           | CompareFieldsIntEq (field1, field2) ->
7971               pr "    if (r->%s != r->%s) {\n" field1 field2;
7972               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
7973                 test_name field1 field2;
7974               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
7975               pr "      return -1;\n";
7976               pr "    }\n"
7977           | CompareFieldsStrEq (field1, field2) ->
7978               pr "    if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
7979               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
7980                 test_name field1 field2;
7981               pr "               r->%s, r->%s);\n" field1 field2;
7982               pr "      return -1;\n";
7983               pr "    }\n"
7984         ) checks
7985       in
7986       List.iter (generate_test_command_call test_name) seq;
7987       generate_test_command_call ~test test_name last
7988   | TestLastFail seq ->
7989       pr "  /* TestLastFail for %s (%d) */\n" name i;
7990       let seq, last = get_seq_last seq in
7991       List.iter (generate_test_command_call test_name) seq;
7992       generate_test_command_call test_name ~expect_error:true last
7993
7994 (* Generate the code to run a command, leaving the result in 'r'.
7995  * If you expect to get an error then you should set expect_error:true.
7996  *)
7997 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
7998   match cmd with
7999   | [] -> assert false
8000   | name :: args ->
8001       (* Look up the command to find out what args/ret it has. *)
8002       let style =
8003         try
8004           let _, style, _, _, _, _, _ =
8005             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
8006           style
8007         with Not_found ->
8008           failwithf "%s: in test, command %s was not found" test_name name in
8009
8010       if List.length (snd style) <> List.length args then
8011         failwithf "%s: in test, wrong number of args given to %s"
8012           test_name name;
8013
8014       pr "  {\n";
8015
8016       List.iter (
8017         function
8018         | OptString n, "NULL" -> ()
8019         | Pathname n, arg
8020         | Device n, arg
8021         | Dev_or_Path n, arg
8022         | String n, arg
8023         | OptString n, arg
8024         | Key n, arg ->
8025             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8026         | BufferIn n, arg ->
8027             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
8028             pr "    size_t %s_size = %d;\n" n (String.length arg)
8029         | Int _, _
8030         | Int64 _, _
8031         | Bool _, _
8032         | FileIn _, _ | FileOut _, _ -> ()
8033         | StringList n, "" | DeviceList n, "" ->
8034             pr "    const char *const %s[1] = { NULL };\n" n
8035         | StringList n, arg | DeviceList n, arg ->
8036             let strs = string_split " " arg in
8037             iteri (
8038               fun i str ->
8039                 pr "    const char *%s_%d = \"%s\";\n" n i (c_quote str);
8040             ) strs;
8041             pr "    const char *const %s[] = {\n" n;
8042             iteri (
8043               fun i _ -> pr "      %s_%d,\n" n i
8044             ) strs;
8045             pr "      NULL\n";
8046             pr "    };\n";
8047       ) (List.combine (snd style) args);
8048
8049       let error_code =
8050         match fst style with
8051         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
8052         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
8053         | RConstString _ | RConstOptString _ ->
8054             pr "    const char *r;\n"; "NULL"
8055         | RString _ -> pr "    char *r;\n"; "NULL"
8056         | RStringList _ | RHashtable _ ->
8057             pr "    char **r;\n";
8058             pr "    size_t i;\n";
8059             "NULL"
8060         | RStruct (_, typ) ->
8061             pr "    struct guestfs_%s *r;\n" typ; "NULL"
8062         | RStructList (_, typ) ->
8063             pr "    struct guestfs_%s_list *r;\n" typ; "NULL"
8064         | RBufferOut _ ->
8065             pr "    char *r;\n";
8066             pr "    size_t size;\n";
8067             "NULL" in
8068
8069       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
8070       pr "    r = guestfs_%s (g" name;
8071
8072       (* Generate the parameters. *)
8073       List.iter (
8074         function
8075         | OptString _, "NULL" -> pr ", NULL"
8076         | Pathname n, _
8077         | Device n, _ | Dev_or_Path n, _
8078         | String n, _
8079         | OptString n, _
8080         | Key n, _ ->
8081             pr ", %s" n
8082         | BufferIn n, _ ->
8083             pr ", %s, %s_size" n n
8084         | FileIn _, arg | FileOut _, arg ->
8085             pr ", \"%s\"" (c_quote arg)
8086         | StringList n, _ | DeviceList n, _ ->
8087             pr ", (char **) %s" n
8088         | Int _, arg ->
8089             let i =
8090               try int_of_string arg
8091               with Failure "int_of_string" ->
8092                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
8093             pr ", %d" i
8094         | Int64 _, arg ->
8095             let i =
8096               try Int64.of_string arg
8097               with Failure "int_of_string" ->
8098                 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
8099             pr ", %Ld" i
8100         | Bool _, arg ->
8101             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
8102       ) (List.combine (snd style) args);
8103
8104       (match fst style with
8105        | RBufferOut _ -> pr ", &size"
8106        | _ -> ()
8107       );
8108
8109       pr ");\n";
8110
8111       if not expect_error then
8112         pr "    if (r == %s)\n" error_code
8113       else
8114         pr "    if (r != %s)\n" error_code;
8115       pr "      return -1;\n";
8116
8117       (* Insert the test code. *)
8118       (match test with
8119        | None -> ()
8120        | Some f -> f ()
8121       );
8122
8123       (match fst style with
8124        | RErr | RInt _ | RInt64 _ | RBool _
8125        | RConstString _ | RConstOptString _ -> ()
8126        | RString _ | RBufferOut _ -> pr "    free (r);\n"
8127        | RStringList _ | RHashtable _ ->
8128            pr "    for (i = 0; r[i] != NULL; ++i)\n";
8129            pr "      free (r[i]);\n";
8130            pr "    free (r);\n"
8131        | RStruct (_, typ) ->
8132            pr "    guestfs_free_%s (r);\n" typ
8133        | RStructList (_, typ) ->
8134            pr "    guestfs_free_%s_list (r);\n" typ
8135       );
8136
8137       pr "  }\n"
8138
8139 and c_quote str =
8140   let str = replace_str str "\r" "\\r" in
8141   let str = replace_str str "\n" "\\n" in
8142   let str = replace_str str "\t" "\\t" in
8143   let str = replace_str str "\000" "\\0" in
8144   str
8145
8146 (* Generate a lot of different functions for guestfish. *)
8147 and generate_fish_cmds () =
8148   generate_header CStyle GPLv2plus;
8149
8150   let all_functions =
8151     List.filter (
8152       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8153     ) all_functions in
8154   let all_functions_sorted =
8155     List.filter (
8156       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8157     ) all_functions_sorted in
8158
8159   pr "#include <config.h>\n";
8160   pr "\n";
8161   pr "#include <stdio.h>\n";
8162   pr "#include <stdlib.h>\n";
8163   pr "#include <string.h>\n";
8164   pr "#include <inttypes.h>\n";
8165   pr "\n";
8166   pr "#include <guestfs.h>\n";
8167   pr "#include \"c-ctype.h\"\n";
8168   pr "#include \"full-write.h\"\n";
8169   pr "#include \"xstrtol.h\"\n";
8170   pr "#include \"fish.h\"\n";
8171   pr "\n";
8172   pr "/* Valid suffixes allowed for numbers.  See Gnulib xstrtol function. */\n";
8173   pr "static const char *xstrtol_suffixes = \"0kKMGTPEZY\";\n";
8174   pr "\n";
8175
8176   (* list_commands function, which implements guestfish -h *)
8177   pr "void list_commands (void)\n";
8178   pr "{\n";
8179   pr "  printf (\"    %%-16s     %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
8180   pr "  list_builtin_commands ();\n";
8181   List.iter (
8182     fun (name, _, _, flags, _, shortdesc, _) ->
8183       let name = replace_char name '_' '-' in
8184       pr "  printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
8185         name shortdesc
8186   ) all_functions_sorted;
8187   pr "  printf (\"    %%s\\n\",";
8188   pr "          _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
8189   pr "}\n";
8190   pr "\n";
8191
8192   (* display_command function, which implements guestfish -h cmd *)
8193   pr "int display_command (const char *cmd)\n";
8194   pr "{\n";
8195   List.iter (
8196     fun (name, style, _, flags, _, shortdesc, longdesc) ->
8197       let name2 = replace_char name '_' '-' in
8198       let alias =
8199         try find_map (function FishAlias n -> Some n | _ -> None) flags
8200         with Not_found -> name in
8201       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
8202       let synopsis =
8203         match snd style with
8204         | [] -> name2
8205         | args ->
8206             let args = List.filter (function Key _ -> false | _ -> true) args in
8207             sprintf "%s %s"
8208               name2 (String.concat " " (List.map name_of_argt args)) in
8209
8210       let warnings =
8211         if List.exists (function Key _ -> true | _ -> false) (snd style) then
8212           "\n\nThis command has one or more key or passphrase parameters.
8213 Guestfish will prompt for these separately."
8214         else "" in
8215
8216       let warnings =
8217         warnings ^
8218           if List.mem ProtocolLimitWarning flags then
8219             ("\n\n" ^ protocol_limit_warning)
8220           else "" in
8221
8222       (* For DangerWillRobinson commands, we should probably have
8223        * guestfish prompt before allowing you to use them (especially
8224        * in interactive mode). XXX
8225        *)
8226       let warnings =
8227         warnings ^
8228           if List.mem DangerWillRobinson flags then
8229             ("\n\n" ^ danger_will_robinson)
8230           else "" in
8231
8232       let warnings =
8233         warnings ^
8234           match deprecation_notice flags with
8235           | None -> ""
8236           | Some txt -> "\n\n" ^ txt in
8237
8238       let describe_alias =
8239         if name <> alias then
8240           sprintf "\n\nYou can use '%s' as an alias for this command." alias
8241         else "" in
8242
8243       pr "  if (";
8244       pr "STRCASEEQ (cmd, \"%s\")" name;
8245       if name <> name2 then
8246         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8247       if name <> alias then
8248         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8249       pr ") {\n";
8250       pr "    pod2text (\"%s\", _(\"%s\"), %S);\n"
8251         name2 shortdesc
8252         ("=head1 SYNOPSIS\n\n " ^ synopsis ^ "\n\n" ^
8253          "=head1 DESCRIPTION\n\n" ^
8254          longdesc ^ warnings ^ describe_alias);
8255       pr "    return 0;\n";
8256       pr "  }\n";
8257       pr "  else\n"
8258   ) all_functions;
8259   pr "    return display_builtin_command (cmd);\n";
8260   pr "}\n";
8261   pr "\n";
8262
8263   let emit_print_list_function typ =
8264     pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
8265       typ typ typ;
8266     pr "{\n";
8267     pr "  unsigned int i;\n";
8268     pr "\n";
8269     pr "  for (i = 0; i < %ss->len; ++i) {\n" typ;
8270     pr "    printf (\"[%%d] = {\\n\", i);\n";
8271     pr "    print_%s_indent (&%ss->val[i], \"  \");\n" typ typ;
8272     pr "    printf (\"}\\n\");\n";
8273     pr "  }\n";
8274     pr "}\n";
8275     pr "\n";
8276   in
8277
8278   (* print_* functions *)
8279   List.iter (
8280     fun (typ, cols) ->
8281       let needs_i =
8282         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
8283
8284       pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
8285       pr "{\n";
8286       if needs_i then (
8287         pr "  unsigned int i;\n";
8288         pr "\n"
8289       );
8290       List.iter (
8291         function
8292         | name, FString ->
8293             pr "  printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
8294         | name, FUUID ->
8295             pr "  printf (\"%%s%s: \", indent);\n" name;
8296             pr "  for (i = 0; i < 32; ++i)\n";
8297             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
8298             pr "  printf (\"\\n\");\n"
8299         | name, FBuffer ->
8300             pr "  printf (\"%%s%s: \", indent);\n" name;
8301             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
8302             pr "    if (c_isprint (%s->%s[i]))\n" typ name;
8303             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
8304             pr "    else\n";
8305             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
8306             pr "  printf (\"\\n\");\n"
8307         | name, (FUInt64|FBytes) ->
8308             pr "  printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
8309               name typ name
8310         | name, FInt64 ->
8311             pr "  printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
8312               name typ name
8313         | name, FUInt32 ->
8314             pr "  printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
8315               name typ name
8316         | name, FInt32 ->
8317             pr "  printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
8318               name typ name
8319         | name, FChar ->
8320             pr "  printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
8321               name typ name
8322         | name, FOptPercent ->
8323             pr "  if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
8324               typ name name typ name;
8325             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
8326       ) cols;
8327       pr "}\n";
8328       pr "\n";
8329   ) structs;
8330
8331   (* Emit a print_TYPE_list function definition only if that function is used. *)
8332   List.iter (
8333     function
8334     | typ, (RStructListOnly | RStructAndList) ->
8335         (* generate the function for typ *)
8336         emit_print_list_function typ
8337     | typ, _ -> () (* empty *)
8338   ) (rstructs_used_by all_functions);
8339
8340   (* Emit a print_TYPE function definition only if that function is used. *)
8341   List.iter (
8342     function
8343     | typ, (RStructOnly | RStructAndList) ->
8344         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
8345         pr "{\n";
8346         pr "  print_%s_indent (%s, \"\");\n" typ typ;
8347         pr "}\n";
8348         pr "\n";
8349     | typ, _ -> () (* empty *)
8350   ) (rstructs_used_by all_functions);
8351
8352   (* run_<action> actions *)
8353   List.iter (
8354     fun (name, style, _, flags, _, _, _) ->
8355       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
8356       pr "{\n";
8357       (match fst style with
8358        | RErr
8359        | RInt _
8360        | RBool _ -> pr "  int r;\n"
8361        | RInt64 _ -> pr "  int64_t r;\n"
8362        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
8363        | RString _ -> pr "  char *r;\n"
8364        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
8365        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
8366        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
8367        | RBufferOut _ ->
8368            pr "  char *r;\n";
8369            pr "  size_t size;\n";
8370       );
8371       List.iter (
8372         function
8373         | Device n
8374         | String n
8375         | OptString n -> pr "  const char *%s;\n" n
8376         | Pathname n
8377         | Dev_or_Path n
8378         | FileIn n
8379         | FileOut n
8380         | Key n -> pr "  char *%s;\n" n
8381         | BufferIn n ->
8382             pr "  const char *%s;\n" n;
8383             pr "  size_t %s_size;\n" n
8384         | StringList n | DeviceList n -> pr "  char **%s;\n" n
8385         | Bool n -> pr "  int %s;\n" n
8386         | Int n -> pr "  int %s;\n" n
8387         | Int64 n -> pr "  int64_t %s;\n" n
8388       ) (snd style);
8389
8390       (* Check and convert parameters. *)
8391       let argc_expected =
8392         let args_no_keys =
8393           List.filter (function Key _ -> false | _ -> true) (snd style) in
8394         List.length args_no_keys in
8395       pr "  if (argc != %d) {\n" argc_expected;
8396       pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
8397         argc_expected;
8398       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
8399       pr "    return -1;\n";
8400       pr "  }\n";
8401
8402       let parse_integer fn fntyp rtyp range name =
8403         pr "  {\n";
8404         pr "    strtol_error xerr;\n";
8405         pr "    %s r;\n" fntyp;
8406         pr "\n";
8407         pr "    xerr = %s (argv[i++], NULL, 0, &r, xstrtol_suffixes);\n" fn;
8408         pr "    if (xerr != LONGINT_OK) {\n";
8409         pr "      fprintf (stderr,\n";
8410         pr "               _(\"%%s: %%s: invalid integer parameter (%%s returned %%d)\\n\"),\n";
8411         pr "               cmd, \"%s\", \"%s\", xerr);\n" name fn;
8412         pr "      return -1;\n";
8413         pr "    }\n";
8414         (match range with
8415          | None -> ()
8416          | Some (min, max, comment) ->
8417              pr "    /* %s */\n" comment;
8418              pr "    if (r < %s || r > %s) {\n" min max;
8419              pr "      fprintf (stderr, _(\"%%s: %%s: integer out of range\\n\"), cmd, \"%s\");\n"
8420                name;
8421              pr "      return -1;\n";
8422              pr "    }\n";
8423              pr "    /* The check above should ensure this assignment does not overflow. */\n";
8424         );
8425         pr "    %s = r;\n" name;
8426         pr "  }\n";
8427       in
8428
8429       if snd style <> [] then
8430         pr "  size_t i = 0;\n";
8431
8432       List.iter (
8433         function
8434         | Device name
8435         | String name ->
8436             pr "  %s = argv[i++];\n" name
8437         | Pathname name
8438         | Dev_or_Path name ->
8439             pr "  %s = resolve_win_path (argv[i++]);\n" name;
8440             pr "  if (%s == NULL) return -1;\n" name
8441         | OptString name ->
8442             pr "  %s = STRNEQ (argv[i], \"\") ? argv[i] : NULL;\n" name;
8443             pr "  i++;\n"
8444         | BufferIn name ->
8445             pr "  %s = argv[i];\n" name;
8446             pr "  %s_size = strlen (argv[i]);\n" name;
8447             pr "  i++;\n"
8448         | FileIn name ->
8449             pr "  %s = file_in (argv[i++]);\n" name;
8450             pr "  if (%s == NULL) return -1;\n" name
8451         | FileOut name ->
8452             pr "  %s = file_out (argv[i++]);\n" name;
8453             pr "  if (%s == NULL) return -1;\n" name
8454         | StringList name | DeviceList name ->
8455             pr "  %s = parse_string_list (argv[i++]);\n" name;
8456             pr "  if (%s == NULL) return -1;\n" name
8457         | Key name ->
8458             pr "  %s = read_key (\"%s\");\n" name name;
8459             pr "  if (%s == NULL) return -1;\n" name
8460         | Bool name ->
8461             pr "  %s = is_true (argv[i++]) ? 1 : 0;\n" name
8462         | Int name ->
8463             let range =
8464               let min = "(-(2LL<<30))"
8465               and max = "((2LL<<30)-1)"
8466               and comment =
8467                 "The Int type in the generator is a signed 31 bit int." in
8468               Some (min, max, comment) in
8469             parse_integer "xstrtoll" "long long" "int" range name
8470         | Int64 name ->
8471             parse_integer "xstrtoll" "long long" "int64_t" None name
8472       ) (snd style);
8473
8474       (* Call C API function. *)
8475       pr "  r = guestfs_%s " name;
8476       generate_c_call_args ~handle:"g" style;
8477       pr ";\n";
8478
8479       List.iter (
8480         function
8481         | Device _ | String _
8482         | OptString _ | Bool _
8483         | Int _ | Int64 _
8484         | BufferIn _ -> ()
8485         | Pathname name | Dev_or_Path name | FileOut name
8486         | Key name ->
8487             pr "  free (%s);\n" name
8488         | FileIn name ->
8489             pr "  free_file_in (%s);\n" name
8490         | StringList name | DeviceList name ->
8491             pr "  free_strings (%s);\n" name
8492       ) (snd style);
8493
8494       (* Any output flags? *)
8495       let fish_output =
8496         let flags = filter_map (
8497           function FishOutput flag -> Some flag | _ -> None
8498         ) flags in
8499         match flags with
8500         | [] -> None
8501         | [f] -> Some f
8502         | _ ->
8503             failwithf "%s: more than one FishOutput flag is not allowed" name in
8504
8505       (* Check return value for errors and display command results. *)
8506       (match fst style with
8507        | RErr -> pr "  return r;\n"
8508        | RInt _ ->
8509            pr "  if (r == -1) return -1;\n";
8510            (match fish_output with
8511             | None ->
8512                 pr "  printf (\"%%d\\n\", r);\n";
8513             | Some FishOutputOctal ->
8514                 pr "  printf (\"%%s%%o\\n\", r != 0 ? \"0\" : \"\", r);\n";
8515             | Some FishOutputHexadecimal ->
8516                 pr "  printf (\"%%s%%x\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8517            pr "  return 0;\n"
8518        | RInt64 _ ->
8519            pr "  if (r == -1) return -1;\n";
8520            (match fish_output with
8521             | None ->
8522                 pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
8523             | Some FishOutputOctal ->
8524                 pr "  printf (\"%%s%%\" PRIo64 \"\\n\", r != 0 ? \"0\" : \"\", r);\n";
8525             | Some FishOutputHexadecimal ->
8526                 pr "  printf (\"%%s%%\" PRIx64 \"\\n\", r != 0 ? \"0x\" : \"\", r);\n");
8527            pr "  return 0;\n"
8528        | RBool _ ->
8529            pr "  if (r == -1) return -1;\n";
8530            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
8531            pr "  return 0;\n"
8532        | RConstString _ ->
8533            pr "  if (r == NULL) return -1;\n";
8534            pr "  printf (\"%%s\\n\", r);\n";
8535            pr "  return 0;\n"
8536        | RConstOptString _ ->
8537            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
8538            pr "  return 0;\n"
8539        | RString _ ->
8540            pr "  if (r == NULL) return -1;\n";
8541            pr "  printf (\"%%s\\n\", r);\n";
8542            pr "  free (r);\n";
8543            pr "  return 0;\n"
8544        | RStringList _ ->
8545            pr "  if (r == NULL) return -1;\n";
8546            pr "  print_strings (r);\n";
8547            pr "  free_strings (r);\n";
8548            pr "  return 0;\n"
8549        | RStruct (_, typ) ->
8550            pr "  if (r == NULL) return -1;\n";
8551            pr "  print_%s (r);\n" typ;
8552            pr "  guestfs_free_%s (r);\n" typ;
8553            pr "  return 0;\n"
8554        | RStructList (_, typ) ->
8555            pr "  if (r == NULL) return -1;\n";
8556            pr "  print_%s_list (r);\n" typ;
8557            pr "  guestfs_free_%s_list (r);\n" typ;
8558            pr "  return 0;\n"
8559        | RHashtable _ ->
8560            pr "  if (r == NULL) return -1;\n";
8561            pr "  print_table (r);\n";
8562            pr "  free_strings (r);\n";
8563            pr "  return 0;\n"
8564        | RBufferOut _ ->
8565            pr "  if (r == NULL) return -1;\n";
8566            pr "  if (full_write (1, r, size) != size) {\n";
8567            pr "    perror (\"write\");\n";
8568            pr "    free (r);\n";
8569            pr "    return -1;\n";
8570            pr "  }\n";
8571            pr "  free (r);\n";
8572            pr "  return 0;\n"
8573       );
8574       pr "}\n";
8575       pr "\n"
8576   ) all_functions;
8577
8578   (* run_action function *)
8579   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
8580   pr "{\n";
8581   List.iter (
8582     fun (name, _, _, flags, _, _, _) ->
8583       let name2 = replace_char name '_' '-' in
8584       let alias =
8585         try find_map (function FishAlias n -> Some n | _ -> None) flags
8586         with Not_found -> name in
8587       pr "  if (";
8588       pr "STRCASEEQ (cmd, \"%s\")" name;
8589       if name <> name2 then
8590         pr " || STRCASEEQ (cmd, \"%s\")" name2;
8591       if name <> alias then
8592         pr " || STRCASEEQ (cmd, \"%s\")" alias;
8593       pr ")\n";
8594       pr "    return run_%s (cmd, argc, argv);\n" name;
8595       pr "  else\n";
8596   ) all_functions;
8597   pr "    {\n";
8598   pr "      fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
8599   pr "      if (command_num == 1)\n";
8600   pr "        extended_help_message ();\n";
8601   pr "      return -1;\n";
8602   pr "    }\n";
8603   pr "  return 0;\n";
8604   pr "}\n";
8605   pr "\n"
8606
8607 (* Readline completion for guestfish. *)
8608 and generate_fish_completion () =
8609   generate_header CStyle GPLv2plus;
8610
8611   let all_functions =
8612     List.filter (
8613       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
8614     ) all_functions in
8615
8616   pr "\
8617 #include <config.h>
8618
8619 #include <stdio.h>
8620 #include <stdlib.h>
8621 #include <string.h>
8622
8623 #ifdef HAVE_LIBREADLINE
8624 #include <readline/readline.h>
8625 #endif
8626
8627 #include \"fish.h\"
8628
8629 #ifdef HAVE_LIBREADLINE
8630
8631 static const char *const commands[] = {
8632   BUILTIN_COMMANDS_FOR_COMPLETION,
8633 ";
8634
8635   (* Get the commands, including the aliases.  They don't need to be
8636    * sorted - the generator() function just does a dumb linear search.
8637    *)
8638   let commands =
8639     List.map (
8640       fun (name, _, _, flags, _, _, _) ->
8641         let name2 = replace_char name '_' '-' in
8642         let alias =
8643           try find_map (function FishAlias n -> Some n | _ -> None) flags
8644           with Not_found -> name in
8645
8646         if name <> alias then [name2; alias] else [name2]
8647     ) all_functions in
8648   let commands = List.flatten commands in
8649
8650   List.iter (pr "  \"%s\",\n") commands;
8651
8652   pr "  NULL
8653 };
8654
8655 static char *
8656 generator (const char *text, int state)
8657 {
8658   static size_t index, len;
8659   const char *name;
8660
8661   if (!state) {
8662     index = 0;
8663     len = strlen (text);
8664   }
8665
8666   rl_attempted_completion_over = 1;
8667
8668   while ((name = commands[index]) != NULL) {
8669     index++;
8670     if (STRCASEEQLEN (name, text, len))
8671       return strdup (name);
8672   }
8673
8674   return NULL;
8675 }
8676
8677 #endif /* HAVE_LIBREADLINE */
8678
8679 #ifdef HAVE_RL_COMPLETION_MATCHES
8680 #define RL_COMPLETION_MATCHES rl_completion_matches
8681 #else
8682 #ifdef HAVE_COMPLETION_MATCHES
8683 #define RL_COMPLETION_MATCHES completion_matches
8684 #endif
8685 #endif /* else just fail if we don't have either symbol */
8686
8687 char **
8688 do_completion (const char *text, int start, int end)
8689 {
8690   char **matches = NULL;
8691
8692 #ifdef HAVE_LIBREADLINE
8693   rl_completion_append_character = ' ';
8694
8695   if (start == 0)
8696     matches = RL_COMPLETION_MATCHES (text, generator);
8697   else if (complete_dest_paths)
8698     matches = RL_COMPLETION_MATCHES (text, complete_dest_paths_generator);
8699 #endif
8700
8701   return matches;
8702 }
8703 ";
8704
8705 (* Generate the POD documentation for guestfish. *)
8706 and generate_fish_actions_pod () =
8707   let all_functions_sorted =
8708     List.filter (
8709       fun (_, _, _, flags, _, _, _) ->
8710         not (List.mem NotInFish flags || List.mem NotInDocs flags)
8711     ) all_functions_sorted in
8712
8713   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
8714
8715   List.iter (
8716     fun (name, style, _, flags, _, _, longdesc) ->
8717       let longdesc =
8718         Str.global_substitute rex (
8719           fun s ->
8720             let sub =
8721               try Str.matched_group 1 s
8722               with Not_found ->
8723                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
8724             "C<" ^ replace_char sub '_' '-' ^ ">"
8725         ) longdesc in
8726       let name = replace_char name '_' '-' in
8727       let alias =
8728         try find_map (function FishAlias n -> Some n | _ -> None) flags
8729         with Not_found -> name in
8730
8731       pr "=head2 %s" name;
8732       if name <> alias then
8733         pr " | %s" alias;
8734       pr "\n";
8735       pr "\n";
8736       pr " %s" name;
8737       List.iter (
8738         function
8739         | Pathname n | Device n | Dev_or_Path n | String n ->
8740             pr " %s" n
8741         | OptString n -> pr " %s" n
8742         | StringList n | DeviceList n -> pr " '%s ...'" n
8743         | Bool _ -> pr " true|false"
8744         | Int n -> pr " %s" n
8745         | Int64 n -> pr " %s" n
8746         | FileIn n | FileOut n -> pr " (%s|-)" n
8747         | BufferIn n -> pr " %s" n
8748         | Key _ -> () (* keys are entered at a prompt *)
8749       ) (snd style);
8750       pr "\n";
8751       pr "\n";
8752       pr "%s\n\n" longdesc;
8753
8754       if List.exists (function FileIn _ | FileOut _ -> true
8755                       | _ -> false) (snd style) then
8756         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
8757
8758       if List.exists (function Key _ -> true | _ -> false) (snd style) then
8759         pr "This command has one or more key or passphrase parameters.
8760 Guestfish will prompt for these separately.\n\n";
8761
8762       if List.mem ProtocolLimitWarning flags then
8763         pr "%s\n\n" protocol_limit_warning;
8764
8765       if List.mem DangerWillRobinson flags then
8766         pr "%s\n\n" danger_will_robinson;
8767
8768       match deprecation_notice flags with
8769       | None -> ()
8770       | Some txt -> pr "%s\n\n" txt
8771   ) all_functions_sorted
8772
8773 (* Generate a C function prototype. *)
8774 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
8775     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
8776     ?(prefix = "")
8777     ?handle name style =
8778   if extern then pr "extern ";
8779   if static then pr "static ";
8780   (match fst style with
8781    | RErr -> pr "int "
8782    | RInt _ -> pr "int "
8783    | RInt64 _ -> pr "int64_t "
8784    | RBool _ -> pr "int "
8785    | RConstString _ | RConstOptString _ -> pr "const char *"
8786    | RString _ | RBufferOut _ -> pr "char *"
8787    | RStringList _ | RHashtable _ -> pr "char **"
8788    | RStruct (_, typ) ->
8789        if not in_daemon then pr "struct guestfs_%s *" typ
8790        else pr "guestfs_int_%s *" typ
8791    | RStructList (_, typ) ->
8792        if not in_daemon then pr "struct guestfs_%s_list *" typ
8793        else pr "guestfs_int_%s_list *" typ
8794   );
8795   let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
8796   pr "%s%s (" prefix name;
8797   if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
8798     pr "void"
8799   else (
8800     let comma = ref false in
8801     (match handle with
8802      | None -> ()
8803      | Some handle -> pr "guestfs_h *%s" handle; comma := true
8804     );
8805     let next () =
8806       if !comma then (
8807         if single_line then pr ", " else pr ",\n\t\t"
8808       );
8809       comma := true
8810     in
8811     List.iter (
8812       function
8813       | Pathname n
8814       | Device n | Dev_or_Path n
8815       | String n
8816       | OptString n
8817       | Key n ->
8818           next ();
8819           pr "const char *%s" n
8820       | StringList n | DeviceList n ->
8821           next ();
8822           pr "char *const *%s" n
8823       | Bool n -> next (); pr "int %s" n
8824       | Int n -> next (); pr "int %s" n
8825       | Int64 n -> next (); pr "int64_t %s" n
8826       | FileIn n
8827       | FileOut n ->
8828           if not in_daemon then (next (); pr "const char *%s" n)
8829       | BufferIn n ->
8830           next ();
8831           pr "const char *%s" n;
8832           next ();
8833           pr "size_t %s_size" n
8834     ) (snd style);
8835     if is_RBufferOut then (next (); pr "size_t *size_r");
8836   );
8837   pr ")";
8838   if semicolon then pr ";";
8839   if newline then pr "\n"
8840
8841 (* Generate C call arguments, eg "(handle, foo, bar)" *)
8842 and generate_c_call_args ?handle ?(decl = false) style =
8843   pr "(";
8844   let comma = ref false in
8845   let next () =
8846     if !comma then pr ", ";
8847     comma := true
8848   in
8849   (match handle with
8850    | None -> ()
8851    | Some handle -> pr "%s" handle; comma := true
8852   );
8853   List.iter (
8854     function
8855     | BufferIn n ->
8856         next ();
8857         pr "%s, %s_size" n n
8858     | arg ->
8859         next ();
8860         pr "%s" (name_of_argt arg)
8861   ) (snd style);
8862   (* For RBufferOut calls, add implicit &size parameter. *)
8863   if not decl then (
8864     match fst style with
8865     | RBufferOut _ ->
8866         next ();
8867         pr "&size"
8868     | _ -> ()
8869   );
8870   pr ")"
8871
8872 (* Generate the OCaml bindings interface. *)
8873 and generate_ocaml_mli () =
8874   generate_header OCamlStyle LGPLv2plus;
8875
8876   pr "\
8877 (** For API documentation you should refer to the C API
8878     in the guestfs(3) manual page.  The OCaml API uses almost
8879     exactly the same calls. *)
8880
8881 type t
8882 (** A [guestfs_h] handle. *)
8883
8884 exception Error of string
8885 (** This exception is raised when there is an error. *)
8886
8887 exception Handle_closed of string
8888 (** This exception is raised if you use a {!Guestfs.t} handle
8889     after calling {!close} on it.  The string is the name of
8890     the function. *)
8891
8892 val create : unit -> t
8893 (** Create a {!Guestfs.t} handle. *)
8894
8895 val close : t -> unit
8896 (** Close the {!Guestfs.t} handle and free up all resources used
8897     by it immediately.
8898
8899     Handles are closed by the garbage collector when they become
8900     unreferenced, but callers can call this in order to provide
8901     predictable cleanup. *)
8902
8903 ";
8904   generate_ocaml_structure_decls ();
8905
8906   (* The actions. *)
8907   List.iter (
8908     fun (name, style, _, _, _, shortdesc, _) ->
8909       generate_ocaml_prototype name style;
8910       pr "(** %s *)\n" shortdesc;
8911       pr "\n"
8912   ) all_functions_sorted
8913
8914 (* Generate the OCaml bindings implementation. *)
8915 and generate_ocaml_ml () =
8916   generate_header OCamlStyle LGPLv2plus;
8917
8918   pr "\
8919 type t
8920
8921 exception Error of string
8922 exception Handle_closed of string
8923
8924 external create : unit -> t = \"ocaml_guestfs_create\"
8925 external close : t -> unit = \"ocaml_guestfs_close\"
8926
8927 (* Give the exceptions names, so they can be raised from the C code. *)
8928 let () =
8929   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
8930   Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
8931
8932 ";
8933
8934   generate_ocaml_structure_decls ();
8935
8936   (* The actions. *)
8937   List.iter (
8938     fun (name, style, _, _, _, shortdesc, _) ->
8939       generate_ocaml_prototype ~is_external:true name style;
8940   ) all_functions_sorted
8941
8942 (* Generate the OCaml bindings C implementation. *)
8943 and generate_ocaml_c () =
8944   generate_header CStyle LGPLv2plus;
8945
8946   pr "\
8947 #include <stdio.h>
8948 #include <stdlib.h>
8949 #include <string.h>
8950
8951 #include <caml/config.h>
8952 #include <caml/alloc.h>
8953 #include <caml/callback.h>
8954 #include <caml/fail.h>
8955 #include <caml/memory.h>
8956 #include <caml/mlvalues.h>
8957 #include <caml/signals.h>
8958
8959 #include \"guestfs.h\"
8960
8961 #include \"guestfs_c.h\"
8962
8963 /* Copy a hashtable of string pairs into an assoc-list.  We return
8964  * the list in reverse order, but hashtables aren't supposed to be
8965  * ordered anyway.
8966  */
8967 static CAMLprim value
8968 copy_table (char * const * argv)
8969 {
8970   CAMLparam0 ();
8971   CAMLlocal5 (rv, pairv, kv, vv, cons);
8972   size_t i;
8973
8974   rv = Val_int (0);
8975   for (i = 0; argv[i] != NULL; i += 2) {
8976     kv = caml_copy_string (argv[i]);
8977     vv = caml_copy_string (argv[i+1]);
8978     pairv = caml_alloc (2, 0);
8979     Store_field (pairv, 0, kv);
8980     Store_field (pairv, 1, vv);
8981     cons = caml_alloc (2, 0);
8982     Store_field (cons, 1, rv);
8983     rv = cons;
8984     Store_field (cons, 0, pairv);
8985   }
8986
8987   CAMLreturn (rv);
8988 }
8989
8990 ";
8991
8992   (* Struct copy functions. *)
8993
8994   let emit_ocaml_copy_list_function typ =
8995     pr "static CAMLprim value\n";
8996     pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
8997     pr "{\n";
8998     pr "  CAMLparam0 ();\n";
8999     pr "  CAMLlocal2 (rv, v);\n";
9000     pr "  unsigned int i;\n";
9001     pr "\n";
9002     pr "  if (%ss->len == 0)\n" typ;
9003     pr "    CAMLreturn (Atom (0));\n";
9004     pr "  else {\n";
9005     pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
9006     pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
9007     pr "      v = copy_%s (&%ss->val[i]);\n" typ typ;
9008     pr "      caml_modify (&Field (rv, i), v);\n";
9009     pr "    }\n";
9010     pr "    CAMLreturn (rv);\n";
9011     pr "  }\n";
9012     pr "}\n";
9013     pr "\n";
9014   in
9015
9016   List.iter (
9017     fun (typ, cols) ->
9018       let has_optpercent_col =
9019         List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
9020
9021       pr "static CAMLprim value\n";
9022       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
9023       pr "{\n";
9024       pr "  CAMLparam0 ();\n";
9025       if has_optpercent_col then
9026         pr "  CAMLlocal3 (rv, v, v2);\n"
9027       else
9028         pr "  CAMLlocal2 (rv, v);\n";
9029       pr "\n";
9030       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
9031       iteri (
9032         fun i col ->
9033           (match col with
9034            | name, FString ->
9035                pr "  v = caml_copy_string (%s->%s);\n" typ name
9036            | name, FBuffer ->
9037                pr "  v = caml_alloc_string (%s->%s_len);\n" typ name;
9038                pr "  memcpy (String_val (v), %s->%s, %s->%s_len);\n"
9039                  typ name typ name
9040            | name, FUUID ->
9041                pr "  v = caml_alloc_string (32);\n";
9042                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
9043            | name, (FBytes|FInt64|FUInt64) ->
9044                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
9045            | name, (FInt32|FUInt32) ->
9046                pr "  v = caml_copy_int32 (%s->%s);\n" typ name
9047            | name, FOptPercent ->
9048                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
9049                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
9050                pr "    v = caml_alloc (1, 0);\n";
9051                pr "    Store_field (v, 0, v2);\n";
9052                pr "  } else /* None */\n";
9053                pr "    v = Val_int (0);\n";
9054            | name, FChar ->
9055                pr "  v = Val_int (%s->%s);\n" typ name
9056           );
9057           pr "  Store_field (rv, %d, v);\n" i
9058       ) cols;
9059       pr "  CAMLreturn (rv);\n";
9060       pr "}\n";
9061       pr "\n";
9062   ) structs;
9063
9064   (* Emit a copy_TYPE_list function definition only if that function is used. *)
9065   List.iter (
9066     function
9067     | typ, (RStructListOnly | RStructAndList) ->
9068         (* generate the function for typ *)
9069         emit_ocaml_copy_list_function typ
9070     | typ, _ -> () (* empty *)
9071   ) (rstructs_used_by all_functions);
9072
9073   (* The wrappers. *)
9074   List.iter (
9075     fun (name, style, _, _, _, _, _) ->
9076       pr "/* Automatically generated wrapper for function\n";
9077       pr " * ";
9078       generate_ocaml_prototype name style;
9079       pr " */\n";
9080       pr "\n";
9081
9082       let params =
9083         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
9084
9085       let needs_extra_vs =
9086         match fst style with RConstOptString _ -> true | _ -> false in
9087
9088       pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9089       pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
9090       List.iter (pr ", value %s") (List.tl params); pr ");\n";
9091       pr "\n";
9092
9093       pr "CAMLprim value\n";
9094       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
9095       List.iter (pr ", value %s") (List.tl params);
9096       pr ")\n";
9097       pr "{\n";
9098
9099       (match params with
9100        | [p1; p2; p3; p4; p5] ->
9101            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
9102        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
9103            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
9104            pr "  CAMLxparam%d (%s);\n"
9105              (List.length rest) (String.concat ", " rest)
9106        | ps ->
9107            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
9108       );
9109       if not needs_extra_vs then
9110         pr "  CAMLlocal1 (rv);\n"
9111       else
9112         pr "  CAMLlocal3 (rv, v, v2);\n";
9113       pr "\n";
9114
9115       pr "  guestfs_h *g = Guestfs_val (gv);\n";
9116       pr "  if (g == NULL)\n";
9117       pr "    ocaml_guestfs_raise_closed (\"%s\");\n" name;
9118       pr "\n";
9119
9120       List.iter (
9121         function
9122         | Pathname n
9123         | Device n | Dev_or_Path n
9124         | String n
9125         | FileIn n
9126         | FileOut n
9127         | Key n ->
9128             (* Copy strings in case the GC moves them: RHBZ#604691 *)
9129             pr "  char *%s = guestfs_safe_strdup (g, String_val (%sv));\n" n n
9130         | OptString n ->
9131             pr "  char *%s =\n" n;
9132             pr "    %sv != Val_int (0) ?" n;
9133             pr "      guestfs_safe_strdup (g, String_val (Field (%sv, 0))) : NULL;\n" n
9134         | BufferIn n ->
9135             pr "  size_t %s_size = caml_string_length (%sv);\n" n n;
9136             pr "  char *%s = guestfs_safe_memdup (g, String_val (%sv), %s_size);\n" n n n
9137         | StringList n | DeviceList n ->
9138             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
9139         | Bool n ->
9140             pr "  int %s = Bool_val (%sv);\n" n n
9141         | Int n ->
9142             pr "  int %s = Int_val (%sv);\n" n n
9143         | Int64 n ->
9144             pr "  int64_t %s = Int64_val (%sv);\n" n n
9145       ) (snd style);
9146       let error_code =
9147         match fst style with
9148         | RErr -> pr "  int r;\n"; "-1"
9149         | RInt _ -> pr "  int r;\n"; "-1"
9150         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
9151         | RBool _ -> pr "  int r;\n"; "-1"
9152         | RConstString _ | RConstOptString _ ->
9153             pr "  const char *r;\n"; "NULL"
9154         | RString _ -> pr "  char *r;\n"; "NULL"
9155         | RStringList _ ->
9156             pr "  size_t i;\n";
9157             pr "  char **r;\n";
9158             "NULL"
9159         | RStruct (_, typ) ->
9160             pr "  struct guestfs_%s *r;\n" typ; "NULL"
9161         | RStructList (_, typ) ->
9162             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
9163         | RHashtable _ ->
9164             pr "  size_t i;\n";
9165             pr "  char **r;\n";
9166             "NULL"
9167         | RBufferOut _ ->
9168             pr "  char *r;\n";
9169             pr "  size_t size;\n";
9170             "NULL" in
9171       pr "\n";
9172
9173       pr "  caml_enter_blocking_section ();\n";
9174       pr "  r = guestfs_%s " name;
9175       generate_c_call_args ~handle:"g" style;
9176       pr ";\n";
9177       pr "  caml_leave_blocking_section ();\n";
9178
9179       (* Free strings if we copied them above. *)
9180       List.iter (
9181         function
9182         | Pathname n | Device n | Dev_or_Path n | String n | OptString n
9183         | FileIn n | FileOut n | BufferIn n | Key n ->
9184             pr "  free (%s);\n" n
9185         | StringList n | DeviceList n ->
9186             pr "  ocaml_guestfs_free_strings (%s);\n" n;
9187         | Bool _ | Int _ | Int64 _ -> ()
9188       ) (snd style);
9189
9190       pr "  if (r == %s)\n" error_code;
9191       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
9192       pr "\n";
9193
9194       (match fst style with
9195        | RErr -> pr "  rv = Val_unit;\n"
9196        | RInt _ -> pr "  rv = Val_int (r);\n"
9197        | RInt64 _ ->
9198            pr "  rv = caml_copy_int64 (r);\n"
9199        | RBool _ -> pr "  rv = Val_bool (r);\n"
9200        | RConstString _ ->
9201            pr "  rv = caml_copy_string (r);\n"
9202        | RConstOptString _ ->
9203            pr "  if (r) { /* Some string */\n";
9204            pr "    v = caml_alloc (1, 0);\n";
9205            pr "    v2 = caml_copy_string (r);\n";
9206            pr "    Store_field (v, 0, v2);\n";
9207            pr "  } else /* None */\n";
9208            pr "    v = Val_int (0);\n";
9209        | RString _ ->
9210            pr "  rv = caml_copy_string (r);\n";
9211            pr "  free (r);\n"
9212        | RStringList _ ->
9213            pr "  rv = caml_copy_string_array ((const char **) r);\n";
9214            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9215            pr "  free (r);\n"
9216        | RStruct (_, typ) ->
9217            pr "  rv = copy_%s (r);\n" typ;
9218            pr "  guestfs_free_%s (r);\n" typ;
9219        | RStructList (_, typ) ->
9220            pr "  rv = copy_%s_list (r);\n" typ;
9221            pr "  guestfs_free_%s_list (r);\n" typ;
9222        | RHashtable _ ->
9223            pr "  rv = copy_table (r);\n";
9224            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
9225            pr "  free (r);\n";
9226        | RBufferOut _ ->
9227            pr "  rv = caml_alloc_string (size);\n";
9228            pr "  memcpy (String_val (rv), r, size);\n";
9229       );
9230
9231       pr "  CAMLreturn (rv);\n";
9232       pr "}\n";
9233       pr "\n";
9234
9235       if List.length params > 5 then (
9236         pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
9237         pr "CAMLprim value ";
9238         pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
9239         pr "CAMLprim value\n";
9240         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
9241         pr "{\n";
9242         pr "  return ocaml_guestfs_%s (argv[0]" name;
9243         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
9244         pr ");\n";
9245         pr "}\n";
9246         pr "\n"
9247       )
9248   ) all_functions_sorted
9249
9250 and generate_ocaml_structure_decls () =
9251   List.iter (
9252     fun (typ, cols) ->
9253       pr "type %s = {\n" typ;
9254       List.iter (
9255         function
9256         | name, FString -> pr "  %s : string;\n" name
9257         | name, FBuffer -> pr "  %s : string;\n" name
9258         | name, FUUID -> pr "  %s : string;\n" name
9259         | name, (FBytes|FInt64|FUInt64) -> pr "  %s : int64;\n" name
9260         | name, (FInt32|FUInt32) -> pr "  %s : int32;\n" name
9261         | name, FChar -> pr "  %s : char;\n" name
9262         | name, FOptPercent -> pr "  %s : float option;\n" name
9263       ) cols;
9264       pr "}\n";
9265       pr "\n"
9266   ) structs
9267
9268 and generate_ocaml_prototype ?(is_external = false) name style =
9269   if is_external then pr "external " else pr "val ";
9270   pr "%s : t -> " name;
9271   List.iter (
9272     function
9273     | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _
9274     | BufferIn _ | Key _ -> pr "string -> "
9275     | OptString _ -> pr "string option -> "
9276     | StringList _ | DeviceList _ -> pr "string array -> "
9277     | Bool _ -> pr "bool -> "
9278     | Int _ -> pr "int -> "
9279     | Int64 _ -> pr "int64 -> "
9280   ) (snd style);
9281   (match fst style with
9282    | RErr -> pr "unit" (* all errors are turned into exceptions *)
9283    | RInt _ -> pr "int"
9284    | RInt64 _ -> pr "int64"
9285    | RBool _ -> pr "bool"
9286    | RConstString _ -> pr "string"
9287    | RConstOptString _ -> pr "string option"
9288    | RString _ | RBufferOut _ -> pr "string"
9289    | RStringList _ -> pr "string array"
9290    | RStruct (_, typ) -> pr "%s" typ
9291    | RStructList (_, typ) -> pr "%s array" typ
9292    | RHashtable _ -> pr "(string * string) list"
9293   );
9294   if is_external then (
9295     pr " = ";
9296     if List.length (snd style) + 1 > 5 then
9297       pr "\"ocaml_guestfs_%s_byte\" " name;
9298     pr "\"ocaml_guestfs_%s\"" name
9299   );
9300   pr "\n"
9301
9302 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
9303 and generate_perl_xs () =
9304   generate_header CStyle LGPLv2plus;
9305
9306   pr "\
9307 #include \"EXTERN.h\"
9308 #include \"perl.h\"
9309 #include \"XSUB.h\"
9310
9311 #include <guestfs.h>
9312
9313 #ifndef PRId64
9314 #define PRId64 \"lld\"
9315 #endif
9316
9317 static SV *
9318 my_newSVll(long long val) {
9319 #ifdef USE_64_BIT_ALL
9320   return newSViv(val);
9321 #else
9322   char buf[100];
9323   int len;
9324   len = snprintf(buf, 100, \"%%\" PRId64, val);
9325   return newSVpv(buf, len);
9326 #endif
9327 }
9328
9329 #ifndef PRIu64
9330 #define PRIu64 \"llu\"
9331 #endif
9332
9333 static SV *
9334 my_newSVull(unsigned long long val) {
9335 #ifdef USE_64_BIT_ALL
9336   return newSVuv(val);
9337 #else
9338   char buf[100];
9339   int len;
9340   len = snprintf(buf, 100, \"%%\" PRIu64, val);
9341   return newSVpv(buf, len);
9342 #endif
9343 }
9344
9345 /* http://www.perlmonks.org/?node_id=680842 */
9346 static char **
9347 XS_unpack_charPtrPtr (SV *arg) {
9348   char **ret;
9349   AV *av;
9350   I32 i;
9351
9352   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
9353     croak (\"array reference expected\");
9354
9355   av = (AV *)SvRV (arg);
9356   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
9357   if (!ret)
9358     croak (\"malloc failed\");
9359
9360   for (i = 0; i <= av_len (av); i++) {
9361     SV **elem = av_fetch (av, i, 0);
9362
9363     if (!elem || !*elem)
9364       croak (\"missing element in list\");
9365
9366     ret[i] = SvPV_nolen (*elem);
9367   }
9368
9369   ret[i] = NULL;
9370
9371   return ret;
9372 }
9373
9374 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
9375
9376 PROTOTYPES: ENABLE
9377
9378 guestfs_h *
9379 _create ()
9380    CODE:
9381       RETVAL = guestfs_create ();
9382       if (!RETVAL)
9383         croak (\"could not create guestfs handle\");
9384       guestfs_set_error_handler (RETVAL, NULL, NULL);
9385  OUTPUT:
9386       RETVAL
9387
9388 void
9389 DESTROY (sv)
9390       SV *sv;
9391  PPCODE:
9392       /* For the 'g' argument above we do the conversion explicitly and
9393        * don't rely on the typemap, because if the handle has been
9394        * explicitly closed we don't want the typemap conversion to
9395        * display an error.
9396        */
9397       HV *hv = (HV *) SvRV (sv);
9398       SV **svp = hv_fetch (hv, \"_g\", 2, 0);
9399       if (svp != NULL) {
9400         guestfs_h *g = (guestfs_h *) SvIV (*svp);
9401         assert (g != NULL);
9402         guestfs_close (g);
9403       }
9404
9405 void
9406 close (g)
9407       guestfs_h *g;
9408  PPCODE:
9409       guestfs_close (g);
9410       /* Avoid double-free in DESTROY method. */
9411       HV *hv = (HV *) SvRV (ST(0));
9412       (void) hv_delete (hv, \"_g\", 2, G_DISCARD);
9413
9414 ";
9415
9416   List.iter (
9417     fun (name, style, _, _, _, _, _) ->
9418       (match fst style with
9419        | RErr -> pr "void\n"
9420        | RInt _ -> pr "SV *\n"
9421        | RInt64 _ -> pr "SV *\n"
9422        | RBool _ -> pr "SV *\n"
9423        | RConstString _ -> pr "SV *\n"
9424        | RConstOptString _ -> pr "SV *\n"
9425        | RString _ -> pr "SV *\n"
9426        | RBufferOut _ -> pr "SV *\n"
9427        | RStringList _
9428        | RStruct _ | RStructList _
9429        | RHashtable _ ->
9430            pr "void\n" (* all lists returned implictly on the stack *)
9431       );
9432       (* Call and arguments. *)
9433       pr "%s (g" name;
9434       List.iter (
9435         fun arg -> pr ", %s" (name_of_argt arg)
9436       ) (snd style);
9437       pr ")\n";
9438       pr "      guestfs_h *g;\n";
9439       iteri (
9440         fun i ->
9441           function
9442           | Pathname n | Device n | Dev_or_Path n | String n
9443           | FileIn n | FileOut n | Key n ->
9444               pr "      char *%s;\n" n
9445           | BufferIn n ->
9446               pr "      char *%s;\n" n;
9447               pr "      size_t %s_size = SvCUR (ST(%d));\n" n (i+1)
9448           | OptString n ->
9449               (* http://www.perlmonks.org/?node_id=554277
9450                * Note that the implicit handle argument means we have
9451                * to add 1 to the ST(x) operator.
9452                *)
9453               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
9454           | StringList n | DeviceList n -> pr "      char **%s;\n" n
9455           | Bool n -> pr "      int %s;\n" n
9456           | Int n -> pr "      int %s;\n" n
9457           | Int64 n -> pr "      int64_t %s;\n" n
9458       ) (snd style);
9459
9460       let do_cleanups () =
9461         List.iter (
9462           function
9463           | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
9464           | Bool _ | Int _ | Int64 _
9465           | FileIn _ | FileOut _
9466           | BufferIn _ | Key _ -> ()
9467           | StringList n | DeviceList n -> pr "      free (%s);\n" n
9468         ) (snd style)
9469       in
9470
9471       (* Code. *)
9472       (match fst style with
9473        | RErr ->
9474            pr "PREINIT:\n";
9475            pr "      int r;\n";
9476            pr " PPCODE:\n";
9477            pr "      r = guestfs_%s " name;
9478            generate_c_call_args ~handle:"g" style;
9479            pr ";\n";
9480            do_cleanups ();
9481            pr "      if (r == -1)\n";
9482            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9483        | RInt n
9484        | RBool n ->
9485            pr "PREINIT:\n";
9486            pr "      int %s;\n" n;
9487            pr "   CODE:\n";
9488            pr "      %s = guestfs_%s " n name;
9489            generate_c_call_args ~handle:"g" style;
9490            pr ";\n";
9491            do_cleanups ();
9492            pr "      if (%s == -1)\n" n;
9493            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9494            pr "      RETVAL = newSViv (%s);\n" n;
9495            pr " OUTPUT:\n";
9496            pr "      RETVAL\n"
9497        | RInt64 n ->
9498            pr "PREINIT:\n";
9499            pr "      int64_t %s;\n" n;
9500            pr "   CODE:\n";
9501            pr "      %s = guestfs_%s " n name;
9502            generate_c_call_args ~handle:"g" style;
9503            pr ";\n";
9504            do_cleanups ();
9505            pr "      if (%s == -1)\n" n;
9506            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9507            pr "      RETVAL = my_newSVll (%s);\n" n;
9508            pr " OUTPUT:\n";
9509            pr "      RETVAL\n"
9510        | RConstString n ->
9511            pr "PREINIT:\n";
9512            pr "      const char *%s;\n" n;
9513            pr "   CODE:\n";
9514            pr "      %s = guestfs_%s " n name;
9515            generate_c_call_args ~handle:"g" style;
9516            pr ";\n";
9517            do_cleanups ();
9518            pr "      if (%s == NULL)\n" n;
9519            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9520            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9521            pr " OUTPUT:\n";
9522            pr "      RETVAL\n"
9523        | RConstOptString n ->
9524            pr "PREINIT:\n";
9525            pr "      const char *%s;\n" n;
9526            pr "   CODE:\n";
9527            pr "      %s = guestfs_%s " n name;
9528            generate_c_call_args ~handle:"g" style;
9529            pr ";\n";
9530            do_cleanups ();
9531            pr "      if (%s == NULL)\n" n;
9532            pr "        RETVAL = &PL_sv_undef;\n";
9533            pr "      else\n";
9534            pr "        RETVAL = newSVpv (%s, 0);\n" n;
9535            pr " OUTPUT:\n";
9536            pr "      RETVAL\n"
9537        | RString n ->
9538            pr "PREINIT:\n";
9539            pr "      char *%s;\n" n;
9540            pr "   CODE:\n";
9541            pr "      %s = guestfs_%s " n name;
9542            generate_c_call_args ~handle:"g" style;
9543            pr ";\n";
9544            do_cleanups ();
9545            pr "      if (%s == NULL)\n" n;
9546            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9547            pr "      RETVAL = newSVpv (%s, 0);\n" n;
9548            pr "      free (%s);\n" n;
9549            pr " OUTPUT:\n";
9550            pr "      RETVAL\n"
9551        | RStringList n | RHashtable n ->
9552            pr "PREINIT:\n";
9553            pr "      char **%s;\n" n;
9554            pr "      size_t i, n;\n";
9555            pr " PPCODE:\n";
9556            pr "      %s = guestfs_%s " n name;
9557            generate_c_call_args ~handle:"g" style;
9558            pr ";\n";
9559            do_cleanups ();
9560            pr "      if (%s == NULL)\n" n;
9561            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9562            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
9563            pr "      EXTEND (SP, n);\n";
9564            pr "      for (i = 0; i < n; ++i) {\n";
9565            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
9566            pr "        free (%s[i]);\n" n;
9567            pr "      }\n";
9568            pr "      free (%s);\n" n;
9569        | RStruct (n, typ) ->
9570            let cols = cols_of_struct typ in
9571            generate_perl_struct_code typ cols name style n do_cleanups
9572        | RStructList (n, typ) ->
9573            let cols = cols_of_struct typ in
9574            generate_perl_struct_list_code typ cols name style n do_cleanups
9575        | RBufferOut n ->
9576            pr "PREINIT:\n";
9577            pr "      char *%s;\n" n;
9578            pr "      size_t size;\n";
9579            pr "   CODE:\n";
9580            pr "      %s = guestfs_%s " n name;
9581            generate_c_call_args ~handle:"g" style;
9582            pr ";\n";
9583            do_cleanups ();
9584            pr "      if (%s == NULL)\n" n;
9585            pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9586            pr "      RETVAL = newSVpvn (%s, size);\n" n;
9587            pr "      free (%s);\n" n;
9588            pr " OUTPUT:\n";
9589            pr "      RETVAL\n"
9590       );
9591
9592       pr "\n"
9593   ) all_functions
9594
9595 and generate_perl_struct_list_code typ cols name style n do_cleanups =
9596   pr "PREINIT:\n";
9597   pr "      struct guestfs_%s_list *%s;\n" typ n;
9598   pr "      size_t i;\n";
9599   pr "      HV *hv;\n";
9600   pr " PPCODE:\n";
9601   pr "      %s = guestfs_%s " n name;
9602   generate_c_call_args ~handle:"g" style;
9603   pr ";\n";
9604   do_cleanups ();
9605   pr "      if (%s == NULL)\n" n;
9606   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9607   pr "      EXTEND (SP, %s->len);\n" n;
9608   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
9609   pr "        hv = newHV ();\n";
9610   List.iter (
9611     function
9612     | name, FString ->
9613         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
9614           name (String.length name) n name
9615     | name, FUUID ->
9616         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
9617           name (String.length name) n name
9618     | name, FBuffer ->
9619         pr "        (void) hv_store (hv, \"%s\", %d, newSVpvn (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
9620           name (String.length name) n name n name
9621     | name, (FBytes|FUInt64) ->
9622         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
9623           name (String.length name) n name
9624     | name, FInt64 ->
9625         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
9626           name (String.length name) n name
9627     | name, (FInt32|FUInt32) ->
9628         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9629           name (String.length name) n name
9630     | name, FChar ->
9631         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
9632           name (String.length name) n name
9633     | name, FOptPercent ->
9634         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
9635           name (String.length name) n name
9636   ) cols;
9637   pr "        PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
9638   pr "      }\n";
9639   pr "      guestfs_free_%s_list (%s);\n" typ n
9640
9641 and generate_perl_struct_code typ cols name style n do_cleanups =
9642   pr "PREINIT:\n";
9643   pr "      struct guestfs_%s *%s;\n" typ n;
9644   pr " PPCODE:\n";
9645   pr "      %s = guestfs_%s " n name;
9646   generate_c_call_args ~handle:"g" style;
9647   pr ";\n";
9648   do_cleanups ();
9649   pr "      if (%s == NULL)\n" n;
9650   pr "        croak (\"%%s\", guestfs_last_error (g));\n";
9651   pr "      EXTEND (SP, 2 * %d);\n" (List.length cols);
9652   List.iter (
9653     fun ((name, _) as col) ->
9654       pr "      PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
9655
9656       match col with
9657       | name, FString ->
9658           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
9659             n name
9660       | name, FBuffer ->
9661           pr "      PUSHs (sv_2mortal (newSVpvn (%s->%s, %s->%s_len)));\n"
9662             n name n name
9663       | name, FUUID ->
9664           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
9665             n name
9666       | name, (FBytes|FUInt64) ->
9667           pr "      PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
9668             n name
9669       | name, FInt64 ->
9670           pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
9671             n name
9672       | name, (FInt32|FUInt32) ->
9673           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9674             n name
9675       | name, FChar ->
9676           pr "      PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
9677             n name
9678       | name, FOptPercent ->
9679           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
9680             n name
9681   ) cols;
9682   pr "      free (%s);\n" n
9683
9684 (* Generate Sys/Guestfs.pm. *)
9685 and generate_perl_pm () =
9686   generate_header HashStyle LGPLv2plus;
9687
9688   pr "\
9689 =pod
9690
9691 =head1 NAME
9692
9693 Sys::Guestfs - Perl bindings for libguestfs
9694
9695 =head1 SYNOPSIS
9696
9697  use Sys::Guestfs;
9698
9699  my $h = Sys::Guestfs->new ();
9700  $h->add_drive ('guest.img');
9701  $h->launch ();
9702  $h->mount ('/dev/sda1', '/');
9703  $h->touch ('/hello');
9704  $h->sync ();
9705
9706 =head1 DESCRIPTION
9707
9708 The C<Sys::Guestfs> module provides a Perl XS binding to the
9709 libguestfs API for examining and modifying virtual machine
9710 disk images.
9711
9712 Amongst the things this is good for: making batch configuration
9713 changes to guests, getting disk used/free statistics (see also:
9714 virt-df), migrating between virtualization systems (see also:
9715 virt-p2v), performing partial backups, performing partial guest
9716 clones, cloning guests and changing registry/UUID/hostname info, and
9717 much else besides.
9718
9719 Libguestfs uses Linux kernel and qemu code, and can access any type of
9720 guest filesystem that Linux and qemu can, including but not limited
9721 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
9722 schemes, qcow, qcow2, vmdk.
9723
9724 Libguestfs provides ways to enumerate guest storage (eg. partitions,
9725 LVs, what filesystem is in each LV, etc.).  It can also run commands
9726 in the context of the guest.  Also you can access filesystems over
9727 FUSE.
9728
9729 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
9730 functions for using libguestfs from Perl, including integration
9731 with libvirt.
9732
9733 =head1 ERRORS
9734
9735 All errors turn into calls to C<croak> (see L<Carp(3)>).
9736
9737 =head1 METHODS
9738
9739 =over 4
9740
9741 =cut
9742
9743 package Sys::Guestfs;
9744
9745 use strict;
9746 use warnings;
9747
9748 # This version number changes whenever a new function
9749 # is added to the libguestfs API.  It is not directly
9750 # related to the libguestfs version number.
9751 use vars qw($VERSION);
9752 $VERSION = '0.%d';
9753
9754 require XSLoader;
9755 XSLoader::load ('Sys::Guestfs');
9756
9757 =item $h = Sys::Guestfs->new ();
9758
9759 Create a new guestfs handle.
9760
9761 =cut
9762
9763 sub new {
9764   my $proto = shift;
9765   my $class = ref ($proto) || $proto;
9766
9767   my $g = Sys::Guestfs::_create ();
9768   my $self = { _g => $g };
9769   bless $self, $class;
9770   return $self;
9771 }
9772
9773 =item $h->close ();
9774
9775 Explicitly close the guestfs handle.
9776
9777 B<Note:> You should not usually call this function.  The handle will
9778 be closed implicitly when its reference count goes to zero (eg.
9779 when it goes out of scope or the program ends).  This call is
9780 only required in some exceptional cases, such as where the program
9781 may contain cached references to the handle 'somewhere' and you
9782 really have to have the close happen right away.  After calling
9783 C<close> the program must not call any method (including C<close>)
9784 on the handle (but the implicit call to C<DESTROY> that happens
9785 when the final reference is cleaned up is OK).
9786
9787 =cut
9788
9789 " max_proc_nr;
9790
9791   (* Actions.  We only need to print documentation for these as
9792    * they are pulled in from the XS code automatically.
9793    *)
9794   List.iter (
9795     fun (name, style, _, flags, _, _, longdesc) ->
9796       if not (List.mem NotInDocs flags) then (
9797         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
9798         pr "=item ";
9799         generate_perl_prototype name style;
9800         pr "\n\n";
9801         pr "%s\n\n" longdesc;
9802         if List.mem ProtocolLimitWarning flags then
9803           pr "%s\n\n" protocol_limit_warning;
9804         if List.mem DangerWillRobinson flags then
9805           pr "%s\n\n" danger_will_robinson;
9806         match deprecation_notice flags with
9807         | None -> ()
9808         | Some txt -> pr "%s\n\n" txt
9809       )
9810   ) all_functions_sorted;
9811
9812   (* End of file. *)
9813   pr "\
9814 =cut
9815
9816 1;
9817
9818 =back
9819
9820 =head1 COPYRIGHT
9821
9822 Copyright (C) %s Red Hat Inc.
9823
9824 =head1 LICENSE
9825
9826 Please see the file COPYING.LIB for the full license.
9827
9828 =head1 SEE ALSO
9829
9830 L<guestfs(3)>,
9831 L<guestfish(1)>,
9832 L<http://libguestfs.org>,
9833 L<Sys::Guestfs::Lib(3)>.
9834
9835 =cut
9836 " copyright_years
9837
9838 and generate_perl_prototype name style =
9839   (match fst style with
9840    | RErr -> ()
9841    | RBool n
9842    | RInt n
9843    | RInt64 n
9844    | RConstString n
9845    | RConstOptString n
9846    | RString n
9847    | RBufferOut n -> pr "$%s = " n
9848    | RStruct (n,_)
9849    | RHashtable n -> pr "%%%s = " n
9850    | RStringList n
9851    | RStructList (n,_) -> pr "@%s = " n
9852   );
9853   pr "$h->%s (" name;
9854   let comma = ref false in
9855   List.iter (
9856     fun arg ->
9857       if !comma then pr ", ";
9858       comma := true;
9859       match arg with
9860       | Pathname n | Device n | Dev_or_Path n | String n
9861       | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n
9862       | BufferIn n | Key n ->
9863           pr "$%s" n
9864       | StringList n | DeviceList n ->
9865           pr "\\@%s" n
9866   ) (snd style);
9867   pr ");"
9868
9869 (* Generate Python C module. *)
9870 and generate_python_c () =
9871   generate_header CStyle LGPLv2plus;
9872
9873   pr "\
9874 #define PY_SSIZE_T_CLEAN 1
9875 #include <Python.h>
9876
9877 #if PY_VERSION_HEX < 0x02050000
9878 typedef int Py_ssize_t;
9879 #define PY_SSIZE_T_MAX INT_MAX
9880 #define PY_SSIZE_T_MIN INT_MIN
9881 #endif
9882
9883 #include <stdio.h>
9884 #include <stdlib.h>
9885 #include <assert.h>
9886
9887 #include \"guestfs.h\"
9888
9889 #ifndef HAVE_PYCAPSULE_NEW
9890 typedef struct {
9891   PyObject_HEAD
9892   guestfs_h *g;
9893 } Pyguestfs_Object;
9894 #endif
9895
9896 static guestfs_h *
9897 get_handle (PyObject *obj)
9898 {
9899   assert (obj);
9900   assert (obj != Py_None);
9901 #ifndef HAVE_PYCAPSULE_NEW
9902   return ((Pyguestfs_Object *) obj)->g;
9903 #else
9904   return (guestfs_h*) PyCapsule_GetPointer(obj, \"guestfs_h\");
9905 #endif
9906 }
9907
9908 static PyObject *
9909 put_handle (guestfs_h *g)
9910 {
9911   assert (g);
9912 #ifndef HAVE_PYCAPSULE_NEW
9913   return
9914     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
9915 #else
9916   return PyCapsule_New ((void *) g, \"guestfs_h\", NULL);
9917 #endif
9918 }
9919
9920 /* This list should be freed (but not the strings) after use. */
9921 static char **
9922 get_string_list (PyObject *obj)
9923 {
9924   size_t i, len;
9925   char **r;
9926
9927   assert (obj);
9928
9929   if (!PyList_Check (obj)) {
9930     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
9931     return NULL;
9932   }
9933
9934   Py_ssize_t slen = PyList_Size (obj);
9935   if (slen == -1) {
9936     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: PyList_Size failure\");
9937     return NULL;
9938   }
9939   len = (size_t) slen;
9940   r = malloc (sizeof (char *) * (len+1));
9941   if (r == NULL) {
9942     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
9943     return NULL;
9944   }
9945
9946   for (i = 0; i < len; ++i)
9947     r[i] = PyString_AsString (PyList_GetItem (obj, i));
9948   r[len] = NULL;
9949
9950   return r;
9951 }
9952
9953 static PyObject *
9954 put_string_list (char * const * const argv)
9955 {
9956   PyObject *list;
9957   int argc, i;
9958
9959   for (argc = 0; argv[argc] != NULL; ++argc)
9960     ;
9961
9962   list = PyList_New (argc);
9963   for (i = 0; i < argc; ++i)
9964     PyList_SetItem (list, i, PyString_FromString (argv[i]));
9965
9966   return list;
9967 }
9968
9969 static PyObject *
9970 put_table (char * const * const argv)
9971 {
9972   PyObject *list, *item;
9973   int argc, i;
9974
9975   for (argc = 0; argv[argc] != NULL; ++argc)
9976     ;
9977
9978   list = PyList_New (argc >> 1);
9979   for (i = 0; i < argc; i += 2) {
9980     item = PyTuple_New (2);
9981     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
9982     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
9983     PyList_SetItem (list, i >> 1, item);
9984   }
9985
9986   return list;
9987 }
9988
9989 static void
9990 free_strings (char **argv)
9991 {
9992   int argc;
9993
9994   for (argc = 0; argv[argc] != NULL; ++argc)
9995     free (argv[argc]);
9996   free (argv);
9997 }
9998
9999 static PyObject *
10000 py_guestfs_create (PyObject *self, PyObject *args)
10001 {
10002   guestfs_h *g;
10003
10004   g = guestfs_create ();
10005   if (g == NULL) {
10006     PyErr_SetString (PyExc_RuntimeError,
10007                      \"guestfs.create: failed to allocate handle\");
10008     return NULL;
10009   }
10010   guestfs_set_error_handler (g, NULL, NULL);
10011   /* This can return NULL, but in that case put_handle will have
10012    * set the Python error string.
10013    */
10014   return put_handle (g);
10015 }
10016
10017 static PyObject *
10018 py_guestfs_close (PyObject *self, PyObject *args)
10019 {
10020   PyObject *py_g;
10021   guestfs_h *g;
10022
10023   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
10024     return NULL;
10025   g = get_handle (py_g);
10026
10027   guestfs_close (g);
10028
10029   Py_INCREF (Py_None);
10030   return Py_None;
10031 }
10032
10033 ";
10034
10035   let emit_put_list_function typ =
10036     pr "static PyObject *\n";
10037     pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
10038     pr "{\n";
10039     pr "  PyObject *list;\n";
10040     pr "  size_t i;\n";
10041     pr "\n";
10042     pr "  list = PyList_New (%ss->len);\n" typ;
10043     pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
10044     pr "    PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
10045     pr "  return list;\n";
10046     pr "};\n";
10047     pr "\n"
10048   in
10049
10050   (* Structures, turned into Python dictionaries. *)
10051   List.iter (
10052     fun (typ, cols) ->
10053       pr "static PyObject *\n";
10054       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
10055       pr "{\n";
10056       pr "  PyObject *dict;\n";
10057       pr "\n";
10058       pr "  dict = PyDict_New ();\n";
10059       List.iter (
10060         function
10061         | name, FString ->
10062             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10063             pr "                        PyString_FromString (%s->%s));\n"
10064               typ name
10065         | name, FBuffer ->
10066             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10067             pr "                        PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
10068               typ name typ name
10069         | name, FUUID ->
10070             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10071             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
10072               typ name
10073         | name, (FBytes|FUInt64) ->
10074             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10075             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
10076               typ name
10077         | name, FInt64 ->
10078             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10079             pr "                        PyLong_FromLongLong (%s->%s));\n"
10080               typ name
10081         | name, FUInt32 ->
10082             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10083             pr "                        PyLong_FromUnsignedLong (%s->%s));\n"
10084               typ name
10085         | name, FInt32 ->
10086             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10087             pr "                        PyLong_FromLong (%s->%s));\n"
10088               typ name
10089         | name, FOptPercent ->
10090             pr "  if (%s->%s >= 0)\n" typ name;
10091             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
10092             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
10093               typ name;
10094             pr "  else {\n";
10095             pr "    Py_INCREF (Py_None);\n";
10096             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
10097             pr "  }\n"
10098         | name, FChar ->
10099             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
10100             pr "                        PyString_FromStringAndSize (&dirent->%s, 1));\n" name
10101       ) cols;
10102       pr "  return dict;\n";
10103       pr "};\n";
10104       pr "\n";
10105
10106   ) structs;
10107
10108   (* Emit a put_TYPE_list function definition only if that function is used. *)
10109   List.iter (
10110     function
10111     | typ, (RStructListOnly | RStructAndList) ->
10112         (* generate the function for typ *)
10113         emit_put_list_function typ
10114     | typ, _ -> () (* empty *)
10115   ) (rstructs_used_by all_functions);
10116
10117   (* Python wrapper functions. *)
10118   List.iter (
10119     fun (name, style, _, _, _, _, _) ->
10120       pr "static PyObject *\n";
10121       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
10122       pr "{\n";
10123
10124       pr "  PyObject *py_g;\n";
10125       pr "  guestfs_h *g;\n";
10126       pr "  PyObject *py_r;\n";
10127
10128       let error_code =
10129         match fst style with
10130         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10131         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10132         | RConstString _ | RConstOptString _ ->
10133             pr "  const char *r;\n"; "NULL"
10134         | RString _ -> pr "  char *r;\n"; "NULL"
10135         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10136         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10137         | RStructList (_, typ) ->
10138             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10139         | RBufferOut _ ->
10140             pr "  char *r;\n";
10141             pr "  size_t size;\n";
10142             "NULL" in
10143
10144       List.iter (
10145         function
10146         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10147         | FileIn n | FileOut n ->
10148             pr "  const char *%s;\n" n
10149         | OptString n -> pr "  const char *%s;\n" n
10150         | BufferIn n ->
10151             pr "  const char *%s;\n" n;
10152             pr "  Py_ssize_t %s_size;\n" n
10153         | StringList n | DeviceList n ->
10154             pr "  PyObject *py_%s;\n" n;
10155             pr "  char **%s;\n" n
10156         | Bool n -> pr "  int %s;\n" n
10157         | Int n -> pr "  int %s;\n" n
10158         | Int64 n -> pr "  long long %s;\n" n
10159       ) (snd style);
10160
10161       pr "\n";
10162
10163       (* Convert the parameters. *)
10164       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
10165       List.iter (
10166         function
10167         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10168         | FileIn _ | FileOut _ -> pr "s"
10169         | OptString _ -> pr "z"
10170         | StringList _ | DeviceList _ -> pr "O"
10171         | Bool _ -> pr "i" (* XXX Python has booleans? *)
10172         | Int _ -> pr "i"
10173         | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
10174                              * emulate C's int/long/long long in Python?
10175                              *)
10176         | BufferIn _ -> pr "s#"
10177       ) (snd style);
10178       pr ":guestfs_%s\",\n" name;
10179       pr "                         &py_g";
10180       List.iter (
10181         function
10182         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10183         | FileIn n | FileOut n -> pr ", &%s" n
10184         | OptString n -> pr ", &%s" n
10185         | StringList n | DeviceList n -> pr ", &py_%s" n
10186         | Bool n -> pr ", &%s" n
10187         | Int n -> pr ", &%s" n
10188         | Int64 n -> pr ", &%s" n
10189         | BufferIn n -> pr ", &%s, &%s_size" n n
10190       ) (snd style);
10191
10192       pr "))\n";
10193       pr "    return NULL;\n";
10194
10195       pr "  g = get_handle (py_g);\n";
10196       List.iter (
10197         function
10198         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10199         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10200         | BufferIn _ -> ()
10201         | StringList n | DeviceList n ->
10202             pr "  %s = get_string_list (py_%s);\n" n n;
10203             pr "  if (!%s) return NULL;\n" n
10204       ) (snd style);
10205
10206       pr "\n";
10207
10208       pr "  r = guestfs_%s " name;
10209       generate_c_call_args ~handle:"g" style;
10210       pr ";\n";
10211
10212       List.iter (
10213         function
10214         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10215         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10216         | BufferIn _ -> ()
10217         | StringList n | DeviceList n ->
10218             pr "  free (%s);\n" n
10219       ) (snd style);
10220
10221       pr "  if (r == %s) {\n" error_code;
10222       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
10223       pr "    return NULL;\n";
10224       pr "  }\n";
10225       pr "\n";
10226
10227       (match fst style with
10228        | RErr ->
10229            pr "  Py_INCREF (Py_None);\n";
10230            pr "  py_r = Py_None;\n"
10231        | RInt _
10232        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
10233        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
10234        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
10235        | RConstOptString _ ->
10236            pr "  if (r)\n";
10237            pr "    py_r = PyString_FromString (r);\n";
10238            pr "  else {\n";
10239            pr "    Py_INCREF (Py_None);\n";
10240            pr "    py_r = Py_None;\n";
10241            pr "  }\n"
10242        | RString _ ->
10243            pr "  py_r = PyString_FromString (r);\n";
10244            pr "  free (r);\n"
10245        | RStringList _ ->
10246            pr "  py_r = put_string_list (r);\n";
10247            pr "  free_strings (r);\n"
10248        | RStruct (_, typ) ->
10249            pr "  py_r = put_%s (r);\n" typ;
10250            pr "  guestfs_free_%s (r);\n" typ
10251        | RStructList (_, typ) ->
10252            pr "  py_r = put_%s_list (r);\n" typ;
10253            pr "  guestfs_free_%s_list (r);\n" typ
10254        | RHashtable n ->
10255            pr "  py_r = put_table (r);\n";
10256            pr "  free_strings (r);\n"
10257        | RBufferOut _ ->
10258            pr "  py_r = PyString_FromStringAndSize (r, size);\n";
10259            pr "  free (r);\n"
10260       );
10261
10262       pr "  return py_r;\n";
10263       pr "}\n";
10264       pr "\n"
10265   ) all_functions;
10266
10267   (* Table of functions. *)
10268   pr "static PyMethodDef methods[] = {\n";
10269   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
10270   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
10271   List.iter (
10272     fun (name, _, _, _, _, _, _) ->
10273       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
10274         name name
10275   ) all_functions;
10276   pr "  { NULL, NULL, 0, NULL }\n";
10277   pr "};\n";
10278   pr "\n";
10279
10280   (* Init function. *)
10281   pr "\
10282 void
10283 initlibguestfsmod (void)
10284 {
10285   static int initialized = 0;
10286
10287   if (initialized) return;
10288   Py_InitModule ((char *) \"libguestfsmod\", methods);
10289   initialized = 1;
10290 }
10291 "
10292
10293 (* Generate Python module. *)
10294 and generate_python_py () =
10295   generate_header HashStyle LGPLv2plus;
10296
10297   pr "\
10298 u\"\"\"Python bindings for libguestfs
10299
10300 import guestfs
10301 g = guestfs.GuestFS ()
10302 g.add_drive (\"guest.img\")
10303 g.launch ()
10304 parts = g.list_partitions ()
10305
10306 The guestfs module provides a Python binding to the libguestfs API
10307 for examining and modifying virtual machine disk images.
10308
10309 Amongst the things this is good for: making batch configuration
10310 changes to guests, getting disk used/free statistics (see also:
10311 virt-df), migrating between virtualization systems (see also:
10312 virt-p2v), performing partial backups, performing partial guest
10313 clones, cloning guests and changing registry/UUID/hostname info, and
10314 much else besides.
10315
10316 Libguestfs uses Linux kernel and qemu code, and can access any type of
10317 guest filesystem that Linux and qemu can, including but not limited
10318 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
10319 schemes, qcow, qcow2, vmdk.
10320
10321 Libguestfs provides ways to enumerate guest storage (eg. partitions,
10322 LVs, what filesystem is in each LV, etc.).  It can also run commands
10323 in the context of the guest.  Also you can access filesystems over
10324 FUSE.
10325
10326 Errors which happen while using the API are turned into Python
10327 RuntimeError exceptions.
10328
10329 To create a guestfs handle you usually have to perform the following
10330 sequence of calls:
10331
10332 # Create the handle, call add_drive at least once, and possibly
10333 # several times if the guest has multiple block devices:
10334 g = guestfs.GuestFS ()
10335 g.add_drive (\"guest.img\")
10336
10337 # Launch the qemu subprocess and wait for it to become ready:
10338 g.launch ()
10339
10340 # Now you can issue commands, for example:
10341 logvols = g.lvs ()
10342
10343 \"\"\"
10344
10345 import libguestfsmod
10346
10347 class GuestFS:
10348     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
10349
10350     def __init__ (self):
10351         \"\"\"Create a new libguestfs handle.\"\"\"
10352         self._o = libguestfsmod.create ()
10353
10354     def __del__ (self):
10355         libguestfsmod.close (self._o)
10356
10357 ";
10358
10359   List.iter (
10360     fun (name, style, _, flags, _, _, longdesc) ->
10361       pr "    def %s " name;
10362       generate_py_call_args ~handle:"self" (snd style);
10363       pr ":\n";
10364
10365       if not (List.mem NotInDocs flags) then (
10366         let doc = replace_str longdesc "C<guestfs_" "C<g." in
10367         let doc =
10368           match fst style with
10369           | RErr | RInt _ | RInt64 _ | RBool _
10370           | RConstOptString _ | RConstString _
10371           | RString _ | RBufferOut _ -> doc
10372           | RStringList _ ->
10373               doc ^ "\n\nThis function returns a list of strings."
10374           | RStruct (_, typ) ->
10375               doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
10376           | RStructList (_, typ) ->
10377               doc ^ sprintf "\n\nThis function returns a list of %ss.  Each %s is represented as a dictionary." typ typ
10378           | RHashtable _ ->
10379               doc ^ "\n\nThis function returns a dictionary." in
10380         let doc =
10381           if List.mem ProtocolLimitWarning flags then
10382             doc ^ "\n\n" ^ protocol_limit_warning
10383           else doc in
10384         let doc =
10385           if List.mem DangerWillRobinson flags then
10386             doc ^ "\n\n" ^ danger_will_robinson
10387           else doc in
10388         let doc =
10389           match deprecation_notice flags with
10390           | None -> doc
10391           | Some txt -> doc ^ "\n\n" ^ txt in
10392         let doc = pod2text ~width:60 name doc in
10393         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
10394         let doc = String.concat "\n        " doc in
10395         pr "        u\"\"\"%s\"\"\"\n" doc;
10396       );
10397       pr "        return libguestfsmod.%s " name;
10398       generate_py_call_args ~handle:"self._o" (snd style);
10399       pr "\n";
10400       pr "\n";
10401   ) all_functions
10402
10403 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
10404 and generate_py_call_args ~handle args =
10405   pr "(%s" handle;
10406   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10407   pr ")"
10408
10409 (* Useful if you need the longdesc POD text as plain text.  Returns a
10410  * list of lines.
10411  *
10412  * Because this is very slow (the slowest part of autogeneration),
10413  * we memoize the results.
10414  *)
10415 and pod2text ~width name longdesc =
10416   let key = width, name, longdesc in
10417   try Hashtbl.find pod2text_memo key
10418   with Not_found ->
10419     let filename, chan = Filename.open_temp_file "gen" ".tmp" in
10420     fprintf chan "=head1 %s\n\n%s\n" name longdesc;
10421     close_out chan;
10422     let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
10423     let chan = open_process_in cmd in
10424     let lines = ref [] in
10425     let rec loop i =
10426       let line = input_line chan in
10427       if i = 1 then             (* discard the first line of output *)
10428         loop (i+1)
10429       else (
10430         let line = triml line in
10431         lines := line :: !lines;
10432         loop (i+1)
10433       ) in
10434     let lines = try loop 1 with End_of_file -> List.rev !lines in
10435     unlink filename;
10436     (match close_process_in chan with
10437      | WEXITED 0 -> ()
10438      | WEXITED i ->
10439          failwithf "pod2text: process exited with non-zero status (%d)" i
10440      | WSIGNALED i | WSTOPPED i ->
10441          failwithf "pod2text: process signalled or stopped by signal %d" i
10442     );
10443     Hashtbl.add pod2text_memo key lines;
10444     pod2text_memo_updated ();
10445     lines
10446
10447 (* Generate ruby bindings. *)
10448 and generate_ruby_c () =
10449   generate_header CStyle LGPLv2plus;
10450
10451   pr "\
10452 #include <stdio.h>
10453 #include <stdlib.h>
10454
10455 #include <ruby.h>
10456
10457 #include \"guestfs.h\"
10458
10459 #include \"extconf.h\"
10460
10461 /* For Ruby < 1.9 */
10462 #ifndef RARRAY_LEN
10463 #define RARRAY_LEN(r) (RARRAY((r))->len)
10464 #endif
10465
10466 static VALUE m_guestfs;                 /* guestfs module */
10467 static VALUE c_guestfs;                 /* guestfs_h handle */
10468 static VALUE e_Error;                   /* used for all errors */
10469
10470 static void ruby_guestfs_free (void *p)
10471 {
10472   if (!p) return;
10473   guestfs_close ((guestfs_h *) p);
10474 }
10475
10476 static VALUE ruby_guestfs_create (VALUE m)
10477 {
10478   guestfs_h *g;
10479
10480   g = guestfs_create ();
10481   if (!g)
10482     rb_raise (e_Error, \"failed to create guestfs handle\");
10483
10484   /* Don't print error messages to stderr by default. */
10485   guestfs_set_error_handler (g, NULL, NULL);
10486
10487   /* Wrap it, and make sure the close function is called when the
10488    * handle goes away.
10489    */
10490   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
10491 }
10492
10493 static VALUE ruby_guestfs_close (VALUE gv)
10494 {
10495   guestfs_h *g;
10496   Data_Get_Struct (gv, guestfs_h, g);
10497
10498   ruby_guestfs_free (g);
10499   DATA_PTR (gv) = NULL;
10500
10501   return Qnil;
10502 }
10503
10504 ";
10505
10506   List.iter (
10507     fun (name, style, _, _, _, _, _) ->
10508       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
10509       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
10510       pr ")\n";
10511       pr "{\n";
10512       pr "  guestfs_h *g;\n";
10513       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
10514       pr "  if (!g)\n";
10515       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
10516         name;
10517       pr "\n";
10518
10519       List.iter (
10520         function
10521         | Pathname n | Device n | Dev_or_Path n | String n | Key n
10522         | FileIn n | FileOut n ->
10523             pr "  Check_Type (%sv, T_STRING);\n" n;
10524             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
10525             pr "  if (!%s)\n" n;
10526             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10527             pr "              \"%s\", \"%s\");\n" n name
10528         | BufferIn n ->
10529             pr "  Check_Type (%sv, T_STRING);\n" n;
10530             pr "  const char *%s = RSTRING (%sv)->ptr;\n" n n;
10531             pr "  if (!%s)\n" n;
10532             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
10533             pr "              \"%s\", \"%s\");\n" n name;
10534             pr "  size_t %s_size = RSTRING (%sv)->len;\n" n n
10535         | OptString n ->
10536             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
10537         | StringList n | DeviceList n ->
10538             pr "  char **%s;\n" n;
10539             pr "  Check_Type (%sv, T_ARRAY);\n" n;
10540             pr "  {\n";
10541             pr "    size_t i, len;\n";
10542             pr "    len = RARRAY_LEN (%sv);\n" n;
10543             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
10544               n;
10545             pr "    for (i = 0; i < len; ++i) {\n";
10546             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
10547             pr "      %s[i] = StringValueCStr (v);\n" n;
10548             pr "    }\n";
10549             pr "    %s[len] = NULL;\n" n;
10550             pr "  }\n";
10551         | Bool n ->
10552             pr "  int %s = RTEST (%sv);\n" n n
10553         | Int n ->
10554             pr "  int %s = NUM2INT (%sv);\n" n n
10555         | Int64 n ->
10556             pr "  long long %s = NUM2LL (%sv);\n" n n
10557       ) (snd style);
10558       pr "\n";
10559
10560       let error_code =
10561         match fst style with
10562         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
10563         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
10564         | RConstString _ | RConstOptString _ ->
10565             pr "  const char *r;\n"; "NULL"
10566         | RString _ -> pr "  char *r;\n"; "NULL"
10567         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
10568         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
10569         | RStructList (_, typ) ->
10570             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
10571         | RBufferOut _ ->
10572             pr "  char *r;\n";
10573             pr "  size_t size;\n";
10574             "NULL" in
10575       pr "\n";
10576
10577       pr "  r = guestfs_%s " name;
10578       generate_c_call_args ~handle:"g" style;
10579       pr ";\n";
10580
10581       List.iter (
10582         function
10583         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
10584         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
10585         | BufferIn _ -> ()
10586         | StringList n | DeviceList n ->
10587             pr "  free (%s);\n" n
10588       ) (snd style);
10589
10590       pr "  if (r == %s)\n" error_code;
10591       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
10592       pr "\n";
10593
10594       (match fst style with
10595        | RErr ->
10596            pr "  return Qnil;\n"
10597        | RInt _ | RBool _ ->
10598            pr "  return INT2NUM (r);\n"
10599        | RInt64 _ ->
10600            pr "  return ULL2NUM (r);\n"
10601        | RConstString _ ->
10602            pr "  return rb_str_new2 (r);\n";
10603        | RConstOptString _ ->
10604            pr "  if (r)\n";
10605            pr "    return rb_str_new2 (r);\n";
10606            pr "  else\n";
10607            pr "    return Qnil;\n";
10608        | RString _ ->
10609            pr "  VALUE rv = rb_str_new2 (r);\n";
10610            pr "  free (r);\n";
10611            pr "  return rv;\n";
10612        | RStringList _ ->
10613            pr "  size_t i, len = 0;\n";
10614            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
10615            pr "  VALUE rv = rb_ary_new2 (len);\n";
10616            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
10617            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
10618            pr "    free (r[i]);\n";
10619            pr "  }\n";
10620            pr "  free (r);\n";
10621            pr "  return rv;\n"
10622        | RStruct (_, typ) ->
10623            let cols = cols_of_struct typ in
10624            generate_ruby_struct_code typ cols
10625        | RStructList (_, typ) ->
10626            let cols = cols_of_struct typ in
10627            generate_ruby_struct_list_code typ cols
10628        | RHashtable _ ->
10629            pr "  VALUE rv = rb_hash_new ();\n";
10630            pr "  size_t i;\n";
10631            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
10632            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
10633            pr "    free (r[i]);\n";
10634            pr "    free (r[i+1]);\n";
10635            pr "  }\n";
10636            pr "  free (r);\n";
10637            pr "  return rv;\n"
10638        | RBufferOut _ ->
10639            pr "  VALUE rv = rb_str_new (r, size);\n";
10640            pr "  free (r);\n";
10641            pr "  return rv;\n";
10642       );
10643
10644       pr "}\n";
10645       pr "\n"
10646   ) all_functions;
10647
10648   pr "\
10649 /* Initialize the module. */
10650 void Init__guestfs ()
10651 {
10652   m_guestfs = rb_define_module (\"Guestfs\");
10653   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
10654   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
10655
10656   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
10657   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
10658
10659 ";
10660   (* Define the rest of the methods. *)
10661   List.iter (
10662     fun (name, style, _, _, _, _, _) ->
10663       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
10664       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
10665   ) all_functions;
10666
10667   pr "}\n"
10668
10669 (* Ruby code to return a struct. *)
10670 and generate_ruby_struct_code typ cols =
10671   pr "  VALUE rv = rb_hash_new ();\n";
10672   List.iter (
10673     function
10674     | name, FString ->
10675         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
10676     | name, FBuffer ->
10677         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
10678     | name, FUUID ->
10679         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
10680     | name, (FBytes|FUInt64) ->
10681         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10682     | name, FInt64 ->
10683         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
10684     | name, FUInt32 ->
10685         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
10686     | name, FInt32 ->
10687         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
10688     | name, FOptPercent ->
10689         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
10690     | name, FChar -> (* XXX wrong? *)
10691         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
10692   ) cols;
10693   pr "  guestfs_free_%s (r);\n" typ;
10694   pr "  return rv;\n"
10695
10696 (* Ruby code to return a struct list. *)
10697 and generate_ruby_struct_list_code typ cols =
10698   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
10699   pr "  size_t i;\n";
10700   pr "  for (i = 0; i < r->len; ++i) {\n";
10701   pr "    VALUE hv = rb_hash_new ();\n";
10702   List.iter (
10703     function
10704     | name, FString ->
10705         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
10706     | name, FBuffer ->
10707         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
10708     | name, FUUID ->
10709         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
10710     | name, (FBytes|FUInt64) ->
10711         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10712     | name, FInt64 ->
10713         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
10714     | name, FUInt32 ->
10715         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
10716     | name, FInt32 ->
10717         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
10718     | name, FOptPercent ->
10719         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
10720     | name, FChar -> (* XXX wrong? *)
10721         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
10722   ) cols;
10723   pr "    rb_ary_push (rv, hv);\n";
10724   pr "  }\n";
10725   pr "  guestfs_free_%s_list (r);\n" typ;
10726   pr "  return rv;\n"
10727
10728 (* Generate Java bindings GuestFS.java file. *)
10729 and generate_java_java () =
10730   generate_header CStyle LGPLv2plus;
10731
10732   pr "\
10733 package com.redhat.et.libguestfs;
10734
10735 import java.util.HashMap;
10736 import com.redhat.et.libguestfs.LibGuestFSException;
10737 import com.redhat.et.libguestfs.PV;
10738 import com.redhat.et.libguestfs.VG;
10739 import com.redhat.et.libguestfs.LV;
10740 import com.redhat.et.libguestfs.Stat;
10741 import com.redhat.et.libguestfs.StatVFS;
10742 import com.redhat.et.libguestfs.IntBool;
10743 import com.redhat.et.libguestfs.Dirent;
10744
10745 /**
10746  * The GuestFS object is a libguestfs handle.
10747  *
10748  * @author rjones
10749  */
10750 public class GuestFS {
10751   // Load the native code.
10752   static {
10753     System.loadLibrary (\"guestfs_jni\");
10754   }
10755
10756   /**
10757    * The native guestfs_h pointer.
10758    */
10759   long g;
10760
10761   /**
10762    * Create a libguestfs handle.
10763    *
10764    * @throws LibGuestFSException
10765    */
10766   public GuestFS () throws LibGuestFSException
10767   {
10768     g = _create ();
10769   }
10770   private native long _create () throws LibGuestFSException;
10771
10772   /**
10773    * Close a libguestfs handle.
10774    *
10775    * You can also leave handles to be collected by the garbage
10776    * collector, but this method ensures that the resources used
10777    * by the handle are freed up immediately.  If you call any
10778    * other methods after closing the handle, you will get an
10779    * exception.
10780    *
10781    * @throws LibGuestFSException
10782    */
10783   public void close () throws LibGuestFSException
10784   {
10785     if (g != 0)
10786       _close (g);
10787     g = 0;
10788   }
10789   private native void _close (long g) throws LibGuestFSException;
10790
10791   public void finalize () throws LibGuestFSException
10792   {
10793     close ();
10794   }
10795
10796 ";
10797
10798   List.iter (
10799     fun (name, style, _, flags, _, shortdesc, longdesc) ->
10800       if not (List.mem NotInDocs flags); then (
10801         let doc = replace_str longdesc "C<guestfs_" "C<g." in
10802         let doc =
10803           if List.mem ProtocolLimitWarning flags then
10804             doc ^ "\n\n" ^ protocol_limit_warning
10805           else doc in
10806         let doc =
10807           if List.mem DangerWillRobinson flags then
10808             doc ^ "\n\n" ^ danger_will_robinson
10809           else doc in
10810         let doc =
10811           match deprecation_notice flags with
10812           | None -> doc
10813           | Some txt -> doc ^ "\n\n" ^ txt in
10814         let doc = pod2text ~width:60 name doc in
10815         let doc = List.map (            (* RHBZ#501883 *)
10816           function
10817           | "" -> "<p>"
10818           | nonempty -> nonempty
10819         ) doc in
10820         let doc = String.concat "\n   * " doc in
10821
10822         pr "  /**\n";
10823         pr "   * %s\n" shortdesc;
10824         pr "   * <p>\n";
10825         pr "   * %s\n" doc;
10826         pr "   * @throws LibGuestFSException\n";
10827         pr "   */\n";
10828         pr "  ";
10829       );
10830       generate_java_prototype ~public:true ~semicolon:false name style;
10831       pr "\n";
10832       pr "  {\n";
10833       pr "    if (g == 0)\n";
10834       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
10835         name;
10836       pr "    ";
10837       if fst style <> RErr then pr "return ";
10838       pr "_%s " name;
10839       generate_java_call_args ~handle:"g" (snd style);
10840       pr ";\n";
10841       pr "  }\n";
10842       pr "  ";
10843       generate_java_prototype ~privat:true ~native:true name style;
10844       pr "\n";
10845       pr "\n";
10846   ) all_functions;
10847
10848   pr "}\n"
10849
10850 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
10851 and generate_java_call_args ~handle args =
10852   pr "(%s" handle;
10853   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
10854   pr ")"
10855
10856 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
10857     ?(semicolon=true) name style =
10858   if privat then pr "private ";
10859   if public then pr "public ";
10860   if native then pr "native ";
10861
10862   (* return type *)
10863   (match fst style with
10864    | RErr -> pr "void ";
10865    | RInt _ -> pr "int ";
10866    | RInt64 _ -> pr "long ";
10867    | RBool _ -> pr "boolean ";
10868    | RConstString _ | RConstOptString _ | RString _
10869    | RBufferOut _ -> pr "String ";
10870    | RStringList _ -> pr "String[] ";
10871    | RStruct (_, typ) ->
10872        let name = java_name_of_struct typ in
10873        pr "%s " name;
10874    | RStructList (_, typ) ->
10875        let name = java_name_of_struct typ in
10876        pr "%s[] " name;
10877    | RHashtable _ -> pr "HashMap<String,String> ";
10878   );
10879
10880   if native then pr "_%s " name else pr "%s " name;
10881   pr "(";
10882   let needs_comma = ref false in
10883   if native then (
10884     pr "long g";
10885     needs_comma := true
10886   );
10887
10888   (* args *)
10889   List.iter (
10890     fun arg ->
10891       if !needs_comma then pr ", ";
10892       needs_comma := true;
10893
10894       match arg with
10895       | Pathname n
10896       | Device n | Dev_or_Path n
10897       | String n
10898       | OptString n
10899       | FileIn n
10900       | FileOut n
10901       | Key n ->
10902           pr "String %s" n
10903       | BufferIn n ->
10904           pr "byte[] %s" n
10905       | StringList n | DeviceList n ->
10906           pr "String[] %s" n
10907       | Bool n ->
10908           pr "boolean %s" n
10909       | Int n ->
10910           pr "int %s" n
10911       | Int64 n ->
10912           pr "long %s" n
10913   ) (snd style);
10914
10915   pr ")\n";
10916   pr "    throws LibGuestFSException";
10917   if semicolon then pr ";"
10918
10919 and generate_java_struct jtyp cols () =
10920   generate_header CStyle LGPLv2plus;
10921
10922   pr "\
10923 package com.redhat.et.libguestfs;
10924
10925 /**
10926  * Libguestfs %s structure.
10927  *
10928  * @author rjones
10929  * @see GuestFS
10930  */
10931 public class %s {
10932 " jtyp jtyp;
10933
10934   List.iter (
10935     function
10936     | name, FString
10937     | name, FUUID
10938     | name, FBuffer -> pr "  public String %s;\n" name
10939     | name, (FBytes|FUInt64|FInt64) -> pr "  public long %s;\n" name
10940     | name, (FUInt32|FInt32) -> pr "  public int %s;\n" name
10941     | name, FChar -> pr "  public char %s;\n" name
10942     | name, FOptPercent ->
10943         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
10944         pr "  public float %s;\n" name
10945   ) cols;
10946
10947   pr "}\n"
10948
10949 and generate_java_c () =
10950   generate_header CStyle LGPLv2plus;
10951
10952   pr "\
10953 #include <stdio.h>
10954 #include <stdlib.h>
10955 #include <string.h>
10956
10957 #include \"com_redhat_et_libguestfs_GuestFS.h\"
10958 #include \"guestfs.h\"
10959
10960 /* Note that this function returns.  The exception is not thrown
10961  * until after the wrapper function returns.
10962  */
10963 static void
10964 throw_exception (JNIEnv *env, const char *msg)
10965 {
10966   jclass cl;
10967   cl = (*env)->FindClass (env,
10968                           \"com/redhat/et/libguestfs/LibGuestFSException\");
10969   (*env)->ThrowNew (env, cl, msg);
10970 }
10971
10972 JNIEXPORT jlong JNICALL
10973 Java_com_redhat_et_libguestfs_GuestFS__1create
10974   (JNIEnv *env, jobject obj)
10975 {
10976   guestfs_h *g;
10977
10978   g = guestfs_create ();
10979   if (g == NULL) {
10980     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
10981     return 0;
10982   }
10983   guestfs_set_error_handler (g, NULL, NULL);
10984   return (jlong) (long) g;
10985 }
10986
10987 JNIEXPORT void JNICALL
10988 Java_com_redhat_et_libguestfs_GuestFS__1close
10989   (JNIEnv *env, jobject obj, jlong jg)
10990 {
10991   guestfs_h *g = (guestfs_h *) (long) jg;
10992   guestfs_close (g);
10993 }
10994
10995 ";
10996
10997   List.iter (
10998     fun (name, style, _, _, _, _, _) ->
10999       pr "JNIEXPORT ";
11000       (match fst style with
11001        | RErr -> pr "void ";
11002        | RInt _ -> pr "jint ";
11003        | RInt64 _ -> pr "jlong ";
11004        | RBool _ -> pr "jboolean ";
11005        | RConstString _ | RConstOptString _ | RString _
11006        | RBufferOut _ -> pr "jstring ";
11007        | RStruct _ | RHashtable _ ->
11008            pr "jobject ";
11009        | RStringList _ | RStructList _ ->
11010            pr "jobjectArray ";
11011       );
11012       pr "JNICALL\n";
11013       pr "Java_com_redhat_et_libguestfs_GuestFS_";
11014       pr "%s" (replace_str ("_" ^ name) "_" "_1");
11015       pr "\n";
11016       pr "  (JNIEnv *env, jobject obj, jlong jg";
11017       List.iter (
11018         function
11019         | Pathname n
11020         | Device n | Dev_or_Path n
11021         | String n
11022         | OptString n
11023         | FileIn n
11024         | FileOut n
11025         | Key n ->
11026             pr ", jstring j%s" n
11027         | BufferIn n ->
11028             pr ", jbyteArray j%s" n
11029         | StringList n | DeviceList n ->
11030             pr ", jobjectArray j%s" n
11031         | Bool n ->
11032             pr ", jboolean j%s" n
11033         | Int n ->
11034             pr ", jint j%s" n
11035         | Int64 n ->
11036             pr ", jlong j%s" n
11037       ) (snd style);
11038       pr ")\n";
11039       pr "{\n";
11040       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
11041       let error_code, no_ret =
11042         match fst style with
11043         | RErr -> pr "  int r;\n"; "-1", ""
11044         | RBool _
11045         | RInt _ -> pr "  int r;\n"; "-1", "0"
11046         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
11047         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11048         | RConstOptString _ -> pr "  const char *r;\n"; "NULL", "NULL"
11049         | RString _ ->
11050             pr "  jstring jr;\n";
11051             pr "  char *r;\n"; "NULL", "NULL"
11052         | RStringList _ ->
11053             pr "  jobjectArray jr;\n";
11054             pr "  int r_len;\n";
11055             pr "  jclass cl;\n";
11056             pr "  jstring jstr;\n";
11057             pr "  char **r;\n"; "NULL", "NULL"
11058         | RStruct (_, typ) ->
11059             pr "  jobject jr;\n";
11060             pr "  jclass cl;\n";
11061             pr "  jfieldID fl;\n";
11062             pr "  struct guestfs_%s *r;\n" typ; "NULL", "NULL"
11063         | RStructList (_, typ) ->
11064             pr "  jobjectArray jr;\n";
11065             pr "  jclass cl;\n";
11066             pr "  jfieldID fl;\n";
11067             pr "  jobject jfl;\n";
11068             pr "  struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
11069         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL"
11070         | RBufferOut _ ->
11071             pr "  jstring jr;\n";
11072             pr "  char *r;\n";
11073             pr "  size_t size;\n";
11074             "NULL", "NULL" in
11075       List.iter (
11076         function
11077         | Pathname n
11078         | Device n | Dev_or_Path n
11079         | String n
11080         | OptString n
11081         | FileIn n
11082         | FileOut n
11083         | Key n ->
11084             pr "  const char *%s;\n" n
11085         | BufferIn n ->
11086             pr "  jbyte *%s;\n" n;
11087             pr "  size_t %s_size;\n" n
11088         | StringList n | DeviceList n ->
11089             pr "  int %s_len;\n" n;
11090             pr "  const char **%s;\n" n
11091         | Bool n
11092         | Int n ->
11093             pr "  int %s;\n" n
11094         | Int64 n ->
11095             pr "  int64_t %s;\n" n
11096       ) (snd style);
11097
11098       let needs_i =
11099         (match fst style with
11100          | RStringList _ | RStructList _ -> true
11101          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
11102          | RConstOptString _
11103          | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
11104           List.exists (function
11105                        | StringList _ -> true
11106                        | DeviceList _ -> true
11107                        | _ -> false) (snd style) in
11108       if needs_i then
11109         pr "  size_t i;\n";
11110
11111       pr "\n";
11112
11113       (* Get the parameters. *)
11114       List.iter (
11115         function
11116         | Pathname n
11117         | Device n | Dev_or_Path n
11118         | String n
11119         | FileIn n
11120         | FileOut n
11121         | Key n ->
11122             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
11123         | OptString n ->
11124             (* This is completely undocumented, but Java null becomes
11125              * a NULL parameter.
11126              *)
11127             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
11128         | BufferIn n ->
11129             pr "  %s = (*env)->GetByteArrayElements (env, j%s, NULL);\n" n n;
11130             pr "  %s_size = (*env)->GetArrayLength (env, j%s);\n" n n
11131         | StringList n | DeviceList n ->
11132             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
11133             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
11134             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11135             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11136               n;
11137             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
11138             pr "  }\n";
11139             pr "  %s[%s_len] = NULL;\n" n n;
11140         | Bool n
11141         | Int n
11142         | Int64 n ->
11143             pr "  %s = j%s;\n" n n
11144       ) (snd style);
11145
11146       (* Make the call. *)
11147       pr "  r = guestfs_%s " name;
11148       generate_c_call_args ~handle:"g" style;
11149       pr ";\n";
11150
11151       (* Release the parameters. *)
11152       List.iter (
11153         function
11154         | Pathname n
11155         | Device n | Dev_or_Path n
11156         | String n
11157         | FileIn n
11158         | FileOut n
11159         | Key n ->
11160             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11161         | OptString n ->
11162             pr "  if (j%s)\n" n;
11163             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
11164         | BufferIn n ->
11165             pr "  (*env)->ReleaseByteArrayElements (env, j%s, %s, 0);\n" n n
11166         | StringList n | DeviceList n ->
11167             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
11168             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
11169               n;
11170             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
11171             pr "  }\n";
11172             pr "  free (%s);\n" n
11173         | Bool n
11174         | Int n
11175         | Int64 n -> ()
11176       ) (snd style);
11177
11178       (* Check for errors. *)
11179       pr "  if (r == %s) {\n" error_code;
11180       pr "    throw_exception (env, guestfs_last_error (g));\n";
11181       pr "    return %s;\n" no_ret;
11182       pr "  }\n";
11183
11184       (* Return value. *)
11185       (match fst style with
11186        | RErr -> ()
11187        | RInt _ -> pr "  return (jint) r;\n"
11188        | RBool _ -> pr "  return (jboolean) r;\n"
11189        | RInt64 _ -> pr "  return (jlong) r;\n"
11190        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
11191        | RConstOptString _ ->
11192            pr "  return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
11193        | RString _ ->
11194            pr "  jr = (*env)->NewStringUTF (env, r);\n";
11195            pr "  free (r);\n";
11196            pr "  return jr;\n"
11197        | RStringList _ ->
11198            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
11199            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
11200            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
11201            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
11202            pr "  for (i = 0; i < r_len; ++i) {\n";
11203            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
11204            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
11205            pr "    free (r[i]);\n";
11206            pr "  }\n";
11207            pr "  free (r);\n";
11208            pr "  return jr;\n"
11209        | RStruct (_, typ) ->
11210            let jtyp = java_name_of_struct typ in
11211            let cols = cols_of_struct typ in
11212            generate_java_struct_return typ jtyp cols
11213        | RStructList (_, typ) ->
11214            let jtyp = java_name_of_struct typ in
11215            let cols = cols_of_struct typ in
11216            generate_java_struct_list_return typ jtyp cols
11217        | RHashtable _ ->
11218            (* XXX *)
11219            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
11220            pr "  return NULL;\n"
11221        | RBufferOut _ ->
11222            pr "  jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
11223            pr "  free (r);\n";
11224            pr "  return jr;\n"
11225       );
11226
11227       pr "}\n";
11228       pr "\n"
11229   ) all_functions
11230
11231 and generate_java_struct_return typ jtyp cols =
11232   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11233   pr "  jr = (*env)->AllocObject (env, cl);\n";
11234   List.iter (
11235     function
11236     | name, FString ->
11237         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11238         pr "  (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
11239     | name, FUUID ->
11240         pr "  {\n";
11241         pr "    char s[33];\n";
11242         pr "    memcpy (s, r->%s, 32);\n" name;
11243         pr "    s[32] = 0;\n";
11244         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11245         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11246         pr "  }\n";
11247     | name, FBuffer ->
11248         pr "  {\n";
11249         pr "    int len = r->%s_len;\n" name;
11250         pr "    char s[len+1];\n";
11251         pr "    memcpy (s, r->%s, len);\n" name;
11252         pr "    s[len] = 0;\n";
11253         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11254         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
11255         pr "  }\n";
11256     | name, (FBytes|FUInt64|FInt64) ->
11257         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11258         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11259     | name, (FUInt32|FInt32) ->
11260         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11261         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11262     | name, FOptPercent ->
11263         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11264         pr "  (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
11265     | name, FChar ->
11266         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11267         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
11268   ) cols;
11269   pr "  free (r);\n";
11270   pr "  return jr;\n"
11271
11272 and generate_java_struct_list_return typ jtyp cols =
11273   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
11274   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
11275   pr "  for (i = 0; i < r->len; ++i) {\n";
11276   pr "    jfl = (*env)->AllocObject (env, cl);\n";
11277   List.iter (
11278     function
11279     | name, FString ->
11280         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11281         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
11282     | name, FUUID ->
11283         pr "    {\n";
11284         pr "      char s[33];\n";
11285         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
11286         pr "      s[32] = 0;\n";
11287         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11288         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11289         pr "    }\n";
11290     | name, FBuffer ->
11291         pr "    {\n";
11292         pr "      int len = r->val[i].%s_len;\n" name;
11293         pr "      char s[len+1];\n";
11294         pr "      memcpy (s, r->val[i].%s, len);\n" name;
11295         pr "      s[len] = 0;\n";
11296         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
11297         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
11298         pr "    }\n";
11299     | name, (FBytes|FUInt64|FInt64) ->
11300         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
11301         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11302     | name, (FUInt32|FInt32) ->
11303         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
11304         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11305     | name, FOptPercent ->
11306         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
11307         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
11308     | name, FChar ->
11309         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
11310         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
11311   ) cols;
11312   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
11313   pr "  }\n";
11314   pr "  guestfs_free_%s_list (r);\n" typ;
11315   pr "  return jr;\n"
11316
11317 and generate_java_makefile_inc () =
11318   generate_header HashStyle GPLv2plus;
11319
11320   pr "java_built_sources = \\\n";
11321   List.iter (
11322     fun (typ, jtyp) ->
11323         pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
11324   ) java_structs;
11325   pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
11326
11327 and generate_haskell_hs () =
11328   generate_header HaskellStyle LGPLv2plus;
11329
11330   (* XXX We only know how to generate partial FFI for Haskell
11331    * at the moment.  Please help out!
11332    *)
11333   let can_generate style =
11334     match style with
11335     | RErr, _
11336     | RInt _, _
11337     | RInt64 _, _ -> true
11338     | RBool _, _
11339     | RConstString _, _
11340     | RConstOptString _, _
11341     | RString _, _
11342     | RStringList _, _
11343     | RStruct _, _
11344     | RStructList _, _
11345     | RHashtable _, _
11346     | RBufferOut _, _ -> false in
11347
11348   pr "\
11349 {-# INCLUDE <guestfs.h> #-}
11350 {-# LANGUAGE ForeignFunctionInterface #-}
11351
11352 module Guestfs (
11353   create";
11354
11355   (* List out the names of the actions we want to export. *)
11356   List.iter (
11357     fun (name, style, _, _, _, _, _) ->
11358       if can_generate style then pr ",\n  %s" name
11359   ) all_functions;
11360
11361   pr "
11362   ) where
11363
11364 -- Unfortunately some symbols duplicate ones already present
11365 -- in Prelude.  We don't know which, so we hard-code a list
11366 -- here.
11367 import Prelude hiding (truncate)
11368
11369 import Foreign
11370 import Foreign.C
11371 import Foreign.C.Types
11372 import IO
11373 import Control.Exception
11374 import Data.Typeable
11375
11376 data GuestfsS = GuestfsS            -- represents the opaque C struct
11377 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
11378 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
11379
11380 -- XXX define properly later XXX
11381 data PV = PV
11382 data VG = VG
11383 data LV = LV
11384 data IntBool = IntBool
11385 data Stat = Stat
11386 data StatVFS = StatVFS
11387 data Hashtable = Hashtable
11388
11389 foreign import ccall unsafe \"guestfs_create\" c_create
11390   :: IO GuestfsP
11391 foreign import ccall unsafe \"&guestfs_close\" c_close
11392   :: FunPtr (GuestfsP -> IO ())
11393 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
11394   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
11395
11396 create :: IO GuestfsH
11397 create = do
11398   p <- c_create
11399   c_set_error_handler p nullPtr nullPtr
11400   h <- newForeignPtr c_close p
11401   return h
11402
11403 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
11404   :: GuestfsP -> IO CString
11405
11406 -- last_error :: GuestfsH -> IO (Maybe String)
11407 -- last_error h = do
11408 --   str <- withForeignPtr h (\\p -> c_last_error p)
11409 --   maybePeek peekCString str
11410
11411 last_error :: GuestfsH -> IO (String)
11412 last_error h = do
11413   str <- withForeignPtr h (\\p -> c_last_error p)
11414   if (str == nullPtr)
11415     then return \"no error\"
11416     else peekCString str
11417
11418 ";
11419
11420   (* Generate wrappers for each foreign function. *)
11421   List.iter (
11422     fun (name, style, _, _, _, _, _) ->
11423       if can_generate style then (
11424         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
11425         pr "  :: ";
11426         generate_haskell_prototype ~handle:"GuestfsP" style;
11427         pr "\n";
11428         pr "\n";
11429         pr "%s :: " name;
11430         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
11431         pr "\n";
11432         pr "%s %s = do\n" name
11433           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
11434         pr "  r <- ";
11435         (* Convert pointer arguments using with* functions. *)
11436         List.iter (
11437           function
11438           | FileIn n
11439           | FileOut n
11440           | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
11441               pr "withCString %s $ \\%s -> " n n
11442           | BufferIn n ->
11443               pr "withCStringLen %s $ \\(%s, %s_size) -> " n n n
11444           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
11445           | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
11446           | Bool _ | Int _ | Int64 _ -> ()
11447         ) (snd style);
11448         (* Convert integer arguments. *)
11449         let args =
11450           List.map (
11451             function
11452             | Bool n -> sprintf "(fromBool %s)" n
11453             | Int n -> sprintf "(fromIntegral %s)" n
11454             | Int64 n -> sprintf "(fromIntegral %s)" n
11455             | FileIn n | FileOut n
11456             | Pathname n | Device n | Dev_or_Path n
11457             | String n | OptString n
11458             | StringList n | DeviceList n
11459             | Key n -> n
11460             | BufferIn n -> sprintf "%s (fromIntegral %s_size)" n n
11461           ) (snd style) in
11462         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
11463           (String.concat " " ("p" :: args));
11464         (match fst style with
11465          | RErr | RInt _ | RInt64 _ | RBool _ ->
11466              pr "  if (r == -1)\n";
11467              pr "    then do\n";
11468              pr "      err <- last_error h\n";
11469              pr "      fail err\n";
11470          | RConstString _ | RConstOptString _ | RString _
11471          | RStringList _ | RStruct _
11472          | RStructList _ | RHashtable _ | RBufferOut _ ->
11473              pr "  if (r == nullPtr)\n";
11474              pr "    then do\n";
11475              pr "      err <- last_error h\n";
11476              pr "      fail err\n";
11477         );
11478         (match fst style with
11479          | RErr ->
11480              pr "    else return ()\n"
11481          | RInt _ ->
11482              pr "    else return (fromIntegral r)\n"
11483          | RInt64 _ ->
11484              pr "    else return (fromIntegral r)\n"
11485          | RBool _ ->
11486              pr "    else return (toBool r)\n"
11487          | RConstString _
11488          | RConstOptString _
11489          | RString _
11490          | RStringList _
11491          | RStruct _
11492          | RStructList _
11493          | RHashtable _
11494          | RBufferOut _ ->
11495              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
11496         );
11497         pr "\n";
11498       )
11499   ) all_functions
11500
11501 and generate_haskell_prototype ~handle ?(hs = false) style =
11502   pr "%s -> " handle;
11503   let string = if hs then "String" else "CString" in
11504   let int = if hs then "Int" else "CInt" in
11505   let bool = if hs then "Bool" else "CInt" in
11506   let int64 = if hs then "Integer" else "Int64" in
11507   List.iter (
11508     fun arg ->
11509       (match arg with
11510        | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _ ->
11511            pr "%s" string
11512        | BufferIn _ ->
11513            if hs then pr "String"
11514            else pr "CString -> CInt"
11515        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
11516        | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
11517        | Bool _ -> pr "%s" bool
11518        | Int _ -> pr "%s" int
11519        | Int64 _ -> pr "%s" int
11520        | FileIn _ -> pr "%s" string
11521        | FileOut _ -> pr "%s" string
11522       );
11523       pr " -> ";
11524   ) (snd style);
11525   pr "IO (";
11526   (match fst style with
11527    | RErr -> if not hs then pr "CInt"
11528    | RInt _ -> pr "%s" int
11529    | RInt64 _ -> pr "%s" int64
11530    | RBool _ -> pr "%s" bool
11531    | RConstString _ -> pr "%s" string
11532    | RConstOptString _ -> pr "Maybe %s" string
11533    | RString _ -> pr "%s" string
11534    | RStringList _ -> pr "[%s]" string
11535    | RStruct (_, typ) ->
11536        let name = java_name_of_struct typ in
11537        pr "%s" name
11538    | RStructList (_, typ) ->
11539        let name = java_name_of_struct typ in
11540        pr "[%s]" name
11541    | RHashtable _ -> pr "Hashtable"
11542    | RBufferOut _ -> pr "%s" string
11543   );
11544   pr ")"
11545
11546 and generate_csharp () =
11547   generate_header CPlusPlusStyle LGPLv2plus;
11548
11549   (* XXX Make this configurable by the C# assembly users. *)
11550   let library = "libguestfs.so.0" in
11551
11552   pr "\
11553 // These C# bindings are highly experimental at present.
11554 //
11555 // Firstly they only work on Linux (ie. Mono).  In order to get them
11556 // to work on Windows (ie. .Net) you would need to port the library
11557 // itself to Windows first.
11558 //
11559 // The second issue is that some calls are known to be incorrect and
11560 // can cause Mono to segfault.  Particularly: calls which pass or
11561 // return string[], or return any structure value.  This is because
11562 // we haven't worked out the correct way to do this from C#.
11563 //
11564 // The third issue is that when compiling you get a lot of warnings.
11565 // We are not sure whether the warnings are important or not.
11566 //
11567 // Fourthly we do not routinely build or test these bindings as part
11568 // of the make && make check cycle, which means that regressions might
11569 // go unnoticed.
11570 //
11571 // Suggestions and patches are welcome.
11572
11573 // To compile:
11574 //
11575 // gmcs Libguestfs.cs
11576 // mono Libguestfs.exe
11577 //
11578 // (You'll probably want to add a Test class / static main function
11579 // otherwise this won't do anything useful).
11580
11581 using System;
11582 using System.IO;
11583 using System.Runtime.InteropServices;
11584 using System.Runtime.Serialization;
11585 using System.Collections;
11586
11587 namespace Guestfs
11588 {
11589   class Error : System.ApplicationException
11590   {
11591     public Error (string message) : base (message) {}
11592     protected Error (SerializationInfo info, StreamingContext context) {}
11593   }
11594
11595   class Guestfs
11596   {
11597     IntPtr _handle;
11598
11599     [DllImport (\"%s\")]
11600     static extern IntPtr guestfs_create ();
11601
11602     public Guestfs ()
11603     {
11604       _handle = guestfs_create ();
11605       if (_handle == IntPtr.Zero)
11606         throw new Error (\"could not create guestfs handle\");
11607     }
11608
11609     [DllImport (\"%s\")]
11610     static extern void guestfs_close (IntPtr h);
11611
11612     ~Guestfs ()
11613     {
11614       guestfs_close (_handle);
11615     }
11616
11617     [DllImport (\"%s\")]
11618     static extern string guestfs_last_error (IntPtr h);
11619
11620 " library library library;
11621
11622   (* Generate C# structure bindings.  We prefix struct names with
11623    * underscore because C# cannot have conflicting struct names and
11624    * method names (eg. "class stat" and "stat").
11625    *)
11626   List.iter (
11627     fun (typ, cols) ->
11628       pr "    [StructLayout (LayoutKind.Sequential)]\n";
11629       pr "    public class _%s {\n" typ;
11630       List.iter (
11631         function
11632         | name, FChar -> pr "      char %s;\n" name
11633         | name, FString -> pr "      string %s;\n" name
11634         | name, FBuffer ->
11635             pr "      uint %s_len;\n" name;
11636             pr "      string %s;\n" name
11637         | name, FUUID ->
11638             pr "      [MarshalAs (UnmanagedType.ByValTStr, SizeConst=16)]\n";
11639             pr "      string %s;\n" name
11640         | name, FUInt32 -> pr "      uint %s;\n" name
11641         | name, FInt32 -> pr "      int %s;\n" name
11642         | name, (FUInt64|FBytes) -> pr "      ulong %s;\n" name
11643         | name, FInt64 -> pr "      long %s;\n" name
11644         | name, FOptPercent -> pr "      float %s; /* [0..100] or -1 */\n" name
11645       ) cols;
11646       pr "    }\n";
11647       pr "\n"
11648   ) structs;
11649
11650   (* Generate C# function bindings. *)
11651   List.iter (
11652     fun (name, style, _, _, _, shortdesc, _) ->
11653       let rec csharp_return_type () =
11654         match fst style with
11655         | RErr -> "void"
11656         | RBool n -> "bool"
11657         | RInt n -> "int"
11658         | RInt64 n -> "long"
11659         | RConstString n
11660         | RConstOptString n
11661         | RString n
11662         | RBufferOut n -> "string"
11663         | RStruct (_,n) -> "_" ^ n
11664         | RHashtable n -> "Hashtable"
11665         | RStringList n -> "string[]"
11666         | RStructList (_,n) -> sprintf "_%s[]" n
11667
11668       and c_return_type () =
11669         match fst style with
11670         | RErr
11671         | RBool _
11672         | RInt _ -> "int"
11673         | RInt64 _ -> "long"
11674         | RConstString _
11675         | RConstOptString _
11676         | RString _
11677         | RBufferOut _ -> "string"
11678         | RStruct (_,n) -> "_" ^ n
11679         | RHashtable _
11680         | RStringList _ -> "string[]"
11681         | RStructList (_,n) -> sprintf "_%s[]" n
11682
11683       and c_error_comparison () =
11684         match fst style with
11685         | RErr
11686         | RBool _
11687         | RInt _
11688         | RInt64 _ -> "== -1"
11689         | RConstString _
11690         | RConstOptString _
11691         | RString _
11692         | RBufferOut _
11693         | RStruct (_,_)
11694         | RHashtable _
11695         | RStringList _
11696         | RStructList (_,_) -> "== null"
11697
11698       and generate_extern_prototype () =
11699         pr "    static extern %s guestfs_%s (IntPtr h"
11700           (c_return_type ()) name;
11701         List.iter (
11702           function
11703           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11704           | FileIn n | FileOut n
11705           | Key n
11706           | BufferIn n ->
11707               pr ", [In] string %s" n
11708           | StringList n | DeviceList n ->
11709               pr ", [In] string[] %s" n
11710           | Bool n ->
11711               pr ", bool %s" n
11712           | Int n ->
11713               pr ", int %s" n
11714           | Int64 n ->
11715               pr ", long %s" n
11716         ) (snd style);
11717         pr ");\n"
11718
11719       and generate_public_prototype () =
11720         pr "    public %s %s (" (csharp_return_type ()) name;
11721         let comma = ref false in
11722         let next () =
11723           if !comma then pr ", ";
11724           comma := true
11725         in
11726         List.iter (
11727           function
11728           | Pathname n | Device n | Dev_or_Path n | String n | OptString n
11729           | FileIn n | FileOut n
11730           | Key n
11731           | BufferIn n ->
11732               next (); pr "string %s" n
11733           | StringList n | DeviceList n ->
11734               next (); pr "string[] %s" n
11735           | Bool n ->
11736               next (); pr "bool %s" n
11737           | Int n ->
11738               next (); pr "int %s" n
11739           | Int64 n ->
11740               next (); pr "long %s" n
11741         ) (snd style);
11742         pr ")\n"
11743
11744       and generate_call () =
11745         pr "guestfs_%s (_handle" name;
11746         List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (snd style);
11747         pr ");\n";
11748       in
11749
11750       pr "    [DllImport (\"%s\")]\n" library;
11751       generate_extern_prototype ();
11752       pr "\n";
11753       pr "    /// <summary>\n";
11754       pr "    /// %s\n" shortdesc;
11755       pr "    /// </summary>\n";
11756       generate_public_prototype ();
11757       pr "    {\n";
11758       pr "      %s r;\n" (c_return_type ());
11759       pr "      r = ";
11760       generate_call ();
11761       pr "      if (r %s)\n" (c_error_comparison ());
11762       pr "        throw new Error (guestfs_last_error (_handle));\n";
11763       (match fst style with
11764        | RErr -> ()
11765        | RBool _ ->
11766            pr "      return r != 0 ? true : false;\n"
11767        | RHashtable _ ->
11768            pr "      Hashtable rr = new Hashtable ();\n";
11769            pr "      for (size_t i = 0; i < r.Length; i += 2)\n";
11770            pr "        rr.Add (r[i], r[i+1]);\n";
11771            pr "      return rr;\n"
11772        | RInt _ | RInt64 _ | RConstString _ | RConstOptString _
11773        | RString _ | RBufferOut _ | RStruct _ | RStringList _
11774        | RStructList _ ->
11775            pr "      return r;\n"
11776       );
11777       pr "    }\n";
11778       pr "\n";
11779   ) all_functions_sorted;
11780
11781   pr "  }
11782 }
11783 "
11784
11785 and generate_bindtests () =
11786   generate_header CStyle LGPLv2plus;
11787
11788   pr "\
11789 #include <stdio.h>
11790 #include <stdlib.h>
11791 #include <inttypes.h>
11792 #include <string.h>
11793
11794 #include \"guestfs.h\"
11795 #include \"guestfs-internal.h\"
11796 #include \"guestfs-internal-actions.h\"
11797 #include \"guestfs_protocol.h\"
11798
11799 #define error guestfs_error
11800 #define safe_calloc guestfs_safe_calloc
11801 #define safe_malloc guestfs_safe_malloc
11802
11803 static void
11804 print_strings (char *const *argv)
11805 {
11806   size_t argc;
11807
11808   printf (\"[\");
11809   for (argc = 0; argv[argc] != NULL; ++argc) {
11810     if (argc > 0) printf (\", \");
11811     printf (\"\\\"%%s\\\"\", argv[argc]);
11812   }
11813   printf (\"]\\n\");
11814 }
11815
11816 /* The test0 function prints its parameters to stdout. */
11817 ";
11818
11819   let test0, tests =
11820     match test_functions with
11821     | [] -> assert false
11822     | test0 :: tests -> test0, tests in
11823
11824   let () =
11825     let (name, style, _, _, _, _, _) = test0 in
11826     generate_prototype ~extern:false ~semicolon:false ~newline:true
11827       ~handle:"g" ~prefix:"guestfs__" name style;
11828     pr "{\n";
11829     List.iter (
11830       function
11831       | Pathname n
11832       | Device n | Dev_or_Path n
11833       | String n
11834       | FileIn n
11835       | FileOut n
11836       | Key n -> pr "  printf (\"%%s\\n\", %s);\n" n
11837       | BufferIn n ->
11838           pr "  {\n";
11839           pr "    size_t i;\n";
11840           pr "    for (i = 0; i < %s_size; ++i)\n" n;
11841           pr "      printf (\"<%%02x>\", %s[i]);\n" n;
11842           pr "    printf (\"\\n\");\n";
11843           pr "  }\n";
11844       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
11845       | StringList n | DeviceList n -> pr "  print_strings (%s);\n" n
11846       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
11847       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
11848       | Int64 n -> pr "  printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
11849     ) (snd style);
11850     pr "  /* Java changes stdout line buffering so we need this: */\n";
11851     pr "  fflush (stdout);\n";
11852     pr "  return 0;\n";
11853     pr "}\n";
11854     pr "\n" in
11855
11856   List.iter (
11857     fun (name, style, _, _, _, _, _) ->
11858       if String.sub name (String.length name - 3) 3 <> "err" then (
11859         pr "/* Test normal return. */\n";
11860         generate_prototype ~extern:false ~semicolon:false ~newline:true
11861           ~handle:"g" ~prefix:"guestfs__" name style;
11862         pr "{\n";
11863         (match fst style with
11864          | RErr ->
11865              pr "  return 0;\n"
11866          | RInt _ ->
11867              pr "  int r;\n";
11868              pr "  sscanf (val, \"%%d\", &r);\n";
11869              pr "  return r;\n"
11870          | RInt64 _ ->
11871              pr "  int64_t r;\n";
11872              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
11873              pr "  return r;\n"
11874          | RBool _ ->
11875              pr "  return STREQ (val, \"true\");\n"
11876          | RConstString _
11877          | RConstOptString _ ->
11878              (* Can't return the input string here.  Return a static
11879               * string so we ensure we get a segfault if the caller
11880               * tries to free it.
11881               *)
11882              pr "  return \"static string\";\n"
11883          | RString _ ->
11884              pr "  return strdup (val);\n"
11885          | RStringList _ ->
11886              pr "  char **strs;\n";
11887              pr "  int n, i;\n";
11888              pr "  sscanf (val, \"%%d\", &n);\n";
11889              pr "  strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
11890              pr "  for (i = 0; i < n; ++i) {\n";
11891              pr "    strs[i] = safe_malloc (g, 16);\n";
11892              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
11893              pr "  }\n";
11894              pr "  strs[n] = NULL;\n";
11895              pr "  return strs;\n"
11896          | RStruct (_, typ) ->
11897              pr "  struct guestfs_%s *r;\n" typ;
11898              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
11899              pr "  return r;\n"
11900          | RStructList (_, typ) ->
11901              pr "  struct guestfs_%s_list *r;\n" typ;
11902              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
11903              pr "  sscanf (val, \"%%d\", &r->len);\n";
11904              pr "  r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
11905              pr "  return r;\n"
11906          | RHashtable _ ->
11907              pr "  char **strs;\n";
11908              pr "  int n, i;\n";
11909              pr "  sscanf (val, \"%%d\", &n);\n";
11910              pr "  strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
11911              pr "  for (i = 0; i < n; ++i) {\n";
11912              pr "    strs[i*2] = safe_malloc (g, 16);\n";
11913              pr "    strs[i*2+1] = safe_malloc (g, 16);\n";
11914              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
11915              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
11916              pr "  }\n";
11917              pr "  strs[n*2] = NULL;\n";
11918              pr "  return strs;\n"
11919          | RBufferOut _ ->
11920              pr "  return strdup (val);\n"
11921         );
11922         pr "}\n";
11923         pr "\n"
11924       ) else (
11925         pr "/* Test error return. */\n";
11926         generate_prototype ~extern:false ~semicolon:false ~newline:true
11927           ~handle:"g" ~prefix:"guestfs__" name style;
11928         pr "{\n";
11929         pr "  error (g, \"error\");\n";
11930         (match fst style with
11931          | RErr | RInt _ | RInt64 _ | RBool _ ->
11932              pr "  return -1;\n"
11933          | RConstString _ | RConstOptString _
11934          | RString _ | RStringList _ | RStruct _
11935          | RStructList _
11936          | RHashtable _
11937          | RBufferOut _ ->
11938              pr "  return NULL;\n"
11939         );
11940         pr "}\n";
11941         pr "\n"
11942       )
11943   ) tests
11944
11945 and generate_ocaml_bindtests () =
11946   generate_header OCamlStyle GPLv2plus;
11947
11948   pr "\
11949 let () =
11950   let g = Guestfs.create () in
11951 ";
11952
11953   let mkargs args =
11954     String.concat " " (
11955       List.map (
11956         function
11957         | CallString s -> "\"" ^ s ^ "\""
11958         | CallOptString None -> "None"
11959         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
11960         | CallStringList xs ->
11961             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
11962         | CallInt i when i >= 0 -> string_of_int i
11963         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
11964         | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
11965         | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
11966         | CallBool b -> string_of_bool b
11967         | CallBuffer s -> sprintf "%S" s
11968       ) args
11969     )
11970   in
11971
11972   generate_lang_bindtests (
11973     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
11974   );
11975
11976   pr "print_endline \"EOF\"\n"
11977
11978 and generate_perl_bindtests () =
11979   pr "#!/usr/bin/perl -w\n";
11980   generate_header HashStyle GPLv2plus;
11981
11982   pr "\
11983 use strict;
11984
11985 use Sys::Guestfs;
11986
11987 my $g = Sys::Guestfs->new ();
11988 ";
11989
11990   let mkargs args =
11991     String.concat ", " (
11992       List.map (
11993         function
11994         | CallString s -> "\"" ^ s ^ "\""
11995         | CallOptString None -> "undef"
11996         | CallOptString (Some s) -> sprintf "\"%s\"" s
11997         | CallStringList xs ->
11998             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
11999         | CallInt i -> string_of_int i
12000         | CallInt64 i -> Int64.to_string i
12001         | CallBool b -> if b then "1" else "0"
12002         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12003       ) args
12004     )
12005   in
12006
12007   generate_lang_bindtests (
12008     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
12009   );
12010
12011   pr "print \"EOF\\n\"\n"
12012
12013 and generate_python_bindtests () =
12014   generate_header HashStyle GPLv2plus;
12015
12016   pr "\
12017 import guestfs
12018
12019 g = guestfs.GuestFS ()
12020 ";
12021
12022   let mkargs args =
12023     String.concat ", " (
12024       List.map (
12025         function
12026         | CallString s -> "\"" ^ s ^ "\""
12027         | CallOptString None -> "None"
12028         | CallOptString (Some s) -> sprintf "\"%s\"" s
12029         | CallStringList xs ->
12030             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12031         | CallInt i -> string_of_int i
12032         | CallInt64 i -> Int64.to_string i
12033         | CallBool b -> if b then "1" else "0"
12034         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12035       ) args
12036     )
12037   in
12038
12039   generate_lang_bindtests (
12040     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
12041   );
12042
12043   pr "print \"EOF\"\n"
12044
12045 and generate_ruby_bindtests () =
12046   generate_header HashStyle GPLv2plus;
12047
12048   pr "\
12049 require 'guestfs'
12050
12051 g = Guestfs::create()
12052 ";
12053
12054   let mkargs args =
12055     String.concat ", " (
12056       List.map (
12057         function
12058         | CallString s -> "\"" ^ s ^ "\""
12059         | CallOptString None -> "nil"
12060         | CallOptString (Some s) -> sprintf "\"%s\"" s
12061         | CallStringList xs ->
12062             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12063         | CallInt i -> string_of_int i
12064         | CallInt64 i -> Int64.to_string i
12065         | CallBool b -> string_of_bool b
12066         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12067       ) args
12068     )
12069   in
12070
12071   generate_lang_bindtests (
12072     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
12073   );
12074
12075   pr "print \"EOF\\n\"\n"
12076
12077 and generate_java_bindtests () =
12078   generate_header CStyle GPLv2plus;
12079
12080   pr "\
12081 import com.redhat.et.libguestfs.*;
12082
12083 public class Bindtests {
12084     public static void main (String[] argv)
12085     {
12086         try {
12087             GuestFS g = new GuestFS ();
12088 ";
12089
12090   let mkargs args =
12091     String.concat ", " (
12092       List.map (
12093         function
12094         | CallString s -> "\"" ^ s ^ "\""
12095         | CallOptString None -> "null"
12096         | CallOptString (Some s) -> sprintf "\"%s\"" s
12097         | CallStringList xs ->
12098             "new String[]{" ^
12099               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
12100         | CallInt i -> string_of_int i
12101         | CallInt64 i -> Int64.to_string i
12102         | CallBool b -> string_of_bool b
12103         | CallBuffer s ->
12104             "new byte[] { " ^ String.concat "," (
12105               map_chars (fun c -> string_of_int (Char.code c)) s
12106             ) ^ " }"
12107       ) args
12108     )
12109   in
12110
12111   generate_lang_bindtests (
12112     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
12113   );
12114
12115   pr "
12116             System.out.println (\"EOF\");
12117         }
12118         catch (Exception exn) {
12119             System.err.println (exn);
12120             System.exit (1);
12121         }
12122     }
12123 }
12124 "
12125
12126 and generate_haskell_bindtests () =
12127   generate_header HaskellStyle GPLv2plus;
12128
12129   pr "\
12130 module Bindtests where
12131 import qualified Guestfs
12132
12133 main = do
12134   g <- Guestfs.create
12135 ";
12136
12137   let mkargs args =
12138     String.concat " " (
12139       List.map (
12140         function
12141         | CallString s -> "\"" ^ s ^ "\""
12142         | CallOptString None -> "Nothing"
12143         | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
12144         | CallStringList xs ->
12145             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
12146         | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
12147         | CallInt i -> string_of_int i
12148         | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
12149         | CallInt64 i -> Int64.to_string i
12150         | CallBool true -> "True"
12151         | CallBool false -> "False"
12152         | CallBuffer s -> "\"" ^ c_quote s ^ "\""
12153       ) args
12154     )
12155   in
12156
12157   generate_lang_bindtests (
12158     fun f args -> pr "  Guestfs.%s g %s\n" f (mkargs args)
12159   );
12160
12161   pr "  putStrLn \"EOF\"\n"
12162
12163 (* Language-independent bindings tests - we do it this way to
12164  * ensure there is parity in testing bindings across all languages.
12165  *)
12166 and generate_lang_bindtests call =
12167   call "test0" [CallString "abc"; CallOptString (Some "def");
12168                 CallStringList []; CallBool false;
12169                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12170                 CallBuffer "abc\000abc"];
12171   call "test0" [CallString "abc"; CallOptString None;
12172                 CallStringList []; CallBool false;
12173                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12174                 CallBuffer "abc\000abc"];
12175   call "test0" [CallString ""; CallOptString (Some "def");
12176                 CallStringList []; CallBool false;
12177                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12178                 CallBuffer "abc\000abc"];
12179   call "test0" [CallString ""; CallOptString (Some "");
12180                 CallStringList []; CallBool false;
12181                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12182                 CallBuffer "abc\000abc"];
12183   call "test0" [CallString "abc"; CallOptString (Some "def");
12184                 CallStringList ["1"]; CallBool false;
12185                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12186                 CallBuffer "abc\000abc"];
12187   call "test0" [CallString "abc"; CallOptString (Some "def");
12188                 CallStringList ["1"; "2"]; CallBool false;
12189                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12190                 CallBuffer "abc\000abc"];
12191   call "test0" [CallString "abc"; CallOptString (Some "def");
12192                 CallStringList ["1"]; CallBool true;
12193                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456";
12194                 CallBuffer "abc\000abc"];
12195   call "test0" [CallString "abc"; CallOptString (Some "def");
12196                 CallStringList ["1"]; CallBool false;
12197                 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456";
12198                 CallBuffer "abc\000abc"];
12199   call "test0" [CallString "abc"; CallOptString (Some "def");
12200                 CallStringList ["1"]; CallBool false;
12201                 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456";
12202                 CallBuffer "abc\000abc"];
12203   call "test0" [CallString "abc"; CallOptString (Some "def");
12204                 CallStringList ["1"]; CallBool false;
12205                 CallInt 1; CallInt64 1L; CallString "123"; CallString "456";
12206                 CallBuffer "abc\000abc"];
12207   call "test0" [CallString "abc"; CallOptString (Some "def");
12208                 CallStringList ["1"]; CallBool false;
12209                 CallInt 2; CallInt64 2L; CallString "123"; CallString "456";
12210                 CallBuffer "abc\000abc"];
12211   call "test0" [CallString "abc"; CallOptString (Some "def");
12212                 CallStringList ["1"]; CallBool false;
12213                 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456";
12214                 CallBuffer "abc\000abc"];
12215   call "test0" [CallString "abc"; CallOptString (Some "def");
12216                 CallStringList ["1"]; CallBool false;
12217                 CallInt 0; CallInt64 0L; CallString ""; CallString "";
12218                 CallBuffer "abc\000abc"]
12219
12220 (* XXX Add here tests of the return and error functions. *)
12221
12222 and generate_max_proc_nr () =
12223   pr "%d\n" max_proc_nr
12224
12225 let output_to filename k =
12226   let filename_new = filename ^ ".new" in
12227   chan := open_out filename_new;
12228   k ();
12229   close_out !chan;
12230   chan := Pervasives.stdout;
12231
12232   (* Is the new file different from the current file? *)
12233   if Sys.file_exists filename && files_equal filename filename_new then
12234     unlink filename_new                 (* same, so skip it *)
12235   else (
12236     (* different, overwrite old one *)
12237     (try chmod filename 0o644 with Unix_error _ -> ());
12238     rename filename_new filename;
12239     chmod filename 0o444;
12240     printf "written %s\n%!" filename;
12241   )
12242
12243 let perror msg = function
12244   | Unix_error (err, _, _) ->
12245       eprintf "%s: %s\n" msg (error_message err)
12246   | exn ->
12247       eprintf "%s: %s\n" msg (Printexc.to_string exn)
12248
12249 (* Main program. *)
12250 let () =
12251   let lock_fd =
12252     try openfile "HACKING" [O_RDWR] 0
12253     with
12254     | Unix_error (ENOENT, _, _) ->
12255         eprintf "\
12256 You are probably running this from the wrong directory.
12257 Run it from the top source directory using the command
12258   src/generator.ml
12259 ";
12260         exit 1
12261     | exn ->
12262         perror "open: HACKING" exn;
12263         exit 1 in
12264
12265   (* Acquire a lock so parallel builds won't try to run the generator
12266    * twice at the same time.  Subsequent builds will wait for the first
12267    * one to finish.  Note the lock is released implicitly when the
12268    * program exits.
12269    *)
12270   (try lockf lock_fd F_LOCK 1
12271    with exn ->
12272      perror "lock: HACKING" exn;
12273      exit 1);
12274
12275   check_functions ();
12276
12277   output_to "src/guestfs_protocol.x" generate_xdr;
12278   output_to "src/guestfs-structs.h" generate_structs_h;
12279   output_to "src/guestfs-actions.h" generate_actions_h;
12280   output_to "src/guestfs-internal-actions.h" generate_internal_actions_h;
12281   output_to "src/actions.c" generate_client_actions;
12282   output_to "src/bindtests.c" generate_bindtests;
12283   output_to "src/guestfs-structs.pod" generate_structs_pod;
12284   output_to "src/guestfs-actions.pod" generate_actions_pod;
12285   output_to "src/guestfs-availability.pod" generate_availability_pod;
12286   output_to "src/MAX_PROC_NR" generate_max_proc_nr;
12287   output_to "src/libguestfs.syms" generate_linker_script;
12288   output_to "daemon/actions.h" generate_daemon_actions_h;
12289   output_to "daemon/stubs.c" generate_daemon_actions;
12290   output_to "daemon/names.c" generate_daemon_names;
12291   output_to "daemon/optgroups.c" generate_daemon_optgroups_c;
12292   output_to "daemon/optgroups.h" generate_daemon_optgroups_h;
12293   output_to "capitests/tests.c" generate_tests;
12294   output_to "fish/cmds.c" generate_fish_cmds;
12295   output_to "fish/completion.c" generate_fish_completion;
12296   output_to "fish/guestfish-actions.pod" generate_fish_actions_pod;
12297   output_to "ocaml/guestfs.mli" generate_ocaml_mli;
12298   output_to "ocaml/guestfs.ml" generate_ocaml_ml;
12299   output_to "ocaml/guestfs_c_actions.c" generate_ocaml_c;
12300   output_to "ocaml/bindtests.ml" generate_ocaml_bindtests;
12301   output_to "perl/Guestfs.xs" generate_perl_xs;
12302   output_to "perl/lib/Sys/Guestfs.pm" generate_perl_pm;
12303   output_to "perl/bindtests.pl" generate_perl_bindtests;
12304   output_to "python/guestfs-py.c" generate_python_c;
12305   output_to "python/guestfs.py" generate_python_py;
12306   output_to "python/bindtests.py" generate_python_bindtests;
12307   output_to "ruby/ext/guestfs/_guestfs.c" generate_ruby_c;
12308   output_to "ruby/bindtests.rb" generate_ruby_bindtests;
12309   output_to "java/com/redhat/et/libguestfs/GuestFS.java" generate_java_java;
12310
12311   List.iter (
12312     fun (typ, jtyp) ->
12313       let cols = cols_of_struct typ in
12314       let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
12315       output_to filename (generate_java_struct jtyp cols);
12316   ) java_structs;
12317
12318   output_to "java/Makefile.inc" generate_java_makefile_inc;
12319   output_to "java/com_redhat_et_libguestfs_GuestFS.c" generate_java_c;
12320   output_to "java/Bindtests.java" generate_java_bindtests;
12321   output_to "haskell/Guestfs.hs" generate_haskell_hs;
12322   output_to "haskell/Bindtests.hs" generate_haskell_bindtests;
12323   output_to "csharp/Libguestfs.cs" generate_csharp;
12324
12325   (* Always generate this file last, and unconditionally.  It's used
12326    * by the Makefile to know when we must re-run the generator.
12327    *)
12328   let chan = open_out "src/stamp-generator" in
12329   fprintf chan "1\n";
12330   close_out chan;
12331
12332   printf "generated %d lines of code\n" !lines