00f3c4ecfdc3500ba7b24dc61c46b8d5ed932361
[libguestfs.git] / src / generator.ml
1 #!/usr/bin/env ocaml
2 (* libguestfs
3  * Copyright (C) 2009 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 below), and
25  * daemon/<somefile>.c to write the implementation.
26  *
27  * After editing this file, run it (./src/generator.ml) to regenerate all the
28  * output files.  Note that if you are using a separate build directory you
29  * must run generator.ml from the _source_ directory.
30  *
31  * IMPORTANT: This script should NOT print any warnings.  If it prints
32  * warnings, you should treat them as errors.
33  * [Need to add -warn-error to ocaml command line]
34  *)
35
36 #load "unix.cma";;
37 #load "str.cma";;
38
39 open Printf
40
41 type style = ret * args
42 and ret =
43     (* "RErr" as a return value means an int used as a simple error
44      * indication, ie. 0 or -1.
45      *)
46   | RErr
47
48     (* "RInt" as a return value means an int which is -1 for error
49      * or any value >= 0 on success.  Only use this for smallish
50      * positive ints (0 <= i < 2^30).
51      *)
52   | RInt of string
53
54     (* "RInt64" is the same as RInt, but is guaranteed to be able
55      * to return a full 64 bit value, _except_ that -1 means error
56      * (so -1 cannot be a valid, non-error return value).
57      *)
58   | RInt64 of string
59
60     (* "RBool" is a bool return value which can be true/false or
61      * -1 for error.
62      *)
63   | RBool of string
64
65     (* "RConstString" is a string that refers to a constant value.
66      * The return value must NOT be NULL (since NULL indicates
67      * an error).
68      *
69      * Try to avoid using this.  In particular you cannot use this
70      * for values returned from the daemon, because there is no
71      * thread-safe way to return them in the C API.
72      *)
73   | RConstString of string
74
75     (* "RConstOptString" is an even more broken version of
76      * "RConstString".  The returned string may be NULL and there
77      * is no way to return an error indication.  Avoid using this!
78      *)
79   | RConstOptString of string
80
81     (* "RString" is a returned string.  It must NOT be NULL, since
82      * a NULL return indicates an error.  The caller frees this.
83      *)
84   | RString of string
85
86     (* "RStringList" is a list of strings.  No string in the list
87      * can be NULL.  The caller frees the strings and the array.
88      *)
89   | RStringList of string
90
91     (* "RStruct" is a function which returns a single named structure
92      * or an error indication (in C, a struct, and in other languages
93      * with varying representations, but usually very efficient).  See
94      * after the function list below for the structures. 
95      *)
96   | RStruct of string * string          (* name of retval, name of struct *)
97
98     (* "RStructList" is a function which returns either a list/array
99      * of structures (could be zero-length), or an error indication.
100      *)
101   | RStructList of string * string      (* name of retval, name of struct *)
102
103     (* Key-value pairs of untyped strings.  Turns into a hashtable or
104      * dictionary in languages which support it.  DON'T use this as a
105      * general "bucket" for results.  Prefer a stronger typed return
106      * value if one is available, or write a custom struct.  Don't use
107      * this if the list could potentially be very long, since it is
108      * inefficient.  Keys should be unique.  NULLs are not permitted.
109      *)
110   | RHashtable of string
111
112     (* "RBufferOut" is handled almost exactly like RString, but
113      * it allows the string to contain arbitrary 8 bit data including
114      * ASCII NUL.  In the C API this causes an implicit extra parameter
115      * to be added of type <size_t *size_r>.  The extra parameter
116      * returns the actual size of the return buffer in bytes.
117      *
118      * Other programming languages support strings with arbitrary 8 bit
119      * data.
120      *
121      * At the RPC layer we have to use the opaque<> type instead of
122      * string<>.  Returned data is still limited to the max message
123      * size (ie. ~ 2 MB).
124      *)
125   | RBufferOut of string
126
127 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
128
129     (* Note in future we should allow a "variable args" parameter as
130      * the final parameter, to allow commands like
131      *   chmod mode file [file(s)...]
132      * This is not implemented yet, but many commands (such as chmod)
133      * are currently defined with the argument order keeping this future
134      * possibility in mind.
135      *)
136 and argt =
137   | String of string    (* const char *name, cannot be NULL *)
138   | OptString of string (* const char *name, may be NULL *)
139   | StringList of string(* list of strings (each string cannot be NULL) *)
140   | Bool of string      (* boolean *)
141   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
142     (* These are treated as filenames (simple string parameters) in
143      * the C API and bindings.  But in the RPC protocol, we transfer
144      * the actual file content up to or down from the daemon.
145      * FileIn: local machine -> daemon (in request)
146      * FileOut: daemon -> local machine (in reply)
147      * In guestfish (only), the special name "-" means read from
148      * stdin or write to stdout.
149      *)
150   | FileIn of string
151   | FileOut of string
152 (* Not implemented:
153     (* Opaque buffer which can contain arbitrary 8 bit data.
154      * In the C API, this is expressed as <char *, int> pair.
155      * Most other languages have a string type which can contain
156      * ASCII NUL.  We use whatever type is appropriate for each
157      * language.
158      * Buffers are limited by the total message size.  To transfer
159      * large blocks of data, use FileIn/FileOut parameters instead.
160      * To return an arbitrary buffer, use RBufferOut.
161      *)
162   | BufferIn of string
163 *)
164
165 type flags =
166   | ProtocolLimitWarning  (* display warning about protocol size limits *)
167   | DangerWillRobinson    (* flags particularly dangerous commands *)
168   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
169   | FishAction of string  (* call this function in guestfish *)
170   | NotInFish             (* do not export via guestfish *)
171   | NotInDocs             (* do not add this function to documentation *)
172   | DeprecatedBy of string (* function is deprecated, use .. instead *)
173
174 (* You can supply zero or as many tests as you want per API call.
175  *
176  * Note that the test environment has 3 block devices, of size 500MB,
177  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
178  * a fourth squashfs block device with some known files on it (/dev/sdd).
179  *
180  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
181  * Number of cylinders was 63 for IDE emulated disks with precisely
182  * the same size.  How exactly this is calculated is a mystery.
183  *
184  * The squashfs block device (/dev/sdd) comes from images/test.sqsh.
185  *
186  * To be able to run the tests in a reasonable amount of time,
187  * the virtual machine and block devices are reused between tests.
188  * So don't try testing kill_subprocess :-x
189  *
190  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
191  *
192  * Don't assume anything about the previous contents of the block
193  * devices.  Use 'Init*' to create some initial scenarios.
194  *
195  * You can add a prerequisite clause to any individual test.  This
196  * is a run-time check, which, if it fails, causes the test to be
197  * skipped.  Useful if testing a command which might not work on
198  * all variations of libguestfs builds.  A test that has prerequisite
199  * of 'Always' is run unconditionally.
200  *
201  * In addition, packagers can skip individual tests by setting the
202  * environment variables:     eg:
203  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
204  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
205  *)
206 type tests = (test_init * test_prereq * test) list
207 and test =
208     (* Run the command sequence and just expect nothing to fail. *)
209   | TestRun of seq
210     (* Run the command sequence and expect the output of the final
211      * command to be the string.
212      *)
213   | TestOutput of seq * string
214     (* Run the command sequence and expect the output of the final
215      * command to be the list of strings.
216      *)
217   | TestOutputList of seq * string list
218     (* Run the command sequence and expect the output of the final
219      * command to be the list of block devices (could be either
220      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
221      * character of each string).
222      *)
223   | TestOutputListOfDevices of seq * string list
224     (* Run the command sequence and expect the output of the final
225      * command to be the integer.
226      *)
227   | TestOutputInt of seq * int
228     (* Run the command sequence and expect the output of the final
229      * command to be <op> <int>, eg. ">=", "1".
230      *)
231   | TestOutputIntOp of seq * string * int
232     (* Run the command sequence and expect the output of the final
233      * command to be a true value (!= 0 or != NULL).
234      *)
235   | TestOutputTrue of seq
236     (* Run the command sequence and expect the output of the final
237      * command to be a false value (== 0 or == NULL, but not an error).
238      *)
239   | TestOutputFalse of seq
240     (* Run the command sequence and expect the output of the final
241      * command to be a list of the given length (but don't care about
242      * content).
243      *)
244   | TestOutputLength of seq * int
245     (* Run the command sequence and expect the output of the final
246      * command to be a buffer (RBufferOut), ie. string + size.
247      *)
248   | TestOutputBuffer of seq * string
249     (* Run the command sequence and expect the output of the final
250      * command to be a structure.
251      *)
252   | TestOutputStruct of seq * test_field_compare list
253     (* Run the command sequence and expect the final command (only)
254      * to fail.
255      *)
256   | TestLastFail of seq
257
258 and test_field_compare =
259   | CompareWithInt of string * int
260   | CompareWithIntOp of string * string * int
261   | CompareWithString of string * string
262   | CompareFieldsIntEq of string * string
263   | CompareFieldsStrEq of string * string
264
265 (* Test prerequisites. *)
266 and test_prereq =
267     (* Test always runs. *)
268   | Always
269     (* Test is currently disabled - eg. it fails, or it tests some
270      * unimplemented feature.
271      *)
272   | Disabled
273     (* 'string' is some C code (a function body) that should return
274      * true or false.  The test will run if the code returns true.
275      *)
276   | If of string
277     (* As for 'If' but the test runs _unless_ the code returns true. *)
278   | Unless of string
279
280 (* Some initial scenarios for testing. *)
281 and test_init =
282     (* Do nothing, block devices could contain random stuff including
283      * LVM PVs, and some filesystems might be mounted.  This is usually
284      * a bad idea.
285      *)
286   | InitNone
287
288     (* Block devices are empty and no filesystems are mounted. *)
289   | InitEmpty
290
291     (* /dev/sda contains a single partition /dev/sda1, which is formatted
292      * as ext2, empty [except for lost+found] and mounted on /.
293      * /dev/sdb and /dev/sdc may have random content.
294      * No LVM.
295      *)
296   | InitBasicFS
297
298     (* /dev/sda:
299      *   /dev/sda1 (is a PV):
300      *     /dev/VG/LV (size 8MB):
301      *       formatted as ext2, empty [except for lost+found], mounted on /
302      * /dev/sdb and /dev/sdc may have random content.
303      *)
304   | InitBasicFSonLVM
305
306     (* /dev/sdd (the squashfs, see images/ directory in source)
307      * is mounted on /
308      *)
309   | InitSquashFS
310
311 (* Sequence of commands for testing. *)
312 and seq = cmd list
313 and cmd = string list
314
315 (* Note about long descriptions: When referring to another
316  * action, use the format C<guestfs_other> (ie. the full name of
317  * the C function).  This will be replaced as appropriate in other
318  * language bindings.
319  *
320  * Apart from that, long descriptions are just perldoc paragraphs.
321  *)
322
323 (* These test functions are used in the language binding tests. *)
324
325 let test_all_args = [
326   String "str";
327   OptString "optstr";
328   StringList "strlist";
329   Bool "b";
330   Int "integer";
331   FileIn "filein";
332   FileOut "fileout";
333 ]
334
335 let test_all_rets = [
336   (* except for RErr, which is tested thoroughly elsewhere *)
337   "test0rint",         RInt "valout";
338   "test0rint64",       RInt64 "valout";
339   "test0rbool",        RBool "valout";
340   "test0rconststring", RConstString "valout";
341   "test0rconstoptstring", RConstOptString "valout";
342   "test0rstring",      RString "valout";
343   "test0rstringlist",  RStringList "valout";
344   "test0rstruct",      RStruct ("valout", "lvm_pv");
345   "test0rstructlist",  RStructList ("valout", "lvm_pv");
346   "test0rhashtable",   RHashtable "valout";
347 ]
348
349 let test_functions = [
350   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
351    [],
352    "internal test function - do not use",
353    "\
354 This is an internal test function which is used to test whether
355 the automatically generated bindings can handle every possible
356 parameter type correctly.
357
358 It echos the contents of each parameter to stdout.
359
360 You probably don't want to call this function.");
361 ] @ List.flatten (
362   List.map (
363     fun (name, ret) ->
364       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
365         [],
366         "internal test function - do not use",
367         "\
368 This is an internal test function which is used to test whether
369 the automatically generated bindings can handle every possible
370 return type correctly.
371
372 It converts string C<val> to the return type.
373
374 You probably don't want to call this function.");
375        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
376         [],
377         "internal test function - do not use",
378         "\
379 This is an internal test function which is used to test whether
380 the automatically generated bindings can handle every possible
381 return type correctly.
382
383 This function always returns an error.
384
385 You probably don't want to call this function.")]
386   ) test_all_rets
387 )
388
389 (* non_daemon_functions are any functions which don't get processed
390  * in the daemon, eg. functions for setting and getting local
391  * configuration values.
392  *)
393
394 let non_daemon_functions = test_functions @ [
395   ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
396    [],
397    "launch the qemu subprocess",
398    "\
399 Internally libguestfs is implemented by running a virtual machine
400 using L<qemu(1)>.
401
402 You should call this after configuring the handle
403 (eg. adding drives) but before performing any actions.");
404
405   ("wait_ready", (RErr, []), -1, [NotInFish],
406    [],
407    "wait until the qemu subprocess launches",
408    "\
409 Internally libguestfs is implemented by running a virtual machine
410 using L<qemu(1)>.
411
412 You should call this after C<guestfs_launch> to wait for the launch
413 to complete.");
414
415   ("kill_subprocess", (RErr, []), -1, [],
416    [],
417    "kill the qemu subprocess",
418    "\
419 This kills the qemu subprocess.  You should never need to call this.");
420
421   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
422    [],
423    "add an image to examine or modify",
424    "\
425 This function adds a virtual machine disk image C<filename> to the
426 guest.  The first time you call this function, the disk appears as IDE
427 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
428 so on.
429
430 You don't necessarily need to be root when using libguestfs.  However
431 you obviously do need sufficient permissions to access the filename
432 for whatever operations you want to perform (ie. read access if you
433 just want to read the image or write access if you want to modify the
434 image).
435
436 This is equivalent to the qemu parameter
437 C<-drive file=filename,cache=off,if=...>.
438
439 Note that this call checks for the existence of C<filename>.  This
440 stops you from specifying other types of drive which are supported
441 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
442 the general C<guestfs_config> call instead.");
443
444   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
445    [],
446    "add a CD-ROM disk image to examine",
447    "\
448 This function adds a virtual CD-ROM disk image to the guest.
449
450 This is equivalent to the qemu parameter C<-cdrom filename>.
451
452 Note that this call checks for the existence of C<filename>.  This
453 stops you from specifying other types of drive which are supported
454 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
455 the general C<guestfs_config> call instead.");
456
457   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
458    [],
459    "add a drive in snapshot mode (read-only)",
460    "\
461 This adds a drive in snapshot mode, making it effectively
462 read-only.
463
464 Note that writes to the device are allowed, and will be seen for
465 the duration of the guestfs handle, but they are written
466 to a temporary file which is discarded as soon as the guestfs
467 handle is closed.  We don't currently have any method to enable
468 changes to be committed, although qemu can support this.
469
470 This is equivalent to the qemu parameter
471 C<-drive file=filename,snapshot=on,if=...>.
472
473 Note that this call checks for the existence of C<filename>.  This
474 stops you from specifying other types of drive which are supported
475 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
476 the general C<guestfs_config> call instead.");
477
478   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
479    [],
480    "add qemu parameters",
481    "\
482 This can be used to add arbitrary qemu command line parameters
483 of the form C<-param value>.  Actually it's not quite arbitrary - we
484 prevent you from setting some parameters which would interfere with
485 parameters that we use.
486
487 The first character of C<param> string must be a C<-> (dash).
488
489 C<value> can be NULL.");
490
491   ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
492    [],
493    "set the qemu binary",
494    "\
495 Set the qemu binary that we will use.
496
497 The default is chosen when the library was compiled by the
498 configure script.
499
500 You can also override this by setting the C<LIBGUESTFS_QEMU>
501 environment variable.
502
503 Setting C<qemu> to C<NULL> restores the default qemu binary.");
504
505   ("get_qemu", (RConstString "qemu", []), -1, [],
506    [InitNone, Always, TestRun (
507       [["get_qemu"]])],
508    "get the qemu binary",
509    "\
510 Return the current qemu binary.
511
512 This is always non-NULL.  If it wasn't set already, then this will
513 return the default qemu binary name.");
514
515   ("set_path", (RErr, [String "path"]), -1, [FishAlias "path"],
516    [],
517    "set the search path",
518    "\
519 Set the path that libguestfs searches for kernel and initrd.img.
520
521 The default is C<$libdir/guestfs> unless overridden by setting
522 C<LIBGUESTFS_PATH> environment variable.
523
524 Setting C<path> to C<NULL> restores the default path.");
525
526   ("get_path", (RConstString "path", []), -1, [],
527    [InitNone, Always, TestRun (
528       [["get_path"]])],
529    "get the search path",
530    "\
531 Return the current search path.
532
533 This is always non-NULL.  If it wasn't set already, then this will
534 return the default path.");
535
536   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
537    [],
538    "add options to kernel command line",
539    "\
540 This function is used to add additional options to the
541 guest kernel command line.
542
543 The default is C<NULL> unless overridden by setting
544 C<LIBGUESTFS_APPEND> environment variable.
545
546 Setting C<append> to C<NULL> means I<no> additional options
547 are passed (libguestfs always adds a few of its own).");
548
549   ("get_append", (RConstOptString "append", []), -1, [],
550    (* This cannot be tested with the current framework.  The
551     * function can return NULL in normal operations, which the
552     * test framework interprets as an error.
553     *)
554    [],
555    "get the additional kernel options",
556    "\
557 Return the additional kernel options which are added to the
558 guest kernel command line.
559
560 If C<NULL> then no options are added.");
561
562   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
563    [],
564    "set autosync mode",
565    "\
566 If C<autosync> is true, this enables autosync.  Libguestfs will make a
567 best effort attempt to run C<guestfs_umount_all> followed by
568 C<guestfs_sync> when the handle is closed
569 (also if the program exits without closing handles).
570
571 This is disabled by default (except in guestfish where it is
572 enabled by default).");
573
574   ("get_autosync", (RBool "autosync", []), -1, [],
575    [InitNone, Always, TestRun (
576       [["get_autosync"]])],
577    "get autosync mode",
578    "\
579 Get the autosync flag.");
580
581   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
582    [],
583    "set verbose mode",
584    "\
585 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
586
587 Verbose messages are disabled unless the environment variable
588 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
589
590   ("get_verbose", (RBool "verbose", []), -1, [],
591    [],
592    "get verbose mode",
593    "\
594 This returns the verbose messages flag.");
595
596   ("is_ready", (RBool "ready", []), -1, [],
597    [InitNone, Always, TestOutputTrue (
598       [["is_ready"]])],
599    "is ready to accept commands",
600    "\
601 This returns true iff this handle is ready to accept commands
602 (in the C<READY> state).
603
604 For more information on states, see L<guestfs(3)>.");
605
606   ("is_config", (RBool "config", []), -1, [],
607    [InitNone, Always, TestOutputFalse (
608       [["is_config"]])],
609    "is in configuration state",
610    "\
611 This returns true iff this handle is being configured
612 (in the C<CONFIG> state).
613
614 For more information on states, see L<guestfs(3)>.");
615
616   ("is_launching", (RBool "launching", []), -1, [],
617    [InitNone, Always, TestOutputFalse (
618       [["is_launching"]])],
619    "is launching subprocess",
620    "\
621 This returns true iff this handle is launching the subprocess
622 (in the C<LAUNCHING> state).
623
624 For more information on states, see L<guestfs(3)>.");
625
626   ("is_busy", (RBool "busy", []), -1, [],
627    [InitNone, Always, TestOutputFalse (
628       [["is_busy"]])],
629    "is busy processing a command",
630    "\
631 This returns true iff this handle is busy processing a command
632 (in the C<BUSY> state).
633
634 For more information on states, see L<guestfs(3)>.");
635
636   ("get_state", (RInt "state", []), -1, [],
637    [],
638    "get the current state",
639    "\
640 This returns the current state as an opaque integer.  This is
641 only useful for printing debug and internal error messages.
642
643 For more information on states, see L<guestfs(3)>.");
644
645   ("set_busy", (RErr, []), -1, [NotInFish],
646    [],
647    "set state to busy",
648    "\
649 This sets the state to C<BUSY>.  This is only used when implementing
650 actions using the low-level API.
651
652 For more information on states, see L<guestfs(3)>.");
653
654   ("set_ready", (RErr, []), -1, [NotInFish],
655    [],
656    "set state to ready",
657    "\
658 This sets the state to C<READY>.  This is only used when implementing
659 actions using the low-level API.
660
661 For more information on states, see L<guestfs(3)>.");
662
663   ("end_busy", (RErr, []), -1, [NotInFish],
664    [],
665    "leave the busy state",
666    "\
667 This sets the state to C<READY>, or if in C<CONFIG> then it leaves the
668 state as is.  This is only used when implementing
669 actions using the low-level API.
670
671 For more information on states, see L<guestfs(3)>.");
672
673   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
674    [InitNone, Always, TestOutputInt (
675       [["set_memsize"; "500"];
676        ["get_memsize"]], 500)],
677    "set memory allocated to the qemu subprocess",
678    "\
679 This sets the memory size in megabytes allocated to the
680 qemu subprocess.  This only has any effect if called before
681 C<guestfs_launch>.
682
683 You can also change this by setting the environment
684 variable C<LIBGUESTFS_MEMSIZE> before the handle is
685 created.
686
687 For more information on the architecture of libguestfs,
688 see L<guestfs(3)>.");
689
690   ("get_memsize", (RInt "memsize", []), -1, [],
691    [InitNone, Always, TestOutputIntOp (
692       [["get_memsize"]], ">=", 256)],
693    "get memory allocated to the qemu subprocess",
694    "\
695 This gets the memory size in megabytes allocated to the
696 qemu subprocess.
697
698 If C<guestfs_set_memsize> was not called
699 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
700 then this returns the compiled-in default value for memsize.
701
702 For more information on the architecture of libguestfs,
703 see L<guestfs(3)>.");
704
705   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
706    [InitNone, Always, TestOutputIntOp (
707       [["get_pid"]], ">=", 1)],
708    "get PID of qemu subprocess",
709    "\
710 Return the process ID of the qemu subprocess.  If there is no
711 qemu subprocess, then this will return an error.
712
713 This is an internal call used for debugging and testing.");
714
715   ("version", (RStruct ("version", "version"), []), -1, [],
716    [InitNone, Always, TestOutputStruct (
717       [["version"]], [CompareWithInt ("major", 1)])],
718    "get the library version number",
719    "\
720 Return the libguestfs version number that the program is linked
721 against.
722
723 Note that because of dynamic linking this is not necessarily
724 the version of libguestfs that you compiled against.  You can
725 compile the program, and then at runtime dynamically link
726 against a completely different C<libguestfs.so> library.
727
728 This call was added in version C<1.0.58>.  In previous
729 versions of libguestfs there was no way to get the version
730 number.  From C code you can use ELF weak linking tricks to find out if
731 this symbol exists (if it doesn't, then it's an earlier version).
732
733 The call returns a structure with four elements.  The first
734 three (C<major>, C<minor> and C<release>) are numbers and
735 correspond to the usual version triplet.  The fourth element
736 (C<extra>) is a string and is normally empty, but may be
737 used for distro-specific information.
738
739 To construct the original version string:
740 C<$major.$minor.$release$extra>
741
742 I<Note:> Don't use this call to test for availability
743 of features.  Distro backports makes this unreliable.");
744
745 ]
746
747 (* daemon_functions are any functions which cause some action
748  * to take place in the daemon.
749  *)
750
751 let daemon_functions = [
752   ("mount", (RErr, [String "device"; String "mountpoint"]), 1, [],
753    [InitEmpty, Always, TestOutput (
754       [["sfdiskM"; "/dev/sda"; ","];
755        ["mkfs"; "ext2"; "/dev/sda1"];
756        ["mount"; "/dev/sda1"; "/"];
757        ["write_file"; "/new"; "new file contents"; "0"];
758        ["cat"; "/new"]], "new file contents")],
759    "mount a guest disk at a position in the filesystem",
760    "\
761 Mount a guest disk at a position in the filesystem.  Block devices
762 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
763 the guest.  If those block devices contain partitions, they will have
764 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
765 names can be used.
766
767 The rules are the same as for L<mount(2)>:  A filesystem must
768 first be mounted on C</> before others can be mounted.  Other
769 filesystems can only be mounted on directories which already
770 exist.
771
772 The mounted filesystem is writable, if we have sufficient permissions
773 on the underlying device.
774
775 The filesystem options C<sync> and C<noatime> are set with this
776 call, in order to improve reliability.");
777
778   ("sync", (RErr, []), 2, [],
779    [ InitEmpty, Always, TestRun [["sync"]]],
780    "sync disks, writes are flushed through to the disk image",
781    "\
782 This syncs the disk, so that any writes are flushed through to the
783 underlying disk image.
784
785 You should always call this if you have modified a disk image, before
786 closing the handle.");
787
788   ("touch", (RErr, [String "path"]), 3, [],
789    [InitBasicFS, Always, TestOutputTrue (
790       [["touch"; "/new"];
791        ["exists"; "/new"]])],
792    "update file timestamps or create a new file",
793    "\
794 Touch acts like the L<touch(1)> command.  It can be used to
795 update the timestamps on a file, or, if the file does not exist,
796 to create a new zero-length file.");
797
798   ("cat", (RString "content", [String "path"]), 4, [ProtocolLimitWarning],
799    [InitSquashFS, Always, TestOutput (
800       [["cat"; "/known-2"]], "abcdef\n")],
801    "list the contents of a file",
802    "\
803 Return the contents of the file named C<path>.
804
805 Note that this function cannot correctly handle binary files
806 (specifically, files containing C<\\0> character which is treated
807 as end of string).  For those you need to use the C<guestfs_read_file>
808 or C<guestfs_download> functions which have a more complex interface.");
809
810   ("ll", (RString "listing", [String "directory"]), 5, [],
811    [], (* XXX Tricky to test because it depends on the exact format
812         * of the 'ls -l' command, which changes between F10 and F11.
813         *)
814    "list the files in a directory (long format)",
815    "\
816 List the files in C<directory> (relative to the root directory,
817 there is no cwd) in the format of 'ls -la'.
818
819 This command is mostly useful for interactive sessions.  It
820 is I<not> intended that you try to parse the output string.");
821
822   ("ls", (RStringList "listing", [String "directory"]), 6, [],
823    [InitBasicFS, Always, TestOutputList (
824       [["touch"; "/new"];
825        ["touch"; "/newer"];
826        ["touch"; "/newest"];
827        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
828    "list the files in a directory",
829    "\
830 List the files in C<directory> (relative to the root directory,
831 there is no cwd).  The '.' and '..' entries are not returned, but
832 hidden files are shown.
833
834 This command is mostly useful for interactive sessions.  Programs
835 should probably use C<guestfs_readdir> instead.");
836
837   ("list_devices", (RStringList "devices", []), 7, [],
838    [InitEmpty, Always, TestOutputListOfDevices (
839       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
840    "list the block devices",
841    "\
842 List all the block devices.
843
844 The full block device names are returned, eg. C</dev/sda>");
845
846   ("list_partitions", (RStringList "partitions", []), 8, [],
847    [InitBasicFS, Always, TestOutputListOfDevices (
848       [["list_partitions"]], ["/dev/sda1"]);
849     InitEmpty, Always, TestOutputListOfDevices (
850       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
851        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
852    "list the partitions",
853    "\
854 List all the partitions detected on all block devices.
855
856 The full partition device names are returned, eg. C</dev/sda1>
857
858 This does not return logical volumes.  For that you will need to
859 call C<guestfs_lvs>.");
860
861   ("pvs", (RStringList "physvols", []), 9, [],
862    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
863       [["pvs"]], ["/dev/sda1"]);
864     InitEmpty, Always, TestOutputListOfDevices (
865       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
866        ["pvcreate"; "/dev/sda1"];
867        ["pvcreate"; "/dev/sda2"];
868        ["pvcreate"; "/dev/sda3"];
869        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
870    "list the LVM physical volumes (PVs)",
871    "\
872 List all the physical volumes detected.  This is the equivalent
873 of the L<pvs(8)> command.
874
875 This returns a list of just the device names that contain
876 PVs (eg. C</dev/sda2>).
877
878 See also C<guestfs_pvs_full>.");
879
880   ("vgs", (RStringList "volgroups", []), 10, [],
881    [InitBasicFSonLVM, Always, TestOutputList (
882       [["vgs"]], ["VG"]);
883     InitEmpty, Always, TestOutputList (
884       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
885        ["pvcreate"; "/dev/sda1"];
886        ["pvcreate"; "/dev/sda2"];
887        ["pvcreate"; "/dev/sda3"];
888        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
889        ["vgcreate"; "VG2"; "/dev/sda3"];
890        ["vgs"]], ["VG1"; "VG2"])],
891    "list the LVM volume groups (VGs)",
892    "\
893 List all the volumes groups detected.  This is the equivalent
894 of the L<vgs(8)> command.
895
896 This returns a list of just the volume group names that were
897 detected (eg. C<VolGroup00>).
898
899 See also C<guestfs_vgs_full>.");
900
901   ("lvs", (RStringList "logvols", []), 11, [],
902    [InitBasicFSonLVM, Always, TestOutputList (
903       [["lvs"]], ["/dev/VG/LV"]);
904     InitEmpty, Always, TestOutputList (
905       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
906        ["pvcreate"; "/dev/sda1"];
907        ["pvcreate"; "/dev/sda2"];
908        ["pvcreate"; "/dev/sda3"];
909        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
910        ["vgcreate"; "VG2"; "/dev/sda3"];
911        ["lvcreate"; "LV1"; "VG1"; "50"];
912        ["lvcreate"; "LV2"; "VG1"; "50"];
913        ["lvcreate"; "LV3"; "VG2"; "50"];
914        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
915    "list the LVM logical volumes (LVs)",
916    "\
917 List all the logical volumes detected.  This is the equivalent
918 of the L<lvs(8)> command.
919
920 This returns a list of the logical volume device names
921 (eg. C</dev/VolGroup00/LogVol00>).
922
923 See also C<guestfs_lvs_full>.");
924
925   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
926    [], (* XXX how to test? *)
927    "list the LVM physical volumes (PVs)",
928    "\
929 List all the physical volumes detected.  This is the equivalent
930 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
931
932   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
933    [], (* XXX how to test? *)
934    "list the LVM volume groups (VGs)",
935    "\
936 List all the volumes groups detected.  This is the equivalent
937 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
938
939   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
940    [], (* XXX how to test? *)
941    "list the LVM logical volumes (LVs)",
942    "\
943 List all the logical volumes detected.  This is the equivalent
944 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
945
946   ("read_lines", (RStringList "lines", [String "path"]), 15, [],
947    [InitSquashFS, Always, TestOutputList (
948       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
949     InitSquashFS, Always, TestOutputList (
950       [["read_lines"; "/empty"]], [])],
951    "read file as lines",
952    "\
953 Return the contents of the file named C<path>.
954
955 The file contents are returned as a list of lines.  Trailing
956 C<LF> and C<CRLF> character sequences are I<not> returned.
957
958 Note that this function cannot correctly handle binary files
959 (specifically, files containing C<\\0> character which is treated
960 as end of line).  For those you need to use the C<guestfs_read_file>
961 function which has a more complex interface.");
962
963   ("aug_init", (RErr, [String "root"; Int "flags"]), 16, [],
964    [], (* XXX Augeas code needs tests. *)
965    "create a new Augeas handle",
966    "\
967 Create a new Augeas handle for editing configuration files.
968 If there was any previous Augeas handle associated with this
969 guestfs session, then it is closed.
970
971 You must call this before using any other C<guestfs_aug_*>
972 commands.
973
974 C<root> is the filesystem root.  C<root> must not be NULL,
975 use C</> instead.
976
977 The flags are the same as the flags defined in
978 E<lt>augeas.hE<gt>, the logical I<or> of the following
979 integers:
980
981 =over 4
982
983 =item C<AUG_SAVE_BACKUP> = 1
984
985 Keep the original file with a C<.augsave> extension.
986
987 =item C<AUG_SAVE_NEWFILE> = 2
988
989 Save changes into a file with extension C<.augnew>, and
990 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
991
992 =item C<AUG_TYPE_CHECK> = 4
993
994 Typecheck lenses (can be expensive).
995
996 =item C<AUG_NO_STDINC> = 8
997
998 Do not use standard load path for modules.
999
1000 =item C<AUG_SAVE_NOOP> = 16
1001
1002 Make save a no-op, just record what would have been changed.
1003
1004 =item C<AUG_NO_LOAD> = 32
1005
1006 Do not load the tree in C<guestfs_aug_init>.
1007
1008 =back
1009
1010 To close the handle, you can call C<guestfs_aug_close>.
1011
1012 To find out more about Augeas, see L<http://augeas.net/>.");
1013
1014   ("aug_close", (RErr, []), 26, [],
1015    [], (* XXX Augeas code needs tests. *)
1016    "close the current Augeas handle",
1017    "\
1018 Close the current Augeas handle and free up any resources
1019 used by it.  After calling this, you have to call
1020 C<guestfs_aug_init> again before you can use any other
1021 Augeas functions.");
1022
1023   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
1024    [], (* XXX Augeas code needs tests. *)
1025    "define an Augeas variable",
1026    "\
1027 Defines an Augeas variable C<name> whose value is the result
1028 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1029 undefined.
1030
1031 On success this returns the number of nodes in C<expr>, or
1032 C<0> if C<expr> evaluates to something which is not a nodeset.");
1033
1034   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
1035    [], (* XXX Augeas code needs tests. *)
1036    "define an Augeas node",
1037    "\
1038 Defines a variable C<name> whose value is the result of
1039 evaluating C<expr>.
1040
1041 If C<expr> evaluates to an empty nodeset, a node is created,
1042 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1043 C<name> will be the nodeset containing that single node.
1044
1045 On success this returns a pair containing the
1046 number of nodes in the nodeset, and a boolean flag
1047 if a node was created.");
1048
1049   ("aug_get", (RString "val", [String "path"]), 19, [],
1050    [], (* XXX Augeas code needs tests. *)
1051    "look up the value of an Augeas path",
1052    "\
1053 Look up the value associated with C<path>.  If C<path>
1054 matches exactly one node, the C<value> is returned.");
1055
1056   ("aug_set", (RErr, [String "path"; String "val"]), 20, [],
1057    [], (* XXX Augeas code needs tests. *)
1058    "set Augeas path to value",
1059    "\
1060 Set the value associated with C<path> to C<value>.");
1061
1062   ("aug_insert", (RErr, [String "path"; String "label"; Bool "before"]), 21, [],
1063    [], (* XXX Augeas code needs tests. *)
1064    "insert a sibling Augeas node",
1065    "\
1066 Create a new sibling C<label> for C<path>, inserting it into
1067 the tree before or after C<path> (depending on the boolean
1068 flag C<before>).
1069
1070 C<path> must match exactly one existing node in the tree, and
1071 C<label> must be a label, ie. not contain C</>, C<*> or end
1072 with a bracketed index C<[N]>.");
1073
1074   ("aug_rm", (RInt "nrnodes", [String "path"]), 22, [],
1075    [], (* XXX Augeas code needs tests. *)
1076    "remove an Augeas path",
1077    "\
1078 Remove C<path> and all of its children.
1079
1080 On success this returns the number of entries which were removed.");
1081
1082   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
1083    [], (* XXX Augeas code needs tests. *)
1084    "move Augeas node",
1085    "\
1086 Move the node C<src> to C<dest>.  C<src> must match exactly
1087 one node.  C<dest> is overwritten if it exists.");
1088
1089   ("aug_match", (RStringList "matches", [String "path"]), 24, [],
1090    [], (* XXX Augeas code needs tests. *)
1091    "return Augeas nodes which match path",
1092    "\
1093 Returns a list of paths which match the path expression C<path>.
1094 The returned paths are sufficiently qualified so that they match
1095 exactly one node in the current tree.");
1096
1097   ("aug_save", (RErr, []), 25, [],
1098    [], (* XXX Augeas code needs tests. *)
1099    "write all pending Augeas changes to disk",
1100    "\
1101 This writes all pending changes to disk.
1102
1103 The flags which were passed to C<guestfs_aug_init> affect exactly
1104 how files are saved.");
1105
1106   ("aug_load", (RErr, []), 27, [],
1107    [], (* XXX Augeas code needs tests. *)
1108    "load files into the tree",
1109    "\
1110 Load files into the tree.
1111
1112 See C<aug_load> in the Augeas documentation for the full gory
1113 details.");
1114
1115   ("aug_ls", (RStringList "matches", [String "path"]), 28, [],
1116    [], (* XXX Augeas code needs tests. *)
1117    "list Augeas nodes under a path",
1118    "\
1119 This is just a shortcut for listing C<guestfs_aug_match>
1120 C<path/*> and sorting the resulting nodes into alphabetical order.");
1121
1122   ("rm", (RErr, [String "path"]), 29, [],
1123    [InitBasicFS, Always, TestRun
1124       [["touch"; "/new"];
1125        ["rm"; "/new"]];
1126     InitBasicFS, Always, TestLastFail
1127       [["rm"; "/new"]];
1128     InitBasicFS, Always, TestLastFail
1129       [["mkdir"; "/new"];
1130        ["rm"; "/new"]]],
1131    "remove a file",
1132    "\
1133 Remove the single file C<path>.");
1134
1135   ("rmdir", (RErr, [String "path"]), 30, [],
1136    [InitBasicFS, Always, TestRun
1137       [["mkdir"; "/new"];
1138        ["rmdir"; "/new"]];
1139     InitBasicFS, Always, TestLastFail
1140       [["rmdir"; "/new"]];
1141     InitBasicFS, Always, TestLastFail
1142       [["touch"; "/new"];
1143        ["rmdir"; "/new"]]],
1144    "remove a directory",
1145    "\
1146 Remove the single directory C<path>.");
1147
1148   ("rm_rf", (RErr, [String "path"]), 31, [],
1149    [InitBasicFS, Always, TestOutputFalse
1150       [["mkdir"; "/new"];
1151        ["mkdir"; "/new/foo"];
1152        ["touch"; "/new/foo/bar"];
1153        ["rm_rf"; "/new"];
1154        ["exists"; "/new"]]],
1155    "remove a file or directory recursively",
1156    "\
1157 Remove the file or directory C<path>, recursively removing the
1158 contents if its a directory.  This is like the C<rm -rf> shell
1159 command.");
1160
1161   ("mkdir", (RErr, [String "path"]), 32, [],
1162    [InitBasicFS, Always, TestOutputTrue
1163       [["mkdir"; "/new"];
1164        ["is_dir"; "/new"]];
1165     InitBasicFS, Always, TestLastFail
1166       [["mkdir"; "/new/foo/bar"]]],
1167    "create a directory",
1168    "\
1169 Create a directory named C<path>.");
1170
1171   ("mkdir_p", (RErr, [String "path"]), 33, [],
1172    [InitBasicFS, Always, TestOutputTrue
1173       [["mkdir_p"; "/new/foo/bar"];
1174        ["is_dir"; "/new/foo/bar"]];
1175     InitBasicFS, Always, TestOutputTrue
1176       [["mkdir_p"; "/new/foo/bar"];
1177        ["is_dir"; "/new/foo"]];
1178     InitBasicFS, Always, TestOutputTrue
1179       [["mkdir_p"; "/new/foo/bar"];
1180        ["is_dir"; "/new"]];
1181     (* Regression tests for RHBZ#503133: *)
1182     InitBasicFS, Always, TestRun
1183       [["mkdir"; "/new"];
1184        ["mkdir_p"; "/new"]];
1185     InitBasicFS, Always, TestLastFail
1186       [["touch"; "/new"];
1187        ["mkdir_p"; "/new"]]],
1188    "create a directory and parents",
1189    "\
1190 Create a directory named C<path>, creating any parent directories
1191 as necessary.  This is like the C<mkdir -p> shell command.");
1192
1193   ("chmod", (RErr, [Int "mode"; String "path"]), 34, [],
1194    [], (* XXX Need stat command to test *)
1195    "change file mode",
1196    "\
1197 Change the mode (permissions) of C<path> to C<mode>.  Only
1198 numeric modes are supported.");
1199
1200   ("chown", (RErr, [Int "owner"; Int "group"; String "path"]), 35, [],
1201    [], (* XXX Need stat command to test *)
1202    "change file owner and group",
1203    "\
1204 Change the file owner to C<owner> and group to C<group>.
1205
1206 Only numeric uid and gid are supported.  If you want to use
1207 names, you will need to locate and parse the password file
1208 yourself (Augeas support makes this relatively easy).");
1209
1210   ("exists", (RBool "existsflag", [String "path"]), 36, [],
1211    [InitSquashFS, Always, TestOutputTrue (
1212       [["exists"; "/empty"]]);
1213     InitSquashFS, Always, TestOutputTrue (
1214       [["exists"; "/directory"]])],
1215    "test if file or directory exists",
1216    "\
1217 This returns C<true> if and only if there is a file, directory
1218 (or anything) with the given C<path> name.
1219
1220 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1221
1222   ("is_file", (RBool "fileflag", [String "path"]), 37, [],
1223    [InitSquashFS, Always, TestOutputTrue (
1224       [["is_file"; "/known-1"]]);
1225     InitSquashFS, Always, TestOutputFalse (
1226       [["is_file"; "/directory"]])],
1227    "test if file exists",
1228    "\
1229 This returns C<true> if and only if there is a file
1230 with the given C<path> name.  Note that it returns false for
1231 other objects like directories.
1232
1233 See also C<guestfs_stat>.");
1234
1235   ("is_dir", (RBool "dirflag", [String "path"]), 38, [],
1236    [InitSquashFS, Always, TestOutputFalse (
1237       [["is_dir"; "/known-3"]]);
1238     InitSquashFS, Always, TestOutputTrue (
1239       [["is_dir"; "/directory"]])],
1240    "test if file exists",
1241    "\
1242 This returns C<true> if and only if there is a directory
1243 with the given C<path> name.  Note that it returns false for
1244 other objects like files.
1245
1246 See also C<guestfs_stat>.");
1247
1248   ("pvcreate", (RErr, [String "device"]), 39, [],
1249    [InitEmpty, Always, TestOutputListOfDevices (
1250       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1251        ["pvcreate"; "/dev/sda1"];
1252        ["pvcreate"; "/dev/sda2"];
1253        ["pvcreate"; "/dev/sda3"];
1254        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1255    "create an LVM physical volume",
1256    "\
1257 This creates an LVM physical volume on the named C<device>,
1258 where C<device> should usually be a partition name such
1259 as C</dev/sda1>.");
1260
1261   ("vgcreate", (RErr, [String "volgroup"; StringList "physvols"]), 40, [],
1262    [InitEmpty, Always, TestOutputList (
1263       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1264        ["pvcreate"; "/dev/sda1"];
1265        ["pvcreate"; "/dev/sda2"];
1266        ["pvcreate"; "/dev/sda3"];
1267        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1268        ["vgcreate"; "VG2"; "/dev/sda3"];
1269        ["vgs"]], ["VG1"; "VG2"])],
1270    "create an LVM volume group",
1271    "\
1272 This creates an LVM volume group called C<volgroup>
1273 from the non-empty list of physical volumes C<physvols>.");
1274
1275   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1276    [InitEmpty, Always, TestOutputList (
1277       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1278        ["pvcreate"; "/dev/sda1"];
1279        ["pvcreate"; "/dev/sda2"];
1280        ["pvcreate"; "/dev/sda3"];
1281        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1282        ["vgcreate"; "VG2"; "/dev/sda3"];
1283        ["lvcreate"; "LV1"; "VG1"; "50"];
1284        ["lvcreate"; "LV2"; "VG1"; "50"];
1285        ["lvcreate"; "LV3"; "VG2"; "50"];
1286        ["lvcreate"; "LV4"; "VG2"; "50"];
1287        ["lvcreate"; "LV5"; "VG2"; "50"];
1288        ["lvs"]],
1289       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1290        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1291    "create an LVM volume group",
1292    "\
1293 This creates an LVM volume group called C<logvol>
1294 on the volume group C<volgroup>, with C<size> megabytes.");
1295
1296   ("mkfs", (RErr, [String "fstype"; String "device"]), 42, [],
1297    [InitEmpty, Always, TestOutput (
1298       [["sfdiskM"; "/dev/sda"; ","];
1299        ["mkfs"; "ext2"; "/dev/sda1"];
1300        ["mount"; "/dev/sda1"; "/"];
1301        ["write_file"; "/new"; "new file contents"; "0"];
1302        ["cat"; "/new"]], "new file contents")],
1303    "make a filesystem",
1304    "\
1305 This creates a filesystem on C<device> (usually a partition
1306 or LVM logical volume).  The filesystem type is C<fstype>, for
1307 example C<ext3>.");
1308
1309   ("sfdisk", (RErr, [String "device";
1310                      Int "cyls"; Int "heads"; Int "sectors";
1311                      StringList "lines"]), 43, [DangerWillRobinson],
1312    [],
1313    "create partitions on a block device",
1314    "\
1315 This is a direct interface to the L<sfdisk(8)> program for creating
1316 partitions on block devices.
1317
1318 C<device> should be a block device, for example C</dev/sda>.
1319
1320 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1321 and sectors on the device, which are passed directly to sfdisk as
1322 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1323 of these, then the corresponding parameter is omitted.  Usually for
1324 'large' disks, you can just pass C<0> for these, but for small
1325 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1326 out the right geometry and you will need to tell it.
1327
1328 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1329 information refer to the L<sfdisk(8)> manpage.
1330
1331 To create a single partition occupying the whole disk, you would
1332 pass C<lines> as a single element list, when the single element being
1333 the string C<,> (comma).
1334
1335 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1336
1337   ("write_file", (RErr, [String "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1338    [InitBasicFS, Always, TestOutput (
1339       [["write_file"; "/new"; "new file contents"; "0"];
1340        ["cat"; "/new"]], "new file contents");
1341     InitBasicFS, Always, TestOutput (
1342       [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1343        ["cat"; "/new"]], "\nnew file contents\n");
1344     InitBasicFS, Always, TestOutput (
1345       [["write_file"; "/new"; "\n\n"; "0"];
1346        ["cat"; "/new"]], "\n\n");
1347     InitBasicFS, Always, TestOutput (
1348       [["write_file"; "/new"; ""; "0"];
1349        ["cat"; "/new"]], "");
1350     InitBasicFS, Always, TestOutput (
1351       [["write_file"; "/new"; "\n\n\n"; "0"];
1352        ["cat"; "/new"]], "\n\n\n");
1353     InitBasicFS, Always, TestOutput (
1354       [["write_file"; "/new"; "\n"; "0"];
1355        ["cat"; "/new"]], "\n")],
1356    "create a file",
1357    "\
1358 This call creates a file called C<path>.  The contents of the
1359 file is the string C<content> (which can contain any 8 bit data),
1360 with length C<size>.
1361
1362 As a special case, if C<size> is C<0>
1363 then the length is calculated using C<strlen> (so in this case
1364 the content cannot contain embedded ASCII NULs).
1365
1366 I<NB.> Owing to a bug, writing content containing ASCII NUL
1367 characters does I<not> work, even if the length is specified.
1368 We hope to resolve this bug in a future version.  In the meantime
1369 use C<guestfs_upload>.");
1370
1371   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1372    [InitEmpty, Always, TestOutputListOfDevices (
1373       [["sfdiskM"; "/dev/sda"; ","];
1374        ["mkfs"; "ext2"; "/dev/sda1"];
1375        ["mount"; "/dev/sda1"; "/"];
1376        ["mounts"]], ["/dev/sda1"]);
1377     InitEmpty, Always, TestOutputList (
1378       [["sfdiskM"; "/dev/sda"; ","];
1379        ["mkfs"; "ext2"; "/dev/sda1"];
1380        ["mount"; "/dev/sda1"; "/"];
1381        ["umount"; "/"];
1382        ["mounts"]], [])],
1383    "unmount a filesystem",
1384    "\
1385 This unmounts the given filesystem.  The filesystem may be
1386 specified either by its mountpoint (path) or the device which
1387 contains the filesystem.");
1388
1389   ("mounts", (RStringList "devices", []), 46, [],
1390    [InitBasicFS, Always, TestOutputListOfDevices (
1391       [["mounts"]], ["/dev/sda1"])],
1392    "show mounted filesystems",
1393    "\
1394 This returns the list of currently mounted filesystems.  It returns
1395 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1396
1397 Some internal mounts are not shown.
1398
1399 See also: C<guestfs_mountpoints>");
1400
1401   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1402    [InitBasicFS, Always, TestOutputList (
1403       [["umount_all"];
1404        ["mounts"]], []);
1405     (* check that umount_all can unmount nested mounts correctly: *)
1406     InitEmpty, Always, TestOutputList (
1407       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1408        ["mkfs"; "ext2"; "/dev/sda1"];
1409        ["mkfs"; "ext2"; "/dev/sda2"];
1410        ["mkfs"; "ext2"; "/dev/sda3"];
1411        ["mount"; "/dev/sda1"; "/"];
1412        ["mkdir"; "/mp1"];
1413        ["mount"; "/dev/sda2"; "/mp1"];
1414        ["mkdir"; "/mp1/mp2"];
1415        ["mount"; "/dev/sda3"; "/mp1/mp2"];
1416        ["mkdir"; "/mp1/mp2/mp3"];
1417        ["umount_all"];
1418        ["mounts"]], [])],
1419    "unmount all filesystems",
1420    "\
1421 This unmounts all mounted filesystems.
1422
1423 Some internal mounts are not unmounted by this call.");
1424
1425   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1426    [],
1427    "remove all LVM LVs, VGs and PVs",
1428    "\
1429 This command removes all LVM logical volumes, volume groups
1430 and physical volumes.");
1431
1432   ("file", (RString "description", [String "path"]), 49, [],
1433    [InitSquashFS, Always, TestOutput (
1434       [["file"; "/empty"]], "empty");
1435     InitSquashFS, Always, TestOutput (
1436       [["file"; "/known-1"]], "ASCII text");
1437     InitSquashFS, Always, TestLastFail (
1438       [["file"; "/notexists"]])],
1439    "determine file type",
1440    "\
1441 This call uses the standard L<file(1)> command to determine
1442 the type or contents of the file.  This also works on devices,
1443 for example to find out whether a partition contains a filesystem.
1444
1445 This call will also transparently look inside various types
1446 of compressed file.
1447
1448 The exact command which runs is C<file -zbsL path>.  Note in
1449 particular that the filename is not prepended to the output
1450 (the C<-b> option).");
1451
1452   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1453    [InitBasicFS, Always, TestOutput (
1454       [["upload"; "test-command"; "/test-command"];
1455        ["chmod"; "0o755"; "/test-command"];
1456        ["command"; "/test-command 1"]], "Result1");
1457     InitBasicFS, Always, TestOutput (
1458       [["upload"; "test-command"; "/test-command"];
1459        ["chmod"; "0o755"; "/test-command"];
1460        ["command"; "/test-command 2"]], "Result2\n");
1461     InitBasicFS, Always, TestOutput (
1462       [["upload"; "test-command"; "/test-command"];
1463        ["chmod"; "0o755"; "/test-command"];
1464        ["command"; "/test-command 3"]], "\nResult3");
1465     InitBasicFS, Always, TestOutput (
1466       [["upload"; "test-command"; "/test-command"];
1467        ["chmod"; "0o755"; "/test-command"];
1468        ["command"; "/test-command 4"]], "\nResult4\n");
1469     InitBasicFS, Always, TestOutput (
1470       [["upload"; "test-command"; "/test-command"];
1471        ["chmod"; "0o755"; "/test-command"];
1472        ["command"; "/test-command 5"]], "\nResult5\n\n");
1473     InitBasicFS, Always, TestOutput (
1474       [["upload"; "test-command"; "/test-command"];
1475        ["chmod"; "0o755"; "/test-command"];
1476        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1477     InitBasicFS, Always, TestOutput (
1478       [["upload"; "test-command"; "/test-command"];
1479        ["chmod"; "0o755"; "/test-command"];
1480        ["command"; "/test-command 7"]], "");
1481     InitBasicFS, Always, TestOutput (
1482       [["upload"; "test-command"; "/test-command"];
1483        ["chmod"; "0o755"; "/test-command"];
1484        ["command"; "/test-command 8"]], "\n");
1485     InitBasicFS, Always, TestOutput (
1486       [["upload"; "test-command"; "/test-command"];
1487        ["chmod"; "0o755"; "/test-command"];
1488        ["command"; "/test-command 9"]], "\n\n");
1489     InitBasicFS, Always, TestOutput (
1490       [["upload"; "test-command"; "/test-command"];
1491        ["chmod"; "0o755"; "/test-command"];
1492        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1493     InitBasicFS, Always, TestOutput (
1494       [["upload"; "test-command"; "/test-command"];
1495        ["chmod"; "0o755"; "/test-command"];
1496        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1497     InitBasicFS, Always, TestLastFail (
1498       [["upload"; "test-command"; "/test-command"];
1499        ["chmod"; "0o755"; "/test-command"];
1500        ["command"; "/test-command"]])],
1501    "run a command from the guest filesystem",
1502    "\
1503 This call runs a command from the guest filesystem.  The
1504 filesystem must be mounted, and must contain a compatible
1505 operating system (ie. something Linux, with the same
1506 or compatible processor architecture).
1507
1508 The single parameter is an argv-style list of arguments.
1509 The first element is the name of the program to run.
1510 Subsequent elements are parameters.  The list must be
1511 non-empty (ie. must contain a program name).  Note that
1512 the command runs directly, and is I<not> invoked via
1513 the shell (see C<guestfs_sh>).
1514
1515 The return value is anything printed to I<stdout> by
1516 the command.
1517
1518 If the command returns a non-zero exit status, then
1519 this function returns an error message.  The error message
1520 string is the content of I<stderr> from the command.
1521
1522 The C<$PATH> environment variable will contain at least
1523 C</usr/bin> and C</bin>.  If you require a program from
1524 another location, you should provide the full path in the
1525 first parameter.
1526
1527 Shared libraries and data files required by the program
1528 must be available on filesystems which are mounted in the
1529 correct places.  It is the caller's responsibility to ensure
1530 all filesystems that are needed are mounted at the right
1531 locations.");
1532
1533   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1534    [InitBasicFS, Always, TestOutputList (
1535       [["upload"; "test-command"; "/test-command"];
1536        ["chmod"; "0o755"; "/test-command"];
1537        ["command_lines"; "/test-command 1"]], ["Result1"]);
1538     InitBasicFS, Always, TestOutputList (
1539       [["upload"; "test-command"; "/test-command"];
1540        ["chmod"; "0o755"; "/test-command"];
1541        ["command_lines"; "/test-command 2"]], ["Result2"]);
1542     InitBasicFS, Always, TestOutputList (
1543       [["upload"; "test-command"; "/test-command"];
1544        ["chmod"; "0o755"; "/test-command"];
1545        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1546     InitBasicFS, Always, TestOutputList (
1547       [["upload"; "test-command"; "/test-command"];
1548        ["chmod"; "0o755"; "/test-command"];
1549        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1550     InitBasicFS, Always, TestOutputList (
1551       [["upload"; "test-command"; "/test-command"];
1552        ["chmod"; "0o755"; "/test-command"];
1553        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1554     InitBasicFS, Always, TestOutputList (
1555       [["upload"; "test-command"; "/test-command"];
1556        ["chmod"; "0o755"; "/test-command"];
1557        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1558     InitBasicFS, Always, TestOutputList (
1559       [["upload"; "test-command"; "/test-command"];
1560        ["chmod"; "0o755"; "/test-command"];
1561        ["command_lines"; "/test-command 7"]], []);
1562     InitBasicFS, Always, TestOutputList (
1563       [["upload"; "test-command"; "/test-command"];
1564        ["chmod"; "0o755"; "/test-command"];
1565        ["command_lines"; "/test-command 8"]], [""]);
1566     InitBasicFS, Always, TestOutputList (
1567       [["upload"; "test-command"; "/test-command"];
1568        ["chmod"; "0o755"; "/test-command"];
1569        ["command_lines"; "/test-command 9"]], ["";""]);
1570     InitBasicFS, Always, TestOutputList (
1571       [["upload"; "test-command"; "/test-command"];
1572        ["chmod"; "0o755"; "/test-command"];
1573        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1574     InitBasicFS, Always, TestOutputList (
1575       [["upload"; "test-command"; "/test-command"];
1576        ["chmod"; "0o755"; "/test-command"];
1577        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1578    "run a command, returning lines",
1579    "\
1580 This is the same as C<guestfs_command>, but splits the
1581 result into a list of lines.
1582
1583 See also: C<guestfs_sh_lines>");
1584
1585   ("stat", (RStruct ("statbuf", "stat"), [String "path"]), 52, [],
1586    [InitSquashFS, Always, TestOutputStruct (
1587       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
1588    "get file information",
1589    "\
1590 Returns file information for the given C<path>.
1591
1592 This is the same as the C<stat(2)> system call.");
1593
1594   ("lstat", (RStruct ("statbuf", "stat"), [String "path"]), 53, [],
1595    [InitSquashFS, Always, TestOutputStruct (
1596       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
1597    "get file information for a symbolic link",
1598    "\
1599 Returns file information for the given C<path>.
1600
1601 This is the same as C<guestfs_stat> except that if C<path>
1602 is a symbolic link, then the link is stat-ed, not the file it
1603 refers to.
1604
1605 This is the same as the C<lstat(2)> system call.");
1606
1607   ("statvfs", (RStruct ("statbuf", "statvfs"), [String "path"]), 54, [],
1608    [InitSquashFS, Always, TestOutputStruct (
1609       [["statvfs"; "/"]], [CompareWithInt ("namemax", 256);
1610                            CompareWithInt ("bsize", 131072)])],
1611    "get file system statistics",
1612    "\
1613 Returns file system statistics for any mounted file system.
1614 C<path> should be a file or directory in the mounted file system
1615 (typically it is the mount point itself, but it doesn't need to be).
1616
1617 This is the same as the C<statvfs(2)> system call.");
1618
1619   ("tune2fs_l", (RHashtable "superblock", [String "device"]), 55, [],
1620    [], (* XXX test *)
1621    "get ext2/ext3/ext4 superblock details",
1622    "\
1623 This returns the contents of the ext2, ext3 or ext4 filesystem
1624 superblock on C<device>.
1625
1626 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
1627 manpage for more details.  The list of fields returned isn't
1628 clearly defined, and depends on both the version of C<tune2fs>
1629 that libguestfs was built against, and the filesystem itself.");
1630
1631   ("blockdev_setro", (RErr, [String "device"]), 56, [],
1632    [InitEmpty, Always, TestOutputTrue (
1633       [["blockdev_setro"; "/dev/sda"];
1634        ["blockdev_getro"; "/dev/sda"]])],
1635    "set block device to read-only",
1636    "\
1637 Sets the block device named C<device> to read-only.
1638
1639 This uses the L<blockdev(8)> command.");
1640
1641   ("blockdev_setrw", (RErr, [String "device"]), 57, [],
1642    [InitEmpty, Always, TestOutputFalse (
1643       [["blockdev_setrw"; "/dev/sda"];
1644        ["blockdev_getro"; "/dev/sda"]])],
1645    "set block device to read-write",
1646    "\
1647 Sets the block device named C<device> to read-write.
1648
1649 This uses the L<blockdev(8)> command.");
1650
1651   ("blockdev_getro", (RBool "ro", [String "device"]), 58, [],
1652    [InitEmpty, Always, TestOutputTrue (
1653       [["blockdev_setro"; "/dev/sda"];
1654        ["blockdev_getro"; "/dev/sda"]])],
1655    "is block device set to read-only",
1656    "\
1657 Returns a boolean indicating if the block device is read-only
1658 (true if read-only, false if not).
1659
1660 This uses the L<blockdev(8)> command.");
1661
1662   ("blockdev_getss", (RInt "sectorsize", [String "device"]), 59, [],
1663    [InitEmpty, Always, TestOutputInt (
1664       [["blockdev_getss"; "/dev/sda"]], 512)],
1665    "get sectorsize of block device",
1666    "\
1667 This returns the size of sectors on a block device.
1668 Usually 512, but can be larger for modern devices.
1669
1670 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1671 for that).
1672
1673 This uses the L<blockdev(8)> command.");
1674
1675   ("blockdev_getbsz", (RInt "blocksize", [String "device"]), 60, [],
1676    [InitEmpty, Always, TestOutputInt (
1677       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1678    "get blocksize of block device",
1679    "\
1680 This returns the block size of a device.
1681
1682 (Note this is different from both I<size in blocks> and
1683 I<filesystem block size>).
1684
1685 This uses the L<blockdev(8)> command.");
1686
1687   ("blockdev_setbsz", (RErr, [String "device"; Int "blocksize"]), 61, [],
1688    [], (* XXX test *)
1689    "set blocksize of block device",
1690    "\
1691 This sets the block size of a device.
1692
1693 (Note this is different from both I<size in blocks> and
1694 I<filesystem block size>).
1695
1696 This uses the L<blockdev(8)> command.");
1697
1698   ("blockdev_getsz", (RInt64 "sizeinsectors", [String "device"]), 62, [],
1699    [InitEmpty, Always, TestOutputInt (
1700       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1701    "get total size of device in 512-byte sectors",
1702    "\
1703 This returns the size of the device in units of 512-byte sectors
1704 (even if the sectorsize isn't 512 bytes ... weird).
1705
1706 See also C<guestfs_blockdev_getss> for the real sector size of
1707 the device, and C<guestfs_blockdev_getsize64> for the more
1708 useful I<size in bytes>.
1709
1710 This uses the L<blockdev(8)> command.");
1711
1712   ("blockdev_getsize64", (RInt64 "sizeinbytes", [String "device"]), 63, [],
1713    [InitEmpty, Always, TestOutputInt (
1714       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1715    "get total size of device in bytes",
1716    "\
1717 This returns the size of the device in bytes.
1718
1719 See also C<guestfs_blockdev_getsz>.
1720
1721 This uses the L<blockdev(8)> command.");
1722
1723   ("blockdev_flushbufs", (RErr, [String "device"]), 64, [],
1724    [InitEmpty, Always, TestRun
1725       [["blockdev_flushbufs"; "/dev/sda"]]],
1726    "flush device buffers",
1727    "\
1728 This tells the kernel to flush internal buffers associated
1729 with C<device>.
1730
1731 This uses the L<blockdev(8)> command.");
1732
1733   ("blockdev_rereadpt", (RErr, [String "device"]), 65, [],
1734    [InitEmpty, Always, TestRun
1735       [["blockdev_rereadpt"; "/dev/sda"]]],
1736    "reread partition table",
1737    "\
1738 Reread the partition table on C<device>.
1739
1740 This uses the L<blockdev(8)> command.");
1741
1742   ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1743    [InitBasicFS, Always, TestOutput (
1744       (* Pick a file from cwd which isn't likely to change. *)
1745       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1746        ["checksum"; "md5"; "/COPYING.LIB"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1747    "upload a file from the local machine",
1748    "\
1749 Upload local file C<filename> to C<remotefilename> on the
1750 filesystem.
1751
1752 C<filename> can also be a named pipe.
1753
1754 See also C<guestfs_download>.");
1755
1756   ("download", (RErr, [String "remotefilename"; FileOut "filename"]), 67, [],
1757    [InitBasicFS, Always, TestOutput (
1758       (* Pick a file from cwd which isn't likely to change. *)
1759       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1760        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1761        ["upload"; "testdownload.tmp"; "/upload"];
1762        ["checksum"; "md5"; "/upload"]], "e3eda01d9815f8d24aae2dbd89b68b06")],
1763    "download a file to the local machine",
1764    "\
1765 Download file C<remotefilename> and save it as C<filename>
1766 on the local machine.
1767
1768 C<filename> can also be a named pipe.
1769
1770 See also C<guestfs_upload>, C<guestfs_cat>.");
1771
1772   ("checksum", (RString "checksum", [String "csumtype"; String "path"]), 68, [],
1773    [InitSquashFS, Always, TestOutput (
1774       [["checksum"; "crc"; "/known-3"]], "2891671662");
1775     InitSquashFS, Always, TestLastFail (
1776       [["checksum"; "crc"; "/notexists"]]);
1777     InitSquashFS, Always, TestOutput (
1778       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
1779     InitSquashFS, Always, TestOutput (
1780       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
1781     InitSquashFS, Always, TestOutput (
1782       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
1783     InitSquashFS, Always, TestOutput (
1784       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
1785     InitSquashFS, Always, TestOutput (
1786       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
1787     InitSquashFS, Always, TestOutput (
1788       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6")],
1789    "compute MD5, SHAx or CRC checksum of file",
1790    "\
1791 This call computes the MD5, SHAx or CRC checksum of the
1792 file named C<path>.
1793
1794 The type of checksum to compute is given by the C<csumtype>
1795 parameter which must have one of the following values:
1796
1797 =over 4
1798
1799 =item C<crc>
1800
1801 Compute the cyclic redundancy check (CRC) specified by POSIX
1802 for the C<cksum> command.
1803
1804 =item C<md5>
1805
1806 Compute the MD5 hash (using the C<md5sum> program).
1807
1808 =item C<sha1>
1809
1810 Compute the SHA1 hash (using the C<sha1sum> program).
1811
1812 =item C<sha224>
1813
1814 Compute the SHA224 hash (using the C<sha224sum> program).
1815
1816 =item C<sha256>
1817
1818 Compute the SHA256 hash (using the C<sha256sum> program).
1819
1820 =item C<sha384>
1821
1822 Compute the SHA384 hash (using the C<sha384sum> program).
1823
1824 =item C<sha512>
1825
1826 Compute the SHA512 hash (using the C<sha512sum> program).
1827
1828 =back
1829
1830 The checksum is returned as a printable string.");
1831
1832   ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1833    [InitBasicFS, Always, TestOutput (
1834       [["tar_in"; "../images/helloworld.tar"; "/"];
1835        ["cat"; "/hello"]], "hello\n")],
1836    "unpack tarfile to directory",
1837    "\
1838 This command uploads and unpacks local file C<tarfile> (an
1839 I<uncompressed> tar file) into C<directory>.
1840
1841 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1842
1843   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1844    [],
1845    "pack directory into tarfile",
1846    "\
1847 This command packs the contents of C<directory> and downloads
1848 it to local file C<tarfile>.
1849
1850 To download a compressed tarball, use C<guestfs_tgz_out>.");
1851
1852   ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1853    [InitBasicFS, Always, TestOutput (
1854       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1855        ["cat"; "/hello"]], "hello\n")],
1856    "unpack compressed tarball to directory",
1857    "\
1858 This command uploads and unpacks local file C<tarball> (a
1859 I<gzip compressed> tar file) into C<directory>.
1860
1861 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1862
1863   ("tgz_out", (RErr, [String "directory"; FileOut "tarball"]), 72, [],
1864    [],
1865    "pack directory into compressed tarball",
1866    "\
1867 This command packs the contents of C<directory> and downloads
1868 it to local file C<tarball>.
1869
1870 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1871
1872   ("mount_ro", (RErr, [String "device"; String "mountpoint"]), 73, [],
1873    [InitBasicFS, Always, TestLastFail (
1874       [["umount"; "/"];
1875        ["mount_ro"; "/dev/sda1"; "/"];
1876        ["touch"; "/new"]]);
1877     InitBasicFS, Always, TestOutput (
1878       [["write_file"; "/new"; "data"; "0"];
1879        ["umount"; "/"];
1880        ["mount_ro"; "/dev/sda1"; "/"];
1881        ["cat"; "/new"]], "data")],
1882    "mount a guest disk, read-only",
1883    "\
1884 This is the same as the C<guestfs_mount> command, but it
1885 mounts the filesystem with the read-only (I<-o ro>) flag.");
1886
1887   ("mount_options", (RErr, [String "options"; String "device"; String "mountpoint"]), 74, [],
1888    [],
1889    "mount a guest disk with mount options",
1890    "\
1891 This is the same as the C<guestfs_mount> command, but it
1892 allows you to set the mount options as for the
1893 L<mount(8)> I<-o> flag.");
1894
1895   ("mount_vfs", (RErr, [String "options"; String "vfstype"; String "device"; String "mountpoint"]), 75, [],
1896    [],
1897    "mount a guest disk with mount options and vfstype",
1898    "\
1899 This is the same as the C<guestfs_mount> command, but it
1900 allows you to set both the mount options and the vfstype
1901 as for the L<mount(8)> I<-o> and I<-t> flags.");
1902
1903   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
1904    [],
1905    "debugging and internals",
1906    "\
1907 The C<guestfs_debug> command exposes some internals of
1908 C<guestfsd> (the guestfs daemon) that runs inside the
1909 qemu subprocess.
1910
1911 There is no comprehensive help for this command.  You have
1912 to look at the file C<daemon/debug.c> in the libguestfs source
1913 to find out what you can do.");
1914
1915   ("lvremove", (RErr, [String "device"]), 77, [],
1916    [InitEmpty, Always, TestOutputList (
1917       [["sfdiskM"; "/dev/sda"; ","];
1918        ["pvcreate"; "/dev/sda1"];
1919        ["vgcreate"; "VG"; "/dev/sda1"];
1920        ["lvcreate"; "LV1"; "VG"; "50"];
1921        ["lvcreate"; "LV2"; "VG"; "50"];
1922        ["lvremove"; "/dev/VG/LV1"];
1923        ["lvs"]], ["/dev/VG/LV2"]);
1924     InitEmpty, Always, TestOutputList (
1925       [["sfdiskM"; "/dev/sda"; ","];
1926        ["pvcreate"; "/dev/sda1"];
1927        ["vgcreate"; "VG"; "/dev/sda1"];
1928        ["lvcreate"; "LV1"; "VG"; "50"];
1929        ["lvcreate"; "LV2"; "VG"; "50"];
1930        ["lvremove"; "/dev/VG"];
1931        ["lvs"]], []);
1932     InitEmpty, Always, TestOutputList (
1933       [["sfdiskM"; "/dev/sda"; ","];
1934        ["pvcreate"; "/dev/sda1"];
1935        ["vgcreate"; "VG"; "/dev/sda1"];
1936        ["lvcreate"; "LV1"; "VG"; "50"];
1937        ["lvcreate"; "LV2"; "VG"; "50"];
1938        ["lvremove"; "/dev/VG"];
1939        ["vgs"]], ["VG"])],
1940    "remove an LVM logical volume",
1941    "\
1942 Remove an LVM logical volume C<device>, where C<device> is
1943 the path to the LV, such as C</dev/VG/LV>.
1944
1945 You can also remove all LVs in a volume group by specifying
1946 the VG name, C</dev/VG>.");
1947
1948   ("vgremove", (RErr, [String "vgname"]), 78, [],
1949    [InitEmpty, Always, TestOutputList (
1950       [["sfdiskM"; "/dev/sda"; ","];
1951        ["pvcreate"; "/dev/sda1"];
1952        ["vgcreate"; "VG"; "/dev/sda1"];
1953        ["lvcreate"; "LV1"; "VG"; "50"];
1954        ["lvcreate"; "LV2"; "VG"; "50"];
1955        ["vgremove"; "VG"];
1956        ["lvs"]], []);
1957     InitEmpty, Always, TestOutputList (
1958       [["sfdiskM"; "/dev/sda"; ","];
1959        ["pvcreate"; "/dev/sda1"];
1960        ["vgcreate"; "VG"; "/dev/sda1"];
1961        ["lvcreate"; "LV1"; "VG"; "50"];
1962        ["lvcreate"; "LV2"; "VG"; "50"];
1963        ["vgremove"; "VG"];
1964        ["vgs"]], [])],
1965    "remove an LVM volume group",
1966    "\
1967 Remove an LVM volume group C<vgname>, (for example C<VG>).
1968
1969 This also forcibly removes all logical volumes in the volume
1970 group (if any).");
1971
1972   ("pvremove", (RErr, [String "device"]), 79, [],
1973    [InitEmpty, Always, TestOutputListOfDevices (
1974       [["sfdiskM"; "/dev/sda"; ","];
1975        ["pvcreate"; "/dev/sda1"];
1976        ["vgcreate"; "VG"; "/dev/sda1"];
1977        ["lvcreate"; "LV1"; "VG"; "50"];
1978        ["lvcreate"; "LV2"; "VG"; "50"];
1979        ["vgremove"; "VG"];
1980        ["pvremove"; "/dev/sda1"];
1981        ["lvs"]], []);
1982     InitEmpty, Always, TestOutputListOfDevices (
1983       [["sfdiskM"; "/dev/sda"; ","];
1984        ["pvcreate"; "/dev/sda1"];
1985        ["vgcreate"; "VG"; "/dev/sda1"];
1986        ["lvcreate"; "LV1"; "VG"; "50"];
1987        ["lvcreate"; "LV2"; "VG"; "50"];
1988        ["vgremove"; "VG"];
1989        ["pvremove"; "/dev/sda1"];
1990        ["vgs"]], []);
1991     InitEmpty, Always, TestOutputListOfDevices (
1992       [["sfdiskM"; "/dev/sda"; ","];
1993        ["pvcreate"; "/dev/sda1"];
1994        ["vgcreate"; "VG"; "/dev/sda1"];
1995        ["lvcreate"; "LV1"; "VG"; "50"];
1996        ["lvcreate"; "LV2"; "VG"; "50"];
1997        ["vgremove"; "VG"];
1998        ["pvremove"; "/dev/sda1"];
1999        ["pvs"]], [])],
2000    "remove an LVM physical volume",
2001    "\
2002 This wipes a physical volume C<device> so that LVM will no longer
2003 recognise it.
2004
2005 The implementation uses the C<pvremove> command which refuses to
2006 wipe physical volumes that contain any volume groups, so you have
2007 to remove those first.");
2008
2009   ("set_e2label", (RErr, [String "device"; String "label"]), 80, [],
2010    [InitBasicFS, Always, TestOutput (
2011       [["set_e2label"; "/dev/sda1"; "testlabel"];
2012        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2013    "set the ext2/3/4 filesystem label",
2014    "\
2015 This sets the ext2/3/4 filesystem label of the filesystem on
2016 C<device> to C<label>.  Filesystem labels are limited to
2017 16 characters.
2018
2019 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2020 to return the existing label on a filesystem.");
2021
2022   ("get_e2label", (RString "label", [String "device"]), 81, [],
2023    [],
2024    "get the ext2/3/4 filesystem label",
2025    "\
2026 This returns the ext2/3/4 filesystem label of the filesystem on
2027 C<device>.");
2028
2029   ("set_e2uuid", (RErr, [String "device"; String "uuid"]), 82, [],
2030    [InitBasicFS, Always, TestOutput (
2031       [["set_e2uuid"; "/dev/sda1"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"];
2032        ["get_e2uuid"; "/dev/sda1"]], "a3a61220-882b-4f61-89f4-cf24dcc7297d");
2033     InitBasicFS, Always, TestOutput (
2034       [["set_e2uuid"; "/dev/sda1"; "clear"];
2035        ["get_e2uuid"; "/dev/sda1"]], "");
2036     (* We can't predict what UUIDs will be, so just check the commands run. *)
2037     InitBasicFS, Always, TestRun (
2038       [["set_e2uuid"; "/dev/sda1"; "random"]]);
2039     InitBasicFS, Always, TestRun (
2040       [["set_e2uuid"; "/dev/sda1"; "time"]])],
2041    "set the ext2/3/4 filesystem UUID",
2042    "\
2043 This sets the ext2/3/4 filesystem UUID of the filesystem on
2044 C<device> to C<uuid>.  The format of the UUID and alternatives
2045 such as C<clear>, C<random> and C<time> are described in the
2046 L<tune2fs(8)> manpage.
2047
2048 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2049 to return the existing UUID of a filesystem.");
2050
2051   ("get_e2uuid", (RString "uuid", [String "device"]), 83, [],
2052    [],
2053    "get the ext2/3/4 filesystem UUID",
2054    "\
2055 This returns the ext2/3/4 filesystem UUID of the filesystem on
2056 C<device>.");
2057
2058   ("fsck", (RInt "status", [String "fstype"; String "device"]), 84, [],
2059    [InitBasicFS, Always, TestOutputInt (
2060       [["umount"; "/dev/sda1"];
2061        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2062     InitBasicFS, Always, TestOutputInt (
2063       [["umount"; "/dev/sda1"];
2064        ["zero"; "/dev/sda1"];
2065        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2066    "run the filesystem checker",
2067    "\
2068 This runs the filesystem checker (fsck) on C<device> which
2069 should have filesystem type C<fstype>.
2070
2071 The returned integer is the status.  See L<fsck(8)> for the
2072 list of status codes from C<fsck>.
2073
2074 Notes:
2075
2076 =over 4
2077
2078 =item *
2079
2080 Multiple status codes can be summed together.
2081
2082 =item *
2083
2084 A non-zero return code can mean \"success\", for example if
2085 errors have been corrected on the filesystem.
2086
2087 =item *
2088
2089 Checking or repairing NTFS volumes is not supported
2090 (by linux-ntfs).
2091
2092 =back
2093
2094 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2095
2096   ("zero", (RErr, [String "device"]), 85, [],
2097    [InitBasicFS, Always, TestOutput (
2098       [["umount"; "/dev/sda1"];
2099        ["zero"; "/dev/sda1"];
2100        ["file"; "/dev/sda1"]], "data")],
2101    "write zeroes to the device",
2102    "\
2103 This command writes zeroes over the first few blocks of C<device>.
2104
2105 How many blocks are zeroed isn't specified (but it's I<not> enough
2106 to securely wipe the device).  It should be sufficient to remove
2107 any partition tables, filesystem superblocks and so on.
2108
2109 See also: C<guestfs_scrub_device>.");
2110
2111   ("grub_install", (RErr, [String "root"; String "device"]), 86, [],
2112    (* Test disabled because grub-install incompatible with virtio-blk driver.
2113     * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2114     *)
2115    [InitBasicFS, Disabled, TestOutputTrue (
2116       [["grub_install"; "/"; "/dev/sda1"];
2117        ["is_dir"; "/boot"]])],
2118    "install GRUB",
2119    "\
2120 This command installs GRUB (the Grand Unified Bootloader) on
2121 C<device>, with the root directory being C<root>.");
2122
2123   ("cp", (RErr, [String "src"; String "dest"]), 87, [],
2124    [InitBasicFS, Always, TestOutput (
2125       [["write_file"; "/old"; "file content"; "0"];
2126        ["cp"; "/old"; "/new"];
2127        ["cat"; "/new"]], "file content");
2128     InitBasicFS, Always, TestOutputTrue (
2129       [["write_file"; "/old"; "file content"; "0"];
2130        ["cp"; "/old"; "/new"];
2131        ["is_file"; "/old"]]);
2132     InitBasicFS, Always, TestOutput (
2133       [["write_file"; "/old"; "file content"; "0"];
2134        ["mkdir"; "/dir"];
2135        ["cp"; "/old"; "/dir/new"];
2136        ["cat"; "/dir/new"]], "file content")],
2137    "copy a file",
2138    "\
2139 This copies a file from C<src> to C<dest> where C<dest> is
2140 either a destination filename or destination directory.");
2141
2142   ("cp_a", (RErr, [String "src"; String "dest"]), 88, [],
2143    [InitBasicFS, Always, TestOutput (
2144       [["mkdir"; "/olddir"];
2145        ["mkdir"; "/newdir"];
2146        ["write_file"; "/olddir/file"; "file content"; "0"];
2147        ["cp_a"; "/olddir"; "/newdir"];
2148        ["cat"; "/newdir/olddir/file"]], "file content")],
2149    "copy a file or directory recursively",
2150    "\
2151 This copies a file or directory from C<src> to C<dest>
2152 recursively using the C<cp -a> command.");
2153
2154   ("mv", (RErr, [String "src"; String "dest"]), 89, [],
2155    [InitBasicFS, Always, TestOutput (
2156       [["write_file"; "/old"; "file content"; "0"];
2157        ["mv"; "/old"; "/new"];
2158        ["cat"; "/new"]], "file content");
2159     InitBasicFS, Always, TestOutputFalse (
2160       [["write_file"; "/old"; "file content"; "0"];
2161        ["mv"; "/old"; "/new"];
2162        ["is_file"; "/old"]])],
2163    "move a file",
2164    "\
2165 This moves a file from C<src> to C<dest> where C<dest> is
2166 either a destination filename or destination directory.");
2167
2168   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2169    [InitEmpty, Always, TestRun (
2170       [["drop_caches"; "3"]])],
2171    "drop kernel page cache, dentries and inodes",
2172    "\
2173 This instructs the guest kernel to drop its page cache,
2174 and/or dentries and inode caches.  The parameter C<whattodrop>
2175 tells the kernel what precisely to drop, see
2176 L<http://linux-mm.org/Drop_Caches>
2177
2178 Setting C<whattodrop> to 3 should drop everything.
2179
2180 This automatically calls L<sync(2)> before the operation,
2181 so that the maximum guest memory is freed.");
2182
2183   ("dmesg", (RString "kmsgs", []), 91, [],
2184    [InitEmpty, Always, TestRun (
2185       [["dmesg"]])],
2186    "return kernel messages",
2187    "\
2188 This returns the kernel messages (C<dmesg> output) from
2189 the guest kernel.  This is sometimes useful for extended
2190 debugging of problems.
2191
2192 Another way to get the same information is to enable
2193 verbose messages with C<guestfs_set_verbose> or by setting
2194 the environment variable C<LIBGUESTFS_DEBUG=1> before
2195 running the program.");
2196
2197   ("ping_daemon", (RErr, []), 92, [],
2198    [InitEmpty, Always, TestRun (
2199       [["ping_daemon"]])],
2200    "ping the guest daemon",
2201    "\
2202 This is a test probe into the guestfs daemon running inside
2203 the qemu subprocess.  Calling this function checks that the
2204 daemon responds to the ping message, without affecting the daemon
2205 or attached block device(s) in any other way.");
2206
2207   ("equal", (RBool "equality", [String "file1"; String "file2"]), 93, [],
2208    [InitBasicFS, Always, TestOutputTrue (
2209       [["write_file"; "/file1"; "contents of a file"; "0"];
2210        ["cp"; "/file1"; "/file2"];
2211        ["equal"; "/file1"; "/file2"]]);
2212     InitBasicFS, Always, TestOutputFalse (
2213       [["write_file"; "/file1"; "contents of a file"; "0"];
2214        ["write_file"; "/file2"; "contents of another file"; "0"];
2215        ["equal"; "/file1"; "/file2"]]);
2216     InitBasicFS, Always, TestLastFail (
2217       [["equal"; "/file1"; "/file2"]])],
2218    "test if two files have equal contents",
2219    "\
2220 This compares the two files C<file1> and C<file2> and returns
2221 true if their content is exactly equal, or false otherwise.
2222
2223 The external L<cmp(1)> program is used for the comparison.");
2224
2225   ("strings", (RStringList "stringsout", [String "path"]), 94, [ProtocolLimitWarning],
2226    [InitSquashFS, Always, TestOutputList (
2227       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2228     InitSquashFS, Always, TestOutputList (
2229       [["strings"; "/empty"]], [])],
2230    "print the printable strings in a file",
2231    "\
2232 This runs the L<strings(1)> command on a file and returns
2233 the list of printable strings found.");
2234
2235   ("strings_e", (RStringList "stringsout", [String "encoding"; String "path"]), 95, [ProtocolLimitWarning],
2236    [InitSquashFS, Always, TestOutputList (
2237       [["strings_e"; "b"; "/known-5"]], []);
2238     InitBasicFS, Disabled, TestOutputList (
2239       [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2240        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2241    "print the printable strings in a file",
2242    "\
2243 This is like the C<guestfs_strings> command, but allows you to
2244 specify the encoding.
2245
2246 See the L<strings(1)> manpage for the full list of encodings.
2247
2248 Commonly useful encodings are C<l> (lower case L) which will
2249 show strings inside Windows/x86 files.
2250
2251 The returned strings are transcoded to UTF-8.");
2252
2253   ("hexdump", (RString "dump", [String "path"]), 96, [ProtocolLimitWarning],
2254    [InitSquashFS, Always, TestOutput (
2255       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2256     (* Test for RHBZ#501888c2 regression which caused large hexdump
2257      * commands to segfault.
2258      *)
2259     InitSquashFS, Always, TestRun (
2260       [["hexdump"; "/100krandom"]])],
2261    "dump a file in hexadecimal",
2262    "\
2263 This runs C<hexdump -C> on the given C<path>.  The result is
2264 the human-readable, canonical hex dump of the file.");
2265
2266   ("zerofree", (RErr, [String "device"]), 97, [],
2267    [InitNone, Always, TestOutput (
2268       [["sfdiskM"; "/dev/sda"; ","];
2269        ["mkfs"; "ext3"; "/dev/sda1"];
2270        ["mount"; "/dev/sda1"; "/"];
2271        ["write_file"; "/new"; "test file"; "0"];
2272        ["umount"; "/dev/sda1"];
2273        ["zerofree"; "/dev/sda1"];
2274        ["mount"; "/dev/sda1"; "/"];
2275        ["cat"; "/new"]], "test file")],
2276    "zero unused inodes and disk blocks on ext2/3 filesystem",
2277    "\
2278 This runs the I<zerofree> program on C<device>.  This program
2279 claims to zero unused inodes and disk blocks on an ext2/3
2280 filesystem, thus making it possible to compress the filesystem
2281 more effectively.
2282
2283 You should B<not> run this program if the filesystem is
2284 mounted.
2285
2286 It is possible that using this program can damage the filesystem
2287 or data on the filesystem.");
2288
2289   ("pvresize", (RErr, [String "device"]), 98, [],
2290    [],
2291    "resize an LVM physical volume",
2292    "\
2293 This resizes (expands or shrinks) an existing LVM physical
2294 volume to match the new size of the underlying device.");
2295
2296   ("sfdisk_N", (RErr, [String "device"; Int "partnum";
2297                        Int "cyls"; Int "heads"; Int "sectors";
2298                        String "line"]), 99, [DangerWillRobinson],
2299    [],
2300    "modify a single partition on a block device",
2301    "\
2302 This runs L<sfdisk(8)> option to modify just the single
2303 partition C<n> (note: C<n> counts from 1).
2304
2305 For other parameters, see C<guestfs_sfdisk>.  You should usually
2306 pass C<0> for the cyls/heads/sectors parameters.");
2307
2308   ("sfdisk_l", (RString "partitions", [String "device"]), 100, [],
2309    [],
2310    "display the partition table",
2311    "\
2312 This displays the partition table on C<device>, in the
2313 human-readable output of the L<sfdisk(8)> command.  It is
2314 not intended to be parsed.");
2315
2316   ("sfdisk_kernel_geometry", (RString "partitions", [String "device"]), 101, [],
2317    [],
2318    "display the kernel geometry",
2319    "\
2320 This displays the kernel's idea of the geometry of C<device>.
2321
2322 The result is in human-readable format, and not designed to
2323 be parsed.");
2324
2325   ("sfdisk_disk_geometry", (RString "partitions", [String "device"]), 102, [],
2326    [],
2327    "display the disk geometry from the partition table",
2328    "\
2329 This displays the disk geometry of C<device> read from the
2330 partition table.  Especially in the case where the underlying
2331 block device has been resized, this can be different from the
2332 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2333
2334 The result is in human-readable format, and not designed to
2335 be parsed.");
2336
2337   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2338    [],
2339    "activate or deactivate all volume groups",
2340    "\
2341 This command activates or (if C<activate> is false) deactivates
2342 all logical volumes in all volume groups.
2343 If activated, then they are made known to the
2344 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2345 then those devices disappear.
2346
2347 This command is the same as running C<vgchange -a y|n>");
2348
2349   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2350    [],
2351    "activate or deactivate some volume groups",
2352    "\
2353 This command activates or (if C<activate> is false) deactivates
2354 all logical volumes in the listed volume groups C<volgroups>.
2355 If activated, then they are made known to the
2356 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2357 then those devices disappear.
2358
2359 This command is the same as running C<vgchange -a y|n volgroups...>
2360
2361 Note that if C<volgroups> is an empty list then B<all> volume groups
2362 are activated or deactivated.");
2363
2364   ("lvresize", (RErr, [String "device"; Int "mbytes"]), 105, [],
2365    [InitNone, Always, TestOutput (
2366       [["sfdiskM"; "/dev/sda"; ","];
2367        ["pvcreate"; "/dev/sda1"];
2368        ["vgcreate"; "VG"; "/dev/sda1"];
2369        ["lvcreate"; "LV"; "VG"; "10"];
2370        ["mkfs"; "ext2"; "/dev/VG/LV"];
2371        ["mount"; "/dev/VG/LV"; "/"];
2372        ["write_file"; "/new"; "test content"; "0"];
2373        ["umount"; "/"];
2374        ["lvresize"; "/dev/VG/LV"; "20"];
2375        ["e2fsck_f"; "/dev/VG/LV"];
2376        ["resize2fs"; "/dev/VG/LV"];
2377        ["mount"; "/dev/VG/LV"; "/"];
2378        ["cat"; "/new"]], "test content")],
2379    "resize an LVM logical volume",
2380    "\
2381 This resizes (expands or shrinks) an existing LVM logical
2382 volume to C<mbytes>.  When reducing, data in the reduced part
2383 is lost.");
2384
2385   ("resize2fs", (RErr, [String "device"]), 106, [],
2386    [], (* lvresize tests this *)
2387    "resize an ext2/ext3 filesystem",
2388    "\
2389 This resizes an ext2 or ext3 filesystem to match the size of
2390 the underlying device.
2391
2392 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2393 on the C<device> before calling this command.  For unknown reasons
2394 C<resize2fs> sometimes gives an error about this and sometimes not.
2395 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2396 calling this function.");
2397
2398   ("find", (RStringList "names", [String "directory"]), 107, [],
2399    [InitBasicFS, Always, TestOutputList (
2400       [["find"; "/"]], ["lost+found"]);
2401     InitBasicFS, Always, TestOutputList (
2402       [["touch"; "/a"];
2403        ["mkdir"; "/b"];
2404        ["touch"; "/b/c"];
2405        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2406     InitBasicFS, Always, TestOutputList (
2407       [["mkdir_p"; "/a/b/c"];
2408        ["touch"; "/a/b/c/d"];
2409        ["find"; "/a/b/"]], ["c"; "c/d"])],
2410    "find all files and directories",
2411    "\
2412 This command lists out all files and directories, recursively,
2413 starting at C<directory>.  It is essentially equivalent to
2414 running the shell command C<find directory -print> but some
2415 post-processing happens on the output, described below.
2416
2417 This returns a list of strings I<without any prefix>.  Thus
2418 if the directory structure was:
2419
2420  /tmp/a
2421  /tmp/b
2422  /tmp/c/d
2423
2424 then the returned list from C<guestfs_find> C</tmp> would be
2425 4 elements:
2426
2427  a
2428  b
2429  c
2430  c/d
2431
2432 If C<directory> is not a directory, then this command returns
2433 an error.
2434
2435 The returned list is sorted.");
2436
2437   ("e2fsck_f", (RErr, [String "device"]), 108, [],
2438    [], (* lvresize tests this *)
2439    "check an ext2/ext3 filesystem",
2440    "\
2441 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2442 filesystem checker on C<device>, noninteractively (C<-p>),
2443 even if the filesystem appears to be clean (C<-f>).
2444
2445 This command is only needed because of C<guestfs_resize2fs>
2446 (q.v.).  Normally you should use C<guestfs_fsck>.");
2447
2448   ("sleep", (RErr, [Int "secs"]), 109, [],
2449    [InitNone, Always, TestRun (
2450       [["sleep"; "1"]])],
2451    "sleep for some seconds",
2452    "\
2453 Sleep for C<secs> seconds.");
2454
2455   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; String "device"]), 110, [],
2456    [InitNone, Always, TestOutputInt (
2457       [["sfdiskM"; "/dev/sda"; ","];
2458        ["mkfs"; "ntfs"; "/dev/sda1"];
2459        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2460     InitNone, Always, TestOutputInt (
2461       [["sfdiskM"; "/dev/sda"; ","];
2462        ["mkfs"; "ext2"; "/dev/sda1"];
2463        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2464    "probe NTFS volume",
2465    "\
2466 This command runs the L<ntfs-3g.probe(8)> command which probes
2467 an NTFS C<device> for mountability.  (Not all NTFS volumes can
2468 be mounted read-write, and some cannot be mounted at all).
2469
2470 C<rw> is a boolean flag.  Set it to true if you want to test
2471 if the volume can be mounted read-write.  Set it to false if
2472 you want to test if the volume can be mounted read-only.
2473
2474 The return value is an integer which C<0> if the operation
2475 would succeed, or some non-zero value documented in the
2476 L<ntfs-3g.probe(8)> manual page.");
2477
2478   ("sh", (RString "output", [String "command"]), 111, [],
2479    [], (* XXX needs tests *)
2480    "run a command via the shell",
2481    "\
2482 This call runs a command from the guest filesystem via the
2483 guest's C</bin/sh>.
2484
2485 This is like C<guestfs_command>, but passes the command to:
2486
2487  /bin/sh -c \"command\"
2488
2489 Depending on the guest's shell, this usually results in
2490 wildcards being expanded, shell expressions being interpolated
2491 and so on.
2492
2493 All the provisos about C<guestfs_command> apply to this call.");
2494
2495   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2496    [], (* XXX needs tests *)
2497    "run a command via the shell returning lines",
2498    "\
2499 This is the same as C<guestfs_sh>, but splits the result
2500 into a list of lines.
2501
2502 See also: C<guestfs_command_lines>");
2503
2504   ("glob_expand", (RStringList "paths", [String "pattern"]), 113, [],
2505    [InitBasicFS, Always, TestOutputList (
2506       [["mkdir_p"; "/a/b/c"];
2507        ["touch"; "/a/b/c/d"];
2508        ["touch"; "/a/b/c/e"];
2509        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2510     InitBasicFS, Always, TestOutputList (
2511       [["mkdir_p"; "/a/b/c"];
2512        ["touch"; "/a/b/c/d"];
2513        ["touch"; "/a/b/c/e"];
2514        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2515     InitBasicFS, Always, TestOutputList (
2516       [["mkdir_p"; "/a/b/c"];
2517        ["touch"; "/a/b/c/d"];
2518        ["touch"; "/a/b/c/e"];
2519        ["glob_expand"; "/a/*/x/*"]], [])],
2520    "expand a wildcard path",
2521    "\
2522 This command searches for all the pathnames matching
2523 C<pattern> according to the wildcard expansion rules
2524 used by the shell.
2525
2526 If no paths match, then this returns an empty list
2527 (note: not an error).
2528
2529 It is just a wrapper around the C L<glob(3)> function
2530 with flags C<GLOB_MARK|GLOB_BRACE>.
2531 See that manual page for more details.");
2532
2533   ("scrub_device", (RErr, [String "device"]), 114, [DangerWillRobinson],
2534    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2535       [["scrub_device"; "/dev/sdc"]])],
2536    "scrub (securely wipe) a device",
2537    "\
2538 This command writes patterns over C<device> to make data retrieval
2539 more difficult.
2540
2541 It is an interface to the L<scrub(1)> program.  See that
2542 manual page for more details.");
2543
2544   ("scrub_file", (RErr, [String "file"]), 115, [],
2545    [InitBasicFS, Always, TestRun (
2546       [["write_file"; "/file"; "content"; "0"];
2547        ["scrub_file"; "/file"]])],
2548    "scrub (securely wipe) a file",
2549    "\
2550 This command writes patterns over a file to make data retrieval
2551 more difficult.
2552
2553 The file is I<removed> after scrubbing.
2554
2555 It is an interface to the L<scrub(1)> program.  See that
2556 manual page for more details.");
2557
2558   ("scrub_freespace", (RErr, [String "dir"]), 116, [],
2559    [], (* XXX needs testing *)
2560    "scrub (securely wipe) free space",
2561    "\
2562 This command creates the directory C<dir> and then fills it
2563 with files until the filesystem is full, and scrubs the files
2564 as for C<guestfs_scrub_file>, and deletes them.
2565 The intention is to scrub any free space on the partition
2566 containing C<dir>.
2567
2568 It is an interface to the L<scrub(1)> program.  See that
2569 manual page for more details.");
2570
2571   ("mkdtemp", (RString "dir", [String "template"]), 117, [],
2572    [InitBasicFS, Always, TestRun (
2573       [["mkdir"; "/tmp"];
2574        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2575    "create a temporary directory",
2576    "\
2577 This command creates a temporary directory.  The
2578 C<template> parameter should be a full pathname for the
2579 temporary directory name with the final six characters being
2580 \"XXXXXX\".
2581
2582 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2583 the second one being suitable for Windows filesystems.
2584
2585 The name of the temporary directory that was created
2586 is returned.
2587
2588 The temporary directory is created with mode 0700
2589 and is owned by root.
2590
2591 The caller is responsible for deleting the temporary
2592 directory and its contents after use.
2593
2594 See also: L<mkdtemp(3)>");
2595
2596   ("wc_l", (RInt "lines", [String "path"]), 118, [],
2597    [InitSquashFS, Always, TestOutputInt (
2598       [["wc_l"; "/10klines"]], 10000)],
2599    "count lines in a file",
2600    "\
2601 This command counts the lines in a file, using the
2602 C<wc -l> external command.");
2603
2604   ("wc_w", (RInt "words", [String "path"]), 119, [],
2605    [InitSquashFS, Always, TestOutputInt (
2606       [["wc_w"; "/10klines"]], 10000)],
2607    "count words in a file",
2608    "\
2609 This command counts the words in a file, using the
2610 C<wc -w> external command.");
2611
2612   ("wc_c", (RInt "chars", [String "path"]), 120, [],
2613    [InitSquashFS, Always, TestOutputInt (
2614       [["wc_c"; "/100kallspaces"]], 102400)],
2615    "count characters in a file",
2616    "\
2617 This command counts the characters in a file, using the
2618 C<wc -c> external command.");
2619
2620   ("head", (RStringList "lines", [String "path"]), 121, [ProtocolLimitWarning],
2621    [InitSquashFS, Always, TestOutputList (
2622       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2623    "return first 10 lines of a file",
2624    "\
2625 This command returns up to the first 10 lines of a file as
2626 a list of strings.");
2627
2628   ("head_n", (RStringList "lines", [Int "nrlines"; String "path"]), 122, [ProtocolLimitWarning],
2629    [InitSquashFS, Always, TestOutputList (
2630       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2631     InitSquashFS, Always, TestOutputList (
2632       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2633     InitSquashFS, Always, TestOutputList (
2634       [["head_n"; "0"; "/10klines"]], [])],
2635    "return first N lines of a file",
2636    "\
2637 If the parameter C<nrlines> is a positive number, this returns the first
2638 C<nrlines> lines of the file C<path>.
2639
2640 If the parameter C<nrlines> is a negative number, this returns lines
2641 from the file C<path>, excluding the last C<nrlines> lines.
2642
2643 If the parameter C<nrlines> is zero, this returns an empty list.");
2644
2645   ("tail", (RStringList "lines", [String "path"]), 123, [ProtocolLimitWarning],
2646    [InitSquashFS, Always, TestOutputList (
2647       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2648    "return last 10 lines of a file",
2649    "\
2650 This command returns up to the last 10 lines of a file as
2651 a list of strings.");
2652
2653   ("tail_n", (RStringList "lines", [Int "nrlines"; String "path"]), 124, [ProtocolLimitWarning],
2654    [InitSquashFS, Always, TestOutputList (
2655       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2656     InitSquashFS, Always, TestOutputList (
2657       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2658     InitSquashFS, Always, TestOutputList (
2659       [["tail_n"; "0"; "/10klines"]], [])],
2660    "return last N lines of a file",
2661    "\
2662 If the parameter C<nrlines> is a positive number, this returns the last
2663 C<nrlines> lines of the file C<path>.
2664
2665 If the parameter C<nrlines> is a negative number, this returns lines
2666 from the file C<path>, starting with the C<-nrlines>th line.
2667
2668 If the parameter C<nrlines> is zero, this returns an empty list.");
2669
2670   ("df", (RString "output", []), 125, [],
2671    [], (* XXX Tricky to test because it depends on the exact format
2672         * of the 'df' command and other imponderables.
2673         *)
2674    "report file system disk space usage",
2675    "\
2676 This command runs the C<df> command to report disk space used.
2677
2678 This command is mostly useful for interactive sessions.  It
2679 is I<not> intended that you try to parse the output string.
2680 Use C<statvfs> from programs.");
2681
2682   ("df_h", (RString "output", []), 126, [],
2683    [], (* XXX Tricky to test because it depends on the exact format
2684         * of the 'df' command and other imponderables.
2685         *)
2686    "report file system disk space usage (human readable)",
2687    "\
2688 This command runs the C<df -h> command to report disk space used
2689 in human-readable format.
2690
2691 This command is mostly useful for interactive sessions.  It
2692 is I<not> intended that you try to parse the output string.
2693 Use C<statvfs> from programs.");
2694
2695   ("du", (RInt64 "sizekb", [String "path"]), 127, [],
2696    [InitSquashFS, Always, TestOutputInt (
2697       [["du"; "/directory"]], 0 (* squashfs doesn't have blocks *))],
2698    "estimate file space usage",
2699    "\
2700 This command runs the C<du -s> command to estimate file space
2701 usage for C<path>.
2702
2703 C<path> can be a file or a directory.  If C<path> is a directory
2704 then the estimate includes the contents of the directory and all
2705 subdirectories (recursively).
2706
2707 The result is the estimated size in I<kilobytes>
2708 (ie. units of 1024 bytes).");
2709
2710   ("initrd_list", (RStringList "filenames", [String "path"]), 128, [],
2711    [InitSquashFS, Always, TestOutputList (
2712       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
2713    "list files in an initrd",
2714    "\
2715 This command lists out files contained in an initrd.
2716
2717 The files are listed without any initial C</> character.  The
2718 files are listed in the order they appear (not necessarily
2719 alphabetical).  Directory names are listed as separate items.
2720
2721 Old Linux kernels (2.4 and earlier) used a compressed ext2
2722 filesystem as initrd.  We I<only> support the newer initramfs
2723 format (compressed cpio files).");
2724
2725   ("mount_loop", (RErr, [String "file"; String "mountpoint"]), 129, [],
2726    [],
2727    "mount a file using the loop device",
2728    "\
2729 This command lets you mount C<file> (a filesystem image
2730 in a file) on a mount point.  It is entirely equivalent to
2731 the command C<mount -o loop file mountpoint>.");
2732
2733   ("mkswap", (RErr, [String "device"]), 130, [],
2734    [InitEmpty, Always, TestRun (
2735       [["sfdiskM"; "/dev/sda"; ","];
2736        ["mkswap"; "/dev/sda1"]])],
2737    "create a swap partition",
2738    "\
2739 Create a swap partition on C<device>.");
2740
2741   ("mkswap_L", (RErr, [String "label"; String "device"]), 131, [],
2742    [InitEmpty, Always, TestRun (
2743       [["sfdiskM"; "/dev/sda"; ","];
2744        ["mkswap_L"; "hello"; "/dev/sda1"]])],
2745    "create a swap partition with a label",
2746    "\
2747 Create a swap partition on C<device> with label C<label>.");
2748
2749   ("mkswap_U", (RErr, [String "uuid"; String "device"]), 132, [],
2750    [InitEmpty, Always, TestRun (
2751       [["sfdiskM"; "/dev/sda"; ","];
2752        ["mkswap_U"; "a3a61220-882b-4f61-89f4-cf24dcc7297d"; "/dev/sda1"]])],
2753    "create a swap partition with an explicit UUID",
2754    "\
2755 Create a swap partition on C<device> with UUID C<uuid>.");
2756
2757   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 133, [],
2758    [InitBasicFS, Always, TestOutputStruct (
2759       [["mknod"; "0o10777"; "0"; "0"; "/node"];
2760        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2761        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2762     InitBasicFS, Always, TestOutputStruct (
2763       [["mknod"; "0o60777"; "66"; "99"; "/node"];
2764        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2765    "make block, character or FIFO devices",
2766    "\
2767 This call creates block or character special devices, or
2768 named pipes (FIFOs).
2769
2770 The C<mode> parameter should be the mode, using the standard
2771 constants.  C<devmajor> and C<devminor> are the
2772 device major and minor numbers, only used when creating block
2773 and character special devices.");
2774
2775   ("mkfifo", (RErr, [Int "mode"; String "path"]), 134, [],
2776    [InitBasicFS, Always, TestOutputStruct (
2777       [["mkfifo"; "0o777"; "/node"];
2778        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2779    "make FIFO (named pipe)",
2780    "\
2781 This call creates a FIFO (named pipe) called C<path> with
2782 mode C<mode>.  It is just a convenient wrapper around
2783 C<guestfs_mknod>.");
2784
2785   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 135, [],
2786    [InitBasicFS, Always, TestOutputStruct (
2787       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2788        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2789    "make block device node",
2790    "\
2791 This call creates a block device node called C<path> with
2792 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2793 It is just a convenient wrapper around C<guestfs_mknod>.");
2794
2795   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; String "path"]), 136, [],
2796    [InitBasicFS, Always, TestOutputStruct (
2797       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2798        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2799    "make char device node",
2800    "\
2801 This call creates a char device node called C<path> with
2802 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2803 It is just a convenient wrapper around C<guestfs_mknod>.");
2804
2805   ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2806    [], (* XXX umask is one of those stateful things that we should
2807         * reset between each test.
2808         *)
2809    "set file mode creation mask (umask)",
2810    "\
2811 This function sets the mask used for creating new files and
2812 device nodes to C<mask & 0777>.
2813
2814 Typical umask values would be C<022> which creates new files
2815 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2816 C<002> which creates new files with permissions like
2817 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2818
2819 The default umask is C<022>.  This is important because it
2820 means that directories and device nodes will be created with
2821 C<0644> or C<0755> mode even if you specify C<0777>.
2822
2823 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2824
2825 This call returns the previous umask.");
2826
2827   ("readdir", (RStructList ("entries", "dirent"), [String "dir"]), 138, [],
2828    [],
2829    "read directories entries",
2830    "\
2831 This returns the list of directory entries in directory C<dir>.
2832
2833 All entries in the directory are returned, including C<.> and
2834 C<..>.  The entries are I<not> sorted, but returned in the same
2835 order as the underlying filesystem.
2836
2837 Also this call returns basic file type information about each
2838 file.  The C<ftyp> field will contain one of the following characters:
2839
2840 =over 4
2841
2842 =item 'b'
2843
2844 Block special
2845
2846 =item 'c'
2847
2848 Char special
2849
2850 =item 'd'
2851
2852 Directory
2853
2854 =item 'f'
2855
2856 FIFO (named pipe)
2857
2858 =item 'l'
2859
2860 Symbolic link
2861
2862 =item 'r'
2863
2864 Regular file
2865
2866 =item 's'
2867
2868 Socket
2869
2870 =item 'u'
2871
2872 Unknown file type
2873
2874 =item '?'
2875
2876 The L<readdir(3)> returned a C<d_type> field with an
2877 unexpected value
2878
2879 =back
2880
2881 This function is primarily intended for use by programs.  To
2882 get a simple list of names, use C<guestfs_ls>.  To get a printable
2883 directory for human consumption, use C<guestfs_ll>.");
2884
2885   ("sfdiskM", (RErr, [String "device"; StringList "lines"]), 139, [DangerWillRobinson],
2886    [],
2887    "create partitions on a block device",
2888    "\
2889 This is a simplified interface to the C<guestfs_sfdisk>
2890 command, where partition sizes are specified in megabytes
2891 only (rounded to the nearest cylinder) and you don't need
2892 to specify the cyls, heads and sectors parameters which
2893 were rarely if ever used anyway.
2894
2895 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
2896
2897   ("zfile", (RString "description", [String "method"; String "path"]), 140, [DeprecatedBy "file"],
2898    [],
2899    "determine file type inside a compressed file",
2900    "\
2901 This command runs C<file> after first decompressing C<path>
2902 using C<method>.
2903
2904 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
2905
2906 Since 1.0.63, use C<guestfs_file> instead which can now
2907 process compressed files.");
2908
2909   ("getxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 141, [],
2910    [],
2911    "list extended attributes of a file or directory",
2912    "\
2913 This call lists the extended attributes of the file or directory
2914 C<path>.
2915
2916 At the system call level, this is a combination of the
2917 L<listxattr(2)> and L<getxattr(2)> calls.
2918
2919 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
2920
2921   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [String "path"]), 142, [],
2922    [],
2923    "list extended attributes of a file or directory",
2924    "\
2925 This is the same as C<guestfs_getxattrs>, but if C<path>
2926 is a symbolic link, then it returns the extended attributes
2927 of the link itself.");
2928
2929   ("setxattr", (RErr, [String "xattr";
2930                        String "val"; Int "vallen"; (* will be BufferIn *)
2931                        String "path"]), 143, [],
2932    [],
2933    "set extended attribute of a file or directory",
2934    "\
2935 This call sets the extended attribute named C<xattr>
2936 of the file C<path> to the value C<val> (of length C<vallen>).
2937 The value is arbitrary 8 bit data.
2938
2939 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
2940
2941   ("lsetxattr", (RErr, [String "xattr";
2942                         String "val"; Int "vallen"; (* will be BufferIn *)
2943                         String "path"]), 144, [],
2944    [],
2945    "set extended attribute of a file or directory",
2946    "\
2947 This is the same as C<guestfs_setxattr>, but if C<path>
2948 is a symbolic link, then it sets an extended attribute
2949 of the link itself.");
2950
2951   ("removexattr", (RErr, [String "xattr"; String "path"]), 145, [],
2952    [],
2953    "remove extended attribute of a file or directory",
2954    "\
2955 This call removes the extended attribute named C<xattr>
2956 of the file C<path>.
2957
2958 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
2959
2960   ("lremovexattr", (RErr, [String "xattr"; String "path"]), 146, [],
2961    [],
2962    "remove extended attribute of a file or directory",
2963    "\
2964 This is the same as C<guestfs_removexattr>, but if C<path>
2965 is a symbolic link, then it removes an extended attribute
2966 of the link itself.");
2967
2968   ("mountpoints", (RHashtable "mps", []), 147, [],
2969    [],
2970    "show mountpoints",
2971    "\
2972 This call is similar to C<guestfs_mounts>.  That call returns
2973 a list of devices.  This one returns a hash table (map) of
2974 device name to directory where the device is mounted.");
2975
2976   ("mkmountpoint", (RErr, [String "path"]), 148, [],
2977    [],
2978    "create a mountpoint",
2979    "\
2980 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
2981 specialized calls that can be used to create extra mountpoints
2982 before mounting the first filesystem.
2983
2984 These calls are I<only> necessary in some very limited circumstances,
2985 mainly the case where you want to mount a mix of unrelated and/or
2986 read-only filesystems together.
2987
2988 For example, live CDs often contain a \"Russian doll\" nest of
2989 filesystems, an ISO outer layer, with a squashfs image inside, with
2990 an ext2/3 image inside that.  You can unpack this as follows
2991 in guestfish:
2992
2993  add-ro Fedora-11-i686-Live.iso
2994  run
2995  mkmountpoint /cd
2996  mkmountpoint /squash
2997  mkmountpoint /ext3
2998  mount /dev/sda /cd
2999  mount-loop /cd/LiveOS/squashfs.img /squash
3000  mount-loop /squash/LiveOS/ext3fs.img /ext3
3001
3002 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3003
3004   ("rmmountpoint", (RErr, [String "path"]), 149, [],
3005    [],
3006    "remove a mountpoint",
3007    "\
3008 This calls removes a mountpoint that was previously created
3009 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3010 for full details.");
3011
3012   ("read_file", (RBufferOut "content", [String "path"]), 150, [ProtocolLimitWarning],
3013    [InitSquashFS, Always, TestOutputBuffer (
3014       [["read_file"; "/known-4"]], "abc\ndef\nghi")],
3015    "read a file",
3016    "\
3017 This calls returns the contents of the file C<path> as a
3018 buffer.
3019
3020 Unlike C<guestfs_cat>, this function can correctly
3021 handle files that contain embedded ASCII NUL characters.
3022 However unlike C<guestfs_download>, this function is limited
3023 in the total size of file that can be handled.");
3024
3025   ("grep", (RStringList "lines", [String "regex"; String "path"]), 151, [ProtocolLimitWarning],
3026    [InitSquashFS, Always, TestOutputList (
3027       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3028     InitSquashFS, Always, TestOutputList (
3029       [["grep"; "nomatch"; "/test-grep.txt"]], [])],
3030    "return lines matching a pattern",
3031    "\
3032 This calls the external C<grep> program and returns the
3033 matching lines.");
3034
3035   ("egrep", (RStringList "lines", [String "regex"; String "path"]), 152, [ProtocolLimitWarning],
3036    [InitSquashFS, Always, TestOutputList (
3037       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3038    "return lines matching a pattern",
3039    "\
3040 This calls the external C<egrep> program and returns the
3041 matching lines.");
3042
3043   ("fgrep", (RStringList "lines", [String "pattern"; String "path"]), 153, [ProtocolLimitWarning],
3044    [InitSquashFS, Always, TestOutputList (
3045       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3046    "return lines matching a pattern",
3047    "\
3048 This calls the external C<fgrep> program and returns the
3049 matching lines.");
3050
3051   ("grepi", (RStringList "lines", [String "regex"; String "path"]), 154, [ProtocolLimitWarning],
3052    [InitSquashFS, Always, TestOutputList (
3053       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3054    "return lines matching a pattern",
3055    "\
3056 This calls the external C<grep -i> program and returns the
3057 matching lines.");
3058
3059   ("egrepi", (RStringList "lines", [String "regex"; String "path"]), 155, [ProtocolLimitWarning],
3060    [InitSquashFS, Always, TestOutputList (
3061       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3062    "return lines matching a pattern",
3063    "\
3064 This calls the external C<egrep -i> program and returns the
3065 matching lines.");
3066
3067   ("fgrepi", (RStringList "lines", [String "pattern"; String "path"]), 156, [ProtocolLimitWarning],
3068    [InitSquashFS, Always, TestOutputList (
3069       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3070    "return lines matching a pattern",
3071    "\
3072 This calls the external C<fgrep -i> program and returns the
3073 matching lines.");
3074
3075   ("zgrep", (RStringList "lines", [String "regex"; String "path"]), 157, [ProtocolLimitWarning],
3076    [InitSquashFS, Always, TestOutputList (
3077       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3078    "return lines matching a pattern",
3079    "\
3080 This calls the external C<zgrep> program and returns the
3081 matching lines.");
3082
3083   ("zegrep", (RStringList "lines", [String "regex"; String "path"]), 158, [ProtocolLimitWarning],
3084    [InitSquashFS, Always, TestOutputList (
3085       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3086    "return lines matching a pattern",
3087    "\
3088 This calls the external C<zegrep> program and returns the
3089 matching lines.");
3090
3091   ("zfgrep", (RStringList "lines", [String "pattern"; String "path"]), 159, [ProtocolLimitWarning],
3092    [InitSquashFS, Always, TestOutputList (
3093       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3094    "return lines matching a pattern",
3095    "\
3096 This calls the external C<zfgrep> program and returns the
3097 matching lines.");
3098
3099   ("zgrepi", (RStringList "lines", [String "regex"; String "path"]), 160, [ProtocolLimitWarning],
3100    [InitSquashFS, Always, TestOutputList (
3101       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3102    "return lines matching a pattern",
3103    "\
3104 This calls the external C<zgrep -i> program and returns the
3105 matching lines.");
3106
3107   ("zegrepi", (RStringList "lines", [String "regex"; String "path"]), 161, [ProtocolLimitWarning],
3108    [InitSquashFS, Always, TestOutputList (
3109       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3110    "return lines matching a pattern",
3111    "\
3112 This calls the external C<zegrep -i> program and returns the
3113 matching lines.");
3114
3115   ("zfgrepi", (RStringList "lines", [String "pattern"; String "path"]), 162, [ProtocolLimitWarning],
3116    [InitSquashFS, Always, TestOutputList (
3117       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3118    "return lines matching a pattern",
3119    "\
3120 This calls the external C<zfgrep -i> program and returns the
3121 matching lines.");
3122
3123 ]
3124
3125 let all_functions = non_daemon_functions @ daemon_functions
3126
3127 (* In some places we want the functions to be displayed sorted
3128  * alphabetically, so this is useful:
3129  *)
3130 let all_functions_sorted =
3131   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
3132                compare n1 n2) all_functions
3133
3134 (* Field types for structures. *)
3135 type field =
3136   | FChar                       (* C 'char' (really, a 7 bit byte). *)
3137   | FString                     (* nul-terminated ASCII string. *)
3138   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
3139   | FUInt32
3140   | FInt32
3141   | FUInt64
3142   | FInt64
3143   | FBytes                      (* Any int measure that counts bytes. *)
3144   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
3145   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
3146
3147 (* Because we generate extra parsing code for LVM command line tools,
3148  * we have to pull out the LVM columns separately here.
3149  *)
3150 let lvm_pv_cols = [
3151   "pv_name", FString;
3152   "pv_uuid", FUUID;
3153   "pv_fmt", FString;
3154   "pv_size", FBytes;
3155   "dev_size", FBytes;
3156   "pv_free", FBytes;
3157   "pv_used", FBytes;
3158   "pv_attr", FString (* XXX *);
3159   "pv_pe_count", FInt64;
3160   "pv_pe_alloc_count", FInt64;
3161   "pv_tags", FString;
3162   "pe_start", FBytes;
3163   "pv_mda_count", FInt64;
3164   "pv_mda_free", FBytes;
3165   (* Not in Fedora 10:
3166      "pv_mda_size", FBytes;
3167   *)
3168 ]
3169 let lvm_vg_cols = [
3170   "vg_name", FString;
3171   "vg_uuid", FUUID;
3172   "vg_fmt", FString;
3173   "vg_attr", FString (* XXX *);
3174   "vg_size", FBytes;
3175   "vg_free", FBytes;
3176   "vg_sysid", FString;
3177   "vg_extent_size", FBytes;
3178   "vg_extent_count", FInt64;
3179   "vg_free_count", FInt64;
3180   "max_lv", FInt64;
3181   "max_pv", FInt64;
3182   "pv_count", FInt64;
3183   "lv_count", FInt64;
3184   "snap_count", FInt64;
3185   "vg_seqno", FInt64;
3186   "vg_tags", FString;
3187   "vg_mda_count", FInt64;
3188   "vg_mda_free", FBytes;
3189   (* Not in Fedora 10:
3190      "vg_mda_size", FBytes;
3191   *)
3192 ]
3193 let lvm_lv_cols = [
3194   "lv_name", FString;
3195   "lv_uuid", FUUID;
3196   "lv_attr", FString (* XXX *);
3197   "lv_major", FInt64;
3198   "lv_minor", FInt64;
3199   "lv_kernel_major", FInt64;
3200   "lv_kernel_minor", FInt64;
3201   "lv_size", FBytes;
3202   "seg_count", FInt64;
3203   "origin", FString;
3204   "snap_percent", FOptPercent;
3205   "copy_percent", FOptPercent;
3206   "move_pv", FString;
3207   "lv_tags", FString;
3208   "mirror_log", FString;
3209   "modules", FString;
3210 ]
3211
3212 (* Names and fields in all structures (in RStruct and RStructList)
3213  * that we support.
3214  *)
3215 let structs = [
3216   (* The old RIntBool return type, only ever used for aug_defnode.  Do
3217    * not use this struct in any new code.
3218    *)
3219   "int_bool", [
3220     "i", FInt32;                (* for historical compatibility *)
3221     "b", FInt32;                (* for historical compatibility *)
3222   ];
3223
3224   (* LVM PVs, VGs, LVs. *)
3225   "lvm_pv", lvm_pv_cols;
3226   "lvm_vg", lvm_vg_cols;
3227   "lvm_lv", lvm_lv_cols;
3228
3229   (* Column names and types from stat structures.
3230    * NB. Can't use things like 'st_atime' because glibc header files
3231    * define some of these as macros.  Ugh.
3232    *)
3233   "stat", [
3234     "dev", FInt64;
3235     "ino", FInt64;
3236     "mode", FInt64;
3237     "nlink", FInt64;
3238     "uid", FInt64;
3239     "gid", FInt64;
3240     "rdev", FInt64;
3241     "size", FInt64;
3242     "blksize", FInt64;
3243     "blocks", FInt64;
3244     "atime", FInt64;
3245     "mtime", FInt64;
3246     "ctime", FInt64;
3247   ];
3248   "statvfs", [
3249     "bsize", FInt64;
3250     "frsize", FInt64;
3251     "blocks", FInt64;
3252     "bfree", FInt64;
3253     "bavail", FInt64;
3254     "files", FInt64;
3255     "ffree", FInt64;
3256     "favail", FInt64;
3257     "fsid", FInt64;
3258     "flag", FInt64;
3259     "namemax", FInt64;
3260   ];
3261
3262   (* Column names in dirent structure. *)
3263   "dirent", [
3264     "ino", FInt64;
3265     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
3266     "ftyp", FChar;
3267     "name", FString;
3268   ];
3269
3270   (* Version numbers. *)
3271   "version", [
3272     "major", FInt64;
3273     "minor", FInt64;
3274     "release", FInt64;
3275     "extra", FString;
3276   ];
3277
3278   (* Extended attribute. *)
3279   "xattr", [
3280     "attrname", FString;
3281     "attrval", FBuffer;
3282   ];
3283 ] (* end of structs *)
3284
3285 (* Ugh, Java has to be different ..
3286  * These names are also used by the Haskell bindings.
3287  *)
3288 let java_structs = [
3289   "int_bool", "IntBool";
3290   "lvm_pv", "PV";
3291   "lvm_vg", "VG";
3292   "lvm_lv", "LV";
3293   "stat", "Stat";
3294   "statvfs", "StatVFS";
3295   "dirent", "Dirent";
3296   "version", "Version";
3297   "xattr", "XAttr";
3298 ]
3299
3300 (* Used for testing language bindings. *)
3301 type callt =
3302   | CallString of string
3303   | CallOptString of string option
3304   | CallStringList of string list
3305   | CallInt of int
3306   | CallBool of bool
3307
3308 (* Used to memoize the result of pod2text. *)
3309 let pod2text_memo_filename = "src/.pod2text.data"
3310 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
3311   try
3312     let chan = open_in pod2text_memo_filename in
3313     let v = input_value chan in
3314     close_in chan;
3315     v
3316   with
3317     _ -> Hashtbl.create 13
3318
3319 (* Useful functions.
3320  * Note we don't want to use any external OCaml libraries which
3321  * makes this a bit harder than it should be.
3322  *)
3323 let failwithf fs = ksprintf failwith fs
3324
3325 let replace_char s c1 c2 =
3326   let s2 = String.copy s in
3327   let r = ref false in
3328   for i = 0 to String.length s2 - 1 do
3329     if String.unsafe_get s2 i = c1 then (
3330       String.unsafe_set s2 i c2;
3331       r := true
3332     )
3333   done;
3334   if not !r then s else s2
3335
3336 let isspace c =
3337   c = ' '
3338   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
3339
3340 let triml ?(test = isspace) str =
3341   let i = ref 0 in
3342   let n = ref (String.length str) in
3343   while !n > 0 && test str.[!i]; do
3344     decr n;
3345     incr i
3346   done;
3347   if !i = 0 then str
3348   else String.sub str !i !n
3349
3350 let trimr ?(test = isspace) str =
3351   let n = ref (String.length str) in
3352   while !n > 0 && test str.[!n-1]; do
3353     decr n
3354   done;
3355   if !n = String.length str then str
3356   else String.sub str 0 !n
3357
3358 let trim ?(test = isspace) str =
3359   trimr ~test (triml ~test str)
3360
3361 let rec find s sub =
3362   let len = String.length s in
3363   let sublen = String.length sub in
3364   let rec loop i =
3365     if i <= len-sublen then (
3366       let rec loop2 j =
3367         if j < sublen then (
3368           if s.[i+j] = sub.[j] then loop2 (j+1)
3369           else -1
3370         ) else
3371           i (* found *)
3372       in
3373       let r = loop2 0 in
3374       if r = -1 then loop (i+1) else r
3375     ) else
3376       -1 (* not found *)
3377   in
3378   loop 0
3379
3380 let rec replace_str s s1 s2 =
3381   let len = String.length s in
3382   let sublen = String.length s1 in
3383   let i = find s s1 in
3384   if i = -1 then s
3385   else (
3386     let s' = String.sub s 0 i in
3387     let s'' = String.sub s (i+sublen) (len-i-sublen) in
3388     s' ^ s2 ^ replace_str s'' s1 s2
3389   )
3390
3391 let rec string_split sep str =
3392   let len = String.length str in
3393   let seplen = String.length sep in
3394   let i = find str sep in
3395   if i = -1 then [str]
3396   else (
3397     let s' = String.sub str 0 i in
3398     let s'' = String.sub str (i+seplen) (len-i-seplen) in
3399     s' :: string_split sep s''
3400   )
3401
3402 let files_equal n1 n2 =
3403   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
3404   match Sys.command cmd with
3405   | 0 -> true
3406   | 1 -> false
3407   | i -> failwithf "%s: failed with error code %d" cmd i
3408
3409 let rec find_map f = function
3410   | [] -> raise Not_found
3411   | x :: xs ->
3412       match f x with
3413       | Some y -> y
3414       | None -> find_map f xs
3415
3416 let iteri f xs =
3417   let rec loop i = function
3418     | [] -> ()
3419     | x :: xs -> f i x; loop (i+1) xs
3420   in
3421   loop 0 xs
3422
3423 let mapi f xs =
3424   let rec loop i = function
3425     | [] -> []
3426     | x :: xs -> let r = f i x in r :: loop (i+1) xs
3427   in
3428   loop 0 xs
3429
3430 let name_of_argt = function
3431   | String n | OptString n | StringList n | Bool n | Int n
3432   | FileIn n | FileOut n -> n
3433
3434 let java_name_of_struct typ =
3435   try List.assoc typ java_structs
3436   with Not_found ->
3437     failwithf
3438       "java_name_of_struct: no java_structs entry corresponding to %s" typ
3439
3440 let cols_of_struct typ =
3441   try List.assoc typ structs
3442   with Not_found ->
3443     failwithf "cols_of_struct: unknown struct %s" typ
3444
3445 let seq_of_test = function
3446   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
3447   | TestOutputListOfDevices (s, _)
3448   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
3449   | TestOutputTrue s | TestOutputFalse s
3450   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
3451   | TestOutputStruct (s, _)
3452   | TestLastFail s -> s
3453
3454 (* Handling for function flags. *)
3455 let protocol_limit_warning =
3456   "Because of the message protocol, there is a transfer limit
3457 of somewhere between 2MB and 4MB.  To transfer large files you should use
3458 FTP."
3459
3460 let danger_will_robinson =
3461   "B<This command is dangerous.  Without careful use you
3462 can easily destroy all your data>."
3463
3464 let deprecation_notice flags =
3465   try
3466     let alt =
3467       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
3468     let txt =
3469       sprintf "This function is deprecated.
3470 In new code, use the C<%s> call instead.
3471
3472 Deprecated functions will not be removed from the API, but the
3473 fact that they are deprecated indicates that there are problems
3474 with correct use of these functions." alt in
3475     Some txt
3476   with
3477     Not_found -> None
3478
3479 (* Check function names etc. for consistency. *)
3480 let check_functions () =
3481   let contains_uppercase str =
3482     let len = String.length str in
3483     let rec loop i =
3484       if i >= len then false
3485       else (
3486         let c = str.[i] in
3487         if c >= 'A' && c <= 'Z' then true
3488         else loop (i+1)
3489       )
3490     in
3491     loop 0
3492   in
3493
3494   (* Check function names. *)
3495   List.iter (
3496     fun (name, _, _, _, _, _, _) ->
3497       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
3498         failwithf "function name %s does not need 'guestfs' prefix" name;
3499       if name = "" then
3500         failwithf "function name is empty";
3501       if name.[0] < 'a' || name.[0] > 'z' then
3502         failwithf "function name %s must start with lowercase a-z" name;
3503       if String.contains name '-' then
3504         failwithf "function name %s should not contain '-', use '_' instead."
3505           name
3506   ) all_functions;
3507
3508   (* Check function parameter/return names. *)
3509   List.iter (
3510     fun (name, style, _, _, _, _, _) ->
3511       let check_arg_ret_name n =
3512         if contains_uppercase n then
3513           failwithf "%s param/ret %s should not contain uppercase chars"
3514             name n;
3515         if String.contains n '-' || String.contains n '_' then
3516           failwithf "%s param/ret %s should not contain '-' or '_'"
3517             name n;
3518         if n = "value" then
3519           failwithf "%s has a param/ret called 'value', which causes conflicts in the OCaml bindings, use something like 'val' or a more descriptive name" name;
3520         if n = "int" || n = "char" || n = "short" || n = "long" then
3521           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
3522         if n = "i" || n = "n" then
3523           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
3524         if n = "argv" || n = "args" then
3525           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name
3526       in
3527
3528       (match fst style with
3529        | RErr -> ()
3530        | RInt n | RInt64 n | RBool n
3531        | RConstString n | RConstOptString n | RString n
3532        | RStringList n | RStruct (n, _) | RStructList (n, _)
3533        | RHashtable n | RBufferOut n ->
3534            check_arg_ret_name n
3535       );
3536       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
3537   ) all_functions;
3538
3539   (* Check short descriptions. *)
3540   List.iter (
3541     fun (name, _, _, _, _, shortdesc, _) ->
3542       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
3543         failwithf "short description of %s should begin with lowercase." name;
3544       let c = shortdesc.[String.length shortdesc-1] in
3545       if c = '\n' || c = '.' then
3546         failwithf "short description of %s should not end with . or \\n." name
3547   ) all_functions;
3548
3549   (* Check long dscriptions. *)
3550   List.iter (
3551     fun (name, _, _, _, _, _, longdesc) ->
3552       if longdesc.[String.length longdesc-1] = '\n' then
3553         failwithf "long description of %s should not end with \\n." name
3554   ) all_functions;
3555
3556   (* Check proc_nrs. *)
3557   List.iter (
3558     fun (name, _, proc_nr, _, _, _, _) ->
3559       if proc_nr <= 0 then
3560         failwithf "daemon function %s should have proc_nr > 0" name
3561   ) daemon_functions;
3562
3563   List.iter (
3564     fun (name, _, proc_nr, _, _, _, _) ->
3565       if proc_nr <> -1 then
3566         failwithf "non-daemon function %s should have proc_nr -1" name
3567   ) non_daemon_functions;
3568
3569   let proc_nrs =
3570     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
3571       daemon_functions in
3572   let proc_nrs =
3573     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
3574   let rec loop = function
3575     | [] -> ()
3576     | [_] -> ()
3577     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
3578         loop rest
3579     | (name1,nr1) :: (name2,nr2) :: _ ->
3580         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
3581           name1 name2 nr1 nr2
3582   in
3583   loop proc_nrs;
3584
3585   (* Check tests. *)
3586   List.iter (
3587     function
3588       (* Ignore functions that have no tests.  We generate a
3589        * warning when the user does 'make check' instead.
3590        *)
3591     | name, _, _, _, [], _, _ -> ()
3592     | name, _, _, _, tests, _, _ ->
3593         let funcs =
3594           List.map (
3595             fun (_, _, test) ->
3596               match seq_of_test test with
3597               | [] ->
3598                   failwithf "%s has a test containing an empty sequence" name
3599               | cmds -> List.map List.hd cmds
3600           ) tests in
3601         let funcs = List.flatten funcs in
3602
3603         let tested = List.mem name funcs in
3604
3605         if not tested then
3606           failwithf "function %s has tests but does not test itself" name
3607   ) all_functions
3608
3609 (* 'pr' prints to the current output file. *)
3610 let chan = ref stdout
3611 let pr fs = ksprintf (output_string !chan) fs
3612
3613 (* Generate a header block in a number of standard styles. *)
3614 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
3615 type license = GPLv2 | LGPLv2
3616
3617 let generate_header comment license =
3618   let c = match comment with
3619     | CStyle ->     pr "/* "; " *"
3620     | HashStyle ->  pr "# ";  "#"
3621     | OCamlStyle -> pr "(* "; " *"
3622     | HaskellStyle -> pr "{- "; "  " in
3623   pr "libguestfs generated file\n";
3624   pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
3625   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
3626   pr "%s\n" c;
3627   pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
3628   pr "%s\n" c;
3629   (match license with
3630    | GPLv2 ->
3631        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
3632        pr "%s it under the terms of the GNU General Public License as published by\n" c;
3633        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
3634        pr "%s (at your option) any later version.\n" c;
3635        pr "%s\n" c;
3636        pr "%s This program is distributed in the hope that it will be useful,\n" c;
3637        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3638        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
3639        pr "%s GNU General Public License for more details.\n" c;
3640        pr "%s\n" c;
3641        pr "%s You should have received a copy of the GNU General Public License along\n" c;
3642        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
3643        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
3644
3645    | LGPLv2 ->
3646        pr "%s This library is free software; you can redistribute it and/or\n" c;
3647        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
3648        pr "%s License as published by the Free Software Foundation; either\n" c;
3649        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
3650        pr "%s\n" c;
3651        pr "%s This library is distributed in the hope that it will be useful,\n" c;
3652        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
3653        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
3654        pr "%s Lesser General Public License for more details.\n" c;
3655        pr "%s\n" c;
3656        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
3657        pr "%s License along with this library; if not, write to the Free Software\n" c;
3658        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
3659   );
3660   (match comment with
3661    | CStyle -> pr " */\n"
3662    | HashStyle -> ()
3663    | OCamlStyle -> pr " *)\n"
3664    | HaskellStyle -> pr "-}\n"
3665   );
3666   pr "\n"
3667
3668 (* Start of main code generation functions below this line. *)
3669
3670 (* Generate the pod documentation for the C API. *)
3671 let rec generate_actions_pod () =
3672   List.iter (
3673     fun (shortname, style, _, flags, _, _, longdesc) ->
3674       if not (List.mem NotInDocs flags) then (
3675         let name = "guestfs_" ^ shortname in
3676         pr "=head2 %s\n\n" name;
3677         pr " ";
3678         generate_prototype ~extern:false ~handle:"handle" name style;
3679         pr "\n\n";
3680         pr "%s\n\n" longdesc;
3681         (match fst style with
3682          | RErr ->
3683              pr "This function returns 0 on success or -1 on error.\n\n"
3684          | RInt _ ->
3685              pr "On error this function returns -1.\n\n"
3686          | RInt64 _ ->
3687              pr "On error this function returns -1.\n\n"
3688          | RBool _ ->
3689              pr "This function returns a C truth value on success or -1 on error.\n\n"
3690          | RConstString _ ->
3691              pr "This function returns a string, or NULL on error.
3692 The string is owned by the guest handle and must I<not> be freed.\n\n"
3693          | RConstOptString _ ->
3694              pr "This function returns a string which may be NULL.
3695 There is way to return an error from this function.
3696 The string is owned by the guest handle and must I<not> be freed.\n\n"
3697          | RString _ ->
3698              pr "This function returns a string, or NULL on error.
3699 I<The caller must free the returned string after use>.\n\n"
3700          | RStringList _ ->
3701              pr "This function returns a NULL-terminated array of strings
3702 (like L<environ(3)>), or NULL if there was an error.
3703 I<The caller must free the strings and the array after use>.\n\n"
3704          | RStruct (_, typ) ->
3705              pr "This function returns a C<struct guestfs_%s *>,
3706 or NULL if there was an error.
3707 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
3708          | RStructList (_, typ) ->
3709              pr "This function returns a C<struct guestfs_%s_list *>
3710 (see E<lt>guestfs-structs.hE<gt>),
3711 or NULL if there was an error.
3712 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
3713          | RHashtable _ ->
3714              pr "This function returns a NULL-terminated array of
3715 strings, or NULL if there was an error.
3716 The array of strings will always have length C<2n+1>, where
3717 C<n> keys and values alternate, followed by the trailing NULL entry.
3718 I<The caller must free the strings and the array after use>.\n\n"
3719          | RBufferOut _ ->
3720              pr "This function returns a buffer, or NULL on error.
3721 The size of the returned buffer is written to C<*size_r>.
3722 I<The caller must free the returned buffer after use>.\n\n"
3723         );
3724         if List.mem ProtocolLimitWarning flags then
3725           pr "%s\n\n" protocol_limit_warning;
3726         if List.mem DangerWillRobinson flags then
3727           pr "%s\n\n" danger_will_robinson;
3728         match deprecation_notice flags with
3729         | None -> ()
3730         | Some txt -> pr "%s\n\n" txt
3731       )
3732   ) all_functions_sorted
3733
3734 and generate_structs_pod () =
3735   (* Structs documentation. *)
3736   List.iter (
3737     fun (typ, cols) ->
3738       pr "=head2 guestfs_%s\n" typ;
3739       pr "\n";
3740       pr " struct guestfs_%s {\n" typ;
3741       List.iter (
3742         function
3743         | name, FChar -> pr "   char %s;\n" name
3744         | name, FUInt32 -> pr "   uint32_t %s;\n" name
3745         | name, FInt32 -> pr "   int32_t %s;\n" name
3746         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
3747         | name, FInt64 -> pr "   int64_t %s;\n" name
3748         | name, FString -> pr "   char *%s;\n" name
3749         | name, FBuffer ->
3750             pr "   /* The next two fields describe a byte array. */\n";
3751             pr "   uint32_t %s_len;\n" name;
3752             pr "   char *%s;\n" name
3753         | name, FUUID ->
3754             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
3755             pr "   char %s[32];\n" name
3756         | name, FOptPercent ->
3757             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
3758             pr "   float %s;\n" name
3759       ) cols;
3760       pr " };\n";
3761       pr " \n";
3762       pr " struct guestfs_%s_list {\n" typ;
3763       pr "   uint32_t len; /* Number of elements in list. */\n";
3764       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
3765       pr " };\n";
3766       pr " \n";
3767       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
3768       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
3769         typ typ;
3770       pr "\n"
3771   ) structs
3772
3773 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
3774  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
3775  *
3776  * We have to use an underscore instead of a dash because otherwise
3777  * rpcgen generates incorrect code.
3778  *
3779  * This header is NOT exported to clients, but see also generate_structs_h.
3780  *)
3781 and generate_xdr () =
3782   generate_header CStyle LGPLv2;
3783
3784   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
3785   pr "typedef string str<>;\n";
3786   pr "\n";
3787
3788   (* Internal structures. *)
3789   List.iter (
3790     function
3791     | typ, cols ->
3792         pr "struct guestfs_int_%s {\n" typ;
3793         List.iter (function
3794                    | name, FChar -> pr "  char %s;\n" name
3795                    | name, FString -> pr "  string %s<>;\n" name
3796                    | name, FBuffer -> pr "  opaque %s<>;\n" name
3797                    | name, FUUID -> pr "  opaque %s[32];\n" name
3798                    | name, (FInt32|FUInt32) -> pr "  int %s;\n" name
3799                    | name, (FInt64|FUInt64|FBytes) -> pr "  hyper %s;\n" name
3800                    | name, FOptPercent -> pr "  float %s;\n" name
3801                   ) cols;
3802         pr "};\n";
3803         pr "\n";
3804         pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
3805         pr "\n";
3806   ) structs;
3807
3808   List.iter (
3809     fun (shortname, style, _, _, _, _, _) ->
3810       let name = "guestfs_" ^ shortname in
3811
3812       (match snd style with
3813        | [] -> ()
3814        | args ->
3815            pr "struct %s_args {\n" name;
3816            List.iter (
3817              function
3818              | String n -> pr "  string %s<>;\n" n
3819              | OptString n -> pr "  str *%s;\n" n
3820              | StringList n -> pr "  str %s<>;\n" n
3821              | Bool n -> pr "  bool %s;\n" n
3822              | Int n -> pr "  int %s;\n" n
3823              | FileIn _ | FileOut _ -> ()
3824            ) args;
3825            pr "};\n\n"
3826       );
3827       (match fst style with
3828        | RErr -> ()
3829        | RInt n ->
3830            pr "struct %s_ret {\n" name;
3831            pr "  int %s;\n" n;
3832            pr "};\n\n"
3833        | RInt64 n ->
3834            pr "struct %s_ret {\n" name;
3835            pr "  hyper %s;\n" n;
3836            pr "};\n\n"
3837        | RBool n ->
3838            pr "struct %s_ret {\n" name;
3839            pr "  bool %s;\n" n;
3840            pr "};\n\n"
3841        | RConstString _ | RConstOptString _ ->
3842            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
3843        | RString n ->
3844            pr "struct %s_ret {\n" name;
3845            pr "  string %s<>;\n" n;
3846            pr "};\n\n"
3847        | RStringList n ->
3848            pr "struct %s_ret {\n" name;
3849            pr "  str %s<>;\n" n;
3850            pr "};\n\n"
3851        | RStruct (n, typ) ->
3852            pr "struct %s_ret {\n" name;
3853            pr "  guestfs_int_%s %s;\n" typ n;
3854            pr "};\n\n"
3855        | RStructList (n, typ) ->
3856            pr "struct %s_ret {\n" name;
3857            pr "  guestfs_int_%s_list %s;\n" typ n;
3858            pr "};\n\n"
3859        | RHashtable n ->
3860            pr "struct %s_ret {\n" name;
3861            pr "  str %s<>;\n" n;
3862            pr "};\n\n"
3863        | RBufferOut n ->
3864            pr "struct %s_ret {\n" name;
3865            pr "  opaque %s<>;\n" n;
3866            pr "};\n\n"
3867       );
3868   ) daemon_functions;
3869
3870   (* Table of procedure numbers. *)
3871   pr "enum guestfs_procedure {\n";
3872   List.iter (
3873     fun (shortname, _, proc_nr, _, _, _, _) ->
3874       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
3875   ) daemon_functions;
3876   pr "  GUESTFS_PROC_NR_PROCS\n";
3877   pr "};\n";
3878   pr "\n";
3879
3880   (* Having to choose a maximum message size is annoying for several
3881    * reasons (it limits what we can do in the API), but it (a) makes
3882    * the protocol a lot simpler, and (b) provides a bound on the size
3883    * of the daemon which operates in limited memory space.  For large
3884    * file transfers you should use FTP.
3885    *)
3886   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
3887   pr "\n";
3888
3889   (* Message header, etc. *)
3890   pr "\
3891 /* The communication protocol is now documented in the guestfs(3)
3892  * manpage.
3893  */
3894
3895 const GUESTFS_PROGRAM = 0x2000F5F5;
3896 const GUESTFS_PROTOCOL_VERSION = 1;
3897
3898 /* These constants must be larger than any possible message length. */
3899 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
3900 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
3901
3902 enum guestfs_message_direction {
3903   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
3904   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
3905 };
3906
3907 enum guestfs_message_status {
3908   GUESTFS_STATUS_OK = 0,
3909   GUESTFS_STATUS_ERROR = 1
3910 };
3911
3912 const GUESTFS_ERROR_LEN = 256;
3913
3914 struct guestfs_message_error {
3915   string error_message<GUESTFS_ERROR_LEN>;
3916 };
3917
3918 struct guestfs_message_header {
3919   unsigned prog;                     /* GUESTFS_PROGRAM */
3920   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
3921   guestfs_procedure proc;            /* GUESTFS_PROC_x */
3922   guestfs_message_direction direction;
3923   unsigned serial;                   /* message serial number */
3924   guestfs_message_status status;
3925 };
3926
3927 const GUESTFS_MAX_CHUNK_SIZE = 8192;
3928
3929 struct guestfs_chunk {
3930   int cancel;                        /* if non-zero, transfer is cancelled */
3931   /* data size is 0 bytes if the transfer has finished successfully */
3932   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
3933 };
3934 "
3935
3936 (* Generate the guestfs-structs.h file. *)
3937 and generate_structs_h () =
3938   generate_header CStyle LGPLv2;
3939
3940   (* This is a public exported header file containing various
3941    * structures.  The structures are carefully written to have
3942    * exactly the same in-memory format as the XDR structures that
3943    * we use on the wire to the daemon.  The reason for creating
3944    * copies of these structures here is just so we don't have to
3945    * export the whole of guestfs_protocol.h (which includes much
3946    * unrelated and XDR-dependent stuff that we don't want to be
3947    * public, or required by clients).
3948    *
3949    * To reiterate, we will pass these structures to and from the
3950    * client with a simple assignment or memcpy, so the format
3951    * must be identical to what rpcgen / the RFC defines.
3952    *)
3953
3954   (* Public structures. *)
3955   List.iter (
3956     fun (typ, cols) ->
3957       pr "struct guestfs_%s {\n" typ;
3958       List.iter (
3959         function
3960         | name, FChar -> pr "  char %s;\n" name
3961         | name, FString -> pr "  char *%s;\n" name
3962         | name, FBuffer ->
3963             pr "  uint32_t %s_len;\n" name;
3964             pr "  char *%s;\n" name
3965         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
3966         | name, FUInt32 -> pr "  uint32_t %s;\n" name
3967         | name, FInt32 -> pr "  int32_t %s;\n" name
3968         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
3969         | name, FInt64 -> pr "  int64_t %s;\n" name
3970         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
3971       ) cols;
3972       pr "};\n";
3973       pr "\n";
3974       pr "struct guestfs_%s_list {\n" typ;
3975       pr "  uint32_t len;\n";
3976       pr "  struct guestfs_%s *val;\n" typ;
3977       pr "};\n";
3978       pr "\n";
3979       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
3980       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
3981       pr "\n"
3982   ) structs
3983
3984 (* Generate the guestfs-actions.h file. *)
3985 and generate_actions_h () =
3986   generate_header CStyle LGPLv2;
3987   List.iter (
3988     fun (shortname, style, _, _, _, _, _) ->
3989       let name = "guestfs_" ^ shortname in
3990       generate_prototype ~single_line:true ~newline:true ~handle:"handle"
3991         name style
3992   ) all_functions
3993
3994 (* Generate the client-side dispatch stubs. *)
3995 and generate_client_actions () =
3996   generate_header CStyle LGPLv2;
3997
3998   pr "\
3999 #include <stdio.h>
4000 #include <stdlib.h>
4001
4002 #include \"guestfs.h\"
4003 #include \"guestfs_protocol.h\"
4004
4005 #define error guestfs_error
4006 #define perrorf guestfs_perrorf
4007 #define safe_malloc guestfs_safe_malloc
4008 #define safe_realloc guestfs_safe_realloc
4009 #define safe_strdup guestfs_safe_strdup
4010 #define safe_memdup guestfs_safe_memdup
4011
4012 /* Check the return message from a call for validity. */
4013 static int
4014 check_reply_header (guestfs_h *g,
4015                     const struct guestfs_message_header *hdr,
4016                     int proc_nr, int serial)
4017 {
4018   if (hdr->prog != GUESTFS_PROGRAM) {
4019     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
4020     return -1;
4021   }
4022   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
4023     error (g, \"wrong protocol version (%%d/%%d)\",
4024            hdr->vers, GUESTFS_PROTOCOL_VERSION);
4025     return -1;
4026   }
4027   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
4028     error (g, \"unexpected message direction (%%d/%%d)\",
4029            hdr->direction, GUESTFS_DIRECTION_REPLY);
4030     return -1;
4031   }
4032   if (hdr->proc != proc_nr) {
4033     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
4034     return -1;
4035   }
4036   if (hdr->serial != serial) {
4037     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
4038     return -1;
4039   }
4040
4041   return 0;
4042 }
4043
4044 /* Check we are in the right state to run a high-level action. */
4045 static int
4046 check_state (guestfs_h *g, const char *caller)
4047 {
4048   if (!guestfs_is_ready (g)) {
4049     if (guestfs_is_config (g))
4050       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
4051         caller);
4052     else if (guestfs_is_launching (g))
4053       error (g, \"%%s: call wait_ready() before using this function\",
4054         caller);
4055     else
4056       error (g, \"%%s called from the wrong state, %%d != READY\",
4057         caller, guestfs_get_state (g));
4058     return -1;
4059   }
4060   return 0;
4061 }
4062
4063 ";
4064
4065   (* Client-side stubs for each function. *)
4066   List.iter (
4067     fun (shortname, style, _, _, _, _, _) ->
4068       let name = "guestfs_" ^ shortname in
4069
4070       (* Generate the context struct which stores the high-level
4071        * state between callback functions.
4072        *)
4073       pr "struct %s_ctx {\n" shortname;
4074       pr "  /* This flag is set by the callbacks, so we know we've done\n";
4075       pr "   * the callbacks as expected, and in the right sequence.\n";
4076       pr "   * 0 = not called, 1 = reply_cb called.\n";
4077       pr "   */\n";
4078       pr "  int cb_sequence;\n";
4079       pr "  struct guestfs_message_header hdr;\n";
4080       pr "  struct guestfs_message_error err;\n";
4081       (match fst style with
4082        | RErr -> ()
4083        | RConstString _ | RConstOptString _ ->
4084            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4085        | RInt _ | RInt64 _
4086        | RBool _ | RString _ | RStringList _
4087        | RStruct _ | RStructList _
4088        | RHashtable _ | RBufferOut _ ->
4089            pr "  struct %s_ret ret;\n" name
4090       );
4091       pr "};\n";
4092       pr "\n";
4093
4094       (* Generate the reply callback function. *)
4095       pr "static void %s_reply_cb (guestfs_h *g, void *data, XDR *xdr)\n" shortname;
4096       pr "{\n";
4097       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
4098       pr "  struct %s_ctx *ctx = (struct %s_ctx *) data;\n" shortname shortname;
4099       pr "\n";
4100       pr "  /* This should definitely not happen. */\n";
4101       pr "  if (ctx->cb_sequence != 0) {\n";
4102       pr "    ctx->cb_sequence = 9999;\n";
4103       pr "    error (g, \"%%s: internal error: reply callback called twice\", \"%s\");\n" name;
4104       pr "    return;\n";
4105       pr "  }\n";
4106       pr "\n";
4107       pr "  ml->main_loop_quit (ml, g);\n";
4108       pr "\n";
4109       pr "  if (!xdr_guestfs_message_header (xdr, &ctx->hdr)) {\n";
4110       pr "    error (g, \"%%s: failed to parse reply header\", \"%s\");\n" name;
4111       pr "    return;\n";
4112       pr "  }\n";
4113       pr "  if (ctx->hdr.status == GUESTFS_STATUS_ERROR) {\n";
4114       pr "    if (!xdr_guestfs_message_error (xdr, &ctx->err)) {\n";
4115       pr "      error (g, \"%%s: failed to parse reply error\", \"%s\");\n"
4116         name;
4117       pr "      return;\n";
4118       pr "    }\n";
4119       pr "    goto done;\n";
4120       pr "  }\n";
4121
4122       (match fst style with
4123        | RErr -> ()
4124        | RConstString _ | RConstOptString _ ->
4125            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4126        | RInt _ | RInt64 _
4127        | RBool _ | RString _ | RStringList _
4128        | RStruct _ | RStructList _
4129        | RHashtable _ | RBufferOut _ ->
4130            pr "  if (!xdr_%s_ret (xdr, &ctx->ret)) {\n" name;
4131            pr "    error (g, \"%%s: failed to parse reply\", \"%s\");\n" name;
4132            pr "    return;\n";
4133            pr "  }\n";
4134       );
4135
4136       pr " done:\n";
4137       pr "  ctx->cb_sequence = 1;\n";
4138       pr "}\n\n";
4139
4140       (* Generate the action stub. *)
4141       generate_prototype ~extern:false ~semicolon:false ~newline:true
4142         ~handle:"g" name style;
4143
4144       let error_code =
4145         match fst style with
4146         | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
4147         | RConstString _ | RConstOptString _ ->
4148             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4149         | RString _ | RStringList _
4150         | RStruct _ | RStructList _
4151         | RHashtable _ | RBufferOut _ ->
4152             "NULL" in
4153
4154       pr "{\n";
4155
4156       (match snd style with
4157        | [] -> ()
4158        | _ -> pr "  struct %s_args args;\n" name
4159       );
4160
4161       pr "  struct %s_ctx ctx;\n" shortname;
4162       pr "  guestfs_main_loop *ml = guestfs_get_main_loop (g);\n";
4163       pr "  int serial;\n";
4164       pr "\n";
4165       pr "  if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
4166       pr "  guestfs_set_busy (g);\n";
4167       pr "\n";
4168       pr "  memset (&ctx, 0, sizeof ctx);\n";
4169       pr "\n";
4170
4171       (* Send the main header and arguments. *)
4172       (match snd style with
4173        | [] ->
4174            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s, NULL, NULL);\n"
4175              (String.uppercase shortname)
4176        | args ->
4177            List.iter (
4178              function
4179              | String n ->
4180                  pr "  args.%s = (char *) %s;\n" n n
4181              | OptString n ->
4182                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
4183              | StringList n ->
4184                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
4185                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
4186              | Bool n ->
4187                  pr "  args.%s = %s;\n" n n
4188              | Int n ->
4189                  pr "  args.%s = %s;\n" n n
4190              | FileIn _ | FileOut _ -> ()
4191            ) args;
4192            pr "  serial = guestfs__send_sync (g, GUESTFS_PROC_%s,\n"
4193              (String.uppercase shortname);
4194            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
4195              name;
4196       );
4197       pr "  if (serial == -1) {\n";
4198       pr "    guestfs_end_busy (g);\n";
4199       pr "    return %s;\n" error_code;
4200       pr "  }\n";
4201       pr "\n";
4202
4203       (* Send any additional files (FileIn) requested. *)
4204       let need_read_reply_label = ref false in
4205       List.iter (
4206         function
4207         | FileIn n ->
4208             pr "  {\n";
4209             pr "    int r;\n";
4210             pr "\n";
4211             pr "    r = guestfs__send_file_sync (g, %s);\n" n;
4212             pr "    if (r == -1) {\n";
4213             pr "      guestfs_end_busy (g);\n";
4214             pr "      return %s;\n" error_code;
4215             pr "    }\n";
4216             pr "    if (r == -2) /* daemon cancelled */\n";
4217             pr "      goto read_reply;\n";
4218             need_read_reply_label := true;
4219             pr "  }\n";
4220             pr "\n";
4221         | _ -> ()
4222       ) (snd style);
4223
4224       (* Wait for the reply from the remote end. *)
4225       if !need_read_reply_label then pr " read_reply:\n";
4226       pr "  guestfs__switch_to_receiving (g);\n";
4227       pr "  ctx.cb_sequence = 0;\n";
4228       pr "  guestfs_set_reply_callback (g, %s_reply_cb, &ctx);\n" shortname;
4229       pr "  (void) ml->main_loop_run (ml, g);\n";
4230       pr "  guestfs_set_reply_callback (g, NULL, NULL);\n";
4231       pr "  if (ctx.cb_sequence != 1) {\n";
4232       pr "    error (g, \"%%s reply failed, see earlier error messages\", \"%s\");\n" name;
4233       pr "    guestfs_end_busy (g);\n";
4234       pr "    return %s;\n" error_code;
4235       pr "  }\n";
4236       pr "\n";
4237
4238       pr "  if (check_reply_header (g, &ctx.hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
4239         (String.uppercase shortname);
4240       pr "    guestfs_end_busy (g);\n";
4241       pr "    return %s;\n" error_code;
4242       pr "  }\n";
4243       pr "\n";
4244
4245       pr "  if (ctx.hdr.status == GUESTFS_STATUS_ERROR) {\n";
4246       pr "    error (g, \"%%s\", ctx.err.error_message);\n";
4247       pr "    free (ctx.err.error_message);\n";
4248       pr "    guestfs_end_busy (g);\n";
4249       pr "    return %s;\n" error_code;
4250       pr "  }\n";
4251       pr "\n";
4252
4253       (* Expecting to receive further files (FileOut)? *)
4254       List.iter (
4255         function
4256         | FileOut n ->
4257             pr "  if (guestfs__receive_file_sync (g, %s) == -1) {\n" n;
4258             pr "    guestfs_end_busy (g);\n";
4259             pr "    return %s;\n" error_code;
4260             pr "  }\n";
4261             pr "\n";
4262         | _ -> ()
4263       ) (snd style);
4264
4265       pr "  guestfs_end_busy (g);\n";
4266
4267       (match fst style with
4268        | RErr -> pr "  return 0;\n"
4269        | RInt n | RInt64 n | RBool n ->
4270            pr "  return ctx.ret.%s;\n" n
4271        | RConstString _ | RConstOptString _ ->
4272            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4273        | RString n ->
4274            pr "  return ctx.ret.%s; /* caller will free */\n" n
4275        | RStringList n | RHashtable n ->
4276            pr "  /* caller will free this, but we need to add a NULL entry */\n";
4277            pr "  ctx.ret.%s.%s_val =\n" n n;
4278            pr "    safe_realloc (g, ctx.ret.%s.%s_val,\n" n n;
4279            pr "                  sizeof (char *) * (ctx.ret.%s.%s_len + 1));\n"
4280              n n;
4281            pr "  ctx.ret.%s.%s_val[ctx.ret.%s.%s_len] = NULL;\n" n n n n;
4282            pr "  return ctx.ret.%s.%s_val;\n" n n
4283        | RStruct (n, _) ->
4284            pr "  /* caller will free this */\n";
4285            pr "  return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4286        | RStructList (n, _) ->
4287            pr "  /* caller will free this */\n";
4288            pr "  return safe_memdup (g, &ctx.ret.%s, sizeof (ctx.ret.%s));\n" n n
4289        | RBufferOut n ->
4290            pr "  *size_r = ctx.ret.%s.%s_len;\n" n n;
4291            pr "  return ctx.ret.%s.%s_val; /* caller will free */\n" n n
4292       );
4293
4294       pr "}\n\n"
4295   ) daemon_functions;
4296
4297   (* Functions to free structures. *)
4298   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
4299   pr " * structure format is identical to the XDR format.  See note in\n";
4300   pr " * generator.ml.\n";
4301   pr " */\n";
4302   pr "\n";
4303
4304   List.iter (
4305     fun (typ, _) ->
4306       pr "void\n";
4307       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
4308       pr "{\n";
4309       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
4310       pr "  free (x);\n";
4311       pr "}\n";
4312       pr "\n";
4313
4314       pr "void\n";
4315       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
4316       pr "{\n";
4317       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
4318       pr "  free (x);\n";
4319       pr "}\n";
4320       pr "\n";
4321
4322   ) structs;
4323
4324 (* Generate daemon/actions.h. *)
4325 and generate_daemon_actions_h () =
4326   generate_header CStyle GPLv2;
4327
4328   pr "#include \"../src/guestfs_protocol.h\"\n";
4329   pr "\n";
4330
4331   List.iter (
4332     fun (name, style, _, _, _, _, _) ->
4333       generate_prototype
4334         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
4335         name style;
4336   ) daemon_functions
4337
4338 (* Generate the server-side stubs. *)
4339 and generate_daemon_actions () =
4340   generate_header CStyle GPLv2;
4341
4342   pr "#include <config.h>\n";
4343   pr "\n";
4344   pr "#include <stdio.h>\n";
4345   pr "#include <stdlib.h>\n";
4346   pr "#include <string.h>\n";
4347   pr "#include <inttypes.h>\n";
4348   pr "#include <ctype.h>\n";
4349   pr "#include <rpc/types.h>\n";
4350   pr "#include <rpc/xdr.h>\n";
4351   pr "\n";
4352   pr "#include \"daemon.h\"\n";
4353   pr "#include \"../src/guestfs_protocol.h\"\n";
4354   pr "#include \"actions.h\"\n";
4355   pr "\n";
4356
4357   List.iter (
4358     fun (name, style, _, _, _, _, _) ->
4359       (* Generate server-side stubs. *)
4360       pr "static void %s_stub (XDR *xdr_in)\n" name;
4361       pr "{\n";
4362       let error_code =
4363         match fst style with
4364         | RErr | RInt _ -> pr "  int r;\n"; "-1"
4365         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
4366         | RBool _ -> pr "  int r;\n"; "-1"
4367         | RConstString _ | RConstOptString _ ->
4368             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4369         | RString _ -> pr "  char *r;\n"; "NULL"
4370         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
4371         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
4372         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
4373         | RBufferOut _ ->
4374             pr "  size_t size;\n";
4375             pr "  char *r;\n";
4376             "NULL" in
4377
4378       (match snd style with
4379        | [] -> ()
4380        | args ->
4381            pr "  struct guestfs_%s_args args;\n" name;
4382            List.iter (
4383              function
4384                (* Note we allow the string to be writable, in order to
4385                 * allow device name translation.  This is safe because
4386                 * we can modify the string (passed from RPC).
4387                 *)
4388              | String n
4389              | OptString n -> pr "  char *%s;\n" n
4390              | StringList n -> pr "  char **%s;\n" n
4391              | Bool n -> pr "  int %s;\n" n
4392              | Int n -> pr "  int %s;\n" n
4393              | FileIn _ | FileOut _ -> ()
4394            ) args
4395       );
4396       pr "\n";
4397
4398       (match snd style with
4399        | [] -> ()
4400        | args ->
4401            pr "  memset (&args, 0, sizeof args);\n";
4402            pr "\n";
4403            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
4404            pr "    reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
4405            pr "    return;\n";
4406            pr "  }\n";
4407            List.iter (
4408              function
4409              | String n -> pr "  %s = args.%s;\n" n n
4410              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
4411              | StringList n ->
4412                  pr "  %s = realloc (args.%s.%s_val,\n" n n n;
4413                  pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
4414                  pr "  if (%s == NULL) {\n" n;
4415                  pr "    reply_with_perror (\"realloc\");\n";
4416                  pr "    goto done;\n";
4417                  pr "  }\n";
4418                  pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
4419                  pr "  args.%s.%s_val = %s;\n" n n n;
4420              | Bool n -> pr "  %s = args.%s;\n" n n
4421              | Int n -> pr "  %s = args.%s;\n" n n
4422              | FileIn _ | FileOut _ -> ()
4423            ) args;
4424            pr "\n"
4425       );
4426
4427       (* Don't want to call the impl with any FileIn or FileOut
4428        * parameters, since these go "outside" the RPC protocol.
4429        *)
4430       let args' =
4431         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
4432           (snd style) in
4433       pr "  r = do_%s " name;
4434       generate_c_call_args (fst style, args');
4435       pr ";\n";
4436
4437       pr "  if (r == %s)\n" error_code;
4438       pr "    /* do_%s has already called reply_with_error */\n" name;
4439       pr "    goto done;\n";
4440       pr "\n";
4441
4442       (* If there are any FileOut parameters, then the impl must
4443        * send its own reply.
4444        *)
4445       let no_reply =
4446         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
4447       if no_reply then
4448         pr "  /* do_%s has already sent a reply */\n" name
4449       else (
4450         match fst style with
4451         | RErr -> pr "  reply (NULL, NULL);\n"
4452         | RInt n | RInt64 n | RBool n ->
4453             pr "  struct guestfs_%s_ret ret;\n" name;
4454             pr "  ret.%s = r;\n" n;
4455             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4456               name
4457         | RConstString _ | RConstOptString _ ->
4458             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4459         | RString n ->
4460             pr "  struct guestfs_%s_ret ret;\n" name;
4461             pr "  ret.%s = r;\n" n;
4462             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4463               name;
4464             pr "  free (r);\n"
4465         | RStringList n | RHashtable n ->
4466             pr "  struct guestfs_%s_ret ret;\n" name;
4467             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
4468             pr "  ret.%s.%s_val = r;\n" n n;
4469             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4470               name;
4471             pr "  free_strings (r);\n"
4472         | RStruct (n, _) ->
4473             pr "  struct guestfs_%s_ret ret;\n" name;
4474             pr "  ret.%s = *r;\n" n;
4475             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4476               name;
4477             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4478               name
4479         | RStructList (n, _) ->
4480             pr "  struct guestfs_%s_ret ret;\n" name;
4481             pr "  ret.%s = *r;\n" n;
4482             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4483               name;
4484             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
4485               name
4486         | RBufferOut n ->
4487             pr "  struct guestfs_%s_ret ret;\n" name;
4488             pr "  ret.%s.%s_val = r;\n" n n;
4489             pr "  ret.%s.%s_len = size;\n" n n;
4490             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
4491               name;
4492             pr "  free (r);\n"
4493       );
4494
4495       (* Free the args. *)
4496       (match snd style with
4497        | [] ->
4498            pr "done: ;\n";
4499        | _ ->
4500            pr "done:\n";
4501            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
4502              name
4503       );
4504
4505       pr "}\n\n";
4506   ) daemon_functions;
4507
4508   (* Dispatch function. *)
4509   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
4510   pr "{\n";
4511   pr "  switch (proc_nr) {\n";
4512
4513   List.iter (
4514     fun (name, style, _, _, _, _, _) ->
4515       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
4516       pr "      %s_stub (xdr_in);\n" name;
4517       pr "      break;\n"
4518   ) daemon_functions;
4519
4520   pr "    default:\n";
4521   pr "      reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d, set LIBGUESTFS_PATH to point to the matching libguestfs appliance directory\", proc_nr);\n";
4522   pr "  }\n";
4523   pr "}\n";
4524   pr "\n";
4525
4526   (* LVM columns and tokenization functions. *)
4527   (* XXX This generates crap code.  We should rethink how we
4528    * do this parsing.
4529    *)
4530   List.iter (
4531     function
4532     | typ, cols ->
4533         pr "static const char *lvm_%s_cols = \"%s\";\n"
4534           typ (String.concat "," (List.map fst cols));
4535         pr "\n";
4536
4537         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
4538         pr "{\n";
4539         pr "  char *tok, *p, *next;\n";
4540         pr "  int i, j;\n";
4541         pr "\n";
4542         (*
4543           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
4544           pr "\n";
4545         *)
4546         pr "  if (!str) {\n";
4547         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
4548         pr "    return -1;\n";
4549         pr "  }\n";
4550         pr "  if (!*str || isspace (*str)) {\n";
4551         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
4552         pr "    return -1;\n";
4553         pr "  }\n";
4554         pr "  tok = str;\n";
4555         List.iter (
4556           fun (name, coltype) ->
4557             pr "  if (!tok) {\n";
4558             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
4559             pr "    return -1;\n";
4560             pr "  }\n";
4561             pr "  p = strchrnul (tok, ',');\n";
4562             pr "  if (*p) next = p+1; else next = NULL;\n";
4563             pr "  *p = '\\0';\n";
4564             (match coltype with
4565              | FString ->
4566                  pr "  r->%s = strdup (tok);\n" name;
4567                  pr "  if (r->%s == NULL) {\n" name;
4568                  pr "    perror (\"strdup\");\n";
4569                  pr "    return -1;\n";
4570                  pr "  }\n"
4571              | FUUID ->
4572                  pr "  for (i = j = 0; i < 32; ++j) {\n";
4573                  pr "    if (tok[j] == '\\0') {\n";
4574                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
4575                  pr "      return -1;\n";
4576                  pr "    } else if (tok[j] != '-')\n";
4577                  pr "      r->%s[i++] = tok[j];\n" name;
4578                  pr "  }\n";
4579              | FBytes ->
4580                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
4581                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4582                  pr "    return -1;\n";
4583                  pr "  }\n";
4584              | FInt64 ->
4585                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
4586                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4587                  pr "    return -1;\n";
4588                  pr "  }\n";
4589              | FOptPercent ->
4590                  pr "  if (tok[0] == '\\0')\n";
4591                  pr "    r->%s = -1;\n" name;
4592                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
4593                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
4594                  pr "    return -1;\n";
4595                  pr "  }\n";
4596              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
4597                  assert false (* can never be an LVM column *)
4598             );
4599             pr "  tok = next;\n";
4600         ) cols;
4601
4602         pr "  if (tok != NULL) {\n";
4603         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
4604         pr "    return -1;\n";
4605         pr "  }\n";
4606         pr "  return 0;\n";
4607         pr "}\n";
4608         pr "\n";
4609
4610         pr "guestfs_int_lvm_%s_list *\n" typ;
4611         pr "parse_command_line_%ss (void)\n" typ;
4612         pr "{\n";
4613         pr "  char *out, *err;\n";
4614         pr "  char *p, *pend;\n";
4615         pr "  int r, i;\n";
4616         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
4617         pr "  void *newp;\n";
4618         pr "\n";
4619         pr "  ret = malloc (sizeof *ret);\n";
4620         pr "  if (!ret) {\n";
4621         pr "    reply_with_perror (\"malloc\");\n";
4622         pr "    return NULL;\n";
4623         pr "  }\n";
4624         pr "\n";
4625         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
4626         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
4627         pr "\n";
4628         pr "  r = command (&out, &err,\n";
4629         pr "           \"/sbin/lvm\", \"%ss\",\n" typ;
4630         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
4631         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
4632         pr "  if (r == -1) {\n";
4633         pr "    reply_with_error (\"%%s\", err);\n";
4634         pr "    free (out);\n";
4635         pr "    free (err);\n";
4636         pr "    free (ret);\n";
4637         pr "    return NULL;\n";
4638         pr "  }\n";
4639         pr "\n";
4640         pr "  free (err);\n";
4641         pr "\n";
4642         pr "  /* Tokenize each line of the output. */\n";
4643         pr "  p = out;\n";
4644         pr "  i = 0;\n";
4645         pr "  while (p) {\n";
4646         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
4647         pr "    if (pend) {\n";
4648         pr "      *pend = '\\0';\n";
4649         pr "      pend++;\n";
4650         pr "    }\n";
4651         pr "\n";
4652         pr "    while (*p && isspace (*p))      /* Skip any leading whitespace. */\n";
4653         pr "      p++;\n";
4654         pr "\n";
4655         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
4656         pr "      p = pend;\n";
4657         pr "      continue;\n";
4658         pr "    }\n";
4659         pr "\n";
4660         pr "    /* Allocate some space to store this next entry. */\n";
4661         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
4662         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
4663         pr "    if (newp == NULL) {\n";
4664         pr "      reply_with_perror (\"realloc\");\n";
4665         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4666         pr "      free (ret);\n";
4667         pr "      free (out);\n";
4668         pr "      return NULL;\n";
4669         pr "    }\n";
4670         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
4671         pr "\n";
4672         pr "    /* Tokenize the next entry. */\n";
4673         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
4674         pr "    if (r == -1) {\n";
4675         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
4676         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
4677         pr "      free (ret);\n";
4678         pr "      free (out);\n";
4679         pr "      return NULL;\n";
4680         pr "    }\n";
4681         pr "\n";
4682         pr "    ++i;\n";
4683         pr "    p = pend;\n";
4684         pr "  }\n";
4685         pr "\n";
4686         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
4687         pr "\n";
4688         pr "  free (out);\n";
4689         pr "  return ret;\n";
4690         pr "}\n"
4691
4692   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
4693
4694 (* Generate a list of function names, for debugging in the daemon.. *)
4695 and generate_daemon_names () =
4696   generate_header CStyle GPLv2;
4697
4698   pr "#include <config.h>\n";
4699   pr "\n";
4700   pr "#include \"daemon.h\"\n";
4701   pr "\n";
4702
4703   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
4704   pr "const char *function_names[] = {\n";
4705   List.iter (
4706     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
4707   ) daemon_functions;
4708   pr "};\n";
4709
4710 (* Generate the tests. *)
4711 and generate_tests () =
4712   generate_header CStyle GPLv2;
4713
4714   pr "\
4715 #include <stdio.h>
4716 #include <stdlib.h>
4717 #include <string.h>
4718 #include <unistd.h>
4719 #include <sys/types.h>
4720 #include <fcntl.h>
4721
4722 #include \"guestfs.h\"
4723
4724 static guestfs_h *g;
4725 static int suppress_error = 0;
4726
4727 static void print_error (guestfs_h *g, void *data, const char *msg)
4728 {
4729   if (!suppress_error)
4730     fprintf (stderr, \"%%s\\n\", msg);
4731 }
4732
4733 static void print_strings (char * const * const argv)
4734 {
4735   int argc;
4736
4737   for (argc = 0; argv[argc] != NULL; ++argc)
4738     printf (\"\\t%%s\\n\", argv[argc]);
4739 }
4740
4741 /*
4742 static void print_table (char * const * const argv)
4743 {
4744   int i;
4745
4746   for (i = 0; argv[i] != NULL; i += 2)
4747     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
4748 }
4749 */
4750
4751 static void no_test_warnings (void)
4752 {
4753 ";
4754
4755   List.iter (
4756     function
4757     | name, _, _, _, [], _, _ ->
4758         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
4759     | name, _, _, _, tests, _, _ -> ()
4760   ) all_functions;
4761
4762   pr "}\n";
4763   pr "\n";
4764
4765   (* Generate the actual tests.  Note that we generate the tests
4766    * in reverse order, deliberately, so that (in general) the
4767    * newest tests run first.  This makes it quicker and easier to
4768    * debug them.
4769    *)
4770   let test_names =
4771     List.map (
4772       fun (name, _, _, _, tests, _, _) ->
4773         mapi (generate_one_test name) tests
4774     ) (List.rev all_functions) in
4775   let test_names = List.concat test_names in
4776   let nr_tests = List.length test_names in
4777
4778   pr "\
4779 int main (int argc, char *argv[])
4780 {
4781   char c = 0;
4782   int failed = 0;
4783   const char *filename;
4784   int fd;
4785   int nr_tests, test_num = 0;
4786
4787   setbuf (stdout, NULL);
4788
4789   no_test_warnings ();
4790
4791   g = guestfs_create ();
4792   if (g == NULL) {
4793     printf (\"guestfs_create FAILED\\n\");
4794     exit (1);
4795   }
4796
4797   guestfs_set_error_handler (g, print_error, NULL);
4798
4799   guestfs_set_path (g, \"../appliance\");
4800
4801   filename = \"test1.img\";
4802   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4803   if (fd == -1) {
4804     perror (filename);
4805     exit (1);
4806   }
4807   if (lseek (fd, %d, SEEK_SET) == -1) {
4808     perror (\"lseek\");
4809     close (fd);
4810     unlink (filename);
4811     exit (1);
4812   }
4813   if (write (fd, &c, 1) == -1) {
4814     perror (\"write\");
4815     close (fd);
4816     unlink (filename);
4817     exit (1);
4818   }
4819   if (close (fd) == -1) {
4820     perror (filename);
4821     unlink (filename);
4822     exit (1);
4823   }
4824   if (guestfs_add_drive (g, filename) == -1) {
4825     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4826     exit (1);
4827   }
4828
4829   filename = \"test2.img\";
4830   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4831   if (fd == -1) {
4832     perror (filename);
4833     exit (1);
4834   }
4835   if (lseek (fd, %d, SEEK_SET) == -1) {
4836     perror (\"lseek\");
4837     close (fd);
4838     unlink (filename);
4839     exit (1);
4840   }
4841   if (write (fd, &c, 1) == -1) {
4842     perror (\"write\");
4843     close (fd);
4844     unlink (filename);
4845     exit (1);
4846   }
4847   if (close (fd) == -1) {
4848     perror (filename);
4849     unlink (filename);
4850     exit (1);
4851   }
4852   if (guestfs_add_drive (g, filename) == -1) {
4853     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4854     exit (1);
4855   }
4856
4857   filename = \"test3.img\";
4858   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
4859   if (fd == -1) {
4860     perror (filename);
4861     exit (1);
4862   }
4863   if (lseek (fd, %d, SEEK_SET) == -1) {
4864     perror (\"lseek\");
4865     close (fd);
4866     unlink (filename);
4867     exit (1);
4868   }
4869   if (write (fd, &c, 1) == -1) {
4870     perror (\"write\");
4871     close (fd);
4872     unlink (filename);
4873     exit (1);
4874   }
4875   if (close (fd) == -1) {
4876     perror (filename);
4877     unlink (filename);
4878     exit (1);
4879   }
4880   if (guestfs_add_drive (g, filename) == -1) {
4881     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
4882     exit (1);
4883   }
4884
4885   if (guestfs_add_drive_ro (g, \"../images/test.sqsh\") == -1) {
4886     printf (\"guestfs_add_drive_ro ../images/test.sqsh FAILED\\n\");
4887     exit (1);
4888   }
4889
4890   if (guestfs_launch (g) == -1) {
4891     printf (\"guestfs_launch FAILED\\n\");
4892     exit (1);
4893   }
4894
4895   /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
4896   alarm (600);
4897
4898   if (guestfs_wait_ready (g) == -1) {
4899     printf (\"guestfs_wait_ready FAILED\\n\");
4900     exit (1);
4901   }
4902
4903   /* Cancel previous alarm. */
4904   alarm (0);
4905
4906   nr_tests = %d;
4907
4908 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
4909
4910   iteri (
4911     fun i test_name ->
4912       pr "  test_num++;\n";
4913       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
4914       pr "  if (%s () == -1) {\n" test_name;
4915       pr "    printf (\"%s FAILED\\n\");\n" test_name;
4916       pr "    failed++;\n";
4917       pr "  }\n";
4918   ) test_names;
4919   pr "\n";
4920
4921   pr "  guestfs_close (g);\n";
4922   pr "  unlink (\"test1.img\");\n";
4923   pr "  unlink (\"test2.img\");\n";
4924   pr "  unlink (\"test3.img\");\n";
4925   pr "\n";
4926
4927   pr "  if (failed > 0) {\n";
4928   pr "    printf (\"***** %%d / %%d tests FAILED *****\\n\", failed, nr_tests);\n";
4929   pr "    exit (1);\n";
4930   pr "  }\n";
4931   pr "\n";
4932
4933   pr "  exit (0);\n";
4934   pr "}\n"
4935
4936 and generate_one_test name i (init, prereq, test) =
4937   let test_name = sprintf "test_%s_%d" name i in
4938
4939   pr "\
4940 static int %s_skip (void)
4941 {
4942   const char *str;
4943
4944   str = getenv (\"TEST_ONLY\");
4945   if (str)
4946     return strstr (str, \"%s\") == NULL;
4947   str = getenv (\"SKIP_%s\");
4948   if (str && strcmp (str, \"1\") == 0) return 1;
4949   str = getenv (\"SKIP_TEST_%s\");
4950   if (str && strcmp (str, \"1\") == 0) return 1;
4951   return 0;
4952 }
4953
4954 " test_name name (String.uppercase test_name) (String.uppercase name);
4955
4956   (match prereq with
4957    | Disabled | Always -> ()
4958    | If code | Unless code ->
4959        pr "static int %s_prereq (void)\n" test_name;
4960        pr "{\n";
4961        pr "  %s\n" code;
4962        pr "}\n";
4963        pr "\n";
4964   );
4965
4966   pr "\
4967 static int %s (void)
4968 {
4969   if (%s_skip ()) {
4970     printf (\"        %%s skipped (reason: environment variable set)\\n\", \"%s\");
4971     return 0;
4972   }
4973
4974 " test_name test_name test_name;
4975
4976   (match prereq with
4977    | Disabled ->
4978        pr "  printf (\"        %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
4979    | If _ ->
4980        pr "  if (! %s_prereq ()) {\n" test_name;
4981        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4982        pr "    return 0;\n";
4983        pr "  }\n";
4984        pr "\n";
4985        generate_one_test_body name i test_name init test;
4986    | Unless _ ->
4987        pr "  if (%s_prereq ()) {\n" test_name;
4988        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
4989        pr "    return 0;\n";
4990        pr "  }\n";
4991        pr "\n";
4992        generate_one_test_body name i test_name init test;
4993    | Always ->
4994        generate_one_test_body name i test_name init test
4995   );
4996
4997   pr "  return 0;\n";
4998   pr "}\n";
4999   pr "\n";
5000   test_name
5001
5002 and generate_one_test_body name i test_name init test =
5003   (match init with
5004    | InitNone (* XXX at some point, InitNone and InitEmpty became
5005                * folded together as the same thing.  Really we should
5006                * make InitNone do nothing at all, but the tests may
5007                * need to be checked to make sure this is OK.
5008                *)
5009    | InitEmpty ->
5010        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
5011        List.iter (generate_test_command_call test_name)
5012          [["blockdev_setrw"; "/dev/sda"];
5013           ["umount_all"];
5014           ["lvm_remove_all"]]
5015    | InitBasicFS ->
5016        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
5017        List.iter (generate_test_command_call test_name)
5018          [["blockdev_setrw"; "/dev/sda"];
5019           ["umount_all"];
5020           ["lvm_remove_all"];
5021           ["sfdiskM"; "/dev/sda"; ","];
5022           ["mkfs"; "ext2"; "/dev/sda1"];
5023           ["mount"; "/dev/sda1"; "/"]]
5024    | InitBasicFSonLVM ->
5025        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
5026          test_name;
5027        List.iter (generate_test_command_call test_name)
5028          [["blockdev_setrw"; "/dev/sda"];
5029           ["umount_all"];
5030           ["lvm_remove_all"];
5031           ["sfdiskM"; "/dev/sda"; ","];
5032           ["pvcreate"; "/dev/sda1"];
5033           ["vgcreate"; "VG"; "/dev/sda1"];
5034           ["lvcreate"; "LV"; "VG"; "8"];
5035           ["mkfs"; "ext2"; "/dev/VG/LV"];
5036           ["mount"; "/dev/VG/LV"; "/"]]
5037    | InitSquashFS ->
5038        pr "  /* InitSquashFS for %s */\n" test_name;
5039        List.iter (generate_test_command_call test_name)
5040          [["blockdev_setrw"; "/dev/sda"];
5041           ["umount_all"];
5042           ["lvm_remove_all"];
5043           ["mount_vfs"; "ro"; "squashfs"; "/dev/sdd"; "/"]]
5044   );
5045
5046   let get_seq_last = function
5047     | [] ->
5048         failwithf "%s: you cannot use [] (empty list) when expecting a command"
5049           test_name
5050     | seq ->
5051         let seq = List.rev seq in
5052         List.rev (List.tl seq), List.hd seq
5053   in
5054
5055   match test with
5056   | TestRun seq ->
5057       pr "  /* TestRun for %s (%d) */\n" name i;
5058       List.iter (generate_test_command_call test_name) seq
5059   | TestOutput (seq, expected) ->
5060       pr "  /* TestOutput for %s (%d) */\n" name i;
5061       pr "  const char *expected = \"%s\";\n" (c_quote expected);
5062       let seq, last = get_seq_last seq in
5063       let test () =
5064         pr "    if (strcmp (r, expected) != 0) {\n";
5065         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
5066         pr "      return -1;\n";
5067         pr "    }\n"
5068       in
5069       List.iter (generate_test_command_call test_name) seq;
5070       generate_test_command_call ~test test_name last
5071   | TestOutputList (seq, expected) ->
5072       pr "  /* TestOutputList for %s (%d) */\n" name i;
5073       let seq, last = get_seq_last seq in
5074       let test () =
5075         iteri (
5076           fun i str ->
5077             pr "    if (!r[%d]) {\n" i;
5078             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
5079             pr "      print_strings (r);\n";
5080             pr "      return -1;\n";
5081             pr "    }\n";
5082             pr "    {\n";
5083             pr "      const char *expected = \"%s\";\n" (c_quote str);
5084             pr "      if (strcmp (r[%d], expected) != 0) {\n" i;
5085             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
5086             pr "        return -1;\n";
5087             pr "      }\n";
5088             pr "    }\n"
5089         ) expected;
5090         pr "    if (r[%d] != NULL) {\n" (List.length expected);
5091         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
5092           test_name;
5093         pr "      print_strings (r);\n";
5094         pr "      return -1;\n";
5095         pr "    }\n"
5096       in
5097       List.iter (generate_test_command_call test_name) seq;
5098       generate_test_command_call ~test test_name last
5099   | TestOutputListOfDevices (seq, expected) ->
5100       pr "  /* TestOutputListOfDevices for %s (%d) */\n" name i;
5101       let seq, last = get_seq_last seq in
5102       let test () =
5103         iteri (
5104           fun i str ->
5105             pr "    if (!r[%d]) {\n" i;
5106             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
5107             pr "      print_strings (r);\n";
5108             pr "      return -1;\n";
5109             pr "    }\n";
5110             pr "    {\n";
5111             pr "      const char *expected = \"%s\";\n" (c_quote str);
5112             pr "      r[%d][5] = 's';\n" i;
5113             pr "      if (strcmp (r[%d], expected) != 0) {\n" i;
5114             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
5115             pr "        return -1;\n";
5116             pr "      }\n";
5117             pr "    }\n"
5118         ) expected;
5119         pr "    if (r[%d] != NULL) {\n" (List.length expected);
5120         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
5121           test_name;
5122         pr "      print_strings (r);\n";
5123         pr "      return -1;\n";
5124         pr "    }\n"
5125       in
5126       List.iter (generate_test_command_call test_name) seq;
5127       generate_test_command_call ~test test_name last
5128   | TestOutputInt (seq, expected) ->
5129       pr "  /* TestOutputInt for %s (%d) */\n" name i;
5130       let seq, last = get_seq_last seq in
5131       let test () =
5132         pr "    if (r != %d) {\n" expected;
5133         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
5134           test_name expected;
5135         pr "               (int) r);\n";
5136         pr "      return -1;\n";
5137         pr "    }\n"
5138       in
5139       List.iter (generate_test_command_call test_name) seq;
5140       generate_test_command_call ~test test_name last
5141   | TestOutputIntOp (seq, op, expected) ->
5142       pr "  /* TestOutputIntOp for %s (%d) */\n" name i;
5143       let seq, last = get_seq_last seq in
5144       let test () =
5145         pr "    if (! (r %s %d)) {\n" op expected;
5146         pr "      fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
5147           test_name op expected;
5148         pr "               (int) r);\n";
5149         pr "      return -1;\n";
5150         pr "    }\n"
5151       in
5152       List.iter (generate_test_command_call test_name) seq;
5153       generate_test_command_call ~test test_name last
5154   | TestOutputTrue seq ->
5155       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
5156       let seq, last = get_seq_last seq in
5157       let test () =
5158         pr "    if (!r) {\n";
5159         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
5160           test_name;
5161         pr "      return -1;\n";
5162         pr "    }\n"
5163       in
5164       List.iter (generate_test_command_call test_name) seq;
5165       generate_test_command_call ~test test_name last
5166   | TestOutputFalse seq ->
5167       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
5168       let seq, last = get_seq_last seq in
5169       let test () =
5170         pr "    if (r) {\n";
5171         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
5172           test_name;
5173         pr "      return -1;\n";
5174         pr "    }\n"
5175       in
5176       List.iter (generate_test_command_call test_name) seq;
5177       generate_test_command_call ~test test_name last
5178   | TestOutputLength (seq, expected) ->
5179       pr "  /* TestOutputLength for %s (%d) */\n" name i;
5180       let seq, last = get_seq_last seq in
5181       let test () =
5182         pr "    int j;\n";
5183         pr "    for (j = 0; j < %d; ++j)\n" expected;
5184         pr "      if (r[j] == NULL) {\n";
5185         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
5186           test_name;
5187         pr "        print_strings (r);\n";
5188         pr "        return -1;\n";
5189         pr "      }\n";
5190         pr "    if (r[j] != NULL) {\n";
5191         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
5192           test_name;
5193         pr "      print_strings (r);\n";
5194         pr "      return -1;\n";
5195         pr "    }\n"
5196       in
5197       List.iter (generate_test_command_call test_name) seq;
5198       generate_test_command_call ~test test_name last
5199   | TestOutputBuffer (seq, expected) ->
5200       pr "  /* TestOutputBuffer for %s (%d) */\n" name i;
5201       pr "  const char *expected = \"%s\";\n" (c_quote expected);
5202       let seq, last = get_seq_last seq in
5203       let len = String.length expected in
5204       let test () =
5205         pr "    if (size != %d) {\n" len;
5206         pr "      fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
5207         pr "      return -1;\n";
5208         pr "    }\n";
5209         pr "    if (strncmp (r, expected, size) != 0) {\n";
5210         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
5211         pr "      return -1;\n";
5212         pr "    }\n"
5213       in
5214       List.iter (generate_test_command_call test_name) seq;
5215       generate_test_command_call ~test test_name last
5216   | TestOutputStruct (seq, checks) ->
5217       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
5218       let seq, last = get_seq_last seq in
5219       let test () =
5220         List.iter (
5221           function
5222           | CompareWithInt (field, expected) ->
5223               pr "    if (r->%s != %d) {\n" field expected;
5224               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
5225                 test_name field expected;
5226               pr "               (int) r->%s);\n" field;
5227               pr "      return -1;\n";
5228               pr "    }\n"
5229           | CompareWithIntOp (field, op, expected) ->
5230               pr "    if (!(r->%s %s %d)) {\n" field op expected;
5231               pr "      fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
5232                 test_name field op expected;
5233               pr "               (int) r->%s);\n" field;
5234               pr "      return -1;\n";
5235               pr "    }\n"
5236           | CompareWithString (field, expected) ->
5237               pr "    if (strcmp (r->%s, \"%s\") != 0) {\n" field expected;
5238               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
5239                 test_name field expected;
5240               pr "               r->%s);\n" field;
5241               pr "      return -1;\n";
5242               pr "    }\n"
5243           | CompareFieldsIntEq (field1, field2) ->
5244               pr "    if (r->%s != r->%s) {\n" field1 field2;
5245               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
5246                 test_name field1 field2;
5247               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
5248               pr "      return -1;\n";
5249               pr "    }\n"
5250           | CompareFieldsStrEq (field1, field2) ->
5251               pr "    if (strcmp (r->%s, r->%s) != 0) {\n" field1 field2;
5252               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
5253                 test_name field1 field2;
5254               pr "               r->%s, r->%s);\n" field1 field2;
5255               pr "      return -1;\n";
5256               pr "    }\n"
5257         ) checks
5258       in
5259       List.iter (generate_test_command_call test_name) seq;
5260       generate_test_command_call ~test test_name last
5261   | TestLastFail seq ->
5262       pr "  /* TestLastFail for %s (%d) */\n" name i;
5263       let seq, last = get_seq_last seq in
5264       List.iter (generate_test_command_call test_name) seq;
5265       generate_test_command_call test_name ~expect_error:true last
5266
5267 (* Generate the code to run a command, leaving the result in 'r'.
5268  * If you expect to get an error then you should set expect_error:true.
5269  *)
5270 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
5271   match cmd with
5272   | [] -> assert false
5273   | name :: args ->
5274       (* Look up the command to find out what args/ret it has. *)
5275       let style =
5276         try
5277           let _, style, _, _, _, _, _ =
5278             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
5279           style
5280         with Not_found ->
5281           failwithf "%s: in test, command %s was not found" test_name name in
5282
5283       if List.length (snd style) <> List.length args then
5284         failwithf "%s: in test, wrong number of args given to %s"
5285           test_name name;
5286
5287       pr "  {\n";
5288
5289       List.iter (
5290         function
5291         | OptString n, "NULL" -> ()
5292         | String n, arg
5293         | OptString n, arg ->
5294             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
5295         | Int _, _
5296         | Bool _, _
5297         | FileIn _, _ | FileOut _, _ -> ()
5298         | StringList n, arg ->
5299             let strs = string_split " " arg in
5300             iteri (
5301               fun i str ->
5302                 pr "    const char *%s_%d = \"%s\";\n" n i (c_quote str);
5303             ) strs;
5304             pr "    const char *%s[] = {\n" n;
5305             iteri (
5306               fun i _ -> pr "      %s_%d,\n" n i
5307             ) strs;
5308             pr "      NULL\n";
5309             pr "    };\n";
5310       ) (List.combine (snd style) args);
5311
5312       let error_code =
5313         match fst style with
5314         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
5315         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
5316         | RConstString _ | RConstOptString _ ->
5317             pr "    const char *r;\n"; "NULL"
5318         | RString _ -> pr "    char *r;\n"; "NULL"
5319         | RStringList _ | RHashtable _ ->
5320             pr "    char **r;\n";
5321             pr "    int i;\n";
5322             "NULL"
5323         | RStruct (_, typ) ->
5324             pr "    struct guestfs_%s *r;\n" typ; "NULL"
5325         | RStructList (_, typ) ->
5326             pr "    struct guestfs_%s_list *r;\n" typ; "NULL"
5327         | RBufferOut _ ->
5328             pr "    char *r;\n";
5329             pr "    size_t size;\n";
5330             "NULL" in
5331
5332       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
5333       pr "    r = guestfs_%s (g" name;
5334
5335       (* Generate the parameters. *)
5336       List.iter (
5337         function
5338         | OptString _, "NULL" -> pr ", NULL"
5339         | String n, _
5340         | OptString n, _ ->
5341             pr ", %s" n
5342         | FileIn _, arg | FileOut _, arg ->
5343             pr ", \"%s\"" (c_quote arg)
5344         | StringList n, _ ->
5345             pr ", %s" n
5346         | Int _, arg ->
5347             let i =
5348               try int_of_string arg
5349               with Failure "int_of_string" ->
5350                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
5351             pr ", %d" i
5352         | Bool _, arg ->
5353             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
5354       ) (List.combine (snd style) args);
5355
5356       (match fst style with
5357        | RBufferOut _ -> pr ", &size"
5358        | _ -> ()
5359       );
5360
5361       pr ");\n";
5362
5363       if not expect_error then
5364         pr "    if (r == %s)\n" error_code
5365       else
5366         pr "    if (r != %s)\n" error_code;
5367       pr "      return -1;\n";
5368
5369       (* Insert the test code. *)
5370       (match test with
5371        | None -> ()
5372        | Some f -> f ()
5373       );
5374
5375       (match fst style with
5376        | RErr | RInt _ | RInt64 _ | RBool _
5377        | RConstString _ | RConstOptString _ -> ()
5378        | RString _ | RBufferOut _ -> pr "    free (r);\n"
5379        | RStringList _ | RHashtable _ ->
5380            pr "    for (i = 0; r[i] != NULL; ++i)\n";
5381            pr "      free (r[i]);\n";
5382            pr "    free (r);\n"
5383        | RStruct (_, typ) ->
5384            pr "    guestfs_free_%s (r);\n" typ
5385        | RStructList (_, typ) ->
5386            pr "    guestfs_free_%s_list (r);\n" typ
5387       );
5388
5389       pr "  }\n"
5390
5391 and c_quote str =
5392   let str = replace_str str "\r" "\\r" in
5393   let str = replace_str str "\n" "\\n" in
5394   let str = replace_str str "\t" "\\t" in
5395   let str = replace_str str "\000" "\\0" in
5396   str
5397
5398 (* Generate a lot of different functions for guestfish. *)
5399 and generate_fish_cmds () =
5400   generate_header CStyle GPLv2;
5401
5402   let all_functions =
5403     List.filter (
5404       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5405     ) all_functions in
5406   let all_functions_sorted =
5407     List.filter (
5408       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5409     ) all_functions_sorted in
5410
5411   pr "#include <stdio.h>\n";
5412   pr "#include <stdlib.h>\n";
5413   pr "#include <string.h>\n";
5414   pr "#include <inttypes.h>\n";
5415   pr "#include <ctype.h>\n";
5416   pr "\n";
5417   pr "#include <guestfs.h>\n";
5418   pr "#include \"fish.h\"\n";
5419   pr "\n";
5420
5421   (* list_commands function, which implements guestfish -h *)
5422   pr "void list_commands (void)\n";
5423   pr "{\n";
5424   pr "  printf (\"    %%-16s     %%s\\n\", \"Command\", \"Description\");\n";
5425   pr "  list_builtin_commands ();\n";
5426   List.iter (
5427     fun (name, _, _, flags, _, shortdesc, _) ->
5428       let name = replace_char name '_' '-' in
5429       pr "  printf (\"%%-20s %%s\\n\", \"%s\", \"%s\");\n"
5430         name shortdesc
5431   ) all_functions_sorted;
5432   pr "  printf (\"    Use -h <cmd> / help <cmd> to show detailed help for a command.\\n\");\n";
5433   pr "}\n";
5434   pr "\n";
5435
5436   (* display_command function, which implements guestfish -h cmd *)
5437   pr "void display_command (const char *cmd)\n";
5438   pr "{\n";
5439   List.iter (
5440     fun (name, style, _, flags, _, shortdesc, longdesc) ->
5441       let name2 = replace_char name '_' '-' in
5442       let alias =
5443         try find_map (function FishAlias n -> Some n | _ -> None) flags
5444         with Not_found -> name in
5445       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
5446       let synopsis =
5447         match snd style with
5448         | [] -> name2
5449         | args ->
5450             sprintf "%s <%s>"
5451               name2 (String.concat "> <" (List.map name_of_argt args)) in
5452
5453       let warnings =
5454         if List.mem ProtocolLimitWarning flags then
5455           ("\n\n" ^ protocol_limit_warning)
5456         else "" in
5457
5458       (* For DangerWillRobinson commands, we should probably have
5459        * guestfish prompt before allowing you to use them (especially
5460        * in interactive mode). XXX
5461        *)
5462       let warnings =
5463         warnings ^
5464           if List.mem DangerWillRobinson flags then
5465             ("\n\n" ^ danger_will_robinson)
5466           else "" in
5467
5468       let warnings =
5469         warnings ^
5470           match deprecation_notice flags with
5471           | None -> ""
5472           | Some txt -> "\n\n" ^ txt in
5473
5474       let describe_alias =
5475         if name <> alias then
5476           sprintf "\n\nYou can use '%s' as an alias for this command." alias
5477         else "" in
5478
5479       pr "  if (";
5480       pr "strcasecmp (cmd, \"%s\") == 0" name;
5481       if name <> name2 then
5482         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5483       if name <> alias then
5484         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5485       pr ")\n";
5486       pr "    pod2text (\"%s - %s\", %S);\n"
5487         name2 shortdesc
5488         (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
5489       pr "  else\n"
5490   ) all_functions;
5491   pr "    display_builtin_command (cmd);\n";
5492   pr "}\n";
5493   pr "\n";
5494
5495   (* print_* functions *)
5496   List.iter (
5497     fun (typ, cols) ->
5498       let needs_i =
5499         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
5500
5501       pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
5502       pr "{\n";
5503       if needs_i then (
5504         pr "  int i;\n";
5505         pr "\n"
5506       );
5507       List.iter (
5508         function
5509         | name, FString ->
5510             pr "  printf (\"%s: %%s\\n\", %s->%s);\n" name typ name
5511         | name, FUUID ->
5512             pr "  printf (\"%s: \");\n" name;
5513             pr "  for (i = 0; i < 32; ++i)\n";
5514             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
5515             pr "  printf (\"\\n\");\n"
5516         | name, FBuffer ->
5517             pr "  printf (\"%s: \");\n" name;
5518             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
5519             pr "    if (isprint (%s->%s[i]))\n" typ name;
5520             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
5521             pr "    else\n";
5522             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
5523             pr "  printf (\"\\n\");\n"
5524         | name, (FUInt64|FBytes) ->
5525             pr "  printf (\"%s: %%\" PRIu64 \"\\n\", %s->%s);\n" name typ name
5526         | name, FInt64 ->
5527             pr "  printf (\"%s: %%\" PRIi64 \"\\n\", %s->%s);\n" name typ name
5528         | name, FUInt32 ->
5529             pr "  printf (\"%s: %%\" PRIu32 \"\\n\", %s->%s);\n" name typ name
5530         | name, FInt32 ->
5531             pr "  printf (\"%s: %%\" PRIi32 \"\\n\", %s->%s);\n" name typ name
5532         | name, FChar ->
5533             pr "  printf (\"%s: %%c\\n\", %s->%s);\n" name typ name
5534         | name, FOptPercent ->
5535             pr "  if (%s->%s >= 0) printf (\"%s: %%g %%%%\\n\", %s->%s);\n"
5536               typ name name typ name;
5537             pr "  else printf (\"%s: \\n\");\n" name
5538       ) cols;
5539       pr "}\n";
5540       pr "\n";
5541       pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
5542         typ typ typ;
5543       pr "{\n";
5544       pr "  int i;\n";
5545       pr "\n";
5546       pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
5547       pr "    print_%s (&%ss->val[i]);\n" typ typ;
5548       pr "}\n";
5549       pr "\n";
5550   ) structs;
5551
5552   (* run_<action> actions *)
5553   List.iter (
5554     fun (name, style, _, flags, _, _, _) ->
5555       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
5556       pr "{\n";
5557       (match fst style with
5558        | RErr
5559        | RInt _
5560        | RBool _ -> pr "  int r;\n"
5561        | RInt64 _ -> pr "  int64_t r;\n"
5562        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
5563        | RString _ -> pr "  char *r;\n"
5564        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
5565        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
5566        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
5567        | RBufferOut _ ->
5568            pr "  char *r;\n";
5569            pr "  size_t size;\n";
5570       );
5571       List.iter (
5572         function
5573         | String n
5574         | OptString n
5575         | FileIn n
5576         | FileOut n -> pr "  const char *%s;\n" n
5577         | StringList n -> pr "  char **%s;\n" n
5578         | Bool n -> pr "  int %s;\n" n
5579         | Int n -> pr "  int %s;\n" n
5580       ) (snd style);
5581
5582       (* Check and convert parameters. *)
5583       let argc_expected = List.length (snd style) in
5584       pr "  if (argc != %d) {\n" argc_expected;
5585       pr "    fprintf (stderr, \"%%s should have %d parameter(s)\\n\", cmd);\n"
5586         argc_expected;
5587       pr "    fprintf (stderr, \"type 'help %%s' for help on %%s\\n\", cmd, cmd);\n";
5588       pr "    return -1;\n";
5589       pr "  }\n";
5590       iteri (
5591         fun i ->
5592           function
5593           | String name -> pr "  %s = argv[%d];\n" name i
5594           | OptString name ->
5595               pr "  %s = strcmp (argv[%d], \"\") != 0 ? argv[%d] : NULL;\n"
5596                 name i i
5597           | FileIn name ->
5598               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdin\";\n"
5599                 name i i
5600           | FileOut name ->
5601               pr "  %s = strcmp (argv[%d], \"-\") != 0 ? argv[%d] : \"/dev/stdout\";\n"
5602                 name i i
5603           | StringList name ->
5604               pr "  %s = parse_string_list (argv[%d]);\n" name i
5605           | Bool name ->
5606               pr "  %s = is_true (argv[%d]) ? 1 : 0;\n" name i
5607           | Int name ->
5608               pr "  %s = atoi (argv[%d]);\n" name i
5609       ) (snd style);
5610
5611       (* Call C API function. *)
5612       let fn =
5613         try find_map (function FishAction n -> Some n | _ -> None) flags
5614         with Not_found -> sprintf "guestfs_%s" name in
5615       pr "  r = %s " fn;
5616       generate_c_call_args ~handle:"g" style;
5617       pr ";\n";
5618
5619       (* Check return value for errors and display command results. *)
5620       (match fst style with
5621        | RErr -> pr "  return r;\n"
5622        | RInt _ ->
5623            pr "  if (r == -1) return -1;\n";
5624            pr "  printf (\"%%d\\n\", r);\n";
5625            pr "  return 0;\n"
5626        | RInt64 _ ->
5627            pr "  if (r == -1) return -1;\n";
5628            pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
5629            pr "  return 0;\n"
5630        | RBool _ ->
5631            pr "  if (r == -1) return -1;\n";
5632            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
5633            pr "  return 0;\n"
5634        | RConstString _ ->
5635            pr "  if (r == NULL) return -1;\n";
5636            pr "  printf (\"%%s\\n\", r);\n";
5637            pr "  return 0;\n"
5638        | RConstOptString _ ->
5639            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
5640            pr "  return 0;\n"
5641        | RString _ ->
5642            pr "  if (r == NULL) return -1;\n";
5643            pr "  printf (\"%%s\\n\", r);\n";
5644            pr "  free (r);\n";
5645            pr "  return 0;\n"
5646        | RStringList _ ->
5647            pr "  if (r == NULL) return -1;\n";
5648            pr "  print_strings (r);\n";
5649            pr "  free_strings (r);\n";
5650            pr "  return 0;\n"
5651        | RStruct (_, typ) ->
5652            pr "  if (r == NULL) return -1;\n";
5653            pr "  print_%s (r);\n" typ;
5654            pr "  guestfs_free_%s (r);\n" typ;
5655            pr "  return 0;\n"
5656        | RStructList (_, typ) ->
5657            pr "  if (r == NULL) return -1;\n";
5658            pr "  print_%s_list (r);\n" typ;
5659            pr "  guestfs_free_%s_list (r);\n" typ;
5660            pr "  return 0;\n"
5661        | RHashtable _ ->
5662            pr "  if (r == NULL) return -1;\n";
5663            pr "  print_table (r);\n";
5664            pr "  free_strings (r);\n";
5665            pr "  return 0;\n"
5666        | RBufferOut _ ->
5667            pr "  if (r == NULL) return -1;\n";
5668            pr "  fwrite (r, size, 1, stdout);\n";
5669            pr "  free (r);\n";
5670            pr "  return 0;\n"
5671       );
5672       pr "}\n";
5673       pr "\n"
5674   ) all_functions;
5675
5676   (* run_action function *)
5677   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
5678   pr "{\n";
5679   List.iter (
5680     fun (name, _, _, flags, _, _, _) ->
5681       let name2 = replace_char name '_' '-' in
5682       let alias =
5683         try find_map (function FishAlias n -> Some n | _ -> None) flags
5684         with Not_found -> name in
5685       pr "  if (";
5686       pr "strcasecmp (cmd, \"%s\") == 0" name;
5687       if name <> name2 then
5688         pr " || strcasecmp (cmd, \"%s\") == 0" name2;
5689       if name <> alias then
5690         pr " || strcasecmp (cmd, \"%s\") == 0" alias;
5691       pr ")\n";
5692       pr "    return run_%s (cmd, argc, argv);\n" name;
5693       pr "  else\n";
5694   ) all_functions;
5695   pr "    {\n";
5696   pr "      fprintf (stderr, \"%%s: unknown command\\n\", cmd);\n";
5697   pr "      return -1;\n";
5698   pr "    }\n";
5699   pr "  return 0;\n";
5700   pr "}\n";
5701   pr "\n"
5702
5703 (* Readline completion for guestfish. *)
5704 and generate_fish_completion () =
5705   generate_header CStyle GPLv2;
5706
5707   let all_functions =
5708     List.filter (
5709       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
5710     ) all_functions in
5711
5712   pr "\
5713 #include <config.h>
5714
5715 #include <stdio.h>
5716 #include <stdlib.h>
5717 #include <string.h>
5718
5719 #ifdef HAVE_LIBREADLINE
5720 #include <readline/readline.h>
5721 #endif
5722
5723 #include \"fish.h\"
5724
5725 #ifdef HAVE_LIBREADLINE
5726
5727 static const char *const commands[] = {
5728   BUILTIN_COMMANDS_FOR_COMPLETION,
5729 ";
5730
5731   (* Get the commands, including the aliases.  They don't need to be
5732    * sorted - the generator() function just does a dumb linear search.
5733    *)
5734   let commands =
5735     List.map (
5736       fun (name, _, _, flags, _, _, _) ->
5737         let name2 = replace_char name '_' '-' in
5738         let alias =
5739           try find_map (function FishAlias n -> Some n | _ -> None) flags
5740           with Not_found -> name in
5741
5742         if name <> alias then [name2; alias] else [name2]
5743     ) all_functions in
5744   let commands = List.flatten commands in
5745
5746   List.iter (pr "  \"%s\",\n") commands;
5747
5748   pr "  NULL
5749 };
5750
5751 static char *
5752 generator (const char *text, int state)
5753 {
5754   static int index, len;
5755   const char *name;
5756
5757   if (!state) {
5758     index = 0;
5759     len = strlen (text);
5760   }
5761
5762   rl_attempted_completion_over = 1;
5763
5764   while ((name = commands[index]) != NULL) {
5765     index++;
5766     if (strncasecmp (name, text, len) == 0)
5767       return strdup (name);
5768   }
5769
5770   return NULL;
5771 }
5772
5773 #endif /* HAVE_LIBREADLINE */
5774
5775 char **do_completion (const char *text, int start, int end)
5776 {
5777   char **matches = NULL;
5778
5779 #ifdef HAVE_LIBREADLINE
5780   rl_completion_append_character = ' ';
5781
5782   if (start == 0)
5783     matches = rl_completion_matches (text, generator);
5784   else if (complete_dest_paths)
5785     matches = rl_completion_matches (text, complete_dest_paths_generator);
5786 #endif
5787
5788   return matches;
5789 }
5790 ";
5791
5792 (* Generate the POD documentation for guestfish. *)
5793 and generate_fish_actions_pod () =
5794   let all_functions_sorted =
5795     List.filter (
5796       fun (_, _, _, flags, _, _, _) ->
5797         not (List.mem NotInFish flags || List.mem NotInDocs flags)
5798     ) all_functions_sorted in
5799
5800   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
5801
5802   List.iter (
5803     fun (name, style, _, flags, _, _, longdesc) ->
5804       let longdesc =
5805         Str.global_substitute rex (
5806           fun s ->
5807             let sub =
5808               try Str.matched_group 1 s
5809               with Not_found ->
5810                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
5811             "C<" ^ replace_char sub '_' '-' ^ ">"
5812         ) longdesc in
5813       let name = replace_char name '_' '-' in
5814       let alias =
5815         try find_map (function FishAlias n -> Some n | _ -> None) flags
5816         with Not_found -> name in
5817
5818       pr "=head2 %s" name;
5819       if name <> alias then
5820         pr " | %s" alias;
5821       pr "\n";
5822       pr "\n";
5823       pr " %s" name;
5824       List.iter (
5825         function
5826         | String n -> pr " %s" n
5827         | OptString n -> pr " %s" n
5828         | StringList n -> pr " '%s ...'" n
5829         | Bool _ -> pr " true|false"
5830         | Int n -> pr " %s" n
5831         | FileIn n | FileOut n -> pr " (%s|-)" n
5832       ) (snd style);
5833       pr "\n";
5834       pr "\n";
5835       pr "%s\n\n" longdesc;
5836
5837       if List.exists (function FileIn _ | FileOut _ -> true
5838                       | _ -> false) (snd style) then
5839         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
5840
5841       if List.mem ProtocolLimitWarning flags then
5842         pr "%s\n\n" protocol_limit_warning;
5843
5844       if List.mem DangerWillRobinson flags then
5845         pr "%s\n\n" danger_will_robinson;
5846
5847       match deprecation_notice flags with
5848       | None -> ()
5849       | Some txt -> pr "%s\n\n" txt
5850   ) all_functions_sorted
5851
5852 (* Generate a C function prototype. *)
5853 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
5854     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
5855     ?(prefix = "")
5856     ?handle name style =
5857   if extern then pr "extern ";
5858   if static then pr "static ";
5859   (match fst style with
5860    | RErr -> pr "int "
5861    | RInt _ -> pr "int "
5862    | RInt64 _ -> pr "int64_t "
5863    | RBool _ -> pr "int "
5864    | RConstString _ | RConstOptString _ -> pr "const char *"
5865    | RString _ | RBufferOut _ -> pr "char *"
5866    | RStringList _ | RHashtable _ -> pr "char **"
5867    | RStruct (_, typ) ->
5868        if not in_daemon then pr "struct guestfs_%s *" typ
5869        else pr "guestfs_int_%s *" typ
5870    | RStructList (_, typ) ->
5871        if not in_daemon then pr "struct guestfs_%s_list *" typ
5872        else pr "guestfs_int_%s_list *" typ
5873   );
5874   let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
5875   pr "%s%s (" prefix name;
5876   if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
5877     pr "void"
5878   else (
5879     let comma = ref false in
5880     (match handle with
5881      | None -> ()
5882      | Some handle -> pr "guestfs_h *%s" handle; comma := true
5883     );
5884     let next () =
5885       if !comma then (
5886         if single_line then pr ", " else pr ",\n\t\t"
5887       );
5888       comma := true
5889     in
5890     List.iter (
5891       function
5892       | String n
5893       | OptString n ->
5894           next ();
5895           if not in_daemon then pr "const char *%s" n
5896           else pr "char *%s" n
5897       | StringList n ->
5898           next ();
5899           if not in_daemon then pr "char * const* const %s" n
5900           else pr "char **%s" n
5901       | Bool n -> next (); pr "int %s" n
5902       | Int n -> next (); pr "int %s" n
5903       | FileIn n
5904       | FileOut n ->
5905           if not in_daemon then (next (); pr "const char *%s" n)
5906     ) (snd style);
5907     if is_RBufferOut then (next (); pr "size_t *size_r");
5908   );
5909   pr ")";
5910   if semicolon then pr ";";
5911   if newline then pr "\n"
5912
5913 (* Generate C call arguments, eg "(handle, foo, bar)" *)
5914 and generate_c_call_args ?handle ?(decl = false) style =
5915   pr "(";
5916   let comma = ref false in
5917   let next () =
5918     if !comma then pr ", ";
5919     comma := true
5920   in
5921   (match handle with
5922    | None -> ()
5923    | Some handle -> pr "%s" handle; comma := true
5924   );
5925   List.iter (
5926     fun arg ->
5927       next ();
5928       pr "%s" (name_of_argt arg)
5929   ) (snd style);
5930   (* For RBufferOut calls, add implicit &size parameter. *)
5931   if not decl then (
5932     match fst style with
5933     | RBufferOut _ ->
5934         next ();
5935         pr "&size"
5936     | _ -> ()
5937   );
5938   pr ")"
5939
5940 (* Generate the OCaml bindings interface. *)
5941 and generate_ocaml_mli () =
5942   generate_header OCamlStyle LGPLv2;
5943
5944   pr "\
5945 (** For API documentation you should refer to the C API
5946     in the guestfs(3) manual page.  The OCaml API uses almost
5947     exactly the same calls. *)
5948
5949 type t
5950 (** A [guestfs_h] handle. *)
5951
5952 exception Error of string
5953 (** This exception is raised when there is an error. *)
5954
5955 val create : unit -> t
5956
5957 val close : t -> unit
5958 (** Handles are closed by the garbage collector when they become
5959     unreferenced, but callers can also call this in order to
5960     provide predictable cleanup. *)
5961
5962 ";
5963   generate_ocaml_structure_decls ();
5964
5965   (* The actions. *)
5966   List.iter (
5967     fun (name, style, _, _, _, shortdesc, _) ->
5968       generate_ocaml_prototype name style;
5969       pr "(** %s *)\n" shortdesc;
5970       pr "\n"
5971   ) all_functions
5972
5973 (* Generate the OCaml bindings implementation. *)
5974 and generate_ocaml_ml () =
5975   generate_header OCamlStyle LGPLv2;
5976
5977   pr "\
5978 type t
5979 exception Error of string
5980 external create : unit -> t = \"ocaml_guestfs_create\"
5981 external close : t -> unit = \"ocaml_guestfs_close\"
5982
5983 let () =
5984   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\")
5985
5986 ";
5987
5988   generate_ocaml_structure_decls ();
5989
5990   (* The actions. *)
5991   List.iter (
5992     fun (name, style, _, _, _, shortdesc, _) ->
5993       generate_ocaml_prototype ~is_external:true name style;
5994   ) all_functions
5995
5996 (* Generate the OCaml bindings C implementation. *)
5997 and generate_ocaml_c () =
5998   generate_header CStyle LGPLv2;
5999
6000   pr "\
6001 #include <stdio.h>
6002 #include <stdlib.h>
6003 #include <string.h>
6004
6005 #include <caml/config.h>
6006 #include <caml/alloc.h>
6007 #include <caml/callback.h>
6008 #include <caml/fail.h>
6009 #include <caml/memory.h>
6010 #include <caml/mlvalues.h>
6011 #include <caml/signals.h>
6012
6013 #include <guestfs.h>
6014
6015 #include \"guestfs_c.h\"
6016
6017 /* Copy a hashtable of string pairs into an assoc-list.  We return
6018  * the list in reverse order, but hashtables aren't supposed to be
6019  * ordered anyway.
6020  */
6021 static CAMLprim value
6022 copy_table (char * const * argv)
6023 {
6024   CAMLparam0 ();
6025   CAMLlocal5 (rv, pairv, kv, vv, cons);
6026   int i;
6027
6028   rv = Val_int (0);
6029   for (i = 0; argv[i] != NULL; i += 2) {
6030     kv = caml_copy_string (argv[i]);
6031     vv = caml_copy_string (argv[i+1]);
6032     pairv = caml_alloc (2, 0);
6033     Store_field (pairv, 0, kv);
6034     Store_field (pairv, 1, vv);
6035     cons = caml_alloc (2, 0);
6036     Store_field (cons, 1, rv);
6037     rv = cons;
6038     Store_field (cons, 0, pairv);
6039   }
6040
6041   CAMLreturn (rv);
6042 }
6043
6044 ";
6045
6046   (* Struct copy functions. *)
6047   List.iter (
6048     fun (typ, cols) ->
6049       let has_optpercent_col =
6050         List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
6051
6052       pr "static CAMLprim value\n";
6053       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
6054       pr "{\n";
6055       pr "  CAMLparam0 ();\n";
6056       if has_optpercent_col then
6057         pr "  CAMLlocal3 (rv, v, v2);\n"
6058       else
6059         pr "  CAMLlocal2 (rv, v);\n";
6060       pr "\n";
6061       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
6062       iteri (
6063         fun i col ->
6064           (match col with
6065            | name, FString ->
6066                pr "  v = caml_copy_string (%s->%s);\n" typ name
6067            | name, FBuffer ->
6068                pr "  v = caml_alloc_string (%s->%s_len);\n" typ name;
6069                pr "  memcpy (String_val (v), %s->%s, %s->%s_len);\n"
6070                  typ name typ name
6071            | name, FUUID ->
6072                pr "  v = caml_alloc_string (32);\n";
6073                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
6074            | name, (FBytes|FInt64|FUInt64) ->
6075                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
6076            | name, (FInt32|FUInt32) ->
6077                pr "  v = caml_copy_int32 (%s->%s);\n" typ name
6078            | name, FOptPercent ->
6079                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
6080                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
6081                pr "    v = caml_alloc (1, 0);\n";
6082                pr "    Store_field (v, 0, v2);\n";
6083                pr "  } else /* None */\n";
6084                pr "    v = Val_int (0);\n";
6085            | name, FChar ->
6086                pr "  v = Val_int (%s->%s);\n" typ name
6087           );
6088           pr "  Store_field (rv, %d, v);\n" i
6089       ) cols;
6090       pr "  CAMLreturn (rv);\n";
6091       pr "}\n";
6092       pr "\n";
6093
6094       pr "static CAMLprim value\n";
6095       pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n"
6096         typ typ typ;
6097       pr "{\n";
6098       pr "  CAMLparam0 ();\n";
6099       pr "  CAMLlocal2 (rv, v);\n";
6100       pr "  int i;\n";
6101       pr "\n";
6102       pr "  if (%ss->len == 0)\n" typ;
6103       pr "    CAMLreturn (Atom (0));\n";
6104       pr "  else {\n";
6105       pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
6106       pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
6107       pr "      v = copy_%s (&%ss->val[i]);\n" typ typ;
6108       pr "      caml_modify (&Field (rv, i), v);\n";
6109       pr "    }\n";
6110       pr "    CAMLreturn (rv);\n";
6111       pr "  }\n";
6112       pr "}\n";
6113       pr "\n";
6114   ) structs;
6115
6116   (* The wrappers. *)
6117   List.iter (
6118     fun (name, style, _, _, _, _, _) ->
6119       let params =
6120         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
6121
6122       let needs_extra_vs =
6123         match fst style with RConstOptString _ -> true | _ -> false in
6124
6125       pr "CAMLprim value\n";
6126       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
6127       List.iter (pr ", value %s") (List.tl params);
6128       pr ")\n";
6129       pr "{\n";
6130
6131       (match params with
6132        | [p1; p2; p3; p4; p5] ->
6133            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
6134        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
6135            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
6136            pr "  CAMLxparam%d (%s);\n"
6137              (List.length rest) (String.concat ", " rest)
6138        | ps ->
6139            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
6140       );
6141       if not needs_extra_vs then
6142         pr "  CAMLlocal1 (rv);\n"
6143       else
6144         pr "  CAMLlocal3 (rv, v, v2);\n";
6145       pr "\n";
6146
6147       pr "  guestfs_h *g = Guestfs_val (gv);\n";
6148       pr "  if (g == NULL)\n";
6149       pr "    caml_failwith (\"%s: used handle after closing it\");\n" name;
6150       pr "\n";
6151
6152       List.iter (
6153         function
6154         | String n
6155         | FileIn n
6156         | FileOut n ->
6157             pr "  const char *%s = String_val (%sv);\n" n n
6158         | OptString n ->
6159             pr "  const char *%s =\n" n;
6160             pr "    %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
6161               n n
6162         | StringList n ->
6163             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
6164         | Bool n ->
6165             pr "  int %s = Bool_val (%sv);\n" n n
6166         | Int n ->
6167             pr "  int %s = Int_val (%sv);\n" n n
6168       ) (snd style);
6169       let error_code =
6170         match fst style with
6171         | RErr -> pr "  int r;\n"; "-1"
6172         | RInt _ -> pr "  int r;\n"; "-1"
6173         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
6174         | RBool _ -> pr "  int r;\n"; "-1"
6175         | RConstString _ | RConstOptString _ ->
6176             pr "  const char *r;\n"; "NULL"
6177         | RString _ -> pr "  char *r;\n"; "NULL"
6178         | RStringList _ ->
6179             pr "  int i;\n";
6180             pr "  char **r;\n";
6181             "NULL"
6182         | RStruct (_, typ) ->
6183             pr "  struct guestfs_%s *r;\n" typ; "NULL"
6184         | RStructList (_, typ) ->
6185             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
6186         | RHashtable _ ->
6187             pr "  int i;\n";
6188             pr "  char **r;\n";
6189             "NULL"
6190         | RBufferOut _ ->
6191             pr "  char *r;\n";
6192             pr "  size_t size;\n";
6193             "NULL" in
6194       pr "\n";
6195
6196       pr "  caml_enter_blocking_section ();\n";
6197       pr "  r = guestfs_%s " name;
6198       generate_c_call_args ~handle:"g" style;
6199       pr ";\n";
6200       pr "  caml_leave_blocking_section ();\n";
6201
6202       List.iter (
6203         function
6204         | StringList n ->
6205             pr "  ocaml_guestfs_free_strings (%s);\n" n;
6206         | String _ | OptString _ | Bool _ | Int _ | FileIn _ | FileOut _ -> ()
6207       ) (snd style);
6208
6209       pr "  if (r == %s)\n" error_code;
6210       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
6211       pr "\n";
6212
6213       (match fst style with
6214        | RErr -> pr "  rv = Val_unit;\n"
6215        | RInt _ -> pr "  rv = Val_int (r);\n"
6216        | RInt64 _ ->
6217            pr "  rv = caml_copy_int64 (r);\n"
6218        | RBool _ -> pr "  rv = Val_bool (r);\n"
6219        | RConstString _ ->
6220            pr "  rv = caml_copy_string (r);\n"
6221        | RConstOptString _ ->
6222            pr "  if (r) { /* Some string */\n";
6223            pr "    v = caml_alloc (1, 0);\n";
6224            pr "    v2 = caml_copy_string (r);\n";
6225            pr "    Store_field (v, 0, v2);\n";
6226            pr "  } else /* None */\n";
6227            pr "    v = Val_int (0);\n";
6228        | RString _ ->
6229            pr "  rv = caml_copy_string (r);\n";
6230            pr "  free (r);\n"
6231        | RStringList _ ->
6232            pr "  rv = caml_copy_string_array ((const char **) r);\n";
6233            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6234            pr "  free (r);\n"
6235        | RStruct (_, typ) ->
6236            pr "  rv = copy_%s (r);\n" typ;
6237            pr "  guestfs_free_%s (r);\n" typ;
6238        | RStructList (_, typ) ->
6239            pr "  rv = copy_%s_list (r);\n" typ;
6240            pr "  guestfs_free_%s_list (r);\n" typ;
6241        | RHashtable _ ->
6242            pr "  rv = copy_table (r);\n";
6243            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
6244            pr "  free (r);\n";
6245        | RBufferOut _ ->
6246            pr "  rv = caml_alloc_string (size);\n";
6247            pr "  memcpy (String_val (rv), r, size);\n";
6248       );
6249
6250       pr "  CAMLreturn (rv);\n";
6251       pr "}\n";
6252       pr "\n";
6253
6254       if List.length params > 5 then (
6255         pr "CAMLprim value\n";
6256         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
6257         pr "{\n";
6258         pr "  return ocaml_guestfs_%s (argv[0]" name;
6259         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
6260         pr ");\n";
6261         pr "}\n";
6262         pr "\n"
6263       )
6264   ) all_functions
6265
6266 and generate_ocaml_structure_decls () =
6267   List.iter (
6268     fun (typ, cols) ->
6269       pr "type %s = {\n" typ;
6270       List.iter (
6271         function
6272         | name, FString -> pr "  %s : string;\n" name
6273         | name, FBuffer -> pr "  %s : string;\n" name
6274         | name, FUUID -> pr "  %s : string;\n" name
6275         | name, (FBytes|FInt64|FUInt64) -> pr "  %s : int64;\n" name
6276         | name, (FInt32|FUInt32) -> pr "  %s : int32;\n" name
6277         | name, FChar -> pr "  %s : char;\n" name
6278         | name, FOptPercent -> pr "  %s : float option;\n" name
6279       ) cols;
6280       pr "}\n";
6281       pr "\n"
6282   ) structs
6283
6284 and generate_ocaml_prototype ?(is_external = false) name style =
6285   if is_external then pr "external " else pr "val ";
6286   pr "%s : t -> " name;
6287   List.iter (
6288     function
6289     | String _ | FileIn _ | FileOut _ -> pr "string -> "
6290     | OptString _ -> pr "string option -> "
6291     | StringList _ -> pr "string array -> "
6292     | Bool _ -> pr "bool -> "
6293     | Int _ -> pr "int -> "
6294   ) (snd style);
6295   (match fst style with
6296    | RErr -> pr "unit" (* all errors are turned into exceptions *)
6297    | RInt _ -> pr "int"
6298    | RInt64 _ -> pr "int64"
6299    | RBool _ -> pr "bool"
6300    | RConstString _ -> pr "string"
6301    | RConstOptString _ -> pr "string option"
6302    | RString _ | RBufferOut _ -> pr "string"
6303    | RStringList _ -> pr "string array"
6304    | RStruct (_, typ) -> pr "%s" typ
6305    | RStructList (_, typ) -> pr "%s array" typ
6306    | RHashtable _ -> pr "(string * string) list"
6307   );
6308   if is_external then (
6309     pr " = ";
6310     if List.length (snd style) + 1 > 5 then
6311       pr "\"ocaml_guestfs_%s_byte\" " name;
6312     pr "\"ocaml_guestfs_%s\"" name
6313   );
6314   pr "\n"
6315
6316 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
6317 and generate_perl_xs () =
6318   generate_header CStyle LGPLv2;
6319
6320   pr "\
6321 #include \"EXTERN.h\"
6322 #include \"perl.h\"
6323 #include \"XSUB.h\"
6324
6325 #include <guestfs.h>
6326
6327 #ifndef PRId64
6328 #define PRId64 \"lld\"
6329 #endif
6330
6331 static SV *
6332 my_newSVll(long long val) {
6333 #ifdef USE_64_BIT_ALL
6334   return newSViv(val);
6335 #else
6336   char buf[100];
6337   int len;
6338   len = snprintf(buf, 100, \"%%\" PRId64, val);
6339   return newSVpv(buf, len);
6340 #endif
6341 }
6342
6343 #ifndef PRIu64
6344 #define PRIu64 \"llu\"
6345 #endif
6346
6347 static SV *
6348 my_newSVull(unsigned long long val) {
6349 #ifdef USE_64_BIT_ALL
6350   return newSVuv(val);
6351 #else
6352   char buf[100];
6353   int len;
6354   len = snprintf(buf, 100, \"%%\" PRIu64, val);
6355   return newSVpv(buf, len);
6356 #endif
6357 }
6358
6359 /* http://www.perlmonks.org/?node_id=680842 */
6360 static char **
6361 XS_unpack_charPtrPtr (SV *arg) {
6362   char **ret;
6363   AV *av;
6364   I32 i;
6365
6366   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
6367     croak (\"array reference expected\");
6368
6369   av = (AV *)SvRV (arg);
6370   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
6371   if (!ret)
6372     croak (\"malloc failed\");
6373
6374   for (i = 0; i <= av_len (av); i++) {
6375     SV **elem = av_fetch (av, i, 0);
6376
6377     if (!elem || !*elem)
6378       croak (\"missing element in list\");
6379
6380     ret[i] = SvPV_nolen (*elem);
6381   }
6382
6383   ret[i] = NULL;
6384
6385   return ret;
6386 }
6387
6388 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
6389
6390 PROTOTYPES: ENABLE
6391
6392 guestfs_h *
6393 _create ()
6394    CODE:
6395       RETVAL = guestfs_create ();
6396       if (!RETVAL)
6397         croak (\"could not create guestfs handle\");
6398       guestfs_set_error_handler (RETVAL, NULL, NULL);
6399  OUTPUT:
6400       RETVAL
6401
6402 void
6403 DESTROY (g)
6404       guestfs_h *g;
6405  PPCODE:
6406       guestfs_close (g);
6407
6408 ";
6409
6410   List.iter (
6411     fun (name, style, _, _, _, _, _) ->
6412       (match fst style with
6413        | RErr -> pr "void\n"
6414        | RInt _ -> pr "SV *\n"
6415        | RInt64 _ -> pr "SV *\n"
6416        | RBool _ -> pr "SV *\n"
6417        | RConstString _ -> pr "SV *\n"
6418        | RConstOptString _ -> pr "SV *\n"
6419        | RString _ -> pr "SV *\n"
6420        | RBufferOut _ -> pr "SV *\n"
6421        | RStringList _
6422        | RStruct _ | RStructList _
6423        | RHashtable _ ->
6424            pr "void\n" (* all lists returned implictly on the stack *)
6425       );
6426       (* Call and arguments. *)
6427       pr "%s " name;
6428       generate_c_call_args ~handle:"g" ~decl:true style;
6429       pr "\n";
6430       pr "      guestfs_h *g;\n";
6431       iteri (
6432         fun i ->
6433           function
6434           | String n | FileIn n | FileOut n -> pr "      char *%s;\n" n
6435           | OptString n ->
6436               (* http://www.perlmonks.org/?node_id=554277
6437                * Note that the implicit handle argument means we have
6438                * to add 1 to the ST(x) operator.
6439                *)
6440               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
6441           | StringList n -> pr "      char **%s;\n" n
6442           | Bool n -> pr "      int %s;\n" n
6443           | Int n -> pr "      int %s;\n" n
6444       ) (snd style);
6445
6446       let do_cleanups () =
6447         List.iter (
6448           function
6449           | String _ | OptString _ | Bool _ | Int _
6450           | FileIn _ | FileOut _ -> ()
6451           | StringList n -> pr "      free (%s);\n" n
6452         ) (snd style)
6453       in
6454
6455       (* Code. *)
6456       (match fst style with
6457        | RErr ->
6458            pr "PREINIT:\n";
6459            pr "      int r;\n";
6460            pr " PPCODE:\n";
6461            pr "      r = guestfs_%s " name;
6462            generate_c_call_args ~handle:"g" style;
6463            pr ";\n";
6464            do_cleanups ();
6465            pr "      if (r == -1)\n";
6466            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6467        | RInt n
6468        | RBool n ->
6469            pr "PREINIT:\n";
6470            pr "      int %s;\n" n;
6471            pr "   CODE:\n";
6472            pr "      %s = guestfs_%s " n name;
6473            generate_c_call_args ~handle:"g" style;
6474            pr ";\n";
6475            do_cleanups ();
6476            pr "      if (%s == -1)\n" n;
6477            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6478            pr "      RETVAL = newSViv (%s);\n" n;
6479            pr " OUTPUT:\n";
6480            pr "      RETVAL\n"
6481        | RInt64 n ->
6482            pr "PREINIT:\n";
6483            pr "      int64_t %s;\n" n;
6484            pr "   CODE:\n";
6485            pr "      %s = guestfs_%s " n name;
6486            generate_c_call_args ~handle:"g" style;
6487            pr ";\n";
6488            do_cleanups ();
6489            pr "      if (%s == -1)\n" n;
6490            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6491            pr "      RETVAL = my_newSVll (%s);\n" n;
6492            pr " OUTPUT:\n";
6493            pr "      RETVAL\n"
6494        | RConstString n ->
6495            pr "PREINIT:\n";
6496            pr "      const char *%s;\n" n;
6497            pr "   CODE:\n";
6498            pr "      %s = guestfs_%s " n name;
6499            generate_c_call_args ~handle:"g" style;
6500            pr ";\n";
6501            do_cleanups ();
6502            pr "      if (%s == NULL)\n" n;
6503            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6504            pr "      RETVAL = newSVpv (%s, 0);\n" n;
6505            pr " OUTPUT:\n";
6506            pr "      RETVAL\n"
6507        | RConstOptString n ->
6508            pr "PREINIT:\n";
6509            pr "      const char *%s;\n" n;
6510            pr "   CODE:\n";
6511            pr "      %s = guestfs_%s " n name;
6512            generate_c_call_args ~handle:"g" style;
6513            pr ";\n";
6514            do_cleanups ();
6515            pr "      if (%s == NULL)\n" n;
6516            pr "        RETVAL = &PL_sv_undef;\n";
6517            pr "      else\n";
6518            pr "        RETVAL = newSVpv (%s, 0);\n" n;
6519            pr " OUTPUT:\n";
6520            pr "      RETVAL\n"
6521        | RString n ->
6522            pr "PREINIT:\n";
6523            pr "      char *%s;\n" n;
6524            pr "   CODE:\n";
6525            pr "      %s = guestfs_%s " n name;
6526            generate_c_call_args ~handle:"g" style;
6527            pr ";\n";
6528            do_cleanups ();
6529            pr "      if (%s == NULL)\n" n;
6530            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6531            pr "      RETVAL = newSVpv (%s, 0);\n" n;
6532            pr "      free (%s);\n" n;
6533            pr " OUTPUT:\n";
6534            pr "      RETVAL\n"
6535        | RStringList n | RHashtable n ->
6536            pr "PREINIT:\n";
6537            pr "      char **%s;\n" n;
6538            pr "      int i, n;\n";
6539            pr " PPCODE:\n";
6540            pr "      %s = guestfs_%s " n name;
6541            generate_c_call_args ~handle:"g" style;
6542            pr ";\n";
6543            do_cleanups ();
6544            pr "      if (%s == NULL)\n" n;
6545            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6546            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
6547            pr "      EXTEND (SP, n);\n";
6548            pr "      for (i = 0; i < n; ++i) {\n";
6549            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
6550            pr "        free (%s[i]);\n" n;
6551            pr "      }\n";
6552            pr "      free (%s);\n" n;
6553        | RStruct (n, typ) ->
6554            let cols = cols_of_struct typ in
6555            generate_perl_struct_code typ cols name style n do_cleanups
6556        | RStructList (n, typ) ->
6557            let cols = cols_of_struct typ in
6558            generate_perl_struct_list_code typ cols name style n do_cleanups
6559        | RBufferOut n ->
6560            pr "PREINIT:\n";
6561            pr "      char *%s;\n" n;
6562            pr "      size_t size;\n";
6563            pr "   CODE:\n";
6564            pr "      %s = guestfs_%s " n name;
6565            generate_c_call_args ~handle:"g" style;
6566            pr ";\n";
6567            do_cleanups ();
6568            pr "      if (%s == NULL)\n" n;
6569            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6570            pr "      RETVAL = newSVpv (%s, size);\n" n;
6571            pr "      free (%s);\n" n;
6572            pr " OUTPUT:\n";
6573            pr "      RETVAL\n"
6574       );
6575
6576       pr "\n"
6577   ) all_functions
6578
6579 and generate_perl_struct_list_code typ cols name style n do_cleanups =
6580   pr "PREINIT:\n";
6581   pr "      struct guestfs_%s_list *%s;\n" typ n;
6582   pr "      int i;\n";
6583   pr "      HV *hv;\n";
6584   pr " PPCODE:\n";
6585   pr "      %s = guestfs_%s " n name;
6586   generate_c_call_args ~handle:"g" style;
6587   pr ";\n";
6588   do_cleanups ();
6589   pr "      if (%s == NULL)\n" n;
6590   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6591   pr "      EXTEND (SP, %s->len);\n" n;
6592   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
6593   pr "        hv = newHV ();\n";
6594   List.iter (
6595     function
6596     | name, FString ->
6597         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
6598           name (String.length name) n name
6599     | name, FUUID ->
6600         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
6601           name (String.length name) n name
6602     | name, FBuffer ->
6603         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
6604           name (String.length name) n name n name
6605     | name, (FBytes|FUInt64) ->
6606         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
6607           name (String.length name) n name
6608     | name, FInt64 ->
6609         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
6610           name (String.length name) n name
6611     | name, (FInt32|FUInt32) ->
6612         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6613           name (String.length name) n name
6614     | name, FChar ->
6615         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
6616           name (String.length name) n name
6617     | name, FOptPercent ->
6618         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
6619           name (String.length name) n name
6620   ) cols;
6621   pr "        PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
6622   pr "      }\n";
6623   pr "      guestfs_free_%s_list (%s);\n" typ n
6624
6625 and generate_perl_struct_code typ cols name style n do_cleanups =
6626   pr "PREINIT:\n";
6627   pr "      struct guestfs_%s *%s;\n" typ n;
6628   pr " PPCODE:\n";
6629   pr "      %s = guestfs_%s " n name;
6630   generate_c_call_args ~handle:"g" style;
6631   pr ";\n";
6632   do_cleanups ();
6633   pr "      if (%s == NULL)\n" n;
6634   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
6635   pr "      EXTEND (SP, 2 * %d);\n" (List.length cols);
6636   List.iter (
6637     fun ((name, _) as col) ->
6638       pr "      PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
6639
6640       match col with
6641       | name, FString ->
6642           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
6643             n name
6644       | name, FBuffer ->
6645           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, %s->%s_len)));\n"
6646             n name n name
6647       | name, FUUID ->
6648           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
6649             n name
6650       | name, (FBytes|FUInt64) ->
6651           pr "      PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
6652             n name
6653       | name, FInt64 ->
6654           pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
6655             n name
6656       | name, (FInt32|FUInt32) ->
6657           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6658             n name
6659       | name, FChar ->
6660           pr "      PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
6661             n name
6662       | name, FOptPercent ->
6663           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
6664             n name
6665   ) cols;
6666   pr "      free (%s);\n" n
6667
6668 (* Generate Sys/Guestfs.pm. *)
6669 and generate_perl_pm () =
6670   generate_header HashStyle LGPLv2;
6671
6672   pr "\
6673 =pod
6674
6675 =head1 NAME
6676
6677 Sys::Guestfs - Perl bindings for libguestfs
6678
6679 =head1 SYNOPSIS
6680
6681  use Sys::Guestfs;
6682
6683  my $h = Sys::Guestfs->new ();
6684  $h->add_drive ('guest.img');
6685  $h->launch ();
6686  $h->wait_ready ();
6687  $h->mount ('/dev/sda1', '/');
6688  $h->touch ('/hello');
6689  $h->sync ();
6690
6691 =head1 DESCRIPTION
6692
6693 The C<Sys::Guestfs> module provides a Perl XS binding to the
6694 libguestfs API for examining and modifying virtual machine
6695 disk images.
6696
6697 Amongst the things this is good for: making batch configuration
6698 changes to guests, getting disk used/free statistics (see also:
6699 virt-df), migrating between virtualization systems (see also:
6700 virt-p2v), performing partial backups, performing partial guest
6701 clones, cloning guests and changing registry/UUID/hostname info, and
6702 much else besides.
6703
6704 Libguestfs uses Linux kernel and qemu code, and can access any type of
6705 guest filesystem that Linux and qemu can, including but not limited
6706 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
6707 schemes, qcow, qcow2, vmdk.
6708
6709 Libguestfs provides ways to enumerate guest storage (eg. partitions,
6710 LVs, what filesystem is in each LV, etc.).  It can also run commands
6711 in the context of the guest.  Also you can access filesystems over FTP.
6712
6713 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
6714 functions for using libguestfs from Perl, including integration
6715 with libvirt.
6716
6717 =head1 ERRORS
6718
6719 All errors turn into calls to C<croak> (see L<Carp(3)>).
6720
6721 =head1 METHODS
6722
6723 =over 4
6724
6725 =cut
6726
6727 package Sys::Guestfs;
6728
6729 use strict;
6730 use warnings;
6731
6732 require XSLoader;
6733 XSLoader::load ('Sys::Guestfs');
6734
6735 =item $h = Sys::Guestfs->new ();
6736
6737 Create a new guestfs handle.
6738
6739 =cut
6740
6741 sub new {
6742   my $proto = shift;
6743   my $class = ref ($proto) || $proto;
6744
6745   my $self = Sys::Guestfs::_create ();
6746   bless $self, $class;
6747   return $self;
6748 }
6749
6750 ";
6751
6752   (* Actions.  We only need to print documentation for these as
6753    * they are pulled in from the XS code automatically.
6754    *)
6755   List.iter (
6756     fun (name, style, _, flags, _, _, longdesc) ->
6757       if not (List.mem NotInDocs flags) then (
6758         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
6759         pr "=item ";
6760         generate_perl_prototype name style;
6761         pr "\n\n";
6762         pr "%s\n\n" longdesc;
6763         if List.mem ProtocolLimitWarning flags then
6764           pr "%s\n\n" protocol_limit_warning;
6765         if List.mem DangerWillRobinson flags then
6766           pr "%s\n\n" danger_will_robinson;
6767         match deprecation_notice flags with
6768         | None -> ()
6769         | Some txt -> pr "%s\n\n" txt
6770       )
6771   ) all_functions_sorted;
6772
6773   (* End of file. *)
6774   pr "\
6775 =cut
6776
6777 1;
6778
6779 =back
6780
6781 =head1 COPYRIGHT
6782
6783 Copyright (C) 2009 Red Hat Inc.
6784
6785 =head1 LICENSE
6786
6787 Please see the file COPYING.LIB for the full license.
6788
6789 =head1 SEE ALSO
6790
6791 L<guestfs(3)>,
6792 L<guestfish(1)>,
6793 L<http://libguestfs.org>,
6794 L<Sys::Guestfs::Lib(3)>.
6795
6796 =cut
6797 "
6798
6799 and generate_perl_prototype name style =
6800   (match fst style with
6801    | RErr -> ()
6802    | RBool n
6803    | RInt n
6804    | RInt64 n
6805    | RConstString n
6806    | RConstOptString n
6807    | RString n
6808    | RBufferOut n -> pr "$%s = " n
6809    | RStruct (n,_)
6810    | RHashtable n -> pr "%%%s = " n
6811    | RStringList n
6812    | RStructList (n,_) -> pr "@%s = " n
6813   );
6814   pr "$h->%s (" name;
6815   let comma = ref false in
6816   List.iter (
6817     fun arg ->
6818       if !comma then pr ", ";
6819       comma := true;
6820       match arg with
6821       | String n | OptString n | Bool n | Int n | FileIn n | FileOut n ->
6822           pr "$%s" n
6823       | StringList n ->
6824           pr "\\@%s" n
6825   ) (snd style);
6826   pr ");"
6827
6828 (* Generate Python C module. *)
6829 and generate_python_c () =
6830   generate_header CStyle LGPLv2;
6831
6832   pr "\
6833 #include <stdio.h>
6834 #include <stdlib.h>
6835 #include <assert.h>
6836
6837 #include <Python.h>
6838
6839 #include \"guestfs.h\"
6840
6841 typedef struct {
6842   PyObject_HEAD
6843   guestfs_h *g;
6844 } Pyguestfs_Object;
6845
6846 static guestfs_h *
6847 get_handle (PyObject *obj)
6848 {
6849   assert (obj);
6850   assert (obj != Py_None);
6851   return ((Pyguestfs_Object *) obj)->g;
6852 }
6853
6854 static PyObject *
6855 put_handle (guestfs_h *g)
6856 {
6857   assert (g);
6858   return
6859     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
6860 }
6861
6862 /* This list should be freed (but not the strings) after use. */
6863 static const char **
6864 get_string_list (PyObject *obj)
6865 {
6866   int i, len;
6867   const char **r;
6868
6869   assert (obj);
6870
6871   if (!PyList_Check (obj)) {
6872     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
6873     return NULL;
6874   }
6875
6876   len = PyList_Size (obj);
6877   r = malloc (sizeof (char *) * (len+1));
6878   if (r == NULL) {
6879     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
6880     return NULL;
6881   }
6882
6883   for (i = 0; i < len; ++i)
6884     r[i] = PyString_AsString (PyList_GetItem (obj, i));
6885   r[len] = NULL;
6886
6887   return r;
6888 }
6889
6890 static PyObject *
6891 put_string_list (char * const * const argv)
6892 {
6893   PyObject *list;
6894   int argc, i;
6895
6896   for (argc = 0; argv[argc] != NULL; ++argc)
6897     ;
6898
6899   list = PyList_New (argc);
6900   for (i = 0; i < argc; ++i)
6901     PyList_SetItem (list, i, PyString_FromString (argv[i]));
6902
6903   return list;
6904 }
6905
6906 static PyObject *
6907 put_table (char * const * const argv)
6908 {
6909   PyObject *list, *item;
6910   int argc, i;
6911
6912   for (argc = 0; argv[argc] != NULL; ++argc)
6913     ;
6914
6915   list = PyList_New (argc >> 1);
6916   for (i = 0; i < argc; i += 2) {
6917     item = PyTuple_New (2);
6918     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
6919     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
6920     PyList_SetItem (list, i >> 1, item);
6921   }
6922
6923   return list;
6924 }
6925
6926 static void
6927 free_strings (char **argv)
6928 {
6929   int argc;
6930
6931   for (argc = 0; argv[argc] != NULL; ++argc)
6932     free (argv[argc]);
6933   free (argv);
6934 }
6935
6936 static PyObject *
6937 py_guestfs_create (PyObject *self, PyObject *args)
6938 {
6939   guestfs_h *g;
6940
6941   g = guestfs_create ();
6942   if (g == NULL) {
6943     PyErr_SetString (PyExc_RuntimeError,
6944                      \"guestfs.create: failed to allocate handle\");
6945     return NULL;
6946   }
6947   guestfs_set_error_handler (g, NULL, NULL);
6948   return put_handle (g);
6949 }
6950
6951 static PyObject *
6952 py_guestfs_close (PyObject *self, PyObject *args)
6953 {
6954   PyObject *py_g;
6955   guestfs_h *g;
6956
6957   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
6958     return NULL;
6959   g = get_handle (py_g);
6960
6961   guestfs_close (g);
6962
6963   Py_INCREF (Py_None);
6964   return Py_None;
6965 }
6966
6967 ";
6968
6969   (* Structures, turned into Python dictionaries. *)
6970   List.iter (
6971     fun (typ, cols) ->
6972       pr "static PyObject *\n";
6973       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
6974       pr "{\n";
6975       pr "  PyObject *dict;\n";
6976       pr "\n";
6977       pr "  dict = PyDict_New ();\n";
6978       List.iter (
6979         function
6980         | name, FString ->
6981             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
6982             pr "                        PyString_FromString (%s->%s));\n"
6983               typ name
6984         | name, FBuffer ->
6985             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
6986             pr "                        PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
6987               typ name typ name
6988         | name, FUUID ->
6989             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
6990             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
6991               typ name
6992         | name, (FBytes|FUInt64) ->
6993             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
6994             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
6995               typ name
6996         | name, FInt64 ->
6997             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
6998             pr "                        PyLong_FromLongLong (%s->%s));\n"
6999               typ name
7000         | name, FUInt32 ->
7001             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
7002             pr "                        PyLong_FromUnsignedLong (%s->%s));\n"
7003               typ name
7004         | name, FInt32 ->
7005             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
7006             pr "                        PyLong_FromLong (%s->%s));\n"
7007               typ name
7008         | name, FOptPercent ->
7009             pr "  if (%s->%s >= 0)\n" typ name;
7010             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
7011             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
7012               typ name;
7013             pr "  else {\n";
7014             pr "    Py_INCREF (Py_None);\n";
7015             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);" name;
7016             pr "  }\n"
7017         | name, FChar ->
7018             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
7019             pr "                        PyString_FromStringAndSize (&dirent->%s, 1));\n" name
7020       ) cols;
7021       pr "  return dict;\n";
7022       pr "};\n";
7023       pr "\n";
7024
7025       pr "static PyObject *\n";
7026       pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
7027       pr "{\n";
7028       pr "  PyObject *list;\n";
7029       pr "  int i;\n";
7030       pr "\n";
7031       pr "  list = PyList_New (%ss->len);\n" typ;
7032       pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
7033       pr "    PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
7034       pr "  return list;\n";
7035       pr "};\n";
7036       pr "\n"
7037   ) structs;
7038
7039   (* Python wrapper functions. *)
7040   List.iter (
7041     fun (name, style, _, _, _, _, _) ->
7042       pr "static PyObject *\n";
7043       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
7044       pr "{\n";
7045
7046       pr "  PyObject *py_g;\n";
7047       pr "  guestfs_h *g;\n";
7048       pr "  PyObject *py_r;\n";
7049
7050       let error_code =
7051         match fst style with
7052         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
7053         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
7054         | RConstString _ | RConstOptString _ ->
7055             pr "  const char *r;\n"; "NULL"
7056         | RString _ -> pr "  char *r;\n"; "NULL"
7057         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
7058         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
7059         | RStructList (_, typ) ->
7060             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
7061         | RBufferOut _ ->
7062             pr "  char *r;\n";
7063             pr "  size_t size;\n";
7064             "NULL" in
7065
7066       List.iter (
7067         function
7068         | String n | FileIn n | FileOut n -> pr "  const char *%s;\n" n
7069         | OptString n -> pr "  const char *%s;\n" n
7070         | StringList n ->
7071             pr "  PyObject *py_%s;\n" n;
7072             pr "  const char **%s;\n" n
7073         | Bool n -> pr "  int %s;\n" n
7074         | Int n -> pr "  int %s;\n" n
7075       ) (snd style);
7076
7077       pr "\n";
7078
7079       (* Convert the parameters. *)
7080       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
7081       List.iter (
7082         function
7083         | String _ | FileIn _ | FileOut _ -> pr "s"
7084         | OptString _ -> pr "z"
7085         | StringList _ -> pr "O"
7086         | Bool _ -> pr "i" (* XXX Python has booleans? *)
7087         | Int _ -> pr "i"
7088       ) (snd style);
7089       pr ":guestfs_%s\",\n" name;
7090       pr "                         &py_g";
7091       List.iter (
7092         function
7093         | String n | FileIn n | FileOut n -> pr ", &%s" n
7094         | OptString n -> pr ", &%s" n
7095         | StringList n -> pr ", &py_%s" n
7096         | Bool n -> pr ", &%s" n
7097         | Int n -> pr ", &%s" n
7098       ) (snd style);
7099
7100       pr "))\n";
7101       pr "    return NULL;\n";
7102
7103       pr "  g = get_handle (py_g);\n";
7104       List.iter (
7105         function
7106         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7107         | StringList n ->
7108             pr "  %s = get_string_list (py_%s);\n" n n;
7109             pr "  if (!%s) return NULL;\n" n
7110       ) (snd style);
7111
7112       pr "\n";
7113
7114       pr "  r = guestfs_%s " name;
7115       generate_c_call_args ~handle:"g" style;
7116       pr ";\n";
7117
7118       List.iter (
7119         function
7120         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7121         | StringList n ->
7122             pr "  free (%s);\n" n
7123       ) (snd style);
7124
7125       pr "  if (r == %s) {\n" error_code;
7126       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
7127       pr "    return NULL;\n";
7128       pr "  }\n";
7129       pr "\n";
7130
7131       (match fst style with
7132        | RErr ->
7133            pr "  Py_INCREF (Py_None);\n";
7134            pr "  py_r = Py_None;\n"
7135        | RInt _
7136        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
7137        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
7138        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
7139        | RConstOptString _ ->
7140            pr "  if (r)\n";
7141            pr "    py_r = PyString_FromString (r);\n";
7142            pr "  else {\n";
7143            pr "    Py_INCREF (Py_None);\n";
7144            pr "    py_r = Py_None;\n";
7145            pr "  }\n"
7146        | RString _ ->
7147            pr "  py_r = PyString_FromString (r);\n";
7148            pr "  free (r);\n"
7149        | RStringList _ ->
7150            pr "  py_r = put_string_list (r);\n";
7151            pr "  free_strings (r);\n"
7152        | RStruct (_, typ) ->
7153            pr "  py_r = put_%s (r);\n" typ;
7154            pr "  guestfs_free_%s (r);\n" typ
7155        | RStructList (_, typ) ->
7156            pr "  py_r = put_%s_list (r);\n" typ;
7157            pr "  guestfs_free_%s_list (r);\n" typ
7158        | RHashtable n ->
7159            pr "  py_r = put_table (r);\n";
7160            pr "  free_strings (r);\n"
7161        | RBufferOut _ ->
7162            pr "  py_r = PyString_FromStringAndSize (r, size);\n";
7163            pr "  free (r);\n"
7164       );
7165
7166       pr "  return py_r;\n";
7167       pr "}\n";
7168       pr "\n"
7169   ) all_functions;
7170
7171   (* Table of functions. *)
7172   pr "static PyMethodDef methods[] = {\n";
7173   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
7174   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
7175   List.iter (
7176     fun (name, _, _, _, _, _, _) ->
7177       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
7178         name name
7179   ) all_functions;
7180   pr "  { NULL, NULL, 0, NULL }\n";
7181   pr "};\n";
7182   pr "\n";
7183
7184   (* Init function. *)
7185   pr "\
7186 void
7187 initlibguestfsmod (void)
7188 {
7189   static int initialized = 0;
7190
7191   if (initialized) return;
7192   Py_InitModule ((char *) \"libguestfsmod\", methods);
7193   initialized = 1;
7194 }
7195 "
7196
7197 (* Generate Python module. *)
7198 and generate_python_py () =
7199   generate_header HashStyle LGPLv2;
7200
7201   pr "\
7202 u\"\"\"Python bindings for libguestfs
7203
7204 import guestfs
7205 g = guestfs.GuestFS ()
7206 g.add_drive (\"guest.img\")
7207 g.launch ()
7208 g.wait_ready ()
7209 parts = g.list_partitions ()
7210
7211 The guestfs module provides a Python binding to the libguestfs API
7212 for examining and modifying virtual machine disk images.
7213
7214 Amongst the things this is good for: making batch configuration
7215 changes to guests, getting disk used/free statistics (see also:
7216 virt-df), migrating between virtualization systems (see also:
7217 virt-p2v), performing partial backups, performing partial guest
7218 clones, cloning guests and changing registry/UUID/hostname info, and
7219 much else besides.
7220
7221 Libguestfs uses Linux kernel and qemu code, and can access any type of
7222 guest filesystem that Linux and qemu can, including but not limited
7223 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
7224 schemes, qcow, qcow2, vmdk.
7225
7226 Libguestfs provides ways to enumerate guest storage (eg. partitions,
7227 LVs, what filesystem is in each LV, etc.).  It can also run commands
7228 in the context of the guest.  Also you can access filesystems over FTP.
7229
7230 Errors which happen while using the API are turned into Python
7231 RuntimeError exceptions.
7232
7233 To create a guestfs handle you usually have to perform the following
7234 sequence of calls:
7235
7236 # Create the handle, call add_drive at least once, and possibly
7237 # several times if the guest has multiple block devices:
7238 g = guestfs.GuestFS ()
7239 g.add_drive (\"guest.img\")
7240
7241 # Launch the qemu subprocess and wait for it to become ready:
7242 g.launch ()
7243 g.wait_ready ()
7244
7245 # Now you can issue commands, for example:
7246 logvols = g.lvs ()
7247
7248 \"\"\"
7249
7250 import libguestfsmod
7251
7252 class GuestFS:
7253     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
7254
7255     def __init__ (self):
7256         \"\"\"Create a new libguestfs handle.\"\"\"
7257         self._o = libguestfsmod.create ()
7258
7259     def __del__ (self):
7260         libguestfsmod.close (self._o)
7261
7262 ";
7263
7264   List.iter (
7265     fun (name, style, _, flags, _, _, longdesc) ->
7266       pr "    def %s " name;
7267       generate_py_call_args ~handle:"self" (snd style);
7268       pr ":\n";
7269
7270       if not (List.mem NotInDocs flags) then (
7271         let doc = replace_str longdesc "C<guestfs_" "C<g." in
7272         let doc =
7273           match fst style with
7274           | RErr | RInt _ | RInt64 _ | RBool _
7275           | RConstOptString _ | RConstString _
7276           | RString _ | RBufferOut _ -> doc
7277           | RStringList _ ->
7278               doc ^ "\n\nThis function returns a list of strings."
7279           | RStruct (_, typ) ->
7280               doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
7281           | RStructList (_, typ) ->
7282               doc ^ sprintf "\n\nThis function returns a list of %ss.  Each %s is represented as a dictionary." typ typ
7283           | RHashtable _ ->
7284               doc ^ "\n\nThis function returns a dictionary." in
7285         let doc =
7286           if List.mem ProtocolLimitWarning flags then
7287             doc ^ "\n\n" ^ protocol_limit_warning
7288           else doc in
7289         let doc =
7290           if List.mem DangerWillRobinson flags then
7291             doc ^ "\n\n" ^ danger_will_robinson
7292           else doc in
7293         let doc =
7294           match deprecation_notice flags with
7295           | None -> doc
7296           | Some txt -> doc ^ "\n\n" ^ txt in
7297         let doc = pod2text ~width:60 name doc in
7298         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
7299         let doc = String.concat "\n        " doc in
7300         pr "        u\"\"\"%s\"\"\"\n" doc;
7301       );
7302       pr "        return libguestfsmod.%s " name;
7303       generate_py_call_args ~handle:"self._o" (snd style);
7304       pr "\n";
7305       pr "\n";
7306   ) all_functions
7307
7308 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
7309 and generate_py_call_args ~handle args =
7310   pr "(%s" handle;
7311   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7312   pr ")"
7313
7314 (* Useful if you need the longdesc POD text as plain text.  Returns a
7315  * list of lines.
7316  *
7317  * Because this is very slow (the slowest part of autogeneration),
7318  * we memoize the results.
7319  *)
7320 and pod2text ~width name longdesc =
7321   let key = width, name, longdesc in
7322   try Hashtbl.find pod2text_memo key
7323   with Not_found ->
7324     let filename, chan = Filename.open_temp_file "gen" ".tmp" in
7325     fprintf chan "=head1 %s\n\n%s\n" name longdesc;
7326     close_out chan;
7327     let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
7328     let chan = Unix.open_process_in cmd in
7329     let lines = ref [] in
7330     let rec loop i =
7331       let line = input_line chan in
7332       if i = 1 then             (* discard the first line of output *)
7333         loop (i+1)
7334       else (
7335         let line = triml line in
7336         lines := line :: !lines;
7337         loop (i+1)
7338       ) in
7339     let lines = try loop 1 with End_of_file -> List.rev !lines in
7340     Unix.unlink filename;
7341     (match Unix.close_process_in chan with
7342      | Unix.WEXITED 0 -> ()
7343      | Unix.WEXITED i ->
7344          failwithf "pod2text: process exited with non-zero status (%d)" i
7345      | Unix.WSIGNALED i | Unix.WSTOPPED i ->
7346          failwithf "pod2text: process signalled or stopped by signal %d" i
7347     );
7348     Hashtbl.add pod2text_memo key lines;
7349     let chan = open_out pod2text_memo_filename in
7350     output_value chan pod2text_memo;
7351     close_out chan;
7352     lines
7353
7354 (* Generate ruby bindings. *)
7355 and generate_ruby_c () =
7356   generate_header CStyle LGPLv2;
7357
7358   pr "\
7359 #include <stdio.h>
7360 #include <stdlib.h>
7361
7362 #include <ruby.h>
7363
7364 #include \"guestfs.h\"
7365
7366 #include \"extconf.h\"
7367
7368 /* For Ruby < 1.9 */
7369 #ifndef RARRAY_LEN
7370 #define RARRAY_LEN(r) (RARRAY((r))->len)
7371 #endif
7372
7373 static VALUE m_guestfs;                 /* guestfs module */
7374 static VALUE c_guestfs;                 /* guestfs_h handle */
7375 static VALUE e_Error;                   /* used for all errors */
7376
7377 static void ruby_guestfs_free (void *p)
7378 {
7379   if (!p) return;
7380   guestfs_close ((guestfs_h *) p);
7381 }
7382
7383 static VALUE ruby_guestfs_create (VALUE m)
7384 {
7385   guestfs_h *g;
7386
7387   g = guestfs_create ();
7388   if (!g)
7389     rb_raise (e_Error, \"failed to create guestfs handle\");
7390
7391   /* Don't print error messages to stderr by default. */
7392   guestfs_set_error_handler (g, NULL, NULL);
7393
7394   /* Wrap it, and make sure the close function is called when the
7395    * handle goes away.
7396    */
7397   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
7398 }
7399
7400 static VALUE ruby_guestfs_close (VALUE gv)
7401 {
7402   guestfs_h *g;
7403   Data_Get_Struct (gv, guestfs_h, g);
7404
7405   ruby_guestfs_free (g);
7406   DATA_PTR (gv) = NULL;
7407
7408   return Qnil;
7409 }
7410
7411 ";
7412
7413   List.iter (
7414     fun (name, style, _, _, _, _, _) ->
7415       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
7416       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
7417       pr ")\n";
7418       pr "{\n";
7419       pr "  guestfs_h *g;\n";
7420       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
7421       pr "  if (!g)\n";
7422       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
7423         name;
7424       pr "\n";
7425
7426       List.iter (
7427         function
7428         | String n | FileIn n | FileOut n ->
7429             pr "  Check_Type (%sv, T_STRING);\n" n;
7430             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
7431             pr "  if (!%s)\n" n;
7432             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
7433             pr "              \"%s\", \"%s\");\n" n name
7434         | OptString n ->
7435             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
7436         | StringList n ->
7437             pr "  char **%s;\n" n;
7438             pr "  Check_Type (%sv, T_ARRAY);\n" n;
7439             pr "  {\n";
7440             pr "    int i, len;\n";
7441             pr "    len = RARRAY_LEN (%sv);\n" n;
7442             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
7443               n;
7444             pr "    for (i = 0; i < len; ++i) {\n";
7445             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
7446             pr "      %s[i] = StringValueCStr (v);\n" n;
7447             pr "    }\n";
7448             pr "    %s[len] = NULL;\n" n;
7449             pr "  }\n";
7450         | Bool n ->
7451             pr "  int %s = RTEST (%sv);\n" n n
7452         | Int n ->
7453             pr "  int %s = NUM2INT (%sv);\n" n n
7454       ) (snd style);
7455       pr "\n";
7456
7457       let error_code =
7458         match fst style with
7459         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
7460         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
7461         | RConstString _ | RConstOptString _ ->
7462             pr "  const char *r;\n"; "NULL"
7463         | RString _ -> pr "  char *r;\n"; "NULL"
7464         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
7465         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
7466         | RStructList (_, typ) ->
7467             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
7468         | RBufferOut _ ->
7469             pr "  char *r;\n";
7470             pr "  size_t size;\n";
7471             "NULL" in
7472       pr "\n";
7473
7474       pr "  r = guestfs_%s " name;
7475       generate_c_call_args ~handle:"g" style;
7476       pr ";\n";
7477
7478       List.iter (
7479         function
7480         | String _ | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ -> ()
7481         | StringList n ->
7482             pr "  free (%s);\n" n
7483       ) (snd style);
7484
7485       pr "  if (r == %s)\n" error_code;
7486       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
7487       pr "\n";
7488
7489       (match fst style with
7490        | RErr ->
7491            pr "  return Qnil;\n"
7492        | RInt _ | RBool _ ->
7493            pr "  return INT2NUM (r);\n"
7494        | RInt64 _ ->
7495            pr "  return ULL2NUM (r);\n"
7496        | RConstString _ ->
7497            pr "  return rb_str_new2 (r);\n";
7498        | RConstOptString _ ->
7499            pr "  if (r)\n";
7500            pr "    return rb_str_new2 (r);\n";
7501            pr "  else\n";
7502            pr "    return Qnil;\n";
7503        | RString _ ->
7504            pr "  VALUE rv = rb_str_new2 (r);\n";
7505            pr "  free (r);\n";
7506            pr "  return rv;\n";
7507        | RStringList _ ->
7508            pr "  int i, len = 0;\n";
7509            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
7510            pr "  VALUE rv = rb_ary_new2 (len);\n";
7511            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
7512            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
7513            pr "    free (r[i]);\n";
7514            pr "  }\n";
7515            pr "  free (r);\n";
7516            pr "  return rv;\n"
7517        | RStruct (_, typ) ->
7518            let cols = cols_of_struct typ in
7519            generate_ruby_struct_code typ cols
7520        | RStructList (_, typ) ->
7521            let cols = cols_of_struct typ in
7522            generate_ruby_struct_list_code typ cols
7523        | RHashtable _ ->
7524            pr "  VALUE rv = rb_hash_new ();\n";
7525            pr "  int i;\n";
7526            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
7527            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
7528            pr "    free (r[i]);\n";
7529            pr "    free (r[i+1]);\n";
7530            pr "  }\n";
7531            pr "  free (r);\n";
7532            pr "  return rv;\n"
7533        | RBufferOut _ ->
7534            pr "  VALUE rv = rb_str_new (r, size);\n";
7535            pr "  free (r);\n";
7536            pr "  return rv;\n";
7537       );
7538
7539       pr "}\n";
7540       pr "\n"
7541   ) all_functions;
7542
7543   pr "\
7544 /* Initialize the module. */
7545 void Init__guestfs ()
7546 {
7547   m_guestfs = rb_define_module (\"Guestfs\");
7548   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
7549   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
7550
7551   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
7552   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
7553
7554 ";
7555   (* Define the rest of the methods. *)
7556   List.iter (
7557     fun (name, style, _, _, _, _, _) ->
7558       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
7559       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
7560   ) all_functions;
7561
7562   pr "}\n"
7563
7564 (* Ruby code to return a struct. *)
7565 and generate_ruby_struct_code typ cols =
7566   pr "  VALUE rv = rb_hash_new ();\n";
7567   List.iter (
7568     function
7569     | name, FString ->
7570         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
7571     | name, FBuffer ->
7572         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
7573     | name, FUUID ->
7574         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
7575     | name, (FBytes|FUInt64) ->
7576         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7577     | name, FInt64 ->
7578         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
7579     | name, FUInt32 ->
7580         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
7581     | name, FInt32 ->
7582         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
7583     | name, FOptPercent ->
7584         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
7585     | name, FChar -> (* XXX wrong? *)
7586         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
7587   ) cols;
7588   pr "  guestfs_free_%s (r);\n" typ;
7589   pr "  return rv;\n"
7590
7591 (* Ruby code to return a struct list. *)
7592 and generate_ruby_struct_list_code typ cols =
7593   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
7594   pr "  int i;\n";
7595   pr "  for (i = 0; i < r->len; ++i) {\n";
7596   pr "    VALUE hv = rb_hash_new ();\n";
7597   List.iter (
7598     function
7599     | name, FString ->
7600         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
7601     | name, FBuffer ->
7602         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, r->val[i].%s_len));\n" name name name
7603     | name, FUUID ->
7604         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
7605     | name, (FBytes|FUInt64) ->
7606         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7607     | name, FInt64 ->
7608         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
7609     | name, FUInt32 ->
7610         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
7611     | name, FInt32 ->
7612         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
7613     | name, FOptPercent ->
7614         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
7615     | name, FChar -> (* XXX wrong? *)
7616         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
7617   ) cols;
7618   pr "    rb_ary_push (rv, hv);\n";
7619   pr "  }\n";
7620   pr "  guestfs_free_%s_list (r);\n" typ;
7621   pr "  return rv;\n"
7622
7623 (* Generate Java bindings GuestFS.java file. *)
7624 and generate_java_java () =
7625   generate_header CStyle LGPLv2;
7626
7627   pr "\
7628 package com.redhat.et.libguestfs;
7629
7630 import java.util.HashMap;
7631 import com.redhat.et.libguestfs.LibGuestFSException;
7632 import com.redhat.et.libguestfs.PV;
7633 import com.redhat.et.libguestfs.VG;
7634 import com.redhat.et.libguestfs.LV;
7635 import com.redhat.et.libguestfs.Stat;
7636 import com.redhat.et.libguestfs.StatVFS;
7637 import com.redhat.et.libguestfs.IntBool;
7638 import com.redhat.et.libguestfs.Dirent;
7639
7640 /**
7641  * The GuestFS object is a libguestfs handle.
7642  *
7643  * @author rjones
7644  */
7645 public class GuestFS {
7646   // Load the native code.
7647   static {
7648     System.loadLibrary (\"guestfs_jni\");
7649   }
7650
7651   /**
7652    * The native guestfs_h pointer.
7653    */
7654   long g;
7655
7656   /**
7657    * Create a libguestfs handle.
7658    *
7659    * @throws LibGuestFSException
7660    */
7661   public GuestFS () throws LibGuestFSException
7662   {
7663     g = _create ();
7664   }
7665   private native long _create () throws LibGuestFSException;
7666
7667   /**
7668    * Close a libguestfs handle.
7669    *
7670    * You can also leave handles to be collected by the garbage
7671    * collector, but this method ensures that the resources used
7672    * by the handle are freed up immediately.  If you call any
7673    * other methods after closing the handle, you will get an
7674    * exception.
7675    *
7676    * @throws LibGuestFSException
7677    */
7678   public void close () throws LibGuestFSException
7679   {
7680     if (g != 0)
7681       _close (g);
7682     g = 0;
7683   }
7684   private native void _close (long g) throws LibGuestFSException;
7685
7686   public void finalize () throws LibGuestFSException
7687   {
7688     close ();
7689   }
7690
7691 ";
7692
7693   List.iter (
7694     fun (name, style, _, flags, _, shortdesc, longdesc) ->
7695       if not (List.mem NotInDocs flags); then (
7696         let doc = replace_str longdesc "C<guestfs_" "C<g." in
7697         let doc =
7698           if List.mem ProtocolLimitWarning flags then
7699             doc ^ "\n\n" ^ protocol_limit_warning
7700           else doc in
7701         let doc =
7702           if List.mem DangerWillRobinson flags then
7703             doc ^ "\n\n" ^ danger_will_robinson
7704           else doc in
7705         let doc =
7706           match deprecation_notice flags with
7707           | None -> doc
7708           | Some txt -> doc ^ "\n\n" ^ txt in
7709         let doc = pod2text ~width:60 name doc in
7710         let doc = List.map (            (* RHBZ#501883 *)
7711           function
7712           | "" -> "<p>"
7713           | nonempty -> nonempty
7714         ) doc in
7715         let doc = String.concat "\n   * " doc in
7716
7717         pr "  /**\n";
7718         pr "   * %s\n" shortdesc;
7719         pr "   * <p>\n";
7720         pr "   * %s\n" doc;
7721         pr "   * @throws LibGuestFSException\n";
7722         pr "   */\n";
7723         pr "  ";
7724       );
7725       generate_java_prototype ~public:true ~semicolon:false name style;
7726       pr "\n";
7727       pr "  {\n";
7728       pr "    if (g == 0)\n";
7729       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
7730         name;
7731       pr "    ";
7732       if fst style <> RErr then pr "return ";
7733       pr "_%s " name;
7734       generate_java_call_args ~handle:"g" (snd style);
7735       pr ";\n";
7736       pr "  }\n";
7737       pr "  ";
7738       generate_java_prototype ~privat:true ~native:true name style;
7739       pr "\n";
7740       pr "\n";
7741   ) all_functions;
7742
7743   pr "}\n"
7744
7745 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
7746 and generate_java_call_args ~handle args =
7747   pr "(%s" handle;
7748   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
7749   pr ")"
7750
7751 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
7752     ?(semicolon=true) name style =
7753   if privat then pr "private ";
7754   if public then pr "public ";
7755   if native then pr "native ";
7756
7757   (* return type *)
7758   (match fst style with
7759    | RErr -> pr "void ";
7760    | RInt _ -> pr "int ";
7761    | RInt64 _ -> pr "long ";
7762    | RBool _ -> pr "boolean ";
7763    | RConstString _ | RConstOptString _ | RString _
7764    | RBufferOut _ -> pr "String ";
7765    | RStringList _ -> pr "String[] ";
7766    | RStruct (_, typ) ->
7767        let name = java_name_of_struct typ in
7768        pr "%s " name;
7769    | RStructList (_, typ) ->
7770        let name = java_name_of_struct typ in
7771        pr "%s[] " name;
7772    | RHashtable _ -> pr "HashMap<String,String> ";
7773   );
7774
7775   if native then pr "_%s " name else pr "%s " name;
7776   pr "(";
7777   let needs_comma = ref false in
7778   if native then (
7779     pr "long g";
7780     needs_comma := true
7781   );
7782
7783   (* args *)
7784   List.iter (
7785     fun arg ->
7786       if !needs_comma then pr ", ";
7787       needs_comma := true;
7788
7789       match arg with
7790       | String n
7791       | OptString n
7792       | FileIn n
7793       | FileOut n ->
7794           pr "String %s" n
7795       | StringList n ->
7796           pr "String[] %s" n
7797       | Bool n ->
7798           pr "boolean %s" n
7799       | Int n ->
7800           pr "int %s" n
7801   ) (snd style);
7802
7803   pr ")\n";
7804   pr "    throws LibGuestFSException";
7805   if semicolon then pr ";"
7806
7807 and generate_java_struct jtyp cols =
7808   generate_header CStyle LGPLv2;
7809
7810   pr "\
7811 package com.redhat.et.libguestfs;
7812
7813 /**
7814  * Libguestfs %s structure.
7815  *
7816  * @author rjones
7817  * @see GuestFS
7818  */
7819 public class %s {
7820 " jtyp jtyp;
7821
7822   List.iter (
7823     function
7824     | name, FString
7825     | name, FUUID
7826     | name, FBuffer -> pr "  public String %s;\n" name
7827     | name, (FBytes|FUInt64|FInt64) -> pr "  public long %s;\n" name
7828     | name, (FUInt32|FInt32) -> pr "  public int %s;\n" name
7829     | name, FChar -> pr "  public char %s;\n" name
7830     | name, FOptPercent ->
7831         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
7832         pr "  public float %s;\n" name
7833   ) cols;
7834
7835   pr "}\n"
7836
7837 and generate_java_c () =
7838   generate_header CStyle LGPLv2;
7839
7840   pr "\
7841 #include <stdio.h>
7842 #include <stdlib.h>
7843 #include <string.h>
7844
7845 #include \"com_redhat_et_libguestfs_GuestFS.h\"
7846 #include \"guestfs.h\"
7847
7848 /* Note that this function returns.  The exception is not thrown
7849  * until after the wrapper function returns.
7850  */
7851 static void
7852 throw_exception (JNIEnv *env, const char *msg)
7853 {
7854   jclass cl;
7855   cl = (*env)->FindClass (env,
7856                           \"com/redhat/et/libguestfs/LibGuestFSException\");
7857   (*env)->ThrowNew (env, cl, msg);
7858 }
7859
7860 JNIEXPORT jlong JNICALL
7861 Java_com_redhat_et_libguestfs_GuestFS__1create
7862   (JNIEnv *env, jobject obj)
7863 {
7864   guestfs_h *g;
7865
7866   g = guestfs_create ();
7867   if (g == NULL) {
7868     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
7869     return 0;
7870   }
7871   guestfs_set_error_handler (g, NULL, NULL);
7872   return (jlong) (long) g;
7873 }
7874
7875 JNIEXPORT void JNICALL
7876 Java_com_redhat_et_libguestfs_GuestFS__1close
7877   (JNIEnv *env, jobject obj, jlong jg)
7878 {
7879   guestfs_h *g = (guestfs_h *) (long) jg;
7880   guestfs_close (g);
7881 }
7882
7883 ";
7884
7885   List.iter (
7886     fun (name, style, _, _, _, _, _) ->
7887       pr "JNIEXPORT ";
7888       (match fst style with
7889        | RErr -> pr "void ";
7890        | RInt _ -> pr "jint ";
7891        | RInt64 _ -> pr "jlong ";
7892        | RBool _ -> pr "jboolean ";
7893        | RConstString _ | RConstOptString _ | RString _
7894        | RBufferOut _ -> pr "jstring ";
7895        | RStruct _ | RHashtable _ ->
7896            pr "jobject ";
7897        | RStringList _ | RStructList _ ->
7898            pr "jobjectArray ";
7899       );
7900       pr "JNICALL\n";
7901       pr "Java_com_redhat_et_libguestfs_GuestFS_";
7902       pr "%s" (replace_str ("_" ^ name) "_" "_1");
7903       pr "\n";
7904       pr "  (JNIEnv *env, jobject obj, jlong jg";
7905       List.iter (
7906         function
7907         | String n
7908         | OptString n
7909         | FileIn n
7910         | FileOut n ->
7911             pr ", jstring j%s" n
7912         | StringList n ->
7913             pr ", jobjectArray j%s" n
7914         | Bool n ->
7915             pr ", jboolean j%s" n
7916         | Int n ->
7917             pr ", jint j%s" n
7918       ) (snd style);
7919       pr ")\n";
7920       pr "{\n";
7921       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
7922       let error_code, no_ret =
7923         match fst style with
7924         | RErr -> pr "  int r;\n"; "-1", ""
7925         | RBool _
7926         | RInt _ -> pr "  int r;\n"; "-1", "0"
7927         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
7928         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
7929         | RConstOptString _ -> pr "  const char *r;\n"; "NULL", "NULL"
7930         | RString _ ->
7931             pr "  jstring jr;\n";
7932             pr "  char *r;\n"; "NULL", "NULL"
7933         | RStringList _ ->
7934             pr "  jobjectArray jr;\n";
7935             pr "  int r_len;\n";
7936             pr "  jclass cl;\n";
7937             pr "  jstring jstr;\n";
7938             pr "  char **r;\n"; "NULL", "NULL"
7939         | RStruct (_, typ) ->
7940             pr "  jobject jr;\n";
7941             pr "  jclass cl;\n";
7942             pr "  jfieldID fl;\n";
7943             pr "  struct guestfs_%s *r;\n" typ; "NULL", "NULL"
7944         | RStructList (_, typ) ->
7945             pr "  jobjectArray jr;\n";
7946             pr "  jclass cl;\n";
7947             pr "  jfieldID fl;\n";
7948             pr "  jobject jfl;\n";
7949             pr "  struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
7950         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL"
7951         | RBufferOut _ ->
7952             pr "  jstring jr;\n";
7953             pr "  char *r;\n";
7954             pr "  size_t size;\n";
7955             "NULL", "NULL" in
7956       List.iter (
7957         function
7958         | String n
7959         | OptString n
7960         | FileIn n
7961         | FileOut n ->
7962             pr "  const char *%s;\n" n
7963         | StringList n ->
7964             pr "  int %s_len;\n" n;
7965             pr "  const char **%s;\n" n
7966         | Bool n
7967         | Int n ->
7968             pr "  int %s;\n" n
7969       ) (snd style);
7970
7971       let needs_i =
7972         (match fst style with
7973          | RStringList _ | RStructList _ -> true
7974          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
7975          | RConstOptString _
7976          | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
7977           List.exists (function StringList _ -> true | _ -> false) (snd style) in
7978       if needs_i then
7979         pr "  int i;\n";
7980
7981       pr "\n";
7982
7983       (* Get the parameters. *)
7984       List.iter (
7985         function
7986         | String n
7987         | FileIn n
7988         | FileOut n ->
7989             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
7990         | OptString n ->
7991             (* This is completely undocumented, but Java null becomes
7992              * a NULL parameter.
7993              *)
7994             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
7995         | StringList n ->
7996             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
7997             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
7998             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
7999             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
8000               n;
8001             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
8002             pr "  }\n";
8003             pr "  %s[%s_len] = NULL;\n" n n;
8004         | Bool n
8005         | Int n ->
8006             pr "  %s = j%s;\n" n n
8007       ) (snd style);
8008
8009       (* Make the call. *)
8010       pr "  r = guestfs_%s " name;
8011       generate_c_call_args ~handle:"g" style;
8012       pr ";\n";
8013
8014       (* Release the parameters. *)
8015       List.iter (
8016         function
8017         | String n
8018         | FileIn n
8019         | FileOut n ->
8020             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
8021         | OptString n ->
8022             pr "  if (j%s)\n" n;
8023             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
8024         | StringList n ->
8025             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
8026             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
8027               n;
8028             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
8029             pr "  }\n";
8030             pr "  free (%s);\n" n
8031         | Bool n
8032         | Int n -> ()
8033       ) (snd style);
8034
8035       (* Check for errors. *)
8036       pr "  if (r == %s) {\n" error_code;
8037       pr "    throw_exception (env, guestfs_last_error (g));\n";
8038       pr "    return %s;\n" no_ret;
8039       pr "  }\n";
8040
8041       (* Return value. *)
8042       (match fst style with
8043        | RErr -> ()
8044        | RInt _ -> pr "  return (jint) r;\n"
8045        | RBool _ -> pr "  return (jboolean) r;\n"
8046        | RInt64 _ -> pr "  return (jlong) r;\n"
8047        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
8048        | RConstOptString _ ->
8049            pr "  return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
8050        | RString _ ->
8051            pr "  jr = (*env)->NewStringUTF (env, r);\n";
8052            pr "  free (r);\n";
8053            pr "  return jr;\n"
8054        | RStringList _ ->
8055            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
8056            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
8057            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
8058            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
8059            pr "  for (i = 0; i < r_len; ++i) {\n";
8060            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
8061            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
8062            pr "    free (r[i]);\n";
8063            pr "  }\n";
8064            pr "  free (r);\n";
8065            pr "  return jr;\n"
8066        | RStruct (_, typ) ->
8067            let jtyp = java_name_of_struct typ in
8068            let cols = cols_of_struct typ in
8069            generate_java_struct_return typ jtyp cols
8070        | RStructList (_, typ) ->
8071            let jtyp = java_name_of_struct typ in
8072            let cols = cols_of_struct typ in
8073            generate_java_struct_list_return typ jtyp cols
8074        | RHashtable _ ->
8075            (* XXX *)
8076            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
8077            pr "  return NULL;\n"
8078        | RBufferOut _ ->
8079            pr "  jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
8080            pr "  free (r);\n";
8081            pr "  return jr;\n"
8082       );
8083
8084       pr "}\n";
8085       pr "\n"
8086   ) all_functions
8087
8088 and generate_java_struct_return typ jtyp cols =
8089   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
8090   pr "  jr = (*env)->AllocObject (env, cl);\n";
8091   List.iter (
8092     function
8093     | name, FString ->
8094         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8095         pr "  (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
8096     | name, FUUID ->
8097         pr "  {\n";
8098         pr "    char s[33];\n";
8099         pr "    memcpy (s, r->%s, 32);\n" name;
8100         pr "    s[32] = 0;\n";
8101         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8102         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
8103         pr "  }\n";
8104     | name, FBuffer ->
8105         pr "  {\n";
8106         pr "    int len = r->%s_len;\n" name;
8107         pr "    char s[len+1];\n";
8108         pr "    memcpy (s, r->%s, len);\n" name;
8109         pr "    s[len] = 0;\n";
8110         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8111         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
8112         pr "  }\n";
8113     | name, (FBytes|FUInt64|FInt64) ->
8114         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
8115         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8116     | name, (FUInt32|FInt32) ->
8117         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
8118         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8119     | name, FOptPercent ->
8120         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
8121         pr "  (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
8122     | name, FChar ->
8123         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
8124         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
8125   ) cols;
8126   pr "  free (r);\n";
8127   pr "  return jr;\n"
8128
8129 and generate_java_struct_list_return typ jtyp cols =
8130   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
8131   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
8132   pr "  for (i = 0; i < r->len; ++i) {\n";
8133   pr "    jfl = (*env)->AllocObject (env, cl);\n";
8134   List.iter (
8135     function
8136     | name, FString ->
8137         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8138         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
8139     | name, FUUID ->
8140         pr "    {\n";
8141         pr "      char s[33];\n";
8142         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
8143         pr "      s[32] = 0;\n";
8144         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8145         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8146         pr "    }\n";
8147     | name, FBuffer ->
8148         pr "    {\n";
8149         pr "      int len = r->val[i].%s_len;\n" name;
8150         pr "      char s[len+1];\n";
8151         pr "      memcpy (s, r->val[i].%s, len);\n" name;
8152         pr "      s[len] = 0;\n";
8153         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
8154         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
8155         pr "    }\n";
8156     | name, (FBytes|FUInt64|FInt64) ->
8157         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
8158         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8159     | name, (FUInt32|FInt32) ->
8160         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
8161         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8162     | name, FOptPercent ->
8163         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
8164         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
8165     | name, FChar ->
8166         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
8167         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
8168   ) cols;
8169   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
8170   pr "  }\n";
8171   pr "  guestfs_free_%s_list (r);\n" typ;
8172   pr "  return jr;\n"
8173
8174 and generate_haskell_hs () =
8175   generate_header HaskellStyle LGPLv2;
8176
8177   (* XXX We only know how to generate partial FFI for Haskell
8178    * at the moment.  Please help out!
8179    *)
8180   let can_generate style =
8181     match style with
8182     | RErr, _
8183     | RInt _, _
8184     | RInt64 _, _ -> true
8185     | RBool _, _
8186     | RConstString _, _
8187     | RConstOptString _, _
8188     | RString _, _
8189     | RStringList _, _
8190     | RStruct _, _
8191     | RStructList _, _
8192     | RHashtable _, _
8193     | RBufferOut _, _ -> false in
8194
8195   pr "\
8196 {-# INCLUDE <guestfs.h> #-}
8197 {-# LANGUAGE ForeignFunctionInterface #-}
8198
8199 module Guestfs (
8200   create";
8201
8202   (* List out the names of the actions we want to export. *)
8203   List.iter (
8204     fun (name, style, _, _, _, _, _) ->
8205       if can_generate style then pr ",\n  %s" name
8206   ) all_functions;
8207
8208   pr "
8209   ) where
8210 import Foreign
8211 import Foreign.C
8212 import Foreign.C.Types
8213 import IO
8214 import Control.Exception
8215 import Data.Typeable
8216
8217 data GuestfsS = GuestfsS            -- represents the opaque C struct
8218 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
8219 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
8220
8221 -- XXX define properly later XXX
8222 data PV = PV
8223 data VG = VG
8224 data LV = LV
8225 data IntBool = IntBool
8226 data Stat = Stat
8227 data StatVFS = StatVFS
8228 data Hashtable = Hashtable
8229
8230 foreign import ccall unsafe \"guestfs_create\" c_create
8231   :: IO GuestfsP
8232 foreign import ccall unsafe \"&guestfs_close\" c_close
8233   :: FunPtr (GuestfsP -> IO ())
8234 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
8235   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
8236
8237 create :: IO GuestfsH
8238 create = do
8239   p <- c_create
8240   c_set_error_handler p nullPtr nullPtr
8241   h <- newForeignPtr c_close p
8242   return h
8243
8244 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
8245   :: GuestfsP -> IO CString
8246
8247 -- last_error :: GuestfsH -> IO (Maybe String)
8248 -- last_error h = do
8249 --   str <- withForeignPtr h (\\p -> c_last_error p)
8250 --   maybePeek peekCString str
8251
8252 last_error :: GuestfsH -> IO (String)
8253 last_error h = do
8254   str <- withForeignPtr h (\\p -> c_last_error p)
8255   if (str == nullPtr)
8256     then return \"no error\"
8257     else peekCString str
8258
8259 ";
8260
8261   (* Generate wrappers for each foreign function. *)
8262   List.iter (
8263     fun (name, style, _, _, _, _, _) ->
8264       if can_generate style then (
8265         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
8266         pr "  :: ";
8267         generate_haskell_prototype ~handle:"GuestfsP" style;
8268         pr "\n";
8269         pr "\n";
8270         pr "%s :: " name;
8271         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
8272         pr "\n";
8273         pr "%s %s = do\n" name
8274           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
8275         pr "  r <- ";
8276         (* Convert pointer arguments using with* functions. *)
8277         List.iter (
8278           function
8279           | FileIn n
8280           | FileOut n
8281           | String n -> pr "withCString %s $ \\%s -> " n n
8282           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
8283           | StringList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
8284           | Bool _ | Int _ -> ()
8285         ) (snd style);
8286         (* Convert integer arguments. *)
8287         let args =
8288           List.map (
8289             function
8290             | Bool n -> sprintf "(fromBool %s)" n
8291             | Int n -> sprintf "(fromIntegral %s)" n
8292             | FileIn n | FileOut n | String n | OptString n | StringList n -> n
8293           ) (snd style) in
8294         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
8295           (String.concat " " ("p" :: args));
8296         (match fst style with
8297          | RErr | RInt _ | RInt64 _ | RBool _ ->
8298              pr "  if (r == -1)\n";
8299              pr "    then do\n";
8300              pr "      err <- last_error h\n";
8301              pr "      fail err\n";
8302          | RConstString _ | RConstOptString _ | RString _
8303          | RStringList _ | RStruct _
8304          | RStructList _ | RHashtable _ | RBufferOut _ ->
8305              pr "  if (r == nullPtr)\n";
8306              pr "    then do\n";
8307              pr "      err <- last_error h\n";
8308              pr "      fail err\n";
8309         );
8310         (match fst style with
8311          | RErr ->
8312              pr "    else return ()\n"
8313          | RInt _ ->
8314              pr "    else return (fromIntegral r)\n"
8315          | RInt64 _ ->
8316              pr "    else return (fromIntegral r)\n"
8317          | RBool _ ->
8318              pr "    else return (toBool r)\n"
8319          | RConstString _
8320          | RConstOptString _
8321          | RString _
8322          | RStringList _
8323          | RStruct _
8324          | RStructList _
8325          | RHashtable _
8326          | RBufferOut _ ->
8327              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
8328         );
8329         pr "\n";
8330       )
8331   ) all_functions
8332
8333 and generate_haskell_prototype ~handle ?(hs = false) style =
8334   pr "%s -> " handle;
8335   let string = if hs then "String" else "CString" in
8336   let int = if hs then "Int" else "CInt" in
8337   let bool = if hs then "Bool" else "CInt" in
8338   let int64 = if hs then "Integer" else "Int64" in
8339   List.iter (
8340     fun arg ->
8341       (match arg with
8342        | String _ -> pr "%s" string
8343        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
8344        | StringList _ -> if hs then pr "[String]" else pr "Ptr CString"
8345        | Bool _ -> pr "%s" bool
8346        | Int _ -> pr "%s" int
8347        | FileIn _ -> pr "%s" string
8348        | FileOut _ -> pr "%s" string
8349       );
8350       pr " -> ";
8351   ) (snd style);
8352   pr "IO (";
8353   (match fst style with
8354    | RErr -> if not hs then pr "CInt"
8355    | RInt _ -> pr "%s" int
8356    | RInt64 _ -> pr "%s" int64
8357    | RBool _ -> pr "%s" bool
8358    | RConstString _ -> pr "%s" string
8359    | RConstOptString _ -> pr "Maybe %s" string
8360    | RString _ -> pr "%s" string
8361    | RStringList _ -> pr "[%s]" string
8362    | RStruct (_, typ) ->
8363        let name = java_name_of_struct typ in
8364        pr "%s" name
8365    | RStructList (_, typ) ->
8366        let name = java_name_of_struct typ in
8367        pr "[%s]" name
8368    | RHashtable _ -> pr "Hashtable"
8369    | RBufferOut _ -> pr "%s" string
8370   );
8371   pr ")"
8372
8373 and generate_bindtests () =
8374   generate_header CStyle LGPLv2;
8375
8376   pr "\
8377 #include <stdio.h>
8378 #include <stdlib.h>
8379 #include <inttypes.h>
8380 #include <string.h>
8381
8382 #include \"guestfs.h\"
8383 #include \"guestfs_protocol.h\"
8384
8385 #define error guestfs_error
8386 #define safe_calloc guestfs_safe_calloc
8387 #define safe_malloc guestfs_safe_malloc
8388
8389 static void
8390 print_strings (char * const* const argv)
8391 {
8392   int argc;
8393
8394   printf (\"[\");
8395   for (argc = 0; argv[argc] != NULL; ++argc) {
8396     if (argc > 0) printf (\", \");
8397     printf (\"\\\"%%s\\\"\", argv[argc]);
8398   }
8399   printf (\"]\\n\");
8400 }
8401
8402 /* The test0 function prints its parameters to stdout. */
8403 ";
8404
8405   let test0, tests =
8406     match test_functions with
8407     | [] -> assert false
8408     | test0 :: tests -> test0, tests in
8409
8410   let () =
8411     let (name, style, _, _, _, _, _) = test0 in
8412     generate_prototype ~extern:false ~semicolon:false ~newline:true
8413       ~handle:"g" ~prefix:"guestfs_" name style;
8414     pr "{\n";
8415     List.iter (
8416       function
8417       | String n
8418       | FileIn n
8419       | FileOut n -> pr "  printf (\"%%s\\n\", %s);\n" n
8420       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
8421       | StringList n -> pr "  print_strings (%s);\n" n
8422       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
8423       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
8424     ) (snd style);
8425     pr "  /* Java changes stdout line buffering so we need this: */\n";
8426     pr "  fflush (stdout);\n";
8427     pr "  return 0;\n";
8428     pr "}\n";
8429     pr "\n" in
8430
8431   List.iter (
8432     fun (name, style, _, _, _, _, _) ->
8433       if String.sub name (String.length name - 3) 3 <> "err" then (
8434         pr "/* Test normal return. */\n";
8435         generate_prototype ~extern:false ~semicolon:false ~newline:true
8436           ~handle:"g" ~prefix:"guestfs_" name style;
8437         pr "{\n";
8438         (match fst style with
8439          | RErr ->
8440              pr "  return 0;\n"
8441          | RInt _ ->
8442              pr "  int r;\n";
8443              pr "  sscanf (val, \"%%d\", &r);\n";
8444              pr "  return r;\n"
8445          | RInt64 _ ->
8446              pr "  int64_t r;\n";
8447              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
8448              pr "  return r;\n"
8449          | RBool _ ->
8450              pr "  return strcmp (val, \"true\") == 0;\n"
8451          | RConstString _
8452          | RConstOptString _ ->
8453              (* Can't return the input string here.  Return a static
8454               * string so we ensure we get a segfault if the caller
8455               * tries to free it.
8456               *)
8457              pr "  return \"static string\";\n"
8458          | RString _ ->
8459              pr "  return strdup (val);\n"
8460          | RStringList _ ->
8461              pr "  char **strs;\n";
8462              pr "  int n, i;\n";
8463              pr "  sscanf (val, \"%%d\", &n);\n";
8464              pr "  strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
8465              pr "  for (i = 0; i < n; ++i) {\n";
8466              pr "    strs[i] = safe_malloc (g, 16);\n";
8467              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
8468              pr "  }\n";
8469              pr "  strs[n] = NULL;\n";
8470              pr "  return strs;\n"
8471          | RStruct (_, typ) ->
8472              pr "  struct guestfs_%s *r;\n" typ;
8473              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
8474              pr "  return r;\n"
8475          | RStructList (_, typ) ->
8476              pr "  struct guestfs_%s_list *r;\n" typ;
8477              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
8478              pr "  sscanf (val, \"%%d\", &r->len);\n";
8479              pr "  r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
8480              pr "  return r;\n"
8481          | RHashtable _ ->
8482              pr "  char **strs;\n";
8483              pr "  int n, i;\n";
8484              pr "  sscanf (val, \"%%d\", &n);\n";
8485              pr "  strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
8486              pr "  for (i = 0; i < n; ++i) {\n";
8487              pr "    strs[i*2] = safe_malloc (g, 16);\n";
8488              pr "    strs[i*2+1] = safe_malloc (g, 16);\n";
8489              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
8490              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
8491              pr "  }\n";
8492              pr "  strs[n*2] = NULL;\n";
8493              pr "  return strs;\n"
8494          | RBufferOut _ ->
8495              pr "  return strdup (val);\n"
8496         );
8497         pr "}\n";
8498         pr "\n"
8499       ) else (
8500         pr "/* Test error return. */\n";
8501         generate_prototype ~extern:false ~semicolon:false ~newline:true
8502           ~handle:"g" ~prefix:"guestfs_" name style;
8503         pr "{\n";
8504         pr "  error (g, \"error\");\n";
8505         (match fst style with
8506          | RErr | RInt _ | RInt64 _ | RBool _ ->
8507              pr "  return -1;\n"
8508          | RConstString _ | RConstOptString _
8509          | RString _ | RStringList _ | RStruct _
8510          | RStructList _
8511          | RHashtable _
8512          | RBufferOut _ ->
8513              pr "  return NULL;\n"
8514         );
8515         pr "}\n";
8516         pr "\n"
8517       )
8518   ) tests
8519
8520 and generate_ocaml_bindtests () =
8521   generate_header OCamlStyle GPLv2;
8522
8523   pr "\
8524 let () =
8525   let g = Guestfs.create () in
8526 ";
8527
8528   let mkargs args =
8529     String.concat " " (
8530       List.map (
8531         function
8532         | CallString s -> "\"" ^ s ^ "\""
8533         | CallOptString None -> "None"
8534         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
8535         | CallStringList xs ->
8536             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
8537         | CallInt i when i >= 0 -> string_of_int i
8538         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
8539         | CallBool b -> string_of_bool b
8540       ) args
8541     )
8542   in
8543
8544   generate_lang_bindtests (
8545     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
8546   );
8547
8548   pr "print_endline \"EOF\"\n"
8549
8550 and generate_perl_bindtests () =
8551   pr "#!/usr/bin/perl -w\n";
8552   generate_header HashStyle GPLv2;
8553
8554   pr "\
8555 use strict;
8556
8557 use Sys::Guestfs;
8558
8559 my $g = Sys::Guestfs->new ();
8560 ";
8561
8562   let mkargs args =
8563     String.concat ", " (
8564       List.map (
8565         function
8566         | CallString s -> "\"" ^ s ^ "\""
8567         | CallOptString None -> "undef"
8568         | CallOptString (Some s) -> sprintf "\"%s\"" s
8569         | CallStringList xs ->
8570             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8571         | CallInt i -> string_of_int i
8572         | CallBool b -> if b then "1" else "0"
8573       ) args
8574     )
8575   in
8576
8577   generate_lang_bindtests (
8578     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
8579   );
8580
8581   pr "print \"EOF\\n\"\n"
8582
8583 and generate_python_bindtests () =
8584   generate_header HashStyle GPLv2;
8585
8586   pr "\
8587 import guestfs
8588
8589 g = guestfs.GuestFS ()
8590 ";
8591
8592   let mkargs args =
8593     String.concat ", " (
8594       List.map (
8595         function
8596         | CallString s -> "\"" ^ s ^ "\""
8597         | CallOptString None -> "None"
8598         | CallOptString (Some s) -> sprintf "\"%s\"" s
8599         | CallStringList xs ->
8600             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8601         | CallInt i -> string_of_int i
8602         | CallBool b -> if b then "1" else "0"
8603       ) args
8604     )
8605   in
8606
8607   generate_lang_bindtests (
8608     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
8609   );
8610
8611   pr "print \"EOF\"\n"
8612
8613 and generate_ruby_bindtests () =
8614   generate_header HashStyle GPLv2;
8615
8616   pr "\
8617 require 'guestfs'
8618
8619 g = Guestfs::create()
8620 ";
8621
8622   let mkargs args =
8623     String.concat ", " (
8624       List.map (
8625         function
8626         | CallString s -> "\"" ^ s ^ "\""
8627         | CallOptString None -> "nil"
8628         | CallOptString (Some s) -> sprintf "\"%s\"" s
8629         | CallStringList xs ->
8630             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8631         | CallInt i -> string_of_int i
8632         | CallBool b -> string_of_bool b
8633       ) args
8634     )
8635   in
8636
8637   generate_lang_bindtests (
8638     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
8639   );
8640
8641   pr "print \"EOF\\n\"\n"
8642
8643 and generate_java_bindtests () =
8644   generate_header CStyle GPLv2;
8645
8646   pr "\
8647 import com.redhat.et.libguestfs.*;
8648
8649 public class Bindtests {
8650     public static void main (String[] argv)
8651     {
8652         try {
8653             GuestFS g = new GuestFS ();
8654 ";
8655
8656   let mkargs args =
8657     String.concat ", " (
8658       List.map (
8659         function
8660         | CallString s -> "\"" ^ s ^ "\""
8661         | CallOptString None -> "null"
8662         | CallOptString (Some s) -> sprintf "\"%s\"" s
8663         | CallStringList xs ->
8664             "new String[]{" ^
8665               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
8666         | CallInt i -> string_of_int i
8667         | CallBool b -> string_of_bool b
8668       ) args
8669     )
8670   in
8671
8672   generate_lang_bindtests (
8673     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
8674   );
8675
8676   pr "
8677             System.out.println (\"EOF\");
8678         }
8679         catch (Exception exn) {
8680             System.err.println (exn);
8681             System.exit (1);
8682         }
8683     }
8684 }
8685 "
8686
8687 and generate_haskell_bindtests () =
8688   generate_header HaskellStyle GPLv2;
8689
8690   pr "\
8691 module Bindtests where
8692 import qualified Guestfs
8693
8694 main = do
8695   g <- Guestfs.create
8696 ";
8697
8698   let mkargs args =
8699     String.concat " " (
8700       List.map (
8701         function
8702         | CallString s -> "\"" ^ s ^ "\""
8703         | CallOptString None -> "Nothing"
8704         | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
8705         | CallStringList xs ->
8706             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
8707         | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
8708         | CallInt i -> string_of_int i
8709         | CallBool true -> "True"
8710         | CallBool false -> "False"
8711       ) args
8712     )
8713   in
8714
8715   generate_lang_bindtests (
8716     fun f args -> pr "  Guestfs.%s g %s\n" f (mkargs args)
8717   );
8718
8719   pr "  putStrLn \"EOF\"\n"
8720
8721 (* Language-independent bindings tests - we do it this way to
8722  * ensure there is parity in testing bindings across all languages.
8723  *)
8724 and generate_lang_bindtests call =
8725   call "test0" [CallString "abc"; CallOptString (Some "def");
8726                 CallStringList []; CallBool false;
8727                 CallInt 0; CallString "123"; CallString "456"];
8728   call "test0" [CallString "abc"; CallOptString None;
8729                 CallStringList []; CallBool false;
8730                 CallInt 0; CallString "123"; CallString "456"];
8731   call "test0" [CallString ""; CallOptString (Some "def");
8732                 CallStringList []; CallBool false;
8733                 CallInt 0; CallString "123"; CallString "456"];
8734   call "test0" [CallString ""; CallOptString (Some "");
8735                 CallStringList []; CallBool false;
8736                 CallInt 0; CallString "123"; CallString "456"];
8737   call "test0" [CallString "abc"; CallOptString (Some "def");
8738                 CallStringList ["1"]; CallBool false;
8739                 CallInt 0; CallString "123"; CallString "456"];
8740   call "test0" [CallString "abc"; CallOptString (Some "def");
8741                 CallStringList ["1"; "2"]; CallBool false;
8742                 CallInt 0; CallString "123"; CallString "456"];
8743   call "test0" [CallString "abc"; CallOptString (Some "def");
8744                 CallStringList ["1"]; CallBool true;
8745                 CallInt 0; CallString "123"; CallString "456"];
8746   call "test0" [CallString "abc"; CallOptString (Some "def");
8747                 CallStringList ["1"]; CallBool false;
8748                 CallInt (-1); CallString "123"; CallString "456"];
8749   call "test0" [CallString "abc"; CallOptString (Some "def");
8750                 CallStringList ["1"]; CallBool false;
8751                 CallInt (-2); CallString "123"; CallString "456"];
8752   call "test0" [CallString "abc"; CallOptString (Some "def");
8753                 CallStringList ["1"]; CallBool false;
8754                 CallInt 1; CallString "123"; CallString "456"];
8755   call "test0" [CallString "abc"; CallOptString (Some "def");
8756                 CallStringList ["1"]; CallBool false;
8757                 CallInt 2; CallString "123"; CallString "456"];
8758   call "test0" [CallString "abc"; CallOptString (Some "def");
8759                 CallStringList ["1"]; CallBool false;
8760                 CallInt 4095; CallString "123"; CallString "456"];
8761   call "test0" [CallString "abc"; CallOptString (Some "def");
8762                 CallStringList ["1"]; CallBool false;
8763                 CallInt 0; CallString ""; CallString ""]
8764
8765 (* XXX Add here tests of the return and error functions. *)
8766
8767 (* This is used to generate the src/MAX_PROC_NR file which
8768  * contains the maximum procedure number, a surrogate for the
8769  * ABI version number.  See src/Makefile.am for the details.
8770  *)
8771 and generate_max_proc_nr () =
8772   let proc_nrs = List.map (
8773     fun (_, _, proc_nr, _, _, _, _) -> proc_nr
8774   ) daemon_functions in
8775
8776   let max_proc_nr = List.fold_left max 0 proc_nrs in
8777
8778   pr "%d\n" max_proc_nr
8779
8780 let output_to filename =
8781   let filename_new = filename ^ ".new" in
8782   chan := open_out filename_new;
8783   let close () =
8784     close_out !chan;
8785     chan := stdout;
8786
8787     (* Is the new file different from the current file? *)
8788     if Sys.file_exists filename && files_equal filename filename_new then
8789       Unix.unlink filename_new          (* same, so skip it *)
8790     else (
8791       (* different, overwrite old one *)
8792       (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
8793       Unix.rename filename_new filename;
8794       Unix.chmod filename 0o444;
8795       printf "written %s\n%!" filename;
8796     )
8797   in
8798   close
8799
8800 (* Main program. *)
8801 let () =
8802   check_functions ();
8803
8804   if not (Sys.file_exists "HACKING") then (
8805     eprintf "\
8806 You are probably running this from the wrong directory.
8807 Run it from the top source directory using the command
8808   src/generator.ml
8809 ";
8810     exit 1
8811   );
8812
8813   let close = output_to "src/guestfs_protocol.x" in
8814   generate_xdr ();
8815   close ();
8816
8817   let close = output_to "src/guestfs-structs.h" in
8818   generate_structs_h ();
8819   close ();
8820
8821   let close = output_to "src/guestfs-actions.h" in
8822   generate_actions_h ();
8823   close ();
8824
8825   let close = output_to "src/guestfs-actions.c" in
8826   generate_client_actions ();
8827   close ();
8828
8829   let close = output_to "daemon/actions.h" in
8830   generate_daemon_actions_h ();
8831   close ();
8832
8833   let close = output_to "daemon/stubs.c" in
8834   generate_daemon_actions ();
8835   close ();
8836
8837   let close = output_to "daemon/names.c" in
8838   generate_daemon_names ();
8839   close ();
8840
8841   let close = output_to "capitests/tests.c" in
8842   generate_tests ();
8843   close ();
8844
8845   let close = output_to "src/guestfs-bindtests.c" in
8846   generate_bindtests ();
8847   close ();
8848
8849   let close = output_to "fish/cmds.c" in
8850   generate_fish_cmds ();
8851   close ();
8852
8853   let close = output_to "fish/completion.c" in
8854   generate_fish_completion ();
8855   close ();
8856
8857   let close = output_to "guestfs-structs.pod" in
8858   generate_structs_pod ();
8859   close ();
8860
8861   let close = output_to "guestfs-actions.pod" in
8862   generate_actions_pod ();
8863   close ();
8864
8865   let close = output_to "guestfish-actions.pod" in
8866   generate_fish_actions_pod ();
8867   close ();
8868
8869   let close = output_to "ocaml/guestfs.mli" in
8870   generate_ocaml_mli ();
8871   close ();
8872
8873   let close = output_to "ocaml/guestfs.ml" in
8874   generate_ocaml_ml ();
8875   close ();
8876
8877   let close = output_to "ocaml/guestfs_c_actions.c" in
8878   generate_ocaml_c ();
8879   close ();
8880
8881   let close = output_to "ocaml/bindtests.ml" in
8882   generate_ocaml_bindtests ();
8883   close ();
8884
8885   let close = output_to "perl/Guestfs.xs" in
8886   generate_perl_xs ();
8887   close ();
8888
8889   let close = output_to "perl/lib/Sys/Guestfs.pm" in
8890   generate_perl_pm ();
8891   close ();
8892
8893   let close = output_to "perl/bindtests.pl" in
8894   generate_perl_bindtests ();
8895   close ();
8896
8897   let close = output_to "python/guestfs-py.c" in
8898   generate_python_c ();
8899   close ();
8900
8901   let close = output_to "python/guestfs.py" in
8902   generate_python_py ();
8903   close ();
8904
8905   let close = output_to "python/bindtests.py" in
8906   generate_python_bindtests ();
8907   close ();
8908
8909   let close = output_to "ruby/ext/guestfs/_guestfs.c" in
8910   generate_ruby_c ();
8911   close ();
8912
8913   let close = output_to "ruby/bindtests.rb" in
8914   generate_ruby_bindtests ();
8915   close ();
8916
8917   let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
8918   generate_java_java ();
8919   close ();
8920
8921   List.iter (
8922     fun (typ, jtyp) ->
8923       let cols = cols_of_struct typ in
8924       let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
8925       let close = output_to filename in
8926       generate_java_struct jtyp cols;
8927       close ();
8928   ) java_structs;
8929
8930   let close = output_to "java/Makefile.inc" in
8931   pr "java_built_sources =";
8932   List.iter (
8933     fun (typ, jtyp) ->
8934         pr " com/redhat/et/libguestfs/%s.java" jtyp;
8935   ) java_structs;
8936   pr " com/redhat/et/libguestfs/GuestFS.java\n";
8937   close ();
8938
8939   let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
8940   generate_java_c ();
8941   close ();
8942
8943   let close = output_to "java/Bindtests.java" in
8944   generate_java_bindtests ();
8945   close ();
8946
8947   let close = output_to "haskell/Guestfs.hs" in
8948   generate_haskell_hs ();
8949   close ();
8950
8951   let close = output_to "haskell/Bindtests.hs" in
8952   generate_haskell_bindtests ();
8953   close ();
8954
8955   let close = output_to "src/MAX_PROC_NR" in
8956   generate_max_proc_nr ();
8957   close ();
8958
8959   (* Always generate this file last, and unconditionally.  It's used
8960    * by the Makefile to know when we must re-run the generator.
8961    *)
8962   let chan = open_out "src/stamp-generator" in
8963   fprintf chan "1\n";
8964   close_out chan