3c1ff2b5aeca6843d253fb57fc0d1c9a810d4e29
[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  *)
34
35 #load "unix.cma";;
36 #load "str.cma";;
37
38 open Printf
39
40 type style = ret * args
41 and ret =
42     (* "RErr" as a return value means an int used as a simple error
43      * indication, ie. 0 or -1.
44      *)
45   | RErr
46
47     (* "RInt" as a return value means an int which is -1 for error
48      * or any value >= 0 on success.  Only use this for smallish
49      * positive ints (0 <= i < 2^30).
50      *)
51   | RInt of string
52
53     (* "RInt64" is the same as RInt, but is guaranteed to be able
54      * to return a full 64 bit value, _except_ that -1 means error
55      * (so -1 cannot be a valid, non-error return value).
56      *)
57   | RInt64 of string
58
59     (* "RBool" is a bool return value which can be true/false or
60      * -1 for error.
61      *)
62   | RBool of string
63
64     (* "RConstString" is a string that refers to a constant value.
65      * The return value must NOT be NULL (since NULL indicates
66      * an error).
67      *
68      * Try to avoid using this.  In particular you cannot use this
69      * for values returned from the daemon, because there is no
70      * thread-safe way to return them in the C API.
71      *)
72   | RConstString of string
73
74     (* "RConstOptString" is an even more broken version of
75      * "RConstString".  The returned string may be NULL and there
76      * is no way to return an error indication.  Avoid using this!
77      *)
78   | RConstOptString of string
79
80     (* "RString" is a returned string.  It must NOT be NULL, since
81      * a NULL return indicates an error.  The caller frees this.
82      *)
83   | RString of string
84
85     (* "RStringList" is a list of strings.  No string in the list
86      * can be NULL.  The caller frees the strings and the array.
87      *)
88   | RStringList of string
89
90     (* "RStruct" is a function which returns a single named structure
91      * or an error indication (in C, a struct, and in other languages
92      * with varying representations, but usually very efficient).  See
93      * after the function list below for the structures.
94      *)
95   | RStruct of string * string          (* name of retval, name of struct *)
96
97     (* "RStructList" is a function which returns either a list/array
98      * of structures (could be zero-length), or an error indication.
99      *)
100   | RStructList of string * string      (* name of retval, name of struct *)
101
102     (* Key-value pairs of untyped strings.  Turns into a hashtable or
103      * dictionary in languages which support it.  DON'T use this as a
104      * general "bucket" for results.  Prefer a stronger typed return
105      * value if one is available, or write a custom struct.  Don't use
106      * this if the list could potentially be very long, since it is
107      * inefficient.  Keys should be unique.  NULLs are not permitted.
108      *)
109   | RHashtable of string
110
111     (* "RBufferOut" is handled almost exactly like RString, but
112      * it allows the string to contain arbitrary 8 bit data including
113      * ASCII NUL.  In the C API this causes an implicit extra parameter
114      * to be added of type <size_t *size_r>.  The extra parameter
115      * returns the actual size of the return buffer in bytes.
116      *
117      * Other programming languages support strings with arbitrary 8 bit
118      * data.
119      *
120      * At the RPC layer we have to use the opaque<> type instead of
121      * string<>.  Returned data is still limited to the max message
122      * size (ie. ~ 2 MB).
123      *)
124   | RBufferOut of string
125
126 and args = argt list    (* Function parameters, guestfs handle is implicit. *)
127
128     (* Note in future we should allow a "variable args" parameter as
129      * the final parameter, to allow commands like
130      *   chmod mode file [file(s)...]
131      * This is not implemented yet, but many commands (such as chmod)
132      * are currently defined with the argument order keeping this future
133      * possibility in mind.
134      *)
135 and argt =
136   | String of string    (* const char *name, cannot be NULL *)
137   | Device of string    (* /dev device name, cannot be NULL *)
138   | Pathname of string  (* file name, cannot be NULL *)
139   | Dev_or_Path of string (* /dev device name or Pathname, cannot be NULL *)
140   | OptString of string (* const char *name, may be NULL *)
141   | StringList of string(* list of strings (each string cannot be NULL) *)
142   | DeviceList of string(* list of Device names (each cannot be NULL) *)
143   | Bool of string      (* boolean *)
144   | Int of string       (* int (smallish ints, signed, <= 31 bits) *)
145   | Int64 of string     (* any 64 bit int *)
146     (* These are treated as filenames (simple string parameters) in
147      * the C API and bindings.  But in the RPC protocol, we transfer
148      * the actual file content up to or down from the daemon.
149      * FileIn: local machine -> daemon (in request)
150      * FileOut: daemon -> local machine (in reply)
151      * In guestfish (only), the special name "-" means read from
152      * stdin or write to stdout.
153      *)
154   | FileIn of string
155   | FileOut of string
156 (* Not implemented:
157     (* Opaque buffer which can contain arbitrary 8 bit data.
158      * In the C API, this is expressed as <char *, int> pair.
159      * Most other languages have a string type which can contain
160      * ASCII NUL.  We use whatever type is appropriate for each
161      * language.
162      * Buffers are limited by the total message size.  To transfer
163      * large blocks of data, use FileIn/FileOut parameters instead.
164      * To return an arbitrary buffer, use RBufferOut.
165      *)
166   | BufferIn of string
167 *)
168
169 type flags =
170   | ProtocolLimitWarning  (* display warning about protocol size limits *)
171   | DangerWillRobinson    (* flags particularly dangerous commands *)
172   | FishAlias of string   (* provide an alias for this cmd in guestfish *)
173   | FishAction of string  (* call this function in guestfish *)
174   | NotInFish             (* do not export via guestfish *)
175   | NotInDocs             (* do not add this function to documentation *)
176   | DeprecatedBy of string (* function is deprecated, use .. instead *)
177
178 (* You can supply zero or as many tests as you want per API call.
179  *
180  * Note that the test environment has 3 block devices, of size 500MB,
181  * 50MB and 10MB (respectively /dev/sda, /dev/sdb, /dev/sdc), and
182  * a fourth ISO block device with some known files on it (/dev/sdd).
183  *
184  * Note for partitioning purposes, the 500MB device has 1015 cylinders.
185  * Number of cylinders was 63 for IDE emulated disks with precisely
186  * the same size.  How exactly this is calculated is a mystery.
187  *
188  * The ISO block device (/dev/sdd) comes from images/test.iso.
189  *
190  * To be able to run the tests in a reasonable amount of time,
191  * the virtual machine and block devices are reused between tests.
192  * So don't try testing kill_subprocess :-x
193  *
194  * Between each test we blockdev-setrw, umount-all, lvm-remove-all.
195  *
196  * Don't assume anything about the previous contents of the block
197  * devices.  Use 'Init*' to create some initial scenarios.
198  *
199  * You can add a prerequisite clause to any individual test.  This
200  * is a run-time check, which, if it fails, causes the test to be
201  * skipped.  Useful if testing a command which might not work on
202  * all variations of libguestfs builds.  A test that has prerequisite
203  * of 'Always' is run unconditionally.
204  *
205  * In addition, packagers can skip individual tests by setting the
206  * environment variables:     eg:
207  *   SKIP_TEST_<CMD>_<NUM>=1  SKIP_TEST_COMMAND_3=1  (skips test #3 of command)
208  *   SKIP_TEST_<CMD>=1        SKIP_TEST_ZEROFREE=1   (skips all zerofree tests)
209  *)
210 type tests = (test_init * test_prereq * test) list
211 and test =
212     (* Run the command sequence and just expect nothing to fail. *)
213   | TestRun of seq
214
215     (* Run the command sequence and expect the output of the final
216      * command to be the string.
217      *)
218   | TestOutput of seq * string
219
220     (* Run the command sequence and expect the output of the final
221      * command to be the list of strings.
222      *)
223   | TestOutputList of seq * string list
224
225     (* Run the command sequence and expect the output of the final
226      * command to be the list of block devices (could be either
227      * "/dev/sd.." or "/dev/hd.." form - we don't check the 5th
228      * character of each string).
229      *)
230   | TestOutputListOfDevices of seq * string list
231
232     (* Run the command sequence and expect the output of the final
233      * command to be the integer.
234      *)
235   | TestOutputInt of seq * int
236
237     (* Run the command sequence and expect the output of the final
238      * command to be <op> <int>, eg. ">=", "1".
239      *)
240   | TestOutputIntOp of seq * string * int
241
242     (* Run the command sequence and expect the output of the final
243      * command to be a true value (!= 0 or != NULL).
244      *)
245   | TestOutputTrue of seq
246
247     (* Run the command sequence and expect the output of the final
248      * command to be a false value (== 0 or == NULL, but not an error).
249      *)
250   | TestOutputFalse of seq
251
252     (* Run the command sequence and expect the output of the final
253      * command to be a list of the given length (but don't care about
254      * content).
255      *)
256   | TestOutputLength of seq * int
257
258     (* Run the command sequence and expect the output of the final
259      * command to be a buffer (RBufferOut), ie. string + size.
260      *)
261   | TestOutputBuffer of seq * string
262
263     (* Run the command sequence and expect the output of the final
264      * command to be a structure.
265      *)
266   | TestOutputStruct of seq * test_field_compare list
267
268     (* Run the command sequence and expect the final command (only)
269      * to fail.
270      *)
271   | TestLastFail of seq
272
273 and test_field_compare =
274   | CompareWithInt of string * int
275   | CompareWithIntOp of string * string * int
276   | CompareWithString of string * string
277   | CompareFieldsIntEq of string * string
278   | CompareFieldsStrEq of string * string
279
280 (* Test prerequisites. *)
281 and test_prereq =
282     (* Test always runs. *)
283   | Always
284
285     (* Test is currently disabled - eg. it fails, or it tests some
286      * unimplemented feature.
287      *)
288   | Disabled
289
290     (* 'string' is some C code (a function body) that should return
291      * true or false.  The test will run if the code returns true.
292      *)
293   | If of string
294
295     (* As for 'If' but the test runs _unless_ the code returns true. *)
296   | Unless of string
297
298 (* Some initial scenarios for testing. *)
299 and test_init =
300     (* Do nothing, block devices could contain random stuff including
301      * LVM PVs, and some filesystems might be mounted.  This is usually
302      * a bad idea.
303      *)
304   | InitNone
305
306     (* Block devices are empty and no filesystems are mounted. *)
307   | InitEmpty
308
309     (* /dev/sda contains a single partition /dev/sda1, with random
310      * content.  /dev/sdb and /dev/sdc may have random content.
311      * No LVM.
312      *)
313   | InitPartition
314
315     (* /dev/sda contains a single partition /dev/sda1, which is formatted
316      * as ext2, empty [except for lost+found] and mounted on /.
317      * /dev/sdb and /dev/sdc may have random content.
318      * No LVM.
319      *)
320   | InitBasicFS
321
322     (* /dev/sda:
323      *   /dev/sda1 (is a PV):
324      *     /dev/VG/LV (size 8MB):
325      *       formatted as ext2, empty [except for lost+found], mounted on /
326      * /dev/sdb and /dev/sdc may have random content.
327      *)
328   | InitBasicFSonLVM
329
330     (* /dev/sdd (the ISO, see images/ directory in source)
331      * is mounted on /
332      *)
333   | InitISOFS
334
335 (* Sequence of commands for testing. *)
336 and seq = cmd list
337 and cmd = string list
338
339 (* Note about long descriptions: When referring to another
340  * action, use the format C<guestfs_other> (ie. the full name of
341  * the C function).  This will be replaced as appropriate in other
342  * language bindings.
343  *
344  * Apart from that, long descriptions are just perldoc paragraphs.
345  *)
346
347 (* Generate a random UUID (used in tests). *)
348 let uuidgen () =
349   let chan = Unix.open_process_in "uuidgen" in
350   let uuid = input_line chan in
351   (match Unix.close_process_in chan with
352    | Unix.WEXITED 0 -> ()
353    | Unix.WEXITED _ ->
354        failwith "uuidgen: process exited with non-zero status"
355    | Unix.WSIGNALED _ | Unix.WSTOPPED _ ->
356        failwith "uuidgen: process signalled or stopped by signal"
357   );
358   uuid
359
360 (* These test functions are used in the language binding tests. *)
361
362 let test_all_args = [
363   String "str";
364   OptString "optstr";
365   StringList "strlist";
366   Bool "b";
367   Int "integer";
368   Int64 "integer64";
369   FileIn "filein";
370   FileOut "fileout";
371 ]
372
373 let test_all_rets = [
374   (* except for RErr, which is tested thoroughly elsewhere *)
375   "test0rint",         RInt "valout";
376   "test0rint64",       RInt64 "valout";
377   "test0rbool",        RBool "valout";
378   "test0rconststring", RConstString "valout";
379   "test0rconstoptstring", RConstOptString "valout";
380   "test0rstring",      RString "valout";
381   "test0rstringlist",  RStringList "valout";
382   "test0rstruct",      RStruct ("valout", "lvm_pv");
383   "test0rstructlist",  RStructList ("valout", "lvm_pv");
384   "test0rhashtable",   RHashtable "valout";
385 ]
386
387 let test_functions = [
388   ("test0", (RErr, test_all_args), -1, [NotInFish; NotInDocs],
389    [],
390    "internal test function - do not use",
391    "\
392 This is an internal test function which is used to test whether
393 the automatically generated bindings can handle every possible
394 parameter type correctly.
395
396 It echos the contents of each parameter to stdout.
397
398 You probably don't want to call this function.");
399 ] @ List.flatten (
400   List.map (
401     fun (name, ret) ->
402       [(name, (ret, [String "val"]), -1, [NotInFish; NotInDocs],
403         [],
404         "internal test function - do not use",
405         "\
406 This is an internal test function which is used to test whether
407 the automatically generated bindings can handle every possible
408 return type correctly.
409
410 It converts string C<val> to the return type.
411
412 You probably don't want to call this function.");
413        (name ^ "err", (ret, []), -1, [NotInFish; NotInDocs],
414         [],
415         "internal test function - do not use",
416         "\
417 This is an internal test function which is used to test whether
418 the automatically generated bindings can handle every possible
419 return type correctly.
420
421 This function always returns an error.
422
423 You probably don't want to call this function.")]
424   ) test_all_rets
425 )
426
427 (* non_daemon_functions are any functions which don't get processed
428  * in the daemon, eg. functions for setting and getting local
429  * configuration values.
430  *)
431
432 let non_daemon_functions = test_functions @ [
433   ("launch", (RErr, []), -1, [FishAlias "run"; FishAction "launch"],
434    [],
435    "launch the qemu subprocess",
436    "\
437 Internally libguestfs is implemented by running a virtual machine
438 using L<qemu(1)>.
439
440 You should call this after configuring the handle
441 (eg. adding drives) but before performing any actions.");
442
443   ("wait_ready", (RErr, []), -1, [NotInFish],
444    [],
445    "wait until the qemu subprocess launches (no op)",
446    "\
447 This function is a no op.
448
449 In versions of the API E<lt> 1.0.71 you had to call this function
450 just after calling C<guestfs_launch> to wait for the launch
451 to complete.  However this is no longer necessary because
452 C<guestfs_launch> now does the waiting.
453
454 If you see any calls to this function in code then you can just
455 remove them, unless you want to retain compatibility with older
456 versions of the API.");
457
458   ("kill_subprocess", (RErr, []), -1, [],
459    [],
460    "kill the qemu subprocess",
461    "\
462 This kills the qemu subprocess.  You should never need to call this.");
463
464   ("add_drive", (RErr, [String "filename"]), -1, [FishAlias "add"],
465    [],
466    "add an image to examine or modify",
467    "\
468 This function adds a virtual machine disk image C<filename> to the
469 guest.  The first time you call this function, the disk appears as IDE
470 disk 0 (C</dev/sda>) in the guest, the second time as C</dev/sdb>, and
471 so on.
472
473 You don't necessarily need to be root when using libguestfs.  However
474 you obviously do need sufficient permissions to access the filename
475 for whatever operations you want to perform (ie. read access if you
476 just want to read the image or write access if you want to modify the
477 image).
478
479 This is equivalent to the qemu parameter
480 C<-drive file=filename,cache=off,if=...>.
481 C<cache=off> is omitted in cases where it is not supported by
482 the underlying filesystem.
483
484 Note that this call checks for the existence of C<filename>.  This
485 stops you from specifying other types of drive which are supported
486 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
487 the general C<guestfs_config> call instead.");
488
489   ("add_cdrom", (RErr, [String "filename"]), -1, [FishAlias "cdrom"],
490    [],
491    "add a CD-ROM disk image to examine",
492    "\
493 This function adds a virtual CD-ROM disk image to the guest.
494
495 This is equivalent to the qemu parameter C<-cdrom filename>.
496
497 Note that this call checks for the existence of C<filename>.  This
498 stops you from specifying other types of drive which are supported
499 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
500 the general C<guestfs_config> call instead.");
501
502   ("add_drive_ro", (RErr, [String "filename"]), -1, [FishAlias "add-ro"],
503    [],
504    "add a drive in snapshot mode (read-only)",
505    "\
506 This adds a drive in snapshot mode, making it effectively
507 read-only.
508
509 Note that writes to the device are allowed, and will be seen for
510 the duration of the guestfs handle, but they are written
511 to a temporary file which is discarded as soon as the guestfs
512 handle is closed.  We don't currently have any method to enable
513 changes to be committed, although qemu can support this.
514
515 This is equivalent to the qemu parameter
516 C<-drive file=filename,snapshot=on,if=...>.
517
518 Note that this call checks for the existence of C<filename>.  This
519 stops you from specifying other types of drive which are supported
520 by qemu such as C<nbd:> and C<http:> URLs.  To specify those, use
521 the general C<guestfs_config> call instead.");
522
523   ("config", (RErr, [String "qemuparam"; OptString "qemuvalue"]), -1, [],
524    [],
525    "add qemu parameters",
526    "\
527 This can be used to add arbitrary qemu command line parameters
528 of the form C<-param value>.  Actually it's not quite arbitrary - we
529 prevent you from setting some parameters which would interfere with
530 parameters that we use.
531
532 The first character of C<param> string must be a C<-> (dash).
533
534 C<value> can be NULL.");
535
536   ("set_qemu", (RErr, [String "qemu"]), -1, [FishAlias "qemu"],
537    [],
538    "set the qemu binary",
539    "\
540 Set the qemu binary that we will use.
541
542 The default is chosen when the library was compiled by the
543 configure script.
544
545 You can also override this by setting the C<LIBGUESTFS_QEMU>
546 environment variable.
547
548 Setting C<qemu> to C<NULL> restores the default qemu binary.");
549
550   ("get_qemu", (RConstString "qemu", []), -1, [],
551    [InitNone, Always, TestRun (
552       [["get_qemu"]])],
553    "get the qemu binary",
554    "\
555 Return the current qemu binary.
556
557 This is always non-NULL.  If it wasn't set already, then this will
558 return the default qemu binary name.");
559
560   ("set_path", (RErr, [String "searchpath"]), -1, [FishAlias "path"],
561    [],
562    "set the search path",
563    "\
564 Set the path that libguestfs searches for kernel and initrd.img.
565
566 The default is C<$libdir/guestfs> unless overridden by setting
567 C<LIBGUESTFS_PATH> environment variable.
568
569 Setting C<path> to C<NULL> restores the default path.");
570
571   ("get_path", (RConstString "path", []), -1, [],
572    [InitNone, Always, TestRun (
573       [["get_path"]])],
574    "get the search path",
575    "\
576 Return the current search path.
577
578 This is always non-NULL.  If it wasn't set already, then this will
579 return the default path.");
580
581   ("set_append", (RErr, [OptString "append"]), -1, [FishAlias "append"],
582    [],
583    "add options to kernel command line",
584    "\
585 This function is used to add additional options to the
586 guest kernel command line.
587
588 The default is C<NULL> unless overridden by setting
589 C<LIBGUESTFS_APPEND> environment variable.
590
591 Setting C<append> to C<NULL> means I<no> additional options
592 are passed (libguestfs always adds a few of its own).");
593
594   ("get_append", (RConstOptString "append", []), -1, [],
595    (* This cannot be tested with the current framework.  The
596     * function can return NULL in normal operations, which the
597     * test framework interprets as an error.
598     *)
599    [],
600    "get the additional kernel options",
601    "\
602 Return the additional kernel options which are added to the
603 guest kernel command line.
604
605 If C<NULL> then no options are added.");
606
607   ("set_autosync", (RErr, [Bool "autosync"]), -1, [FishAlias "autosync"],
608    [],
609    "set autosync mode",
610    "\
611 If C<autosync> is true, this enables autosync.  Libguestfs will make a
612 best effort attempt to run C<guestfs_umount_all> followed by
613 C<guestfs_sync> when the handle is closed
614 (also if the program exits without closing handles).
615
616 This is disabled by default (except in guestfish where it is
617 enabled by default).");
618
619   ("get_autosync", (RBool "autosync", []), -1, [],
620    [InitNone, Always, TestRun (
621       [["get_autosync"]])],
622    "get autosync mode",
623    "\
624 Get the autosync flag.");
625
626   ("set_verbose", (RErr, [Bool "verbose"]), -1, [FishAlias "verbose"],
627    [],
628    "set verbose mode",
629    "\
630 If C<verbose> is true, this turns on verbose messages (to C<stderr>).
631
632 Verbose messages are disabled unless the environment variable
633 C<LIBGUESTFS_DEBUG> is defined and set to C<1>.");
634
635   ("get_verbose", (RBool "verbose", []), -1, [],
636    [],
637    "get verbose mode",
638    "\
639 This returns the verbose messages flag.");
640
641   ("is_ready", (RBool "ready", []), -1, [],
642    [InitNone, Always, TestOutputTrue (
643       [["is_ready"]])],
644    "is ready to accept commands",
645    "\
646 This returns true iff this handle is ready to accept commands
647 (in the C<READY> state).
648
649 For more information on states, see L<guestfs(3)>.");
650
651   ("is_config", (RBool "config", []), -1, [],
652    [InitNone, Always, TestOutputFalse (
653       [["is_config"]])],
654    "is in configuration state",
655    "\
656 This returns true iff this handle is being configured
657 (in the C<CONFIG> state).
658
659 For more information on states, see L<guestfs(3)>.");
660
661   ("is_launching", (RBool "launching", []), -1, [],
662    [InitNone, Always, TestOutputFalse (
663       [["is_launching"]])],
664    "is launching subprocess",
665    "\
666 This returns true iff this handle is launching the subprocess
667 (in the C<LAUNCHING> state).
668
669 For more information on states, see L<guestfs(3)>.");
670
671   ("is_busy", (RBool "busy", []), -1, [],
672    [InitNone, Always, TestOutputFalse (
673       [["is_busy"]])],
674    "is busy processing a command",
675    "\
676 This returns true iff this handle is busy processing a command
677 (in the C<BUSY> state).
678
679 For more information on states, see L<guestfs(3)>.");
680
681   ("get_state", (RInt "state", []), -1, [],
682    [],
683    "get the current state",
684    "\
685 This returns the current state as an opaque integer.  This is
686 only useful for printing debug and internal error messages.
687
688 For more information on states, see L<guestfs(3)>.");
689
690   ("set_memsize", (RErr, [Int "memsize"]), -1, [FishAlias "memsize"],
691    [InitNone, Always, TestOutputInt (
692       [["set_memsize"; "500"];
693        ["get_memsize"]], 500)],
694    "set memory allocated to the qemu subprocess",
695    "\
696 This sets the memory size in megabytes allocated to the
697 qemu subprocess.  This only has any effect if called before
698 C<guestfs_launch>.
699
700 You can also change this by setting the environment
701 variable C<LIBGUESTFS_MEMSIZE> before the handle is
702 created.
703
704 For more information on the architecture of libguestfs,
705 see L<guestfs(3)>.");
706
707   ("get_memsize", (RInt "memsize", []), -1, [],
708    [InitNone, Always, TestOutputIntOp (
709       [["get_memsize"]], ">=", 256)],
710    "get memory allocated to the qemu subprocess",
711    "\
712 This gets the memory size in megabytes allocated to the
713 qemu subprocess.
714
715 If C<guestfs_set_memsize> was not called
716 on this handle, and if C<LIBGUESTFS_MEMSIZE> was not set,
717 then this returns the compiled-in default value for memsize.
718
719 For more information on the architecture of libguestfs,
720 see L<guestfs(3)>.");
721
722   ("get_pid", (RInt "pid", []), -1, [FishAlias "pid"],
723    [InitNone, Always, TestOutputIntOp (
724       [["get_pid"]], ">=", 1)],
725    "get PID of qemu subprocess",
726    "\
727 Return the process ID of the qemu subprocess.  If there is no
728 qemu subprocess, then this will return an error.
729
730 This is an internal call used for debugging and testing.");
731
732   ("version", (RStruct ("version", "version"), []), -1, [],
733    [InitNone, Always, TestOutputStruct (
734       [["version"]], [CompareWithInt ("major", 1)])],
735    "get the library version number",
736    "\
737 Return the libguestfs version number that the program is linked
738 against.
739
740 Note that because of dynamic linking this is not necessarily
741 the version of libguestfs that you compiled against.  You can
742 compile the program, and then at runtime dynamically link
743 against a completely different C<libguestfs.so> library.
744
745 This call was added in version C<1.0.58>.  In previous
746 versions of libguestfs there was no way to get the version
747 number.  From C code you can use ELF weak linking tricks to find out if
748 this symbol exists (if it doesn't, then it's an earlier version).
749
750 The call returns a structure with four elements.  The first
751 three (C<major>, C<minor> and C<release>) are numbers and
752 correspond to the usual version triplet.  The fourth element
753 (C<extra>) is a string and is normally empty, but may be
754 used for distro-specific information.
755
756 To construct the original version string:
757 C<$major.$minor.$release$extra>
758
759 I<Note:> Don't use this call to test for availability
760 of features.  Distro backports makes this unreliable.");
761
762   ("set_selinux", (RErr, [Bool "selinux"]), -1, [FishAlias "selinux"],
763    [InitNone, Always, TestOutputTrue (
764       [["set_selinux"; "true"];
765        ["get_selinux"]])],
766    "set SELinux enabled or disabled at appliance boot",
767    "\
768 This sets the selinux flag that is passed to the appliance
769 at boot time.  The default is C<selinux=0> (disabled).
770
771 Note that if SELinux is enabled, it is always in
772 Permissive mode (C<enforcing=0>).
773
774 For more information on the architecture of libguestfs,
775 see L<guestfs(3)>.");
776
777   ("get_selinux", (RBool "selinux", []), -1, [],
778    [],
779    "get SELinux enabled flag",
780    "\
781 This returns the current setting of the selinux flag which
782 is passed to the appliance at boot time.  See C<guestfs_set_selinux>.
783
784 For more information on the architecture of libguestfs,
785 see L<guestfs(3)>.");
786
787   ("set_trace", (RErr, [Bool "trace"]), -1, [FishAlias "trace"],
788    [InitNone, Always, TestOutputFalse (
789       [["set_trace"; "false"];
790        ["get_trace"]])],
791    "enable or disable command traces",
792    "\
793 If the command trace flag is set to 1, then commands are
794 printed on stdout before they are executed in a format
795 which is very similar to the one used by guestfish.  In
796 other words, you can run a program with this enabled, and
797 you will get out a script which you can feed to guestfish
798 to perform the same set of actions.
799
800 If you want to trace C API calls into libguestfs (and
801 other libraries) then possibly a better way is to use
802 the external ltrace(1) command.
803
804 Command traces are disabled unless the environment variable
805 C<LIBGUESTFS_TRACE> is defined and set to C<1>.");
806
807   ("get_trace", (RBool "trace", []), -1, [],
808    [],
809    "get command trace enabled flag",
810    "\
811 Return the command trace flag.");
812
813   ("set_direct", (RErr, [Bool "direct"]), -1, [FishAlias "direct"],
814    [InitNone, Always, TestOutputFalse (
815       [["set_direct"; "false"];
816        ["get_direct"]])],
817    "enable or disable direct appliance mode",
818    "\
819 If the direct appliance mode flag is enabled, then stdin and
820 stdout are passed directly through to the appliance once it
821 is launched.
822
823 One consequence of this is that log messages aren't caught
824 by the library and handled by C<guestfs_set_log_message_callback>,
825 but go straight to stdout.
826
827 You probably don't want to use this unless you know what you
828 are doing.
829
830 The default is disabled.");
831
832   ("get_direct", (RBool "direct", []), -1, [],
833    [],
834    "get direct appliance mode flag",
835    "\
836 Return the direct appliance mode flag.");
837
838   ("set_recovery_proc", (RErr, [Bool "recoveryproc"]), -1, [FishAlias "recovery-proc"],
839    [InitNone, Always, TestOutputTrue (
840       [["set_recovery_proc"; "true"];
841        ["get_recovery_proc"]])],
842    "enable or disable the recovery process",
843    "\
844 If this is called with the parameter C<false> then
845 C<guestfs_launch> does not create a recovery process.  The
846 purpose of the recovery process is to stop runaway qemu
847 processes in the case where the main program aborts abruptly.
848
849 This only has any effect if called before C<guestfs_launch>,
850 and the default is true.
851
852 About the only time when you would want to disable this is
853 if the main process will fork itself into the background
854 (\"daemonize\" itself).  In this case the recovery process
855 thinks that the main program has disappeared and so kills
856 qemu, which is not very helpful.");
857
858   ("get_recovery_proc", (RBool "recoveryproc", []), -1, [],
859    [],
860    "get recovery process enabled flag",
861    "\
862 Return the recovery process enabled flag.");
863
864 ]
865
866 (* daemon_functions are any functions which cause some action
867  * to take place in the daemon.
868  *)
869
870 let daemon_functions = [
871   ("mount", (RErr, [Device "device"; String "mountpoint"]), 1, [],
872    [InitEmpty, Always, TestOutput (
873       [["sfdiskM"; "/dev/sda"; ","];
874        ["mkfs"; "ext2"; "/dev/sda1"];
875        ["mount"; "/dev/sda1"; "/"];
876        ["write_file"; "/new"; "new file contents"; "0"];
877        ["cat"; "/new"]], "new file contents")],
878    "mount a guest disk at a position in the filesystem",
879    "\
880 Mount a guest disk at a position in the filesystem.  Block devices
881 are named C</dev/sda>, C</dev/sdb> and so on, as they were added to
882 the guest.  If those block devices contain partitions, they will have
883 the usual names (eg. C</dev/sda1>).  Also LVM C</dev/VG/LV>-style
884 names can be used.
885
886 The rules are the same as for L<mount(2)>:  A filesystem must
887 first be mounted on C</> before others can be mounted.  Other
888 filesystems can only be mounted on directories which already
889 exist.
890
891 The mounted filesystem is writable, if we have sufficient permissions
892 on the underlying device.
893
894 The filesystem options C<sync> and C<noatime> are set with this
895 call, in order to improve reliability.");
896
897   ("sync", (RErr, []), 2, [],
898    [ InitEmpty, Always, TestRun [["sync"]]],
899    "sync disks, writes are flushed through to the disk image",
900    "\
901 This syncs the disk, so that any writes are flushed through to the
902 underlying disk image.
903
904 You should always call this if you have modified a disk image, before
905 closing the handle.");
906
907   ("touch", (RErr, [Pathname "path"]), 3, [],
908    [InitBasicFS, Always, TestOutputTrue (
909       [["touch"; "/new"];
910        ["exists"; "/new"]])],
911    "update file timestamps or create a new file",
912    "\
913 Touch acts like the L<touch(1)> command.  It can be used to
914 update the timestamps on a file, or, if the file does not exist,
915 to create a new zero-length file.");
916
917   ("cat", (RString "content", [Pathname "path"]), 4, [ProtocolLimitWarning],
918    [InitISOFS, Always, TestOutput (
919       [["cat"; "/known-2"]], "abcdef\n")],
920    "list the contents of a file",
921    "\
922 Return the contents of the file named C<path>.
923
924 Note that this function cannot correctly handle binary files
925 (specifically, files containing C<\\0> character which is treated
926 as end of string).  For those you need to use the C<guestfs_read_file>
927 or C<guestfs_download> functions which have a more complex interface.");
928
929   ("ll", (RString "listing", [Pathname "directory"]), 5, [],
930    [], (* XXX Tricky to test because it depends on the exact format
931         * of the 'ls -l' command, which changes between F10 and F11.
932         *)
933    "list the files in a directory (long format)",
934    "\
935 List the files in C<directory> (relative to the root directory,
936 there is no cwd) in the format of 'ls -la'.
937
938 This command is mostly useful for interactive sessions.  It
939 is I<not> intended that you try to parse the output string.");
940
941   ("ls", (RStringList "listing", [Pathname "directory"]), 6, [],
942    [InitBasicFS, Always, TestOutputList (
943       [["touch"; "/new"];
944        ["touch"; "/newer"];
945        ["touch"; "/newest"];
946        ["ls"; "/"]], ["lost+found"; "new"; "newer"; "newest"])],
947    "list the files in a directory",
948    "\
949 List the files in C<directory> (relative to the root directory,
950 there is no cwd).  The '.' and '..' entries are not returned, but
951 hidden files are shown.
952
953 This command is mostly useful for interactive sessions.  Programs
954 should probably use C<guestfs_readdir> instead.");
955
956   ("list_devices", (RStringList "devices", []), 7, [],
957    [InitEmpty, Always, TestOutputListOfDevices (
958       [["list_devices"]], ["/dev/sda"; "/dev/sdb"; "/dev/sdc"; "/dev/sdd"])],
959    "list the block devices",
960    "\
961 List all the block devices.
962
963 The full block device names are returned, eg. C</dev/sda>");
964
965   ("list_partitions", (RStringList "partitions", []), 8, [],
966    [InitBasicFS, Always, TestOutputListOfDevices (
967       [["list_partitions"]], ["/dev/sda1"]);
968     InitEmpty, Always, TestOutputListOfDevices (
969       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
970        ["list_partitions"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
971    "list the partitions",
972    "\
973 List all the partitions detected on all block devices.
974
975 The full partition device names are returned, eg. C</dev/sda1>
976
977 This does not return logical volumes.  For that you will need to
978 call C<guestfs_lvs>.");
979
980   ("pvs", (RStringList "physvols", []), 9, [],
981    [InitBasicFSonLVM, Always, TestOutputListOfDevices (
982       [["pvs"]], ["/dev/sda1"]);
983     InitEmpty, Always, TestOutputListOfDevices (
984       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
985        ["pvcreate"; "/dev/sda1"];
986        ["pvcreate"; "/dev/sda2"];
987        ["pvcreate"; "/dev/sda3"];
988        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
989    "list the LVM physical volumes (PVs)",
990    "\
991 List all the physical volumes detected.  This is the equivalent
992 of the L<pvs(8)> command.
993
994 This returns a list of just the device names that contain
995 PVs (eg. C</dev/sda2>).
996
997 See also C<guestfs_pvs_full>.");
998
999   ("vgs", (RStringList "volgroups", []), 10, [],
1000    [InitBasicFSonLVM, Always, TestOutputList (
1001       [["vgs"]], ["VG"]);
1002     InitEmpty, Always, TestOutputList (
1003       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1004        ["pvcreate"; "/dev/sda1"];
1005        ["pvcreate"; "/dev/sda2"];
1006        ["pvcreate"; "/dev/sda3"];
1007        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1008        ["vgcreate"; "VG2"; "/dev/sda3"];
1009        ["vgs"]], ["VG1"; "VG2"])],
1010    "list the LVM volume groups (VGs)",
1011    "\
1012 List all the volumes groups detected.  This is the equivalent
1013 of the L<vgs(8)> command.
1014
1015 This returns a list of just the volume group names that were
1016 detected (eg. C<VolGroup00>).
1017
1018 See also C<guestfs_vgs_full>.");
1019
1020   ("lvs", (RStringList "logvols", []), 11, [],
1021    [InitBasicFSonLVM, Always, TestOutputList (
1022       [["lvs"]], ["/dev/VG/LV"]);
1023     InitEmpty, Always, TestOutputList (
1024       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1025        ["pvcreate"; "/dev/sda1"];
1026        ["pvcreate"; "/dev/sda2"];
1027        ["pvcreate"; "/dev/sda3"];
1028        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1029        ["vgcreate"; "VG2"; "/dev/sda3"];
1030        ["lvcreate"; "LV1"; "VG1"; "50"];
1031        ["lvcreate"; "LV2"; "VG1"; "50"];
1032        ["lvcreate"; "LV3"; "VG2"; "50"];
1033        ["lvs"]], ["/dev/VG1/LV1"; "/dev/VG1/LV2"; "/dev/VG2/LV3"])],
1034    "list the LVM logical volumes (LVs)",
1035    "\
1036 List all the logical volumes detected.  This is the equivalent
1037 of the L<lvs(8)> command.
1038
1039 This returns a list of the logical volume device names
1040 (eg. C</dev/VolGroup00/LogVol00>).
1041
1042 See also C<guestfs_lvs_full>.");
1043
1044   ("pvs_full", (RStructList ("physvols", "lvm_pv"), []), 12, [],
1045    [], (* XXX how to test? *)
1046    "list the LVM physical volumes (PVs)",
1047    "\
1048 List all the physical volumes detected.  This is the equivalent
1049 of the L<pvs(8)> command.  The \"full\" version includes all fields.");
1050
1051   ("vgs_full", (RStructList ("volgroups", "lvm_vg"), []), 13, [],
1052    [], (* XXX how to test? *)
1053    "list the LVM volume groups (VGs)",
1054    "\
1055 List all the volumes groups detected.  This is the equivalent
1056 of the L<vgs(8)> command.  The \"full\" version includes all fields.");
1057
1058   ("lvs_full", (RStructList ("logvols", "lvm_lv"), []), 14, [],
1059    [], (* XXX how to test? *)
1060    "list the LVM logical volumes (LVs)",
1061    "\
1062 List all the logical volumes detected.  This is the equivalent
1063 of the L<lvs(8)> command.  The \"full\" version includes all fields.");
1064
1065   ("read_lines", (RStringList "lines", [Pathname "path"]), 15, [],
1066    [InitISOFS, Always, TestOutputList (
1067       [["read_lines"; "/known-4"]], ["abc"; "def"; "ghi"]);
1068     InitISOFS, Always, TestOutputList (
1069       [["read_lines"; "/empty"]], [])],
1070    "read file as lines",
1071    "\
1072 Return the contents of the file named C<path>.
1073
1074 The file contents are returned as a list of lines.  Trailing
1075 C<LF> and C<CRLF> character sequences are I<not> returned.
1076
1077 Note that this function cannot correctly handle binary files
1078 (specifically, files containing C<\\0> character which is treated
1079 as end of line).  For those you need to use the C<guestfs_read_file>
1080 function which has a more complex interface.");
1081
1082   ("aug_init", (RErr, [Pathname "root"; Int "flags"]), 16, [],
1083    [], (* XXX Augeas code needs tests. *)
1084    "create a new Augeas handle",
1085    "\
1086 Create a new Augeas handle for editing configuration files.
1087 If there was any previous Augeas handle associated with this
1088 guestfs session, then it is closed.
1089
1090 You must call this before using any other C<guestfs_aug_*>
1091 commands.
1092
1093 C<root> is the filesystem root.  C<root> must not be NULL,
1094 use C</> instead.
1095
1096 The flags are the same as the flags defined in
1097 E<lt>augeas.hE<gt>, the logical I<or> of the following
1098 integers:
1099
1100 =over 4
1101
1102 =item C<AUG_SAVE_BACKUP> = 1
1103
1104 Keep the original file with a C<.augsave> extension.
1105
1106 =item C<AUG_SAVE_NEWFILE> = 2
1107
1108 Save changes into a file with extension C<.augnew>, and
1109 do not overwrite original.  Overrides C<AUG_SAVE_BACKUP>.
1110
1111 =item C<AUG_TYPE_CHECK> = 4
1112
1113 Typecheck lenses (can be expensive).
1114
1115 =item C<AUG_NO_STDINC> = 8
1116
1117 Do not use standard load path for modules.
1118
1119 =item C<AUG_SAVE_NOOP> = 16
1120
1121 Make save a no-op, just record what would have been changed.
1122
1123 =item C<AUG_NO_LOAD> = 32
1124
1125 Do not load the tree in C<guestfs_aug_init>.
1126
1127 =back
1128
1129 To close the handle, you can call C<guestfs_aug_close>.
1130
1131 To find out more about Augeas, see L<http://augeas.net/>.");
1132
1133   ("aug_close", (RErr, []), 26, [],
1134    [], (* XXX Augeas code needs tests. *)
1135    "close the current Augeas handle",
1136    "\
1137 Close the current Augeas handle and free up any resources
1138 used by it.  After calling this, you have to call
1139 C<guestfs_aug_init> again before you can use any other
1140 Augeas functions.");
1141
1142   ("aug_defvar", (RInt "nrnodes", [String "name"; OptString "expr"]), 17, [],
1143    [], (* XXX Augeas code needs tests. *)
1144    "define an Augeas variable",
1145    "\
1146 Defines an Augeas variable C<name> whose value is the result
1147 of evaluating C<expr>.  If C<expr> is NULL, then C<name> is
1148 undefined.
1149
1150 On success this returns the number of nodes in C<expr>, or
1151 C<0> if C<expr> evaluates to something which is not a nodeset.");
1152
1153   ("aug_defnode", (RStruct ("nrnodescreated", "int_bool"), [String "name"; String "expr"; String "val"]), 18, [],
1154    [], (* XXX Augeas code needs tests. *)
1155    "define an Augeas node",
1156    "\
1157 Defines a variable C<name> whose value is the result of
1158 evaluating C<expr>.
1159
1160 If C<expr> evaluates to an empty nodeset, a node is created,
1161 equivalent to calling C<guestfs_aug_set> C<expr>, C<value>.
1162 C<name> will be the nodeset containing that single node.
1163
1164 On success this returns a pair containing the
1165 number of nodes in the nodeset, and a boolean flag
1166 if a node was created.");
1167
1168   ("aug_get", (RString "val", [String "augpath"]), 19, [],
1169    [], (* XXX Augeas code needs tests. *)
1170    "look up the value of an Augeas path",
1171    "\
1172 Look up the value associated with C<path>.  If C<path>
1173 matches exactly one node, the C<value> is returned.");
1174
1175   ("aug_set", (RErr, [String "augpath"; String "val"]), 20, [],
1176    [], (* XXX Augeas code needs tests. *)
1177    "set Augeas path to value",
1178    "\
1179 Set the value associated with C<path> to C<value>.");
1180
1181   ("aug_insert", (RErr, [String "augpath"; String "label"; Bool "before"]), 21, [],
1182    [], (* XXX Augeas code needs tests. *)
1183    "insert a sibling Augeas node",
1184    "\
1185 Create a new sibling C<label> for C<path>, inserting it into
1186 the tree before or after C<path> (depending on the boolean
1187 flag C<before>).
1188
1189 C<path> must match exactly one existing node in the tree, and
1190 C<label> must be a label, ie. not contain C</>, C<*> or end
1191 with a bracketed index C<[N]>.");
1192
1193   ("aug_rm", (RInt "nrnodes", [String "augpath"]), 22, [],
1194    [], (* XXX Augeas code needs tests. *)
1195    "remove an Augeas path",
1196    "\
1197 Remove C<path> and all of its children.
1198
1199 On success this returns the number of entries which were removed.");
1200
1201   ("aug_mv", (RErr, [String "src"; String "dest"]), 23, [],
1202    [], (* XXX Augeas code needs tests. *)
1203    "move Augeas node",
1204    "\
1205 Move the node C<src> to C<dest>.  C<src> must match exactly
1206 one node.  C<dest> is overwritten if it exists.");
1207
1208   ("aug_match", (RStringList "matches", [String "augpath"]), 24, [],
1209    [], (* XXX Augeas code needs tests. *)
1210    "return Augeas nodes which match augpath",
1211    "\
1212 Returns a list of paths which match the path expression C<path>.
1213 The returned paths are sufficiently qualified so that they match
1214 exactly one node in the current tree.");
1215
1216   ("aug_save", (RErr, []), 25, [],
1217    [], (* XXX Augeas code needs tests. *)
1218    "write all pending Augeas changes to disk",
1219    "\
1220 This writes all pending changes to disk.
1221
1222 The flags which were passed to C<guestfs_aug_init> affect exactly
1223 how files are saved.");
1224
1225   ("aug_load", (RErr, []), 27, [],
1226    [], (* XXX Augeas code needs tests. *)
1227    "load files into the tree",
1228    "\
1229 Load files into the tree.
1230
1231 See C<aug_load> in the Augeas documentation for the full gory
1232 details.");
1233
1234   ("aug_ls", (RStringList "matches", [String "augpath"]), 28, [],
1235    [], (* XXX Augeas code needs tests. *)
1236    "list Augeas nodes under augpath",
1237    "\
1238 This is just a shortcut for listing C<guestfs_aug_match>
1239 C<path/*> and sorting the resulting nodes into alphabetical order.");
1240
1241   ("rm", (RErr, [Pathname "path"]), 29, [],
1242    [InitBasicFS, Always, TestRun
1243       [["touch"; "/new"];
1244        ["rm"; "/new"]];
1245     InitBasicFS, Always, TestLastFail
1246       [["rm"; "/new"]];
1247     InitBasicFS, Always, TestLastFail
1248       [["mkdir"; "/new"];
1249        ["rm"; "/new"]]],
1250    "remove a file",
1251    "\
1252 Remove the single file C<path>.");
1253
1254   ("rmdir", (RErr, [Pathname "path"]), 30, [],
1255    [InitBasicFS, Always, TestRun
1256       [["mkdir"; "/new"];
1257        ["rmdir"; "/new"]];
1258     InitBasicFS, Always, TestLastFail
1259       [["rmdir"; "/new"]];
1260     InitBasicFS, Always, TestLastFail
1261       [["touch"; "/new"];
1262        ["rmdir"; "/new"]]],
1263    "remove a directory",
1264    "\
1265 Remove the single directory C<path>.");
1266
1267   ("rm_rf", (RErr, [Pathname "path"]), 31, [],
1268    [InitBasicFS, Always, TestOutputFalse
1269       [["mkdir"; "/new"];
1270        ["mkdir"; "/new/foo"];
1271        ["touch"; "/new/foo/bar"];
1272        ["rm_rf"; "/new"];
1273        ["exists"; "/new"]]],
1274    "remove a file or directory recursively",
1275    "\
1276 Remove the file or directory C<path>, recursively removing the
1277 contents if its a directory.  This is like the C<rm -rf> shell
1278 command.");
1279
1280   ("mkdir", (RErr, [Pathname "path"]), 32, [],
1281    [InitBasicFS, Always, TestOutputTrue
1282       [["mkdir"; "/new"];
1283        ["is_dir"; "/new"]];
1284     InitBasicFS, Always, TestLastFail
1285       [["mkdir"; "/new/foo/bar"]]],
1286    "create a directory",
1287    "\
1288 Create a directory named C<path>.");
1289
1290   ("mkdir_p", (RErr, [Pathname "path"]), 33, [],
1291    [InitBasicFS, Always, TestOutputTrue
1292       [["mkdir_p"; "/new/foo/bar"];
1293        ["is_dir"; "/new/foo/bar"]];
1294     InitBasicFS, Always, TestOutputTrue
1295       [["mkdir_p"; "/new/foo/bar"];
1296        ["is_dir"; "/new/foo"]];
1297     InitBasicFS, Always, TestOutputTrue
1298       [["mkdir_p"; "/new/foo/bar"];
1299        ["is_dir"; "/new"]];
1300     (* Regression tests for RHBZ#503133: *)
1301     InitBasicFS, Always, TestRun
1302       [["mkdir"; "/new"];
1303        ["mkdir_p"; "/new"]];
1304     InitBasicFS, Always, TestLastFail
1305       [["touch"; "/new"];
1306        ["mkdir_p"; "/new"]]],
1307    "create a directory and parents",
1308    "\
1309 Create a directory named C<path>, creating any parent directories
1310 as necessary.  This is like the C<mkdir -p> shell command.");
1311
1312   ("chmod", (RErr, [Int "mode"; Pathname "path"]), 34, [],
1313    [], (* XXX Need stat command to test *)
1314    "change file mode",
1315    "\
1316 Change the mode (permissions) of C<path> to C<mode>.  Only
1317 numeric modes are supported.");
1318
1319   ("chown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 35, [],
1320    [], (* XXX Need stat command to test *)
1321    "change file owner and group",
1322    "\
1323 Change the file owner to C<owner> and group to C<group>.
1324
1325 Only numeric uid and gid are supported.  If you want to use
1326 names, you will need to locate and parse the password file
1327 yourself (Augeas support makes this relatively easy).");
1328
1329   ("exists", (RBool "existsflag", [Pathname "path"]), 36, [],
1330    [InitISOFS, Always, TestOutputTrue (
1331       [["exists"; "/empty"]]);
1332     InitISOFS, Always, TestOutputTrue (
1333       [["exists"; "/directory"]])],
1334    "test if file or directory exists",
1335    "\
1336 This returns C<true> if and only if there is a file, directory
1337 (or anything) with the given C<path> name.
1338
1339 See also C<guestfs_is_file>, C<guestfs_is_dir>, C<guestfs_stat>.");
1340
1341   ("is_file", (RBool "fileflag", [Pathname "path"]), 37, [],
1342    [InitISOFS, Always, TestOutputTrue (
1343       [["is_file"; "/known-1"]]);
1344     InitISOFS, Always, TestOutputFalse (
1345       [["is_file"; "/directory"]])],
1346    "test if file exists",
1347    "\
1348 This returns C<true> if and only if there is a file
1349 with the given C<path> name.  Note that it returns false for
1350 other objects like directories.
1351
1352 See also C<guestfs_stat>.");
1353
1354   ("is_dir", (RBool "dirflag", [Pathname "path"]), 38, [],
1355    [InitISOFS, Always, TestOutputFalse (
1356       [["is_dir"; "/known-3"]]);
1357     InitISOFS, Always, TestOutputTrue (
1358       [["is_dir"; "/directory"]])],
1359    "test if file exists",
1360    "\
1361 This returns C<true> if and only if there is a directory
1362 with the given C<path> name.  Note that it returns false for
1363 other objects like files.
1364
1365 See also C<guestfs_stat>.");
1366
1367   ("pvcreate", (RErr, [Device "device"]), 39, [],
1368    [InitEmpty, Always, TestOutputListOfDevices (
1369       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1370        ["pvcreate"; "/dev/sda1"];
1371        ["pvcreate"; "/dev/sda2"];
1372        ["pvcreate"; "/dev/sda3"];
1373        ["pvs"]], ["/dev/sda1"; "/dev/sda2"; "/dev/sda3"])],
1374    "create an LVM physical volume",
1375    "\
1376 This creates an LVM physical volume on the named C<device>,
1377 where C<device> should usually be a partition name such
1378 as C</dev/sda1>.");
1379
1380   ("vgcreate", (RErr, [String "volgroup"; DeviceList "physvols"]), 40, [],
1381    [InitEmpty, Always, TestOutputList (
1382       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1383        ["pvcreate"; "/dev/sda1"];
1384        ["pvcreate"; "/dev/sda2"];
1385        ["pvcreate"; "/dev/sda3"];
1386        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1387        ["vgcreate"; "VG2"; "/dev/sda3"];
1388        ["vgs"]], ["VG1"; "VG2"])],
1389    "create an LVM volume group",
1390    "\
1391 This creates an LVM volume group called C<volgroup>
1392 from the non-empty list of physical volumes C<physvols>.");
1393
1394   ("lvcreate", (RErr, [String "logvol"; String "volgroup"; Int "mbytes"]), 41, [],
1395    [InitEmpty, Always, TestOutputList (
1396       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1397        ["pvcreate"; "/dev/sda1"];
1398        ["pvcreate"; "/dev/sda2"];
1399        ["pvcreate"; "/dev/sda3"];
1400        ["vgcreate"; "VG1"; "/dev/sda1 /dev/sda2"];
1401        ["vgcreate"; "VG2"; "/dev/sda3"];
1402        ["lvcreate"; "LV1"; "VG1"; "50"];
1403        ["lvcreate"; "LV2"; "VG1"; "50"];
1404        ["lvcreate"; "LV3"; "VG2"; "50"];
1405        ["lvcreate"; "LV4"; "VG2"; "50"];
1406        ["lvcreate"; "LV5"; "VG2"; "50"];
1407        ["lvs"]],
1408       ["/dev/VG1/LV1"; "/dev/VG1/LV2";
1409        "/dev/VG2/LV3"; "/dev/VG2/LV4"; "/dev/VG2/LV5"])],
1410    "create an LVM volume group",
1411    "\
1412 This creates an LVM volume group called C<logvol>
1413 on the volume group C<volgroup>, with C<size> megabytes.");
1414
1415   ("mkfs", (RErr, [String "fstype"; Device "device"]), 42, [],
1416    [InitEmpty, Always, TestOutput (
1417       [["sfdiskM"; "/dev/sda"; ","];
1418        ["mkfs"; "ext2"; "/dev/sda1"];
1419        ["mount"; "/dev/sda1"; "/"];
1420        ["write_file"; "/new"; "new file contents"; "0"];
1421        ["cat"; "/new"]], "new file contents")],
1422    "make a filesystem",
1423    "\
1424 This creates a filesystem on C<device> (usually a partition
1425 or LVM logical volume).  The filesystem type is C<fstype>, for
1426 example C<ext3>.");
1427
1428   ("sfdisk", (RErr, [Device "device";
1429                      Int "cyls"; Int "heads"; Int "sectors";
1430                      StringList "lines"]), 43, [DangerWillRobinson],
1431    [],
1432    "create partitions on a block device",
1433    "\
1434 This is a direct interface to the L<sfdisk(8)> program for creating
1435 partitions on block devices.
1436
1437 C<device> should be a block device, for example C</dev/sda>.
1438
1439 C<cyls>, C<heads> and C<sectors> are the number of cylinders, heads
1440 and sectors on the device, which are passed directly to sfdisk as
1441 the I<-C>, I<-H> and I<-S> parameters.  If you pass C<0> for any
1442 of these, then the corresponding parameter is omitted.  Usually for
1443 'large' disks, you can just pass C<0> for these, but for small
1444 (floppy-sized) disks, sfdisk (or rather, the kernel) cannot work
1445 out the right geometry and you will need to tell it.
1446
1447 C<lines> is a list of lines that we feed to C<sfdisk>.  For more
1448 information refer to the L<sfdisk(8)> manpage.
1449
1450 To create a single partition occupying the whole disk, you would
1451 pass C<lines> as a single element list, when the single element being
1452 the string C<,> (comma).
1453
1454 See also: C<guestfs_sfdisk_l>, C<guestfs_sfdisk_N>");
1455
1456   ("write_file", (RErr, [Pathname "path"; String "content"; Int "size"]), 44, [ProtocolLimitWarning],
1457    [InitBasicFS, Always, TestOutput (
1458       [["write_file"; "/new"; "new file contents"; "0"];
1459        ["cat"; "/new"]], "new file contents");
1460     InitBasicFS, Always, TestOutput (
1461       [["write_file"; "/new"; "\nnew file contents\n"; "0"];
1462        ["cat"; "/new"]], "\nnew file contents\n");
1463     InitBasicFS, Always, TestOutput (
1464       [["write_file"; "/new"; "\n\n"; "0"];
1465        ["cat"; "/new"]], "\n\n");
1466     InitBasicFS, Always, TestOutput (
1467       [["write_file"; "/new"; ""; "0"];
1468        ["cat"; "/new"]], "");
1469     InitBasicFS, Always, TestOutput (
1470       [["write_file"; "/new"; "\n\n\n"; "0"];
1471        ["cat"; "/new"]], "\n\n\n");
1472     InitBasicFS, Always, TestOutput (
1473       [["write_file"; "/new"; "\n"; "0"];
1474        ["cat"; "/new"]], "\n")],
1475    "create a file",
1476    "\
1477 This call creates a file called C<path>.  The contents of the
1478 file is the string C<content> (which can contain any 8 bit data),
1479 with length C<size>.
1480
1481 As a special case, if C<size> is C<0>
1482 then the length is calculated using C<strlen> (so in this case
1483 the content cannot contain embedded ASCII NULs).
1484
1485 I<NB.> Owing to a bug, writing content containing ASCII NUL
1486 characters does I<not> work, even if the length is specified.
1487 We hope to resolve this bug in a future version.  In the meantime
1488 use C<guestfs_upload>.");
1489
1490   ("umount", (RErr, [String "pathordevice"]), 45, [FishAlias "unmount"],
1491    [InitEmpty, Always, TestOutputListOfDevices (
1492       [["sfdiskM"; "/dev/sda"; ","];
1493        ["mkfs"; "ext2"; "/dev/sda1"];
1494        ["mount"; "/dev/sda1"; "/"];
1495        ["mounts"]], ["/dev/sda1"]);
1496     InitEmpty, Always, TestOutputList (
1497       [["sfdiskM"; "/dev/sda"; ","];
1498        ["mkfs"; "ext2"; "/dev/sda1"];
1499        ["mount"; "/dev/sda1"; "/"];
1500        ["umount"; "/"];
1501        ["mounts"]], [])],
1502    "unmount a filesystem",
1503    "\
1504 This unmounts the given filesystem.  The filesystem may be
1505 specified either by its mountpoint (path) or the device which
1506 contains the filesystem.");
1507
1508   ("mounts", (RStringList "devices", []), 46, [],
1509    [InitBasicFS, Always, TestOutputListOfDevices (
1510       [["mounts"]], ["/dev/sda1"])],
1511    "show mounted filesystems",
1512    "\
1513 This returns the list of currently mounted filesystems.  It returns
1514 the list of devices (eg. C</dev/sda1>, C</dev/VG/LV>).
1515
1516 Some internal mounts are not shown.
1517
1518 See also: C<guestfs_mountpoints>");
1519
1520   ("umount_all", (RErr, []), 47, [FishAlias "unmount-all"],
1521    [InitBasicFS, Always, TestOutputList (
1522       [["umount_all"];
1523        ["mounts"]], []);
1524     (* check that umount_all can unmount nested mounts correctly: *)
1525     InitEmpty, Always, TestOutputList (
1526       [["sfdiskM"; "/dev/sda"; ",100 ,200 ,"];
1527        ["mkfs"; "ext2"; "/dev/sda1"];
1528        ["mkfs"; "ext2"; "/dev/sda2"];
1529        ["mkfs"; "ext2"; "/dev/sda3"];
1530        ["mount"; "/dev/sda1"; "/"];
1531        ["mkdir"; "/mp1"];
1532        ["mount"; "/dev/sda2"; "/mp1"];
1533        ["mkdir"; "/mp1/mp2"];
1534        ["mount"; "/dev/sda3"; "/mp1/mp2"];
1535        ["mkdir"; "/mp1/mp2/mp3"];
1536        ["umount_all"];
1537        ["mounts"]], [])],
1538    "unmount all filesystems",
1539    "\
1540 This unmounts all mounted filesystems.
1541
1542 Some internal mounts are not unmounted by this call.");
1543
1544   ("lvm_remove_all", (RErr, []), 48, [DangerWillRobinson],
1545    [],
1546    "remove all LVM LVs, VGs and PVs",
1547    "\
1548 This command removes all LVM logical volumes, volume groups
1549 and physical volumes.");
1550
1551   ("file", (RString "description", [Dev_or_Path "path"]), 49, [],
1552    [InitISOFS, Always, TestOutput (
1553       [["file"; "/empty"]], "empty");
1554     InitISOFS, Always, TestOutput (
1555       [["file"; "/known-1"]], "ASCII text");
1556     InitISOFS, Always, TestLastFail (
1557       [["file"; "/notexists"]])],
1558    "determine file type",
1559    "\
1560 This call uses the standard L<file(1)> command to determine
1561 the type or contents of the file.  This also works on devices,
1562 for example to find out whether a partition contains a filesystem.
1563
1564 This call will also transparently look inside various types
1565 of compressed file.
1566
1567 The exact command which runs is C<file -zbsL path>.  Note in
1568 particular that the filename is not prepended to the output
1569 (the C<-b> option).");
1570
1571   ("command", (RString "output", [StringList "arguments"]), 50, [ProtocolLimitWarning],
1572    [InitBasicFS, Always, TestOutput (
1573       [["upload"; "test-command"; "/test-command"];
1574        ["chmod"; "0o755"; "/test-command"];
1575        ["command"; "/test-command 1"]], "Result1");
1576     InitBasicFS, Always, TestOutput (
1577       [["upload"; "test-command"; "/test-command"];
1578        ["chmod"; "0o755"; "/test-command"];
1579        ["command"; "/test-command 2"]], "Result2\n");
1580     InitBasicFS, Always, TestOutput (
1581       [["upload"; "test-command"; "/test-command"];
1582        ["chmod"; "0o755"; "/test-command"];
1583        ["command"; "/test-command 3"]], "\nResult3");
1584     InitBasicFS, Always, TestOutput (
1585       [["upload"; "test-command"; "/test-command"];
1586        ["chmod"; "0o755"; "/test-command"];
1587        ["command"; "/test-command 4"]], "\nResult4\n");
1588     InitBasicFS, Always, TestOutput (
1589       [["upload"; "test-command"; "/test-command"];
1590        ["chmod"; "0o755"; "/test-command"];
1591        ["command"; "/test-command 5"]], "\nResult5\n\n");
1592     InitBasicFS, Always, TestOutput (
1593       [["upload"; "test-command"; "/test-command"];
1594        ["chmod"; "0o755"; "/test-command"];
1595        ["command"; "/test-command 6"]], "\n\nResult6\n\n");
1596     InitBasicFS, Always, TestOutput (
1597       [["upload"; "test-command"; "/test-command"];
1598        ["chmod"; "0o755"; "/test-command"];
1599        ["command"; "/test-command 7"]], "");
1600     InitBasicFS, Always, TestOutput (
1601       [["upload"; "test-command"; "/test-command"];
1602        ["chmod"; "0o755"; "/test-command"];
1603        ["command"; "/test-command 8"]], "\n");
1604     InitBasicFS, Always, TestOutput (
1605       [["upload"; "test-command"; "/test-command"];
1606        ["chmod"; "0o755"; "/test-command"];
1607        ["command"; "/test-command 9"]], "\n\n");
1608     InitBasicFS, Always, TestOutput (
1609       [["upload"; "test-command"; "/test-command"];
1610        ["chmod"; "0o755"; "/test-command"];
1611        ["command"; "/test-command 10"]], "Result10-1\nResult10-2\n");
1612     InitBasicFS, Always, TestOutput (
1613       [["upload"; "test-command"; "/test-command"];
1614        ["chmod"; "0o755"; "/test-command"];
1615        ["command"; "/test-command 11"]], "Result11-1\nResult11-2");
1616     InitBasicFS, Always, TestLastFail (
1617       [["upload"; "test-command"; "/test-command"];
1618        ["chmod"; "0o755"; "/test-command"];
1619        ["command"; "/test-command"]])],
1620    "run a command from the guest filesystem",
1621    "\
1622 This call runs a command from the guest filesystem.  The
1623 filesystem must be mounted, and must contain a compatible
1624 operating system (ie. something Linux, with the same
1625 or compatible processor architecture).
1626
1627 The single parameter is an argv-style list of arguments.
1628 The first element is the name of the program to run.
1629 Subsequent elements are parameters.  The list must be
1630 non-empty (ie. must contain a program name).  Note that
1631 the command runs directly, and is I<not> invoked via
1632 the shell (see C<guestfs_sh>).
1633
1634 The return value is anything printed to I<stdout> by
1635 the command.
1636
1637 If the command returns a non-zero exit status, then
1638 this function returns an error message.  The error message
1639 string is the content of I<stderr> from the command.
1640
1641 The C<$PATH> environment variable will contain at least
1642 C</usr/bin> and C</bin>.  If you require a program from
1643 another location, you should provide the full path in the
1644 first parameter.
1645
1646 Shared libraries and data files required by the program
1647 must be available on filesystems which are mounted in the
1648 correct places.  It is the caller's responsibility to ensure
1649 all filesystems that are needed are mounted at the right
1650 locations.");
1651
1652   ("command_lines", (RStringList "lines", [StringList "arguments"]), 51, [ProtocolLimitWarning],
1653    [InitBasicFS, Always, TestOutputList (
1654       [["upload"; "test-command"; "/test-command"];
1655        ["chmod"; "0o755"; "/test-command"];
1656        ["command_lines"; "/test-command 1"]], ["Result1"]);
1657     InitBasicFS, Always, TestOutputList (
1658       [["upload"; "test-command"; "/test-command"];
1659        ["chmod"; "0o755"; "/test-command"];
1660        ["command_lines"; "/test-command 2"]], ["Result2"]);
1661     InitBasicFS, Always, TestOutputList (
1662       [["upload"; "test-command"; "/test-command"];
1663        ["chmod"; "0o755"; "/test-command"];
1664        ["command_lines"; "/test-command 3"]], ["";"Result3"]);
1665     InitBasicFS, Always, TestOutputList (
1666       [["upload"; "test-command"; "/test-command"];
1667        ["chmod"; "0o755"; "/test-command"];
1668        ["command_lines"; "/test-command 4"]], ["";"Result4"]);
1669     InitBasicFS, Always, TestOutputList (
1670       [["upload"; "test-command"; "/test-command"];
1671        ["chmod"; "0o755"; "/test-command"];
1672        ["command_lines"; "/test-command 5"]], ["";"Result5";""]);
1673     InitBasicFS, Always, TestOutputList (
1674       [["upload"; "test-command"; "/test-command"];
1675        ["chmod"; "0o755"; "/test-command"];
1676        ["command_lines"; "/test-command 6"]], ["";"";"Result6";""]);
1677     InitBasicFS, Always, TestOutputList (
1678       [["upload"; "test-command"; "/test-command"];
1679        ["chmod"; "0o755"; "/test-command"];
1680        ["command_lines"; "/test-command 7"]], []);
1681     InitBasicFS, Always, TestOutputList (
1682       [["upload"; "test-command"; "/test-command"];
1683        ["chmod"; "0o755"; "/test-command"];
1684        ["command_lines"; "/test-command 8"]], [""]);
1685     InitBasicFS, Always, TestOutputList (
1686       [["upload"; "test-command"; "/test-command"];
1687        ["chmod"; "0o755"; "/test-command"];
1688        ["command_lines"; "/test-command 9"]], ["";""]);
1689     InitBasicFS, Always, TestOutputList (
1690       [["upload"; "test-command"; "/test-command"];
1691        ["chmod"; "0o755"; "/test-command"];
1692        ["command_lines"; "/test-command 10"]], ["Result10-1";"Result10-2"]);
1693     InitBasicFS, Always, TestOutputList (
1694       [["upload"; "test-command"; "/test-command"];
1695        ["chmod"; "0o755"; "/test-command"];
1696        ["command_lines"; "/test-command 11"]], ["Result11-1";"Result11-2"])],
1697    "run a command, returning lines",
1698    "\
1699 This is the same as C<guestfs_command>, but splits the
1700 result into a list of lines.
1701
1702 See also: C<guestfs_sh_lines>");
1703
1704   ("stat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 52, [],
1705    [InitISOFS, Always, TestOutputStruct (
1706       [["stat"; "/empty"]], [CompareWithInt ("size", 0)])],
1707    "get file information",
1708    "\
1709 Returns file information for the given C<path>.
1710
1711 This is the same as the C<stat(2)> system call.");
1712
1713   ("lstat", (RStruct ("statbuf", "stat"), [Pathname "path"]), 53, [],
1714    [InitISOFS, Always, TestOutputStruct (
1715       [["lstat"; "/empty"]], [CompareWithInt ("size", 0)])],
1716    "get file information for a symbolic link",
1717    "\
1718 Returns file information for the given C<path>.
1719
1720 This is the same as C<guestfs_stat> except that if C<path>
1721 is a symbolic link, then the link is stat-ed, not the file it
1722 refers to.
1723
1724 This is the same as the C<lstat(2)> system call.");
1725
1726   ("statvfs", (RStruct ("statbuf", "statvfs"), [Pathname "path"]), 54, [],
1727    [InitISOFS, Always, TestOutputStruct (
1728       [["statvfs"; "/"]], [CompareWithInt ("namemax", 255)])],
1729    "get file system statistics",
1730    "\
1731 Returns file system statistics for any mounted file system.
1732 C<path> should be a file or directory in the mounted file system
1733 (typically it is the mount point itself, but it doesn't need to be).
1734
1735 This is the same as the C<statvfs(2)> system call.");
1736
1737   ("tune2fs_l", (RHashtable "superblock", [Device "device"]), 55, [],
1738    [], (* XXX test *)
1739    "get ext2/ext3/ext4 superblock details",
1740    "\
1741 This returns the contents of the ext2, ext3 or ext4 filesystem
1742 superblock on C<device>.
1743
1744 It is the same as running C<tune2fs -l device>.  See L<tune2fs(8)>
1745 manpage for more details.  The list of fields returned isn't
1746 clearly defined, and depends on both the version of C<tune2fs>
1747 that libguestfs was built against, and the filesystem itself.");
1748
1749   ("blockdev_setro", (RErr, [Device "device"]), 56, [],
1750    [InitEmpty, Always, TestOutputTrue (
1751       [["blockdev_setro"; "/dev/sda"];
1752        ["blockdev_getro"; "/dev/sda"]])],
1753    "set block device to read-only",
1754    "\
1755 Sets the block device named C<device> to read-only.
1756
1757 This uses the L<blockdev(8)> command.");
1758
1759   ("blockdev_setrw", (RErr, [Device "device"]), 57, [],
1760    [InitEmpty, Always, TestOutputFalse (
1761       [["blockdev_setrw"; "/dev/sda"];
1762        ["blockdev_getro"; "/dev/sda"]])],
1763    "set block device to read-write",
1764    "\
1765 Sets the block device named C<device> to read-write.
1766
1767 This uses the L<blockdev(8)> command.");
1768
1769   ("blockdev_getro", (RBool "ro", [Device "device"]), 58, [],
1770    [InitEmpty, Always, TestOutputTrue (
1771       [["blockdev_setro"; "/dev/sda"];
1772        ["blockdev_getro"; "/dev/sda"]])],
1773    "is block device set to read-only",
1774    "\
1775 Returns a boolean indicating if the block device is read-only
1776 (true if read-only, false if not).
1777
1778 This uses the L<blockdev(8)> command.");
1779
1780   ("blockdev_getss", (RInt "sectorsize", [Device "device"]), 59, [],
1781    [InitEmpty, Always, TestOutputInt (
1782       [["blockdev_getss"; "/dev/sda"]], 512)],
1783    "get sectorsize of block device",
1784    "\
1785 This returns the size of sectors on a block device.
1786 Usually 512, but can be larger for modern devices.
1787
1788 (Note, this is not the size in sectors, use C<guestfs_blockdev_getsz>
1789 for that).
1790
1791 This uses the L<blockdev(8)> command.");
1792
1793   ("blockdev_getbsz", (RInt "blocksize", [Device "device"]), 60, [],
1794    [InitEmpty, Always, TestOutputInt (
1795       [["blockdev_getbsz"; "/dev/sda"]], 4096)],
1796    "get blocksize of block device",
1797    "\
1798 This returns the block size of a device.
1799
1800 (Note this is different from both I<size in blocks> and
1801 I<filesystem block size>).
1802
1803 This uses the L<blockdev(8)> command.");
1804
1805   ("blockdev_setbsz", (RErr, [Device "device"; Int "blocksize"]), 61, [],
1806    [], (* XXX test *)
1807    "set blocksize of block device",
1808    "\
1809 This sets the block size of a device.
1810
1811 (Note this is different from both I<size in blocks> and
1812 I<filesystem block size>).
1813
1814 This uses the L<blockdev(8)> command.");
1815
1816   ("blockdev_getsz", (RInt64 "sizeinsectors", [Device "device"]), 62, [],
1817    [InitEmpty, Always, TestOutputInt (
1818       [["blockdev_getsz"; "/dev/sda"]], 1024000)],
1819    "get total size of device in 512-byte sectors",
1820    "\
1821 This returns the size of the device in units of 512-byte sectors
1822 (even if the sectorsize isn't 512 bytes ... weird).
1823
1824 See also C<guestfs_blockdev_getss> for the real sector size of
1825 the device, and C<guestfs_blockdev_getsize64> for the more
1826 useful I<size in bytes>.
1827
1828 This uses the L<blockdev(8)> command.");
1829
1830   ("blockdev_getsize64", (RInt64 "sizeinbytes", [Device "device"]), 63, [],
1831    [InitEmpty, Always, TestOutputInt (
1832       [["blockdev_getsize64"; "/dev/sda"]], 524288000)],
1833    "get total size of device in bytes",
1834    "\
1835 This returns the size of the device in bytes.
1836
1837 See also C<guestfs_blockdev_getsz>.
1838
1839 This uses the L<blockdev(8)> command.");
1840
1841   ("blockdev_flushbufs", (RErr, [Device "device"]), 64, [],
1842    [InitEmpty, Always, TestRun
1843       [["blockdev_flushbufs"; "/dev/sda"]]],
1844    "flush device buffers",
1845    "\
1846 This tells the kernel to flush internal buffers associated
1847 with C<device>.
1848
1849 This uses the L<blockdev(8)> command.");
1850
1851   ("blockdev_rereadpt", (RErr, [Device "device"]), 65, [],
1852    [InitEmpty, Always, TestRun
1853       [["blockdev_rereadpt"; "/dev/sda"]]],
1854    "reread partition table",
1855    "\
1856 Reread the partition table on C<device>.
1857
1858 This uses the L<blockdev(8)> command.");
1859
1860   ("upload", (RErr, [FileIn "filename"; String "remotefilename"]), 66, [],
1861    [InitBasicFS, Always, TestOutput (
1862       (* Pick a file from cwd which isn't likely to change. *)
1863       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1864        ["checksum"; "md5"; "/COPYING.LIB"]],
1865         Digest.to_hex (Digest.file "COPYING.LIB"))],
1866    "upload a file from the local machine",
1867    "\
1868 Upload local file C<filename> to C<remotefilename> on the
1869 filesystem.
1870
1871 C<filename> can also be a named pipe.
1872
1873 See also C<guestfs_download>.");
1874
1875   ("download", (RErr, [Dev_or_Path "remotefilename"; FileOut "filename"]), 67, [],
1876    [InitBasicFS, Always, TestOutput (
1877       (* Pick a file from cwd which isn't likely to change. *)
1878       [["upload"; "../COPYING.LIB"; "/COPYING.LIB"];
1879        ["download"; "/COPYING.LIB"; "testdownload.tmp"];
1880        ["upload"; "testdownload.tmp"; "/upload"];
1881        ["checksum"; "md5"; "/upload"]],
1882         Digest.to_hex (Digest.file "COPYING.LIB"))],
1883    "download a file to the local machine",
1884    "\
1885 Download file C<remotefilename> and save it as C<filename>
1886 on the local machine.
1887
1888 C<filename> can also be a named pipe.
1889
1890 See also C<guestfs_upload>, C<guestfs_cat>.");
1891
1892   ("checksum", (RString "checksum", [String "csumtype"; Pathname "path"]), 68, [],
1893    [InitISOFS, Always, TestOutput (
1894       [["checksum"; "crc"; "/known-3"]], "2891671662");
1895     InitISOFS, Always, TestLastFail (
1896       [["checksum"; "crc"; "/notexists"]]);
1897     InitISOFS, Always, TestOutput (
1898       [["checksum"; "md5"; "/known-3"]], "46d6ca27ee07cdc6fa99c2e138cc522c");
1899     InitISOFS, Always, TestOutput (
1900       [["checksum"; "sha1"; "/known-3"]], "b7ebccc3ee418311091c3eda0a45b83c0a770f15");
1901     InitISOFS, Always, TestOutput (
1902       [["checksum"; "sha224"; "/known-3"]], "d2cd1774b28f3659c14116be0a6dc2bb5c4b350ce9cd5defac707741");
1903     InitISOFS, Always, TestOutput (
1904       [["checksum"; "sha256"; "/known-3"]], "75bb71b90cd20cb13f86d2bea8dad63ac7194e7517c3b52b8d06ff52d3487d30");
1905     InitISOFS, Always, TestOutput (
1906       [["checksum"; "sha384"; "/known-3"]], "5fa7883430f357b5d7b7271d3a1d2872b51d73cba72731de6863d3dea55f30646af2799bef44d5ea776a5ec7941ac640");
1907     InitISOFS, Always, TestOutput (
1908       [["checksum"; "sha512"; "/known-3"]], "2794062c328c6b216dca90443b7f7134c5f40e56bd0ed7853123275a09982a6f992e6ca682f9d2fba34a4c5e870d8fe077694ff831e3032a004ee077e00603f6")],
1909    "compute MD5, SHAx or CRC checksum of file",
1910    "\
1911 This call computes the MD5, SHAx or CRC checksum of the
1912 file named C<path>.
1913
1914 The type of checksum to compute is given by the C<csumtype>
1915 parameter which must have one of the following values:
1916
1917 =over 4
1918
1919 =item C<crc>
1920
1921 Compute the cyclic redundancy check (CRC) specified by POSIX
1922 for the C<cksum> command.
1923
1924 =item C<md5>
1925
1926 Compute the MD5 hash (using the C<md5sum> program).
1927
1928 =item C<sha1>
1929
1930 Compute the SHA1 hash (using the C<sha1sum> program).
1931
1932 =item C<sha224>
1933
1934 Compute the SHA224 hash (using the C<sha224sum> program).
1935
1936 =item C<sha256>
1937
1938 Compute the SHA256 hash (using the C<sha256sum> program).
1939
1940 =item C<sha384>
1941
1942 Compute the SHA384 hash (using the C<sha384sum> program).
1943
1944 =item C<sha512>
1945
1946 Compute the SHA512 hash (using the C<sha512sum> program).
1947
1948 =back
1949
1950 The checksum is returned as a printable string.");
1951
1952   ("tar_in", (RErr, [FileIn "tarfile"; String "directory"]), 69, [],
1953    [InitBasicFS, Always, TestOutput (
1954       [["tar_in"; "../images/helloworld.tar"; "/"];
1955        ["cat"; "/hello"]], "hello\n")],
1956    "unpack tarfile to directory",
1957    "\
1958 This command uploads and unpacks local file C<tarfile> (an
1959 I<uncompressed> tar file) into C<directory>.
1960
1961 To upload a compressed tarball, use C<guestfs_tgz_in>.");
1962
1963   ("tar_out", (RErr, [String "directory"; FileOut "tarfile"]), 70, [],
1964    [],
1965    "pack directory into tarfile",
1966    "\
1967 This command packs the contents of C<directory> and downloads
1968 it to local file C<tarfile>.
1969
1970 To download a compressed tarball, use C<guestfs_tgz_out>.");
1971
1972   ("tgz_in", (RErr, [FileIn "tarball"; String "directory"]), 71, [],
1973    [InitBasicFS, Always, TestOutput (
1974       [["tgz_in"; "../images/helloworld.tar.gz"; "/"];
1975        ["cat"; "/hello"]], "hello\n")],
1976    "unpack compressed tarball to directory",
1977    "\
1978 This command uploads and unpacks local file C<tarball> (a
1979 I<gzip compressed> tar file) into C<directory>.
1980
1981 To upload an uncompressed tarball, use C<guestfs_tar_in>.");
1982
1983   ("tgz_out", (RErr, [Pathname "directory"; FileOut "tarball"]), 72, [],
1984    [],
1985    "pack directory into compressed tarball",
1986    "\
1987 This command packs the contents of C<directory> and downloads
1988 it to local file C<tarball>.
1989
1990 To download an uncompressed tarball, use C<guestfs_tar_out>.");
1991
1992   ("mount_ro", (RErr, [Device "device"; String "mountpoint"]), 73, [],
1993    [InitBasicFS, Always, TestLastFail (
1994       [["umount"; "/"];
1995        ["mount_ro"; "/dev/sda1"; "/"];
1996        ["touch"; "/new"]]);
1997     InitBasicFS, Always, TestOutput (
1998       [["write_file"; "/new"; "data"; "0"];
1999        ["umount"; "/"];
2000        ["mount_ro"; "/dev/sda1"; "/"];
2001        ["cat"; "/new"]], "data")],
2002    "mount a guest disk, read-only",
2003    "\
2004 This is the same as the C<guestfs_mount> command, but it
2005 mounts the filesystem with the read-only (I<-o ro>) flag.");
2006
2007   ("mount_options", (RErr, [String "options"; Device "device"; String "mountpoint"]), 74, [],
2008    [],
2009    "mount a guest disk with mount options",
2010    "\
2011 This is the same as the C<guestfs_mount> command, but it
2012 allows you to set the mount options as for the
2013 L<mount(8)> I<-o> flag.");
2014
2015   ("mount_vfs", (RErr, [String "options"; String "vfstype"; Device "device"; String "mountpoint"]), 75, [],
2016    [],
2017    "mount a guest disk with mount options and vfstype",
2018    "\
2019 This is the same as the C<guestfs_mount> command, but it
2020 allows you to set both the mount options and the vfstype
2021 as for the L<mount(8)> I<-o> and I<-t> flags.");
2022
2023   ("debug", (RString "result", [String "subcmd"; StringList "extraargs"]), 76, [],
2024    [],
2025    "debugging and internals",
2026    "\
2027 The C<guestfs_debug> command exposes some internals of
2028 C<guestfsd> (the guestfs daemon) that runs inside the
2029 qemu subprocess.
2030
2031 There is no comprehensive help for this command.  You have
2032 to look at the file C<daemon/debug.c> in the libguestfs source
2033 to find out what you can do.");
2034
2035   ("lvremove", (RErr, [Device "device"]), 77, [],
2036    [InitEmpty, Always, TestOutputList (
2037       [["sfdiskM"; "/dev/sda"; ","];
2038        ["pvcreate"; "/dev/sda1"];
2039        ["vgcreate"; "VG"; "/dev/sda1"];
2040        ["lvcreate"; "LV1"; "VG"; "50"];
2041        ["lvcreate"; "LV2"; "VG"; "50"];
2042        ["lvremove"; "/dev/VG/LV1"];
2043        ["lvs"]], ["/dev/VG/LV2"]);
2044     InitEmpty, Always, TestOutputList (
2045       [["sfdiskM"; "/dev/sda"; ","];
2046        ["pvcreate"; "/dev/sda1"];
2047        ["vgcreate"; "VG"; "/dev/sda1"];
2048        ["lvcreate"; "LV1"; "VG"; "50"];
2049        ["lvcreate"; "LV2"; "VG"; "50"];
2050        ["lvremove"; "/dev/VG"];
2051        ["lvs"]], []);
2052     InitEmpty, Always, TestOutputList (
2053       [["sfdiskM"; "/dev/sda"; ","];
2054        ["pvcreate"; "/dev/sda1"];
2055        ["vgcreate"; "VG"; "/dev/sda1"];
2056        ["lvcreate"; "LV1"; "VG"; "50"];
2057        ["lvcreate"; "LV2"; "VG"; "50"];
2058        ["lvremove"; "/dev/VG"];
2059        ["vgs"]], ["VG"])],
2060    "remove an LVM logical volume",
2061    "\
2062 Remove an LVM logical volume C<device>, where C<device> is
2063 the path to the LV, such as C</dev/VG/LV>.
2064
2065 You can also remove all LVs in a volume group by specifying
2066 the VG name, C</dev/VG>.");
2067
2068   ("vgremove", (RErr, [String "vgname"]), 78, [],
2069    [InitEmpty, Always, TestOutputList (
2070       [["sfdiskM"; "/dev/sda"; ","];
2071        ["pvcreate"; "/dev/sda1"];
2072        ["vgcreate"; "VG"; "/dev/sda1"];
2073        ["lvcreate"; "LV1"; "VG"; "50"];
2074        ["lvcreate"; "LV2"; "VG"; "50"];
2075        ["vgremove"; "VG"];
2076        ["lvs"]], []);
2077     InitEmpty, Always, TestOutputList (
2078       [["sfdiskM"; "/dev/sda"; ","];
2079        ["pvcreate"; "/dev/sda1"];
2080        ["vgcreate"; "VG"; "/dev/sda1"];
2081        ["lvcreate"; "LV1"; "VG"; "50"];
2082        ["lvcreate"; "LV2"; "VG"; "50"];
2083        ["vgremove"; "VG"];
2084        ["vgs"]], [])],
2085    "remove an LVM volume group",
2086    "\
2087 Remove an LVM volume group C<vgname>, (for example C<VG>).
2088
2089 This also forcibly removes all logical volumes in the volume
2090 group (if any).");
2091
2092   ("pvremove", (RErr, [Device "device"]), 79, [],
2093    [InitEmpty, Always, TestOutputListOfDevices (
2094       [["sfdiskM"; "/dev/sda"; ","];
2095        ["pvcreate"; "/dev/sda1"];
2096        ["vgcreate"; "VG"; "/dev/sda1"];
2097        ["lvcreate"; "LV1"; "VG"; "50"];
2098        ["lvcreate"; "LV2"; "VG"; "50"];
2099        ["vgremove"; "VG"];
2100        ["pvremove"; "/dev/sda1"];
2101        ["lvs"]], []);
2102     InitEmpty, Always, TestOutputListOfDevices (
2103       [["sfdiskM"; "/dev/sda"; ","];
2104        ["pvcreate"; "/dev/sda1"];
2105        ["vgcreate"; "VG"; "/dev/sda1"];
2106        ["lvcreate"; "LV1"; "VG"; "50"];
2107        ["lvcreate"; "LV2"; "VG"; "50"];
2108        ["vgremove"; "VG"];
2109        ["pvremove"; "/dev/sda1"];
2110        ["vgs"]], []);
2111     InitEmpty, Always, TestOutputListOfDevices (
2112       [["sfdiskM"; "/dev/sda"; ","];
2113        ["pvcreate"; "/dev/sda1"];
2114        ["vgcreate"; "VG"; "/dev/sda1"];
2115        ["lvcreate"; "LV1"; "VG"; "50"];
2116        ["lvcreate"; "LV2"; "VG"; "50"];
2117        ["vgremove"; "VG"];
2118        ["pvremove"; "/dev/sda1"];
2119        ["pvs"]], [])],
2120    "remove an LVM physical volume",
2121    "\
2122 This wipes a physical volume C<device> so that LVM will no longer
2123 recognise it.
2124
2125 The implementation uses the C<pvremove> command which refuses to
2126 wipe physical volumes that contain any volume groups, so you have
2127 to remove those first.");
2128
2129   ("set_e2label", (RErr, [Device "device"; String "label"]), 80, [],
2130    [InitBasicFS, Always, TestOutput (
2131       [["set_e2label"; "/dev/sda1"; "testlabel"];
2132        ["get_e2label"; "/dev/sda1"]], "testlabel")],
2133    "set the ext2/3/4 filesystem label",
2134    "\
2135 This sets the ext2/3/4 filesystem label of the filesystem on
2136 C<device> to C<label>.  Filesystem labels are limited to
2137 16 characters.
2138
2139 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2label>
2140 to return the existing label on a filesystem.");
2141
2142   ("get_e2label", (RString "label", [Device "device"]), 81, [],
2143    [],
2144    "get the ext2/3/4 filesystem label",
2145    "\
2146 This returns the ext2/3/4 filesystem label of the filesystem on
2147 C<device>.");
2148
2149   ("set_e2uuid", (RErr, [Device "device"; String "uuid"]), 82, [],
2150    (let uuid = uuidgen () in
2151     [InitBasicFS, Always, TestOutput (
2152        [["set_e2uuid"; "/dev/sda1"; uuid];
2153         ["get_e2uuid"; "/dev/sda1"]], uuid);
2154      InitBasicFS, Always, TestOutput (
2155        [["set_e2uuid"; "/dev/sda1"; "clear"];
2156         ["get_e2uuid"; "/dev/sda1"]], "");
2157      (* We can't predict what UUIDs will be, so just check the commands run. *)
2158      InitBasicFS, Always, TestRun (
2159        [["set_e2uuid"; "/dev/sda1"; "random"]]);
2160      InitBasicFS, Always, TestRun (
2161        [["set_e2uuid"; "/dev/sda1"; "time"]])]),
2162    "set the ext2/3/4 filesystem UUID",
2163    "\
2164 This sets the ext2/3/4 filesystem UUID of the filesystem on
2165 C<device> to C<uuid>.  The format of the UUID and alternatives
2166 such as C<clear>, C<random> and C<time> are described in the
2167 L<tune2fs(8)> manpage.
2168
2169 You can use either C<guestfs_tune2fs_l> or C<guestfs_get_e2uuid>
2170 to return the existing UUID of a filesystem.");
2171
2172   ("get_e2uuid", (RString "uuid", [Device "device"]), 83, [],
2173    [],
2174    "get the ext2/3/4 filesystem UUID",
2175    "\
2176 This returns the ext2/3/4 filesystem UUID of the filesystem on
2177 C<device>.");
2178
2179   ("fsck", (RInt "status", [String "fstype"; Device "device"]), 84, [],
2180    [InitBasicFS, Always, TestOutputInt (
2181       [["umount"; "/dev/sda1"];
2182        ["fsck"; "ext2"; "/dev/sda1"]], 0);
2183     InitBasicFS, Always, TestOutputInt (
2184       [["umount"; "/dev/sda1"];
2185        ["zero"; "/dev/sda1"];
2186        ["fsck"; "ext2"; "/dev/sda1"]], 8)],
2187    "run the filesystem checker",
2188    "\
2189 This runs the filesystem checker (fsck) on C<device> which
2190 should have filesystem type C<fstype>.
2191
2192 The returned integer is the status.  See L<fsck(8)> for the
2193 list of status codes from C<fsck>.
2194
2195 Notes:
2196
2197 =over 4
2198
2199 =item *
2200
2201 Multiple status codes can be summed together.
2202
2203 =item *
2204
2205 A non-zero return code can mean \"success\", for example if
2206 errors have been corrected on the filesystem.
2207
2208 =item *
2209
2210 Checking or repairing NTFS volumes is not supported
2211 (by linux-ntfs).
2212
2213 =back
2214
2215 This command is entirely equivalent to running C<fsck -a -t fstype device>.");
2216
2217   ("zero", (RErr, [Device "device"]), 85, [],
2218    [InitBasicFS, Always, TestOutput (
2219       [["umount"; "/dev/sda1"];
2220        ["zero"; "/dev/sda1"];
2221        ["file"; "/dev/sda1"]], "data")],
2222    "write zeroes to the device",
2223    "\
2224 This command writes zeroes over the first few blocks of C<device>.
2225
2226 How many blocks are zeroed isn't specified (but it's I<not> enough
2227 to securely wipe the device).  It should be sufficient to remove
2228 any partition tables, filesystem superblocks and so on.
2229
2230 See also: C<guestfs_scrub_device>.");
2231
2232   ("grub_install", (RErr, [Pathname "root"; Device "device"]), 86, [],
2233    (* Test disabled because grub-install incompatible with virtio-blk driver.
2234     * See also: https://bugzilla.redhat.com/show_bug.cgi?id=479760
2235     *)
2236    [InitBasicFS, Disabled, TestOutputTrue (
2237       [["grub_install"; "/"; "/dev/sda1"];
2238        ["is_dir"; "/boot"]])],
2239    "install GRUB",
2240    "\
2241 This command installs GRUB (the Grand Unified Bootloader) on
2242 C<device>, with the root directory being C<root>.");
2243
2244   ("cp", (RErr, [Pathname "src"; Pathname "dest"]), 87, [],
2245    [InitBasicFS, Always, TestOutput (
2246       [["write_file"; "/old"; "file content"; "0"];
2247        ["cp"; "/old"; "/new"];
2248        ["cat"; "/new"]], "file content");
2249     InitBasicFS, Always, TestOutputTrue (
2250       [["write_file"; "/old"; "file content"; "0"];
2251        ["cp"; "/old"; "/new"];
2252        ["is_file"; "/old"]]);
2253     InitBasicFS, Always, TestOutput (
2254       [["write_file"; "/old"; "file content"; "0"];
2255        ["mkdir"; "/dir"];
2256        ["cp"; "/old"; "/dir/new"];
2257        ["cat"; "/dir/new"]], "file content")],
2258    "copy a file",
2259    "\
2260 This copies a file from C<src> to C<dest> where C<dest> is
2261 either a destination filename or destination directory.");
2262
2263   ("cp_a", (RErr, [Pathname "src"; Pathname "dest"]), 88, [],
2264    [InitBasicFS, Always, TestOutput (
2265       [["mkdir"; "/olddir"];
2266        ["mkdir"; "/newdir"];
2267        ["write_file"; "/olddir/file"; "file content"; "0"];
2268        ["cp_a"; "/olddir"; "/newdir"];
2269        ["cat"; "/newdir/olddir/file"]], "file content")],
2270    "copy a file or directory recursively",
2271    "\
2272 This copies a file or directory from C<src> to C<dest>
2273 recursively using the C<cp -a> command.");
2274
2275   ("mv", (RErr, [Pathname "src"; Pathname "dest"]), 89, [],
2276    [InitBasicFS, Always, TestOutput (
2277       [["write_file"; "/old"; "file content"; "0"];
2278        ["mv"; "/old"; "/new"];
2279        ["cat"; "/new"]], "file content");
2280     InitBasicFS, Always, TestOutputFalse (
2281       [["write_file"; "/old"; "file content"; "0"];
2282        ["mv"; "/old"; "/new"];
2283        ["is_file"; "/old"]])],
2284    "move a file",
2285    "\
2286 This moves a file from C<src> to C<dest> where C<dest> is
2287 either a destination filename or destination directory.");
2288
2289   ("drop_caches", (RErr, [Int "whattodrop"]), 90, [],
2290    [InitEmpty, Always, TestRun (
2291       [["drop_caches"; "3"]])],
2292    "drop kernel page cache, dentries and inodes",
2293    "\
2294 This instructs the guest kernel to drop its page cache,
2295 and/or dentries and inode caches.  The parameter C<whattodrop>
2296 tells the kernel what precisely to drop, see
2297 L<http://linux-mm.org/Drop_Caches>
2298
2299 Setting C<whattodrop> to 3 should drop everything.
2300
2301 This automatically calls L<sync(2)> before the operation,
2302 so that the maximum guest memory is freed.");
2303
2304   ("dmesg", (RString "kmsgs", []), 91, [],
2305    [InitEmpty, Always, TestRun (
2306       [["dmesg"]])],
2307    "return kernel messages",
2308    "\
2309 This returns the kernel messages (C<dmesg> output) from
2310 the guest kernel.  This is sometimes useful for extended
2311 debugging of problems.
2312
2313 Another way to get the same information is to enable
2314 verbose messages with C<guestfs_set_verbose> or by setting
2315 the environment variable C<LIBGUESTFS_DEBUG=1> before
2316 running the program.");
2317
2318   ("ping_daemon", (RErr, []), 92, [],
2319    [InitEmpty, Always, TestRun (
2320       [["ping_daemon"]])],
2321    "ping the guest daemon",
2322    "\
2323 This is a test probe into the guestfs daemon running inside
2324 the qemu subprocess.  Calling this function checks that the
2325 daemon responds to the ping message, without affecting the daemon
2326 or attached block device(s) in any other way.");
2327
2328   ("equal", (RBool "equality", [Pathname "file1"; Pathname "file2"]), 93, [],
2329    [InitBasicFS, Always, TestOutputTrue (
2330       [["write_file"; "/file1"; "contents of a file"; "0"];
2331        ["cp"; "/file1"; "/file2"];
2332        ["equal"; "/file1"; "/file2"]]);
2333     InitBasicFS, Always, TestOutputFalse (
2334       [["write_file"; "/file1"; "contents of a file"; "0"];
2335        ["write_file"; "/file2"; "contents of another file"; "0"];
2336        ["equal"; "/file1"; "/file2"]]);
2337     InitBasicFS, Always, TestLastFail (
2338       [["equal"; "/file1"; "/file2"]])],
2339    "test if two files have equal contents",
2340    "\
2341 This compares the two files C<file1> and C<file2> and returns
2342 true if their content is exactly equal, or false otherwise.
2343
2344 The external L<cmp(1)> program is used for the comparison.");
2345
2346   ("strings", (RStringList "stringsout", [Pathname "path"]), 94, [ProtocolLimitWarning],
2347    [InitISOFS, Always, TestOutputList (
2348       [["strings"; "/known-5"]], ["abcdefghi"; "jklmnopqr"]);
2349     InitISOFS, Always, TestOutputList (
2350       [["strings"; "/empty"]], [])],
2351    "print the printable strings in a file",
2352    "\
2353 This runs the L<strings(1)> command on a file and returns
2354 the list of printable strings found.");
2355
2356   ("strings_e", (RStringList "stringsout", [String "encoding"; Pathname "path"]), 95, [ProtocolLimitWarning],
2357    [InitISOFS, Always, TestOutputList (
2358       [["strings_e"; "b"; "/known-5"]], []);
2359     InitBasicFS, Disabled, TestOutputList (
2360       [["write_file"; "/new"; "\000h\000e\000l\000l\000o\000\n\000w\000o\000r\000l\000d\000\n"; "24"];
2361        ["strings_e"; "b"; "/new"]], ["hello"; "world"])],
2362    "print the printable strings in a file",
2363    "\
2364 This is like the C<guestfs_strings> command, but allows you to
2365 specify the encoding.
2366
2367 See the L<strings(1)> manpage for the full list of encodings.
2368
2369 Commonly useful encodings are C<l> (lower case L) which will
2370 show strings inside Windows/x86 files.
2371
2372 The returned strings are transcoded to UTF-8.");
2373
2374   ("hexdump", (RString "dump", [Pathname "path"]), 96, [ProtocolLimitWarning],
2375    [InitISOFS, Always, TestOutput (
2376       [["hexdump"; "/known-4"]], "00000000  61 62 63 0a 64 65 66 0a  67 68 69                 |abc.def.ghi|\n0000000b\n");
2377     (* Test for RHBZ#501888c2 regression which caused large hexdump
2378      * commands to segfault.
2379      *)
2380     InitISOFS, Always, TestRun (
2381       [["hexdump"; "/100krandom"]])],
2382    "dump a file in hexadecimal",
2383    "\
2384 This runs C<hexdump -C> on the given C<path>.  The result is
2385 the human-readable, canonical hex dump of the file.");
2386
2387   ("zerofree", (RErr, [Device "device"]), 97, [],
2388    [InitNone, Always, TestOutput (
2389       [["sfdiskM"; "/dev/sda"; ","];
2390        ["mkfs"; "ext3"; "/dev/sda1"];
2391        ["mount"; "/dev/sda1"; "/"];
2392        ["write_file"; "/new"; "test file"; "0"];
2393        ["umount"; "/dev/sda1"];
2394        ["zerofree"; "/dev/sda1"];
2395        ["mount"; "/dev/sda1"; "/"];
2396        ["cat"; "/new"]], "test file")],
2397    "zero unused inodes and disk blocks on ext2/3 filesystem",
2398    "\
2399 This runs the I<zerofree> program on C<device>.  This program
2400 claims to zero unused inodes and disk blocks on an ext2/3
2401 filesystem, thus making it possible to compress the filesystem
2402 more effectively.
2403
2404 You should B<not> run this program if the filesystem is
2405 mounted.
2406
2407 It is possible that using this program can damage the filesystem
2408 or data on the filesystem.");
2409
2410   ("pvresize", (RErr, [Device "device"]), 98, [],
2411    [],
2412    "resize an LVM physical volume",
2413    "\
2414 This resizes (expands or shrinks) an existing LVM physical
2415 volume to match the new size of the underlying device.");
2416
2417   ("sfdisk_N", (RErr, [Device "device"; Int "partnum";
2418                        Int "cyls"; Int "heads"; Int "sectors";
2419                        String "line"]), 99, [DangerWillRobinson],
2420    [],
2421    "modify a single partition on a block device",
2422    "\
2423 This runs L<sfdisk(8)> option to modify just the single
2424 partition C<n> (note: C<n> counts from 1).
2425
2426 For other parameters, see C<guestfs_sfdisk>.  You should usually
2427 pass C<0> for the cyls/heads/sectors parameters.");
2428
2429   ("sfdisk_l", (RString "partitions", [Device "device"]), 100, [],
2430    [],
2431    "display the partition table",
2432    "\
2433 This displays the partition table on C<device>, in the
2434 human-readable output of the L<sfdisk(8)> command.  It is
2435 not intended to be parsed.");
2436
2437   ("sfdisk_kernel_geometry", (RString "partitions", [Device "device"]), 101, [],
2438    [],
2439    "display the kernel geometry",
2440    "\
2441 This displays the kernel's idea of the geometry of C<device>.
2442
2443 The result is in human-readable format, and not designed to
2444 be parsed.");
2445
2446   ("sfdisk_disk_geometry", (RString "partitions", [Device "device"]), 102, [],
2447    [],
2448    "display the disk geometry from the partition table",
2449    "\
2450 This displays the disk geometry of C<device> read from the
2451 partition table.  Especially in the case where the underlying
2452 block device has been resized, this can be different from the
2453 kernel's idea of the geometry (see C<guestfs_sfdisk_kernel_geometry>).
2454
2455 The result is in human-readable format, and not designed to
2456 be parsed.");
2457
2458   ("vg_activate_all", (RErr, [Bool "activate"]), 103, [],
2459    [],
2460    "activate or deactivate all volume groups",
2461    "\
2462 This command activates or (if C<activate> is false) deactivates
2463 all logical volumes in all volume groups.
2464 If activated, then they are made known to the
2465 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2466 then those devices disappear.
2467
2468 This command is the same as running C<vgchange -a y|n>");
2469
2470   ("vg_activate", (RErr, [Bool "activate"; StringList "volgroups"]), 104, [],
2471    [],
2472    "activate or deactivate some volume groups",
2473    "\
2474 This command activates or (if C<activate> is false) deactivates
2475 all logical volumes in the listed volume groups C<volgroups>.
2476 If activated, then they are made known to the
2477 kernel, ie. they appear as C</dev/mapper> devices.  If deactivated,
2478 then those devices disappear.
2479
2480 This command is the same as running C<vgchange -a y|n volgroups...>
2481
2482 Note that if C<volgroups> is an empty list then B<all> volume groups
2483 are activated or deactivated.");
2484
2485   ("lvresize", (RErr, [Device "device"; Int "mbytes"]), 105, [],
2486    [InitNone, Always, TestOutput (
2487       [["sfdiskM"; "/dev/sda"; ","];
2488        ["pvcreate"; "/dev/sda1"];
2489        ["vgcreate"; "VG"; "/dev/sda1"];
2490        ["lvcreate"; "LV"; "VG"; "10"];
2491        ["mkfs"; "ext2"; "/dev/VG/LV"];
2492        ["mount"; "/dev/VG/LV"; "/"];
2493        ["write_file"; "/new"; "test content"; "0"];
2494        ["umount"; "/"];
2495        ["lvresize"; "/dev/VG/LV"; "20"];
2496        ["e2fsck_f"; "/dev/VG/LV"];
2497        ["resize2fs"; "/dev/VG/LV"];
2498        ["mount"; "/dev/VG/LV"; "/"];
2499        ["cat"; "/new"]], "test content")],
2500    "resize an LVM logical volume",
2501    "\
2502 This resizes (expands or shrinks) an existing LVM logical
2503 volume to C<mbytes>.  When reducing, data in the reduced part
2504 is lost.");
2505
2506   ("resize2fs", (RErr, [Device "device"]), 106, [],
2507    [], (* lvresize tests this *)
2508    "resize an ext2/ext3 filesystem",
2509    "\
2510 This resizes an ext2 or ext3 filesystem to match the size of
2511 the underlying device.
2512
2513 I<Note:> It is sometimes required that you run C<guestfs_e2fsck_f>
2514 on the C<device> before calling this command.  For unknown reasons
2515 C<resize2fs> sometimes gives an error about this and sometimes not.
2516 In any case, it is always safe to call C<guestfs_e2fsck_f> before
2517 calling this function.");
2518
2519   ("find", (RStringList "names", [Pathname "directory"]), 107, [ProtocolLimitWarning],
2520    [InitBasicFS, Always, TestOutputList (
2521       [["find"; "/"]], ["lost+found"]);
2522     InitBasicFS, Always, TestOutputList (
2523       [["touch"; "/a"];
2524        ["mkdir"; "/b"];
2525        ["touch"; "/b/c"];
2526        ["find"; "/"]], ["a"; "b"; "b/c"; "lost+found"]);
2527     InitBasicFS, Always, TestOutputList (
2528       [["mkdir_p"; "/a/b/c"];
2529        ["touch"; "/a/b/c/d"];
2530        ["find"; "/a/b/"]], ["c"; "c/d"])],
2531    "find all files and directories",
2532    "\
2533 This command lists out all files and directories, recursively,
2534 starting at C<directory>.  It is essentially equivalent to
2535 running the shell command C<find directory -print> but some
2536 post-processing happens on the output, described below.
2537
2538 This returns a list of strings I<without any prefix>.  Thus
2539 if the directory structure was:
2540
2541  /tmp/a
2542  /tmp/b
2543  /tmp/c/d
2544
2545 then the returned list from C<guestfs_find> C</tmp> would be
2546 4 elements:
2547
2548  a
2549  b
2550  c
2551  c/d
2552
2553 If C<directory> is not a directory, then this command returns
2554 an error.
2555
2556 The returned list is sorted.
2557
2558 See also C<guestfs_find0>.");
2559
2560   ("e2fsck_f", (RErr, [Device "device"]), 108, [],
2561    [], (* lvresize tests this *)
2562    "check an ext2/ext3 filesystem",
2563    "\
2564 This runs C<e2fsck -p -f device>, ie. runs the ext2/ext3
2565 filesystem checker on C<device>, noninteractively (C<-p>),
2566 even if the filesystem appears to be clean (C<-f>).
2567
2568 This command is only needed because of C<guestfs_resize2fs>
2569 (q.v.).  Normally you should use C<guestfs_fsck>.");
2570
2571   ("sleep", (RErr, [Int "secs"]), 109, [],
2572    [InitNone, Always, TestRun (
2573       [["sleep"; "1"]])],
2574    "sleep for some seconds",
2575    "\
2576 Sleep for C<secs> seconds.");
2577
2578   ("ntfs_3g_probe", (RInt "status", [Bool "rw"; Device "device"]), 110, [],
2579    [InitNone, Always, TestOutputInt (
2580       [["sfdiskM"; "/dev/sda"; ","];
2581        ["mkfs"; "ntfs"; "/dev/sda1"];
2582        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 0);
2583     InitNone, Always, TestOutputInt (
2584       [["sfdiskM"; "/dev/sda"; ","];
2585        ["mkfs"; "ext2"; "/dev/sda1"];
2586        ["ntfs_3g_probe"; "true"; "/dev/sda1"]], 12)],
2587    "probe NTFS volume",
2588    "\
2589 This command runs the L<ntfs-3g.probe(8)> command which probes
2590 an NTFS C<device> for mountability.  (Not all NTFS volumes can
2591 be mounted read-write, and some cannot be mounted at all).
2592
2593 C<rw> is a boolean flag.  Set it to true if you want to test
2594 if the volume can be mounted read-write.  Set it to false if
2595 you want to test if the volume can be mounted read-only.
2596
2597 The return value is an integer which C<0> if the operation
2598 would succeed, or some non-zero value documented in the
2599 L<ntfs-3g.probe(8)> manual page.");
2600
2601   ("sh", (RString "output", [String "command"]), 111, [],
2602    [], (* XXX needs tests *)
2603    "run a command via the shell",
2604    "\
2605 This call runs a command from the guest filesystem via the
2606 guest's C</bin/sh>.
2607
2608 This is like C<guestfs_command>, but passes the command to:
2609
2610  /bin/sh -c \"command\"
2611
2612 Depending on the guest's shell, this usually results in
2613 wildcards being expanded, shell expressions being interpolated
2614 and so on.
2615
2616 All the provisos about C<guestfs_command> apply to this call.");
2617
2618   ("sh_lines", (RStringList "lines", [String "command"]), 112, [],
2619    [], (* XXX needs tests *)
2620    "run a command via the shell returning lines",
2621    "\
2622 This is the same as C<guestfs_sh>, but splits the result
2623 into a list of lines.
2624
2625 See also: C<guestfs_command_lines>");
2626
2627   ("glob_expand", (RStringList "paths", [Pathname "pattern"]), 113, [],
2628    (* Use Pathname here, and hence ABS_PATH (pattern,... in generated
2629     * code in stubs.c, since all valid glob patterns must start with "/".
2630     * There is no concept of "cwd" in libguestfs, hence no "."-relative names.
2631     *)
2632    [InitBasicFS, Always, TestOutputList (
2633       [["mkdir_p"; "/a/b/c"];
2634        ["touch"; "/a/b/c/d"];
2635        ["touch"; "/a/b/c/e"];
2636        ["glob_expand"; "/a/b/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2637     InitBasicFS, Always, TestOutputList (
2638       [["mkdir_p"; "/a/b/c"];
2639        ["touch"; "/a/b/c/d"];
2640        ["touch"; "/a/b/c/e"];
2641        ["glob_expand"; "/a/*/c/*"]], ["/a/b/c/d"; "/a/b/c/e"]);
2642     InitBasicFS, Always, TestOutputList (
2643       [["mkdir_p"; "/a/b/c"];
2644        ["touch"; "/a/b/c/d"];
2645        ["touch"; "/a/b/c/e"];
2646        ["glob_expand"; "/a/*/x/*"]], [])],
2647    "expand a wildcard path",
2648    "\
2649 This command searches for all the pathnames matching
2650 C<pattern> according to the wildcard expansion rules
2651 used by the shell.
2652
2653 If no paths match, then this returns an empty list
2654 (note: not an error).
2655
2656 It is just a wrapper around the C L<glob(3)> function
2657 with flags C<GLOB_MARK|GLOB_BRACE>.
2658 See that manual page for more details.");
2659
2660   ("scrub_device", (RErr, [Device "device"]), 114, [DangerWillRobinson],
2661    [InitNone, Always, TestRun ( (* use /dev/sdc because it's smaller *)
2662       [["scrub_device"; "/dev/sdc"]])],
2663    "scrub (securely wipe) a device",
2664    "\
2665 This command writes patterns over C<device> to make data retrieval
2666 more difficult.
2667
2668 It is an interface to the L<scrub(1)> program.  See that
2669 manual page for more details.");
2670
2671   ("scrub_file", (RErr, [Pathname "file"]), 115, [],
2672    [InitBasicFS, Always, TestRun (
2673       [["write_file"; "/file"; "content"; "0"];
2674        ["scrub_file"; "/file"]])],
2675    "scrub (securely wipe) a file",
2676    "\
2677 This command writes patterns over a file to make data retrieval
2678 more difficult.
2679
2680 The file is I<removed> after scrubbing.
2681
2682 It is an interface to the L<scrub(1)> program.  See that
2683 manual page for more details.");
2684
2685   ("scrub_freespace", (RErr, [Pathname "dir"]), 116, [],
2686    [], (* XXX needs testing *)
2687    "scrub (securely wipe) free space",
2688    "\
2689 This command creates the directory C<dir> and then fills it
2690 with files until the filesystem is full, and scrubs the files
2691 as for C<guestfs_scrub_file>, and deletes them.
2692 The intention is to scrub any free space on the partition
2693 containing C<dir>.
2694
2695 It is an interface to the L<scrub(1)> program.  See that
2696 manual page for more details.");
2697
2698   ("mkdtemp", (RString "dir", [Pathname "template"]), 117, [],
2699    [InitBasicFS, Always, TestRun (
2700       [["mkdir"; "/tmp"];
2701        ["mkdtemp"; "/tmp/tmpXXXXXX"]])],
2702    "create a temporary directory",
2703    "\
2704 This command creates a temporary directory.  The
2705 C<template> parameter should be a full pathname for the
2706 temporary directory name with the final six characters being
2707 \"XXXXXX\".
2708
2709 For example: \"/tmp/myprogXXXXXX\" or \"/Temp/myprogXXXXXX\",
2710 the second one being suitable for Windows filesystems.
2711
2712 The name of the temporary directory that was created
2713 is returned.
2714
2715 The temporary directory is created with mode 0700
2716 and is owned by root.
2717
2718 The caller is responsible for deleting the temporary
2719 directory and its contents after use.
2720
2721 See also: L<mkdtemp(3)>");
2722
2723   ("wc_l", (RInt "lines", [Pathname "path"]), 118, [],
2724    [InitISOFS, Always, TestOutputInt (
2725       [["wc_l"; "/10klines"]], 10000)],
2726    "count lines in a file",
2727    "\
2728 This command counts the lines in a file, using the
2729 C<wc -l> external command.");
2730
2731   ("wc_w", (RInt "words", [Pathname "path"]), 119, [],
2732    [InitISOFS, Always, TestOutputInt (
2733       [["wc_w"; "/10klines"]], 10000)],
2734    "count words in a file",
2735    "\
2736 This command counts the words in a file, using the
2737 C<wc -w> external command.");
2738
2739   ("wc_c", (RInt "chars", [Pathname "path"]), 120, [],
2740    [InitISOFS, Always, TestOutputInt (
2741       [["wc_c"; "/100kallspaces"]], 102400)],
2742    "count characters in a file",
2743    "\
2744 This command counts the characters in a file, using the
2745 C<wc -c> external command.");
2746
2747   ("head", (RStringList "lines", [Pathname "path"]), 121, [ProtocolLimitWarning],
2748    [InitISOFS, Always, TestOutputList (
2749       [["head"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz";"3abcdefghijklmnopqrstuvwxyz";"4abcdefghijklmnopqrstuvwxyz";"5abcdefghijklmnopqrstuvwxyz";"6abcdefghijklmnopqrstuvwxyz";"7abcdefghijklmnopqrstuvwxyz";"8abcdefghijklmnopqrstuvwxyz";"9abcdefghijklmnopqrstuvwxyz"])],
2750    "return first 10 lines of a file",
2751    "\
2752 This command returns up to the first 10 lines of a file as
2753 a list of strings.");
2754
2755   ("head_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 122, [ProtocolLimitWarning],
2756    [InitISOFS, Always, TestOutputList (
2757       [["head_n"; "3"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2758     InitISOFS, Always, TestOutputList (
2759       [["head_n"; "-9997"; "/10klines"]], ["0abcdefghijklmnopqrstuvwxyz";"1abcdefghijklmnopqrstuvwxyz";"2abcdefghijklmnopqrstuvwxyz"]);
2760     InitISOFS, Always, TestOutputList (
2761       [["head_n"; "0"; "/10klines"]], [])],
2762    "return first N lines of a file",
2763    "\
2764 If the parameter C<nrlines> is a positive number, this returns the first
2765 C<nrlines> lines of the file C<path>.
2766
2767 If the parameter C<nrlines> is a negative number, this returns lines
2768 from the file C<path>, excluding the last C<nrlines> lines.
2769
2770 If the parameter C<nrlines> is zero, this returns an empty list.");
2771
2772   ("tail", (RStringList "lines", [Pathname "path"]), 123, [ProtocolLimitWarning],
2773    [InitISOFS, Always, TestOutputList (
2774       [["tail"; "/10klines"]], ["9990abcdefghijklmnopqrstuvwxyz";"9991abcdefghijklmnopqrstuvwxyz";"9992abcdefghijklmnopqrstuvwxyz";"9993abcdefghijklmnopqrstuvwxyz";"9994abcdefghijklmnopqrstuvwxyz";"9995abcdefghijklmnopqrstuvwxyz";"9996abcdefghijklmnopqrstuvwxyz";"9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"])],
2775    "return last 10 lines of a file",
2776    "\
2777 This command returns up to the last 10 lines of a file as
2778 a list of strings.");
2779
2780   ("tail_n", (RStringList "lines", [Int "nrlines"; Pathname "path"]), 124, [ProtocolLimitWarning],
2781    [InitISOFS, Always, TestOutputList (
2782       [["tail_n"; "3"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2783     InitISOFS, Always, TestOutputList (
2784       [["tail_n"; "-9998"; "/10klines"]], ["9997abcdefghijklmnopqrstuvwxyz";"9998abcdefghijklmnopqrstuvwxyz";"9999abcdefghijklmnopqrstuvwxyz"]);
2785     InitISOFS, Always, TestOutputList (
2786       [["tail_n"; "0"; "/10klines"]], [])],
2787    "return last N lines of a file",
2788    "\
2789 If the parameter C<nrlines> is a positive number, this returns the last
2790 C<nrlines> lines of the file C<path>.
2791
2792 If the parameter C<nrlines> is a negative number, this returns lines
2793 from the file C<path>, starting with the C<-nrlines>th line.
2794
2795 If the parameter C<nrlines> is zero, this returns an empty list.");
2796
2797   ("df", (RString "output", []), 125, [],
2798    [], (* XXX Tricky to test because it depends on the exact format
2799         * of the 'df' command and other imponderables.
2800         *)
2801    "report file system disk space usage",
2802    "\
2803 This command runs the C<df> command to report disk space used.
2804
2805 This command is mostly useful for interactive sessions.  It
2806 is I<not> intended that you try to parse the output string.
2807 Use C<statvfs> from programs.");
2808
2809   ("df_h", (RString "output", []), 126, [],
2810    [], (* XXX Tricky to test because it depends on the exact format
2811         * of the 'df' command and other imponderables.
2812         *)
2813    "report file system disk space usage (human readable)",
2814    "\
2815 This command runs the C<df -h> command to report disk space used
2816 in human-readable format.
2817
2818 This command is mostly useful for interactive sessions.  It
2819 is I<not> intended that you try to parse the output string.
2820 Use C<statvfs> from programs.");
2821
2822   ("du", (RInt64 "sizekb", [Pathname "path"]), 127, [],
2823    [InitISOFS, Always, TestOutputInt (
2824       [["du"; "/directory"]], 2 (* ISO fs blocksize is 2K *))],
2825    "estimate file space usage",
2826    "\
2827 This command runs the C<du -s> command to estimate file space
2828 usage for C<path>.
2829
2830 C<path> can be a file or a directory.  If C<path> is a directory
2831 then the estimate includes the contents of the directory and all
2832 subdirectories (recursively).
2833
2834 The result is the estimated size in I<kilobytes>
2835 (ie. units of 1024 bytes).");
2836
2837   ("initrd_list", (RStringList "filenames", [Pathname "path"]), 128, [],
2838    [InitISOFS, Always, TestOutputList (
2839       [["initrd_list"; "/initrd"]], ["empty";"known-1";"known-2";"known-3";"known-4"; "known-5"])],
2840    "list files in an initrd",
2841    "\
2842 This command lists out files contained in an initrd.
2843
2844 The files are listed without any initial C</> character.  The
2845 files are listed in the order they appear (not necessarily
2846 alphabetical).  Directory names are listed as separate items.
2847
2848 Old Linux kernels (2.4 and earlier) used a compressed ext2
2849 filesystem as initrd.  We I<only> support the newer initramfs
2850 format (compressed cpio files).");
2851
2852   ("mount_loop", (RErr, [Pathname "file"; Pathname "mountpoint"]), 129, [],
2853    [],
2854    "mount a file using the loop device",
2855    "\
2856 This command lets you mount C<file> (a filesystem image
2857 in a file) on a mount point.  It is entirely equivalent to
2858 the command C<mount -o loop file mountpoint>.");
2859
2860   ("mkswap", (RErr, [Device "device"]), 130, [],
2861    [InitEmpty, Always, TestRun (
2862       [["sfdiskM"; "/dev/sda"; ","];
2863        ["mkswap"; "/dev/sda1"]])],
2864    "create a swap partition",
2865    "\
2866 Create a swap partition on C<device>.");
2867
2868   ("mkswap_L", (RErr, [String "label"; Device "device"]), 131, [],
2869    [InitEmpty, Always, TestRun (
2870       [["sfdiskM"; "/dev/sda"; ","];
2871        ["mkswap_L"; "hello"; "/dev/sda1"]])],
2872    "create a swap partition with a label",
2873    "\
2874 Create a swap partition on C<device> with label C<label>.
2875
2876 Note that you cannot attach a swap label to a block device
2877 (eg. C</dev/sda>), just to a partition.  This appears to be
2878 a limitation of the kernel or swap tools.");
2879
2880   ("mkswap_U", (RErr, [String "uuid"; Device "device"]), 132, [],
2881    (let uuid = uuidgen () in
2882     [InitEmpty, Always, TestRun (
2883        [["sfdiskM"; "/dev/sda"; ","];
2884         ["mkswap_U"; uuid; "/dev/sda1"]])]),
2885    "create a swap partition with an explicit UUID",
2886    "\
2887 Create a swap partition on C<device> with UUID C<uuid>.");
2888
2889   ("mknod", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 133, [],
2890    [InitBasicFS, Always, TestOutputStruct (
2891       [["mknod"; "0o10777"; "0"; "0"; "/node"];
2892        (* NB: default umask 022 means 0777 -> 0755 in these tests *)
2893        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)]);
2894     InitBasicFS, Always, TestOutputStruct (
2895       [["mknod"; "0o60777"; "66"; "99"; "/node"];
2896        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2897    "make block, character or FIFO devices",
2898    "\
2899 This call creates block or character special devices, or
2900 named pipes (FIFOs).
2901
2902 The C<mode> parameter should be the mode, using the standard
2903 constants.  C<devmajor> and C<devminor> are the
2904 device major and minor numbers, only used when creating block
2905 and character special devices.");
2906
2907   ("mkfifo", (RErr, [Int "mode"; Pathname "path"]), 134, [],
2908    [InitBasicFS, Always, TestOutputStruct (
2909       [["mkfifo"; "0o777"; "/node"];
2910        ["stat"; "/node"]], [CompareWithInt ("mode", 0o10755)])],
2911    "make FIFO (named pipe)",
2912    "\
2913 This call creates a FIFO (named pipe) called C<path> with
2914 mode C<mode>.  It is just a convenient wrapper around
2915 C<guestfs_mknod>.");
2916
2917   ("mknod_b", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 135, [],
2918    [InitBasicFS, Always, TestOutputStruct (
2919       [["mknod_b"; "0o777"; "99"; "66"; "/node"];
2920        ["stat"; "/node"]], [CompareWithInt ("mode", 0o60755)])],
2921    "make block device node",
2922    "\
2923 This call creates a block device node called C<path> with
2924 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2925 It is just a convenient wrapper around C<guestfs_mknod>.");
2926
2927   ("mknod_c", (RErr, [Int "mode"; Int "devmajor"; Int "devminor"; Pathname "path"]), 136, [],
2928    [InitBasicFS, Always, TestOutputStruct (
2929       [["mknod_c"; "0o777"; "99"; "66"; "/node"];
2930        ["stat"; "/node"]], [CompareWithInt ("mode", 0o20755)])],
2931    "make char device node",
2932    "\
2933 This call creates a char device node called C<path> with
2934 mode C<mode> and device major/minor C<devmajor> and C<devminor>.
2935 It is just a convenient wrapper around C<guestfs_mknod>.");
2936
2937   ("umask", (RInt "oldmask", [Int "mask"]), 137, [],
2938    [], (* XXX umask is one of those stateful things that we should
2939         * reset between each test.
2940         *)
2941    "set file mode creation mask (umask)",
2942    "\
2943 This function sets the mask used for creating new files and
2944 device nodes to C<mask & 0777>.
2945
2946 Typical umask values would be C<022> which creates new files
2947 with permissions like \"-rw-r--r--\" or \"-rwxr-xr-x\", and
2948 C<002> which creates new files with permissions like
2949 \"-rw-rw-r--\" or \"-rwxrwxr-x\".
2950
2951 The default umask is C<022>.  This is important because it
2952 means that directories and device nodes will be created with
2953 C<0644> or C<0755> mode even if you specify C<0777>.
2954
2955 See also L<umask(2)>, C<guestfs_mknod>, C<guestfs_mkdir>.
2956
2957 This call returns the previous umask.");
2958
2959   ("readdir", (RStructList ("entries", "dirent"), [Pathname "dir"]), 138, [],
2960    [],
2961    "read directories entries",
2962    "\
2963 This returns the list of directory entries in directory C<dir>.
2964
2965 All entries in the directory are returned, including C<.> and
2966 C<..>.  The entries are I<not> sorted, but returned in the same
2967 order as the underlying filesystem.
2968
2969 Also this call returns basic file type information about each
2970 file.  The C<ftyp> field will contain one of the following characters:
2971
2972 =over 4
2973
2974 =item 'b'
2975
2976 Block special
2977
2978 =item 'c'
2979
2980 Char special
2981
2982 =item 'd'
2983
2984 Directory
2985
2986 =item 'f'
2987
2988 FIFO (named pipe)
2989
2990 =item 'l'
2991
2992 Symbolic link
2993
2994 =item 'r'
2995
2996 Regular file
2997
2998 =item 's'
2999
3000 Socket
3001
3002 =item 'u'
3003
3004 Unknown file type
3005
3006 =item '?'
3007
3008 The L<readdir(3)> returned a C<d_type> field with an
3009 unexpected value
3010
3011 =back
3012
3013 This function is primarily intended for use by programs.  To
3014 get a simple list of names, use C<guestfs_ls>.  To get a printable
3015 directory for human consumption, use C<guestfs_ll>.");
3016
3017   ("sfdiskM", (RErr, [Device "device"; StringList "lines"]), 139, [DangerWillRobinson],
3018    [],
3019    "create partitions on a block device",
3020    "\
3021 This is a simplified interface to the C<guestfs_sfdisk>
3022 command, where partition sizes are specified in megabytes
3023 only (rounded to the nearest cylinder) and you don't need
3024 to specify the cyls, heads and sectors parameters which
3025 were rarely if ever used anyway.
3026
3027 See also C<guestfs_sfdisk> and the L<sfdisk(8)> manpage.");
3028
3029   ("zfile", (RString "description", [String "meth"; Pathname "path"]), 140, [DeprecatedBy "file"],
3030    [],
3031    "determine file type inside a compressed file",
3032    "\
3033 This command runs C<file> after first decompressing C<path>
3034 using C<method>.
3035
3036 C<method> must be one of C<gzip>, C<compress> or C<bzip2>.
3037
3038 Since 1.0.63, use C<guestfs_file> instead which can now
3039 process compressed files.");
3040
3041   ("getxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 141, [],
3042    [],
3043    "list extended attributes of a file or directory",
3044    "\
3045 This call lists the extended attributes of the file or directory
3046 C<path>.
3047
3048 At the system call level, this is a combination of the
3049 L<listxattr(2)> and L<getxattr(2)> calls.
3050
3051 See also: C<guestfs_lgetxattrs>, L<attr(5)>.");
3052
3053   ("lgetxattrs", (RStructList ("xattrs", "xattr"), [Pathname "path"]), 142, [],
3054    [],
3055    "list extended attributes of a file or directory",
3056    "\
3057 This is the same as C<guestfs_getxattrs>, but if C<path>
3058 is a symbolic link, then it returns the extended attributes
3059 of the link itself.");
3060
3061   ("setxattr", (RErr, [String "xattr";
3062                        String "val"; Int "vallen"; (* will be BufferIn *)
3063                        Pathname "path"]), 143, [],
3064    [],
3065    "set extended attribute of a file or directory",
3066    "\
3067 This call sets the extended attribute named C<xattr>
3068 of the file C<path> to the value C<val> (of length C<vallen>).
3069 The value is arbitrary 8 bit data.
3070
3071 See also: C<guestfs_lsetxattr>, L<attr(5)>.");
3072
3073   ("lsetxattr", (RErr, [String "xattr";
3074                         String "val"; Int "vallen"; (* will be BufferIn *)
3075                         Pathname "path"]), 144, [],
3076    [],
3077    "set extended attribute of a file or directory",
3078    "\
3079 This is the same as C<guestfs_setxattr>, but if C<path>
3080 is a symbolic link, then it sets an extended attribute
3081 of the link itself.");
3082
3083   ("removexattr", (RErr, [String "xattr"; Pathname "path"]), 145, [],
3084    [],
3085    "remove extended attribute of a file or directory",
3086    "\
3087 This call removes the extended attribute named C<xattr>
3088 of the file C<path>.
3089
3090 See also: C<guestfs_lremovexattr>, L<attr(5)>.");
3091
3092   ("lremovexattr", (RErr, [String "xattr"; Pathname "path"]), 146, [],
3093    [],
3094    "remove extended attribute of a file or directory",
3095    "\
3096 This is the same as C<guestfs_removexattr>, but if C<path>
3097 is a symbolic link, then it removes an extended attribute
3098 of the link itself.");
3099
3100   ("mountpoints", (RHashtable "mps", []), 147, [],
3101    [],
3102    "show mountpoints",
3103    "\
3104 This call is similar to C<guestfs_mounts>.  That call returns
3105 a list of devices.  This one returns a hash table (map) of
3106 device name to directory where the device is mounted.");
3107
3108   ("mkmountpoint", (RErr, [String "exemptpath"]), 148, [],
3109   (* This is a special case: while you would expect a parameter
3110    * of type "Pathname", that doesn't work, because it implies
3111    * NEED_ROOT in the generated calling code in stubs.c, and
3112    * this function cannot use NEED_ROOT.
3113    *)
3114    [],
3115    "create a mountpoint",
3116    "\
3117 C<guestfs_mkmountpoint> and C<guestfs_rmmountpoint> are
3118 specialized calls that can be used to create extra mountpoints
3119 before mounting the first filesystem.
3120
3121 These calls are I<only> necessary in some very limited circumstances,
3122 mainly the case where you want to mount a mix of unrelated and/or
3123 read-only filesystems together.
3124
3125 For example, live CDs often contain a \"Russian doll\" nest of
3126 filesystems, an ISO outer layer, with a squashfs image inside, with
3127 an ext2/3 image inside that.  You can unpack this as follows
3128 in guestfish:
3129
3130  add-ro Fedora-11-i686-Live.iso
3131  run
3132  mkmountpoint /cd
3133  mkmountpoint /squash
3134  mkmountpoint /ext3
3135  mount /dev/sda /cd
3136  mount-loop /cd/LiveOS/squashfs.img /squash
3137  mount-loop /squash/LiveOS/ext3fs.img /ext3
3138
3139 The inner filesystem is now unpacked under the /ext3 mountpoint.");
3140
3141   ("rmmountpoint", (RErr, [String "exemptpath"]), 149, [],
3142    [],
3143    "remove a mountpoint",
3144    "\
3145 This calls removes a mountpoint that was previously created
3146 with C<guestfs_mkmountpoint>.  See C<guestfs_mkmountpoint>
3147 for full details.");
3148
3149   ("read_file", (RBufferOut "content", [Pathname "path"]), 150, [ProtocolLimitWarning],
3150    [InitISOFS, Always, TestOutputBuffer (
3151       [["read_file"; "/known-4"]], "abc\ndef\nghi")],
3152    "read a file",
3153    "\
3154 This calls returns the contents of the file C<path> as a
3155 buffer.
3156
3157 Unlike C<guestfs_cat>, this function can correctly
3158 handle files that contain embedded ASCII NUL characters.
3159 However unlike C<guestfs_download>, this function is limited
3160 in the total size of file that can be handled.");
3161
3162   ("grep", (RStringList "lines", [String "regex"; Pathname "path"]), 151, [ProtocolLimitWarning],
3163    [InitISOFS, Always, TestOutputList (
3164       [["grep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"]);
3165     InitISOFS, Always, TestOutputList (
3166       [["grep"; "nomatch"; "/test-grep.txt"]], [])],
3167    "return lines matching a pattern",
3168    "\
3169 This calls the external C<grep> program and returns the
3170 matching lines.");
3171
3172   ("egrep", (RStringList "lines", [String "regex"; Pathname "path"]), 152, [ProtocolLimitWarning],
3173    [InitISOFS, Always, TestOutputList (
3174       [["egrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3175    "return lines matching a pattern",
3176    "\
3177 This calls the external C<egrep> program and returns the
3178 matching lines.");
3179
3180   ("fgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 153, [ProtocolLimitWarning],
3181    [InitISOFS, Always, TestOutputList (
3182       [["fgrep"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"])],
3183    "return lines matching a pattern",
3184    "\
3185 This calls the external C<fgrep> program and returns the
3186 matching lines.");
3187
3188   ("grepi", (RStringList "lines", [String "regex"; Pathname "path"]), 154, [ProtocolLimitWarning],
3189    [InitISOFS, Always, TestOutputList (
3190       [["grepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3191    "return lines matching a pattern",
3192    "\
3193 This calls the external C<grep -i> program and returns the
3194 matching lines.");
3195
3196   ("egrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 155, [ProtocolLimitWarning],
3197    [InitISOFS, Always, TestOutputList (
3198       [["egrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3199    "return lines matching a pattern",
3200    "\
3201 This calls the external C<egrep -i> program and returns the
3202 matching lines.");
3203
3204   ("fgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 156, [ProtocolLimitWarning],
3205    [InitISOFS, Always, TestOutputList (
3206       [["fgrepi"; "abc"; "/test-grep.txt"]], ["abc"; "abc123"; "ABC"])],
3207    "return lines matching a pattern",
3208    "\
3209 This calls the external C<fgrep -i> program and returns the
3210 matching lines.");
3211
3212   ("zgrep", (RStringList "lines", [String "regex"; Pathname "path"]), 157, [ProtocolLimitWarning],
3213    [InitISOFS, Always, TestOutputList (
3214       [["zgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3215    "return lines matching a pattern",
3216    "\
3217 This calls the external C<zgrep> program and returns the
3218 matching lines.");
3219
3220   ("zegrep", (RStringList "lines", [String "regex"; Pathname "path"]), 158, [ProtocolLimitWarning],
3221    [InitISOFS, Always, TestOutputList (
3222       [["zegrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3223    "return lines matching a pattern",
3224    "\
3225 This calls the external C<zegrep> program and returns the
3226 matching lines.");
3227
3228   ("zfgrep", (RStringList "lines", [String "pattern"; Pathname "path"]), 159, [ProtocolLimitWarning],
3229    [InitISOFS, Always, TestOutputList (
3230       [["zfgrep"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"])],
3231    "return lines matching a pattern",
3232    "\
3233 This calls the external C<zfgrep> program and returns the
3234 matching lines.");
3235
3236   ("zgrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 160, [ProtocolLimitWarning],
3237    [InitISOFS, Always, TestOutputList (
3238       [["zgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3239    "return lines matching a pattern",
3240    "\
3241 This calls the external C<zgrep -i> program and returns the
3242 matching lines.");
3243
3244   ("zegrepi", (RStringList "lines", [String "regex"; Pathname "path"]), 161, [ProtocolLimitWarning],
3245    [InitISOFS, Always, TestOutputList (
3246       [["zegrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3247    "return lines matching a pattern",
3248    "\
3249 This calls the external C<zegrep -i> program and returns the
3250 matching lines.");
3251
3252   ("zfgrepi", (RStringList "lines", [String "pattern"; Pathname "path"]), 162, [ProtocolLimitWarning],
3253    [InitISOFS, Always, TestOutputList (
3254       [["zfgrepi"; "abc"; "/test-grep.txt.gz"]], ["abc"; "abc123"; "ABC"])],
3255    "return lines matching a pattern",
3256    "\
3257 This calls the external C<zfgrep -i> program and returns the
3258 matching lines.");
3259
3260   ("realpath", (RString "rpath", [Pathname "path"]), 163, [],
3261    [InitISOFS, Always, TestOutput (
3262       [["realpath"; "/../directory"]], "/directory")],
3263    "canonicalized absolute pathname",
3264    "\
3265 Return the canonicalized absolute pathname of C<path>.  The
3266 returned path has no C<.>, C<..> or symbolic link path elements.");
3267
3268   ("ln", (RErr, [String "target"; Pathname "linkname"]), 164, [],
3269    [InitBasicFS, Always, TestOutputStruct (
3270       [["touch"; "/a"];
3271        ["ln"; "/a"; "/b"];
3272        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3273    "create a hard link",
3274    "\
3275 This command creates a hard link using the C<ln> command.");
3276
3277   ("ln_f", (RErr, [String "target"; Pathname "linkname"]), 165, [],
3278    [InitBasicFS, Always, TestOutputStruct (
3279       [["touch"; "/a"];
3280        ["touch"; "/b"];
3281        ["ln_f"; "/a"; "/b"];
3282        ["stat"; "/b"]], [CompareWithInt ("nlink", 2)])],
3283    "create a hard link",
3284    "\
3285 This command creates a hard link using the C<ln -f> command.
3286 The C<-f> option removes the link (C<linkname>) if it exists already.");
3287
3288   ("ln_s", (RErr, [String "target"; Pathname "linkname"]), 166, [],
3289    [InitBasicFS, Always, TestOutputStruct (
3290       [["touch"; "/a"];
3291        ["ln_s"; "a"; "/b"];
3292        ["lstat"; "/b"]], [CompareWithInt ("mode", 0o120777)])],
3293    "create a symbolic link",
3294    "\
3295 This command creates a symbolic link using the C<ln -s> command.");
3296
3297   ("ln_sf", (RErr, [String "target"; Pathname "linkname"]), 167, [],
3298    [InitBasicFS, Always, TestOutput (
3299       [["mkdir_p"; "/a/b"];
3300        ["touch"; "/a/b/c"];
3301        ["ln_sf"; "../d"; "/a/b/c"];
3302        ["readlink"; "/a/b/c"]], "../d")],
3303    "create a symbolic link",
3304    "\
3305 This command creates a symbolic link using the C<ln -sf> command,
3306 The C<-f> option removes the link (C<linkname>) if it exists already.");
3307
3308   ("readlink", (RString "link", [Pathname "path"]), 168, [],
3309    [] (* XXX tested above *),
3310    "read the target of a symbolic link",
3311    "\
3312 This command reads the target of a symbolic link.");
3313
3314   ("fallocate", (RErr, [Pathname "path"; Int "len"]), 169, [],
3315    [InitBasicFS, Always, TestOutputStruct (
3316       [["fallocate"; "/a"; "1000000"];
3317        ["stat"; "/a"]], [CompareWithInt ("size", 1_000_000)])],
3318    "preallocate a file in the guest filesystem",
3319    "\
3320 This command preallocates a file (containing zero bytes) named
3321 C<path> of size C<len> bytes.  If the file exists already, it
3322 is overwritten.
3323
3324 Do not confuse this with the guestfish-specific
3325 C<alloc> command which allocates a file in the host and
3326 attaches it as a device.");
3327
3328   ("swapon_device", (RErr, [Device "device"]), 170, [],
3329    [InitPartition, Always, TestRun (
3330       [["mkswap"; "/dev/sda1"];
3331        ["swapon_device"; "/dev/sda1"];
3332        ["swapoff_device"; "/dev/sda1"]])],
3333    "enable swap on device",
3334    "\
3335 This command enables the libguestfs appliance to use the
3336 swap device or partition named C<device>.  The increased
3337 memory is made available for all commands, for example
3338 those run using C<guestfs_command> or C<guestfs_sh>.
3339
3340 Note that you should not swap to existing guest swap
3341 partitions unless you know what you are doing.  They may
3342 contain hibernation information, or other information that
3343 the guest doesn't want you to trash.  You also risk leaking
3344 information about the host to the guest this way.  Instead,
3345 attach a new host device to the guest and swap on that.");
3346
3347   ("swapoff_device", (RErr, [Device "device"]), 171, [],
3348    [], (* XXX tested by swapon_device *)
3349    "disable swap on device",
3350    "\
3351 This command disables the libguestfs appliance swap
3352 device or partition named C<device>.
3353 See C<guestfs_swapon_device>.");
3354
3355   ("swapon_file", (RErr, [Pathname "file"]), 172, [],
3356    [InitBasicFS, Always, TestRun (
3357       [["fallocate"; "/swap"; "8388608"];
3358        ["mkswap_file"; "/swap"];
3359        ["swapon_file"; "/swap"];
3360        ["swapoff_file"; "/swap"]])],
3361    "enable swap on file",
3362    "\
3363 This command enables swap to a file.
3364 See C<guestfs_swapon_device> for other notes.");
3365
3366   ("swapoff_file", (RErr, [Pathname "file"]), 173, [],
3367    [], (* XXX tested by swapon_file *)
3368    "disable swap on file",
3369    "\
3370 This command disables the libguestfs appliance swap on file.");
3371
3372   ("swapon_label", (RErr, [String "label"]), 174, [],
3373    [InitEmpty, Always, TestRun (
3374       [["sfdiskM"; "/dev/sdb"; ","];
3375        ["mkswap_L"; "swapit"; "/dev/sdb1"];
3376        ["swapon_label"; "swapit"];
3377        ["swapoff_label"; "swapit"];
3378        ["zero"; "/dev/sdb"];
3379        ["blockdev_rereadpt"; "/dev/sdb"]])],
3380    "enable swap on labeled swap partition",
3381    "\
3382 This command enables swap to a labeled swap partition.
3383 See C<guestfs_swapon_device> for other notes.");
3384
3385   ("swapoff_label", (RErr, [String "label"]), 175, [],
3386    [], (* XXX tested by swapon_label *)
3387    "disable swap on labeled swap partition",
3388    "\
3389 This command disables the libguestfs appliance swap on
3390 labeled swap partition.");
3391
3392   ("swapon_uuid", (RErr, [String "uuid"]), 176, [],
3393    (let uuid = uuidgen () in
3394     [InitEmpty, Always, TestRun (
3395        [["mkswap_U"; uuid; "/dev/sdb"];
3396         ["swapon_uuid"; uuid];
3397         ["swapoff_uuid"; uuid]])]),
3398    "enable swap on swap partition by UUID",
3399    "\
3400 This command enables swap to a swap partition with the given UUID.
3401 See C<guestfs_swapon_device> for other notes.");
3402
3403   ("swapoff_uuid", (RErr, [String "uuid"]), 177, [],
3404    [], (* XXX tested by swapon_uuid *)
3405    "disable swap on swap partition by UUID",
3406    "\
3407 This command disables the libguestfs appliance swap partition
3408 with the given UUID.");
3409
3410   ("mkswap_file", (RErr, [Pathname "path"]), 178, [],
3411    [InitBasicFS, Always, TestRun (
3412       [["fallocate"; "/swap"; "8388608"];
3413        ["mkswap_file"; "/swap"]])],
3414    "create a swap file",
3415    "\
3416 Create a swap file.
3417
3418 This command just writes a swap file signature to an existing
3419 file.  To create the file itself, use something like C<guestfs_fallocate>.");
3420
3421   ("inotify_init", (RErr, [Int "maxevents"]), 179, [],
3422    [InitISOFS, Always, TestRun (
3423       [["inotify_init"; "0"]])],
3424    "create an inotify handle",
3425    "\
3426 This command creates a new inotify handle.
3427 The inotify subsystem can be used to notify events which happen to
3428 objects in the guest filesystem.
3429
3430 C<maxevents> is the maximum number of events which will be
3431 queued up between calls to C<guestfs_inotify_read> or
3432 C<guestfs_inotify_files>.
3433 If this is passed as C<0>, then the kernel (or previously set)
3434 default is used.  For Linux 2.6.29 the default was 16384 events.
3435 Beyond this limit, the kernel throws away events, but records
3436 the fact that it threw them away by setting a flag
3437 C<IN_Q_OVERFLOW> in the returned structure list (see
3438 C<guestfs_inotify_read>).
3439
3440 Before any events are generated, you have to add some
3441 watches to the internal watch list.  See:
3442 C<guestfs_inotify_add_watch>,
3443 C<guestfs_inotify_rm_watch> and
3444 C<guestfs_inotify_watch_all>.
3445
3446 Queued up events should be read periodically by calling
3447 C<guestfs_inotify_read>
3448 (or C<guestfs_inotify_files> which is just a helpful
3449 wrapper around C<guestfs_inotify_read>).  If you don't
3450 read the events out often enough then you risk the internal
3451 queue overflowing.
3452
3453 The handle should be closed after use by calling
3454 C<guestfs_inotify_close>.  This also removes any
3455 watches automatically.
3456
3457 See also L<inotify(7)> for an overview of the inotify interface
3458 as exposed by the Linux kernel, which is roughly what we expose
3459 via libguestfs.  Note that there is one global inotify handle
3460 per libguestfs instance.");
3461
3462   ("inotify_add_watch", (RInt64 "wd", [Pathname "path"; Int "mask"]), 180, [],
3463    [InitBasicFS, Always, TestOutputList (
3464       [["inotify_init"; "0"];
3465        ["inotify_add_watch"; "/"; "1073741823"];
3466        ["touch"; "/a"];
3467        ["touch"; "/b"];
3468        ["inotify_files"]], ["a"; "b"])],
3469    "add an inotify watch",
3470    "\
3471 Watch C<path> for the events listed in C<mask>.
3472
3473 Note that if C<path> is a directory then events within that
3474 directory are watched, but this does I<not> happen recursively
3475 (in subdirectories).
3476
3477 Note for non-C or non-Linux callers: the inotify events are
3478 defined by the Linux kernel ABI and are listed in
3479 C</usr/include/sys/inotify.h>.");
3480
3481   ("inotify_rm_watch", (RErr, [Int(*XXX64*) "wd"]), 181, [],
3482    [],
3483    "remove an inotify watch",
3484    "\
3485 Remove a previously defined inotify watch.
3486 See C<guestfs_inotify_add_watch>.");
3487
3488   ("inotify_read", (RStructList ("events", "inotify_event"), []), 182, [],
3489    [],
3490    "return list of inotify events",
3491    "\
3492 Return the complete queue of events that have happened
3493 since the previous read call.
3494
3495 If no events have happened, this returns an empty list.
3496
3497 I<Note>: In order to make sure that all events have been
3498 read, you must call this function repeatedly until it
3499 returns an empty list.  The reason is that the call will
3500 read events up to the maximum appliance-to-host message
3501 size and leave remaining events in the queue.");
3502
3503   ("inotify_files", (RStringList "paths", []), 183, [],
3504    [],
3505    "return list of watched files that had events",
3506    "\
3507 This function is a helpful wrapper around C<guestfs_inotify_read>
3508 which just returns a list of pathnames of objects that were
3509 touched.  The returned pathnames are sorted and deduplicated.");
3510
3511   ("inotify_close", (RErr, []), 184, [],
3512    [],
3513    "close the inotify handle",
3514    "\
3515 This closes the inotify handle which was previously
3516 opened by inotify_init.  It removes all watches, throws
3517 away any pending events, and deallocates all resources.");
3518
3519   ("setcon", (RErr, [String "context"]), 185, [],
3520    [],
3521    "set SELinux security context",
3522    "\
3523 This sets the SELinux security context of the daemon
3524 to the string C<context>.
3525
3526 See the documentation about SELINUX in L<guestfs(3)>.");
3527
3528   ("getcon", (RString "context", []), 186, [],
3529    [],
3530    "get SELinux security context",
3531    "\
3532 This gets the SELinux security context of the daemon.
3533
3534 See the documentation about SELINUX in L<guestfs(3)>,
3535 and C<guestfs_setcon>");
3536
3537   ("mkfs_b", (RErr, [String "fstype"; Int "blocksize"; Device "device"]), 187, [],
3538    [InitEmpty, Always, TestOutput (
3539       [["sfdiskM"; "/dev/sda"; ","];
3540        ["mkfs_b"; "ext2"; "4096"; "/dev/sda1"];
3541        ["mount"; "/dev/sda1"; "/"];
3542        ["write_file"; "/new"; "new file contents"; "0"];
3543        ["cat"; "/new"]], "new file contents")],
3544    "make a filesystem with block size",
3545    "\
3546 This call is similar to C<guestfs_mkfs>, but it allows you to
3547 control the block size of the resulting filesystem.  Supported
3548 block sizes depend on the filesystem type, but typically they
3549 are C<1024>, C<2048> or C<4096> only.");
3550
3551   ("mke2journal", (RErr, [Int "blocksize"; Device "device"]), 188, [],
3552    [InitEmpty, Always, TestOutput (
3553       [["sfdiskM"; "/dev/sda"; ",100 ,"];
3554        ["mke2journal"; "4096"; "/dev/sda1"];
3555        ["mke2fs_J"; "ext2"; "4096"; "/dev/sda2"; "/dev/sda1"];
3556        ["mount"; "/dev/sda2"; "/"];
3557        ["write_file"; "/new"; "new file contents"; "0"];
3558        ["cat"; "/new"]], "new file contents")],
3559    "make ext2/3/4 external journal",
3560    "\
3561 This creates an ext2 external journal on C<device>.  It is equivalent
3562 to the command:
3563
3564  mke2fs -O journal_dev -b blocksize device");
3565
3566   ("mke2journal_L", (RErr, [Int "blocksize"; String "label"; Device "device"]), 189, [],
3567    [InitEmpty, Always, TestOutput (
3568       [["sfdiskM"; "/dev/sda"; ",100 ,"];
3569        ["mke2journal_L"; "4096"; "JOURNAL"; "/dev/sda1"];
3570        ["mke2fs_JL"; "ext2"; "4096"; "/dev/sda2"; "JOURNAL"];
3571        ["mount"; "/dev/sda2"; "/"];
3572        ["write_file"; "/new"; "new file contents"; "0"];
3573        ["cat"; "/new"]], "new file contents")],
3574    "make ext2/3/4 external journal with label",
3575    "\
3576 This creates an ext2 external journal on C<device> with label C<label>.");
3577
3578   ("mke2journal_U", (RErr, [Int "blocksize"; String "uuid"; Device "device"]), 190, [],
3579    (let uuid = uuidgen () in
3580     [InitEmpty, Always, TestOutput (
3581        [["sfdiskM"; "/dev/sda"; ",100 ,"];
3582         ["mke2journal_U"; "4096"; uuid; "/dev/sda1"];
3583         ["mke2fs_JU"; "ext2"; "4096"; "/dev/sda2"; uuid];
3584         ["mount"; "/dev/sda2"; "/"];
3585         ["write_file"; "/new"; "new file contents"; "0"];
3586         ["cat"; "/new"]], "new file contents")]),
3587    "make ext2/3/4 external journal with UUID",
3588    "\
3589 This creates an ext2 external journal on C<device> with UUID C<uuid>.");
3590
3591   ("mke2fs_J", (RErr, [String "fstype"; Int "blocksize"; Device "device"; Device "journal"]), 191, [],
3592    [],
3593    "make ext2/3/4 filesystem with external journal",
3594    "\
3595 This creates an ext2/3/4 filesystem on C<device> with
3596 an external journal on C<journal>.  It is equivalent
3597 to the command:
3598
3599  mke2fs -t fstype -b blocksize -J device=<journal> <device>
3600
3601 See also C<guestfs_mke2journal>.");
3602
3603   ("mke2fs_JL", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "label"]), 192, [],
3604    [],
3605    "make ext2/3/4 filesystem with external journal",
3606    "\
3607 This creates an ext2/3/4 filesystem on C<device> with
3608 an external journal on the journal labeled C<label>.
3609
3610 See also C<guestfs_mke2journal_L>.");
3611
3612   ("mke2fs_JU", (RErr, [String "fstype"; Int "blocksize"; Device "device"; String "uuid"]), 193, [],
3613    [],
3614    "make ext2/3/4 filesystem with external journal",
3615    "\
3616 This creates an ext2/3/4 filesystem on C<device> with
3617 an external journal on the journal with UUID C<uuid>.
3618
3619 See also C<guestfs_mke2journal_U>.");
3620
3621   ("modprobe", (RErr, [String "modulename"]), 194, [],
3622    [InitNone, Always, TestRun [["modprobe"; "fat"]]],
3623    "load a kernel module",
3624    "\
3625 This loads a kernel module in the appliance.
3626
3627 The kernel module must have been whitelisted when libguestfs
3628 was built (see C<appliance/kmod.whitelist.in> in the source).");
3629
3630   ("echo_daemon", (RString "output", [StringList "words"]), 195, [],
3631    [InitNone, Always, TestOutput (
3632      [["echo_daemon"; "This is a test"]], "This is a test"
3633    )],
3634    "echo arguments back to the client",
3635    "\
3636 This command concatenate the list of C<words> passed with single spaces between
3637 them and returns the resulting string.
3638
3639 You can use this command to test the connection through to the daemon.
3640
3641 See also C<guestfs_ping_daemon>.");
3642
3643   ("find0", (RErr, [Pathname "directory"; FileOut "files"]), 196, [],
3644    [], (* There is a regression test for this. *)
3645    "find all files and directories, returning NUL-separated list",
3646    "\
3647 This command lists out all files and directories, recursively,
3648 starting at C<directory>, placing the resulting list in the
3649 external file called C<files>.
3650
3651 This command works the same way as C<guestfs_find> with the
3652 following exceptions:
3653
3654 =over 4
3655
3656 =item *
3657
3658 The resulting list is written to an external file.
3659
3660 =item *
3661
3662 Items (filenames) in the result are separated
3663 by C<\\0> characters.  See L<find(1)> option I<-print0>.
3664
3665 =item *
3666
3667 This command is not limited in the number of names that it
3668 can return.
3669
3670 =item *
3671
3672 The result list is not sorted.
3673
3674 =back");
3675
3676   ("case_sensitive_path", (RString "rpath", [Pathname "path"]), 197, [],
3677    [InitISOFS, Always, TestOutput (
3678       [["case_sensitive_path"; "/DIRECTORY"]], "/directory");
3679     InitISOFS, Always, TestOutput (
3680       [["case_sensitive_path"; "/DIRECTORY/"]], "/directory");
3681     InitISOFS, Always, TestOutput (
3682       [["case_sensitive_path"; "/Known-1"]], "/known-1");
3683     InitISOFS, Always, TestLastFail (
3684       [["case_sensitive_path"; "/Known-1/"]]);
3685     InitBasicFS, Always, TestOutput (
3686       [["mkdir"; "/a"];
3687        ["mkdir"; "/a/bbb"];
3688        ["touch"; "/a/bbb/c"];
3689        ["case_sensitive_path"; "/A/bbB/C"]], "/a/bbb/c");
3690     InitBasicFS, Always, TestOutput (
3691       [["mkdir"; "/a"];
3692        ["mkdir"; "/a/bbb"];
3693        ["touch"; "/a/bbb/c"];
3694        ["case_sensitive_path"; "/A////bbB/C"]], "/a/bbb/c");
3695     InitBasicFS, Always, TestLastFail (
3696       [["mkdir"; "/a"];
3697        ["mkdir"; "/a/bbb"];
3698        ["touch"; "/a/bbb/c"];
3699        ["case_sensitive_path"; "/A/bbb/../bbb/C"]])],
3700    "return true path on case-insensitive filesystem",
3701    "\
3702 This can be used to resolve case insensitive paths on
3703 a filesystem which is case sensitive.  The use case is
3704 to resolve paths which you have read from Windows configuration
3705 files or the Windows Registry, to the true path.
3706
3707 The command handles a peculiarity of the Linux ntfs-3g
3708 filesystem driver (and probably others), which is that although
3709 the underlying filesystem is case-insensitive, the driver
3710 exports the filesystem to Linux as case-sensitive.
3711
3712 One consequence of this is that special directories such
3713 as C<c:\\windows> may appear as C</WINDOWS> or C</windows>
3714 (or other things) depending on the precise details of how
3715 they were created.  In Windows itself this would not be
3716 a problem.
3717
3718 Bug or feature?  You decide:
3719 L<http://www.tuxera.com/community/ntfs-3g-faq/#posixfilenames1>
3720
3721 This function resolves the true case of each element in the
3722 path and returns the case-sensitive path.
3723
3724 Thus C<guestfs_case_sensitive_path> (\"/Windows/System32\")
3725 might return C<\"/WINDOWS/system32\"> (the exact return value
3726 would depend on details of how the directories were originally
3727 created under Windows).
3728
3729 I<Note>:
3730 This function does not handle drive names, backslashes etc.
3731
3732 See also C<guestfs_realpath>.");
3733
3734   ("vfs_type", (RString "fstype", [Device "device"]), 198, [],
3735    [InitBasicFS, Always, TestOutput (
3736       [["vfs_type"; "/dev/sda1"]], "ext2")],
3737    "get the Linux VFS type corresponding to a mounted device",
3738    "\
3739 This command gets the block device type corresponding to
3740 a mounted device called C<device>.
3741
3742 Usually the result is the name of the Linux VFS module that
3743 is used to mount this device (probably determined automatically
3744 if you used the C<guestfs_mount> call).");
3745
3746   ("truncate", (RErr, [Pathname "path"]), 199, [],
3747    [InitBasicFS, Always, TestOutputStruct (
3748       [["write_file"; "/test"; "some stuff so size is not zero"; "0"];
3749        ["truncate"; "/test"];
3750        ["stat"; "/test"]], [CompareWithInt ("size", 0)])],
3751    "truncate a file to zero size",
3752    "\
3753 This command truncates C<path> to a zero-length file.  The
3754 file must exist already.");
3755
3756   ("truncate_size", (RErr, [Pathname "path"; Int64 "size"]), 200, [],
3757    [InitBasicFS, Always, TestOutputStruct (
3758       [["touch"; "/test"];
3759        ["truncate_size"; "/test"; "1000"];
3760        ["stat"; "/test"]], [CompareWithInt ("size", 1000)])],
3761    "truncate a file to a particular size",
3762    "\
3763 This command truncates C<path> to size C<size> bytes.  The file
3764 must exist already.  If the file is smaller than C<size> then
3765 the file is extended to the required size with null bytes.");
3766
3767   ("utimens", (RErr, [Pathname "path"; Int64 "atsecs"; Int64 "atnsecs"; Int64 "mtsecs"; Int64 "mtnsecs"]), 201, [],
3768    [InitBasicFS, Always, TestOutputStruct (
3769       [["touch"; "/test"];
3770        ["utimens"; "/test"; "12345"; "67890"; "9876"; "5432"];
3771        ["stat"; "/test"]], [CompareWithInt ("mtime", 9876)])],
3772    "set timestamp of a file with nanosecond precision",
3773    "\
3774 This command sets the timestamps of a file with nanosecond
3775 precision.
3776
3777 C<atsecs, atnsecs> are the last access time (atime) in secs and
3778 nanoseconds from the epoch.
3779
3780 C<mtsecs, mtnsecs> are the last modification time (mtime) in
3781 secs and nanoseconds from the epoch.
3782
3783 If the C<*nsecs> field contains the special value C<-1> then
3784 the corresponding timestamp is set to the current time.  (The
3785 C<*secs> field is ignored in this case).
3786
3787 If the C<*nsecs> field contains the special value C<-2> then
3788 the corresponding timestamp is left unchanged.  (The
3789 C<*secs> field is ignored in this case).");
3790
3791   ("mkdir_mode", (RErr, [Pathname "path"; Int "mode"]), 202, [],
3792    [InitBasicFS, Always, TestOutputStruct (
3793       [["mkdir_mode"; "/test"; "0o111"];
3794        ["stat"; "/test"]], [CompareWithInt ("mode", 0o40111)])],
3795    "create a directory with a particular mode",
3796    "\
3797 This command creates a directory, setting the initial permissions
3798 of the directory to C<mode>.  See also C<guestfs_mkdir>.");
3799
3800   ("lchown", (RErr, [Int "owner"; Int "group"; Pathname "path"]), 203, [],
3801    [], (* XXX *)
3802    "change file owner and group",
3803    "\
3804 Change the file owner to C<owner> and group to C<group>.
3805 This is like C<guestfs_chown> but if C<path> is a symlink then
3806 the link itself is changed, not the target.
3807
3808 Only numeric uid and gid are supported.  If you want to use
3809 names, you will need to locate and parse the password file
3810 yourself (Augeas support makes this relatively easy).");
3811
3812   ("lstatlist", (RStructList ("statbufs", "stat"), [Pathname "path"; StringList "names"]), 204, [],
3813    [], (* XXX *)
3814    "lstat on multiple files",
3815    "\
3816 This call allows you to perform the C<guestfs_lstat> operation
3817 on multiple files, where all files are in the directory C<path>.
3818 C<names> is the list of files from this directory.
3819
3820 On return you get a list of stat structs, with a one-to-one
3821 correspondence to the C<names> list.  If any name did not exist
3822 or could not be lstat'd, then the C<ino> field of that structure
3823 is set to C<-1>.
3824
3825 This call is intended for programs that want to efficiently
3826 list a directory contents without making many round-trips.
3827 See also C<guestfs_lxattrlist> for a similarly efficient call
3828 for getting extended attributes.  Very long directory listings
3829 might cause the protocol message size to be exceeded, causing
3830 this call to fail.  The caller must split up such requests
3831 into smaller groups of names.");
3832
3833   ("lxattrlist", (RStructList ("xattrs", "xattr"), [Pathname "path"; StringList "names"]), 205, [],
3834    [], (* XXX *)
3835    "lgetxattr on multiple files",
3836    "\
3837 This call allows you to get the extended attributes
3838 of multiple files, where all files are in the directory C<path>.
3839 C<names> is the list of files from this directory.
3840
3841 On return you get a flat list of xattr structs which must be
3842 interpreted sequentially.  The first xattr struct always has a zero-length
3843 C<attrname>.  C<attrval> in this struct is zero-length
3844 to indicate there was an error doing C<lgetxattr> for this
3845 file, I<or> is a C string which is a decimal number
3846 (the number of following attributes for this file, which could
3847 be C<\"0\">).  Then after the first xattr struct are the
3848 zero or more attributes for the first named file.
3849 This repeats for the second and subsequent files.
3850
3851 This call is intended for programs that want to efficiently
3852 list a directory contents without making many round-trips.
3853 See also C<guestfs_lstatlist> for a similarly efficient call
3854 for getting standard stats.  Very long directory listings
3855 might cause the protocol message size to be exceeded, causing
3856 this call to fail.  The caller must split up such requests
3857 into smaller groups of names.");
3858
3859   ("readlinklist", (RStringList "links", [Pathname "path"; StringList "names"]), 206, [],
3860    [], (* XXX *)
3861    "readlink on multiple files",
3862    "\
3863 This call allows you to do a C<readlink> operation
3864 on multiple files, where all files are in the directory C<path>.
3865 C<names> is the list of files from this directory.
3866
3867 On return you get a list of strings, with a one-to-one
3868 correspondence to the C<names> list.  Each string is the
3869 value of the symbol link.
3870
3871 If the C<readlink(2)> operation fails on any name, then
3872 the corresponding result string is the empty string C<\"\">.
3873 However the whole operation is completed even if there
3874 were C<readlink(2)> errors, and so you can call this
3875 function with names where you don't know if they are
3876 symbolic links already (albeit slightly less efficient).
3877
3878 This call is intended for programs that want to efficiently
3879 list a directory contents without making many round-trips.
3880 Very long directory listings might cause the protocol
3881 message size to be exceeded, causing
3882 this call to fail.  The caller must split up such requests
3883 into smaller groups of names.");
3884
3885   ("pread", (RBufferOut "content", [Pathname "path"; Int "count"; Int64 "offset"]), 207, [ProtocolLimitWarning],
3886    [InitISOFS, Always, TestOutputBuffer (
3887       [["pread"; "/known-4"; "1"; "3"]], "\n")],
3888    "read part of a file",
3889    "\
3890 This command lets you read part of a file.  It reads C<count>
3891 bytes of the file, starting at C<offset>, from file C<path>.
3892
3893 This may read fewer bytes than requested.  For further details
3894 see the L<pread(2)> system call.");
3895
3896 ]
3897
3898 let all_functions = non_daemon_functions @ daemon_functions
3899
3900 (* In some places we want the functions to be displayed sorted
3901  * alphabetically, so this is useful:
3902  *)
3903 let all_functions_sorted =
3904   List.sort (fun (n1,_,_,_,_,_,_) (n2,_,_,_,_,_,_) ->
3905                compare n1 n2) all_functions
3906
3907 (* Field types for structures. *)
3908 type field =
3909   | FChar                       (* C 'char' (really, a 7 bit byte). *)
3910   | FString                     (* nul-terminated ASCII string, NOT NULL. *)
3911   | FBuffer                     (* opaque buffer of bytes, (char *, int) pair *)
3912   | FUInt32
3913   | FInt32
3914   | FUInt64
3915   | FInt64
3916   | FBytes                      (* Any int measure that counts bytes. *)
3917   | FUUID                       (* 32 bytes long, NOT nul-terminated. *)
3918   | FOptPercent                 (* [0..100], or -1 meaning "not present". *)
3919
3920 (* Because we generate extra parsing code for LVM command line tools,
3921  * we have to pull out the LVM columns separately here.
3922  *)
3923 let lvm_pv_cols = [
3924   "pv_name", FString;
3925   "pv_uuid", FUUID;
3926   "pv_fmt", FString;
3927   "pv_size", FBytes;
3928   "dev_size", FBytes;
3929   "pv_free", FBytes;
3930   "pv_used", FBytes;
3931   "pv_attr", FString (* XXX *);
3932   "pv_pe_count", FInt64;
3933   "pv_pe_alloc_count", FInt64;
3934   "pv_tags", FString;
3935   "pe_start", FBytes;
3936   "pv_mda_count", FInt64;
3937   "pv_mda_free", FBytes;
3938   (* Not in Fedora 10:
3939      "pv_mda_size", FBytes;
3940   *)
3941 ]
3942 let lvm_vg_cols = [
3943   "vg_name", FString;
3944   "vg_uuid", FUUID;
3945   "vg_fmt", FString;
3946   "vg_attr", FString (* XXX *);
3947   "vg_size", FBytes;
3948   "vg_free", FBytes;
3949   "vg_sysid", FString;
3950   "vg_extent_size", FBytes;
3951   "vg_extent_count", FInt64;
3952   "vg_free_count", FInt64;
3953   "max_lv", FInt64;
3954   "max_pv", FInt64;
3955   "pv_count", FInt64;
3956   "lv_count", FInt64;
3957   "snap_count", FInt64;
3958   "vg_seqno", FInt64;
3959   "vg_tags", FString;
3960   "vg_mda_count", FInt64;
3961   "vg_mda_free", FBytes;
3962   (* Not in Fedora 10:
3963      "vg_mda_size", FBytes;
3964   *)
3965 ]
3966 let lvm_lv_cols = [
3967   "lv_name", FString;
3968   "lv_uuid", FUUID;
3969   "lv_attr", FString (* XXX *);
3970   "lv_major", FInt64;
3971   "lv_minor", FInt64;
3972   "lv_kernel_major", FInt64;
3973   "lv_kernel_minor", FInt64;
3974   "lv_size", FBytes;
3975   "seg_count", FInt64;
3976   "origin", FString;
3977   "snap_percent", FOptPercent;
3978   "copy_percent", FOptPercent;
3979   "move_pv", FString;
3980   "lv_tags", FString;
3981   "mirror_log", FString;
3982   "modules", FString;
3983 ]
3984
3985 (* Names and fields in all structures (in RStruct and RStructList)
3986  * that we support.
3987  *)
3988 let structs = [
3989   (* The old RIntBool return type, only ever used for aug_defnode.  Do
3990    * not use this struct in any new code.
3991    *)
3992   "int_bool", [
3993     "i", FInt32;                (* for historical compatibility *)
3994     "b", FInt32;                (* for historical compatibility *)
3995   ];
3996
3997   (* LVM PVs, VGs, LVs. *)
3998   "lvm_pv", lvm_pv_cols;
3999   "lvm_vg", lvm_vg_cols;
4000   "lvm_lv", lvm_lv_cols;
4001
4002   (* Column names and types from stat structures.
4003    * NB. Can't use things like 'st_atime' because glibc header files
4004    * define some of these as macros.  Ugh.
4005    *)
4006   "stat", [
4007     "dev", FInt64;
4008     "ino", FInt64;
4009     "mode", FInt64;
4010     "nlink", FInt64;
4011     "uid", FInt64;
4012     "gid", FInt64;
4013     "rdev", FInt64;
4014     "size", FInt64;
4015     "blksize", FInt64;
4016     "blocks", FInt64;
4017     "atime", FInt64;
4018     "mtime", FInt64;
4019     "ctime", FInt64;
4020   ];
4021   "statvfs", [
4022     "bsize", FInt64;
4023     "frsize", FInt64;
4024     "blocks", FInt64;
4025     "bfree", FInt64;
4026     "bavail", FInt64;
4027     "files", FInt64;
4028     "ffree", FInt64;
4029     "favail", FInt64;
4030     "fsid", FInt64;
4031     "flag", FInt64;
4032     "namemax", FInt64;
4033   ];
4034
4035   (* Column names in dirent structure. *)
4036   "dirent", [
4037     "ino", FInt64;
4038     (* 'b' 'c' 'd' 'f' (FIFO) 'l' 'r' (regular file) 's' 'u' '?' *)
4039     "ftyp", FChar;
4040     "name", FString;
4041   ];
4042
4043   (* Version numbers. *)
4044   "version", [
4045     "major", FInt64;
4046     "minor", FInt64;
4047     "release", FInt64;
4048     "extra", FString;
4049   ];
4050
4051   (* Extended attribute. *)
4052   "xattr", [
4053     "attrname", FString;
4054     "attrval", FBuffer;
4055   ];
4056
4057   (* Inotify events. *)
4058   "inotify_event", [
4059     "in_wd", FInt64;
4060     "in_mask", FUInt32;
4061     "in_cookie", FUInt32;
4062     "in_name", FString;
4063   ];
4064 ] (* end of structs *)
4065
4066 (* Ugh, Java has to be different ..
4067  * These names are also used by the Haskell bindings.
4068  *)
4069 let java_structs = [
4070   "int_bool", "IntBool";
4071   "lvm_pv", "PV";
4072   "lvm_vg", "VG";
4073   "lvm_lv", "LV";
4074   "stat", "Stat";
4075   "statvfs", "StatVFS";
4076   "dirent", "Dirent";
4077   "version", "Version";
4078   "xattr", "XAttr";
4079   "inotify_event", "INotifyEvent";
4080 ]
4081
4082 (* What structs are actually returned. *)
4083 type rstructs_used_t = RStructOnly | RStructListOnly | RStructAndList
4084
4085 (* Returns a list of RStruct/RStructList structs that are returned
4086  * by any function.  Each element of returned list is a pair:
4087  *
4088  * (structname, RStructOnly)
4089  *    == there exists function which returns RStruct (_, structname)
4090  * (structname, RStructListOnly)
4091  *    == there exists function which returns RStructList (_, structname)
4092  * (structname, RStructAndList)
4093  *    == there are functions returning both RStruct (_, structname)
4094  *                                      and RStructList (_, structname)
4095  *)
4096 let rstructs_used_by functions =
4097   (* ||| is a "logical OR" for rstructs_used_t *)
4098   let (|||) a b =
4099     match a, b with
4100     | RStructAndList, _
4101     | _, RStructAndList -> RStructAndList
4102     | RStructOnly, RStructListOnly
4103     | RStructListOnly, RStructOnly -> RStructAndList
4104     | RStructOnly, RStructOnly -> RStructOnly
4105     | RStructListOnly, RStructListOnly -> RStructListOnly
4106   in
4107
4108   let h = Hashtbl.create 13 in
4109
4110   (* if elem->oldv exists, update entry using ||| operator,
4111    * else just add elem->newv to the hash
4112    *)
4113   let update elem newv =
4114     try  let oldv = Hashtbl.find h elem in
4115          Hashtbl.replace h elem (newv ||| oldv)
4116     with Not_found -> Hashtbl.add h elem newv
4117   in
4118
4119   List.iter (
4120     fun (_, style, _, _, _, _, _) ->
4121       match fst style with
4122       | RStruct (_, structname) -> update structname RStructOnly
4123       | RStructList (_, structname) -> update structname RStructListOnly
4124       | _ -> ()
4125   ) functions;
4126
4127   (* return key->values as a list of (key,value) *)
4128   Hashtbl.fold (fun key value xs -> (key, value) :: xs) h []
4129
4130 (* Used for testing language bindings. *)
4131 type callt =
4132   | CallString of string
4133   | CallOptString of string option
4134   | CallStringList of string list
4135   | CallInt of int
4136   | CallInt64 of int64
4137   | CallBool of bool
4138
4139 (* Used to memoize the result of pod2text. *)
4140 let pod2text_memo_filename = "src/.pod2text.data"
4141 let pod2text_memo : ((int * string * string), string list) Hashtbl.t =
4142   try
4143     let chan = open_in pod2text_memo_filename in
4144     let v = input_value chan in
4145     close_in chan;
4146     v
4147   with
4148     _ -> Hashtbl.create 13
4149 let pod2text_memo_updated () =
4150   let chan = open_out pod2text_memo_filename in
4151   output_value chan pod2text_memo;
4152   close_out chan
4153
4154 (* Useful functions.
4155  * Note we don't want to use any external OCaml libraries which
4156  * makes this a bit harder than it should be.
4157  *)
4158 let failwithf fs = ksprintf failwith fs
4159
4160 let replace_char s c1 c2 =
4161   let s2 = String.copy s in
4162   let r = ref false in
4163   for i = 0 to String.length s2 - 1 do
4164     if String.unsafe_get s2 i = c1 then (
4165       String.unsafe_set s2 i c2;
4166       r := true
4167     )
4168   done;
4169   if not !r then s else s2
4170
4171 let isspace c =
4172   c = ' '
4173   (* || c = '\f' *) || c = '\n' || c = '\r' || c = '\t' (* || c = '\v' *)
4174
4175 let triml ?(test = isspace) str =
4176   let i = ref 0 in
4177   let n = ref (String.length str) in
4178   while !n > 0 && test str.[!i]; do
4179     decr n;
4180     incr i
4181   done;
4182   if !i = 0 then str
4183   else String.sub str !i !n
4184
4185 let trimr ?(test = isspace) str =
4186   let n = ref (String.length str) in
4187   while !n > 0 && test str.[!n-1]; do
4188     decr n
4189   done;
4190   if !n = String.length str then str
4191   else String.sub str 0 !n
4192
4193 let trim ?(test = isspace) str =
4194   trimr ~test (triml ~test str)
4195
4196 let rec find s sub =
4197   let len = String.length s in
4198   let sublen = String.length sub in
4199   let rec loop i =
4200     if i <= len-sublen then (
4201       let rec loop2 j =
4202         if j < sublen then (
4203           if s.[i+j] = sub.[j] then loop2 (j+1)
4204           else -1
4205         ) else
4206           i (* found *)
4207       in
4208       let r = loop2 0 in
4209       if r = -1 then loop (i+1) else r
4210     ) else
4211       -1 (* not found *)
4212   in
4213   loop 0
4214
4215 let rec replace_str s s1 s2 =
4216   let len = String.length s in
4217   let sublen = String.length s1 in
4218   let i = find s s1 in
4219   if i = -1 then s
4220   else (
4221     let s' = String.sub s 0 i in
4222     let s'' = String.sub s (i+sublen) (len-i-sublen) in
4223     s' ^ s2 ^ replace_str s'' s1 s2
4224   )
4225
4226 let rec string_split sep str =
4227   let len = String.length str in
4228   let seplen = String.length sep in
4229   let i = find str sep in
4230   if i = -1 then [str]
4231   else (
4232     let s' = String.sub str 0 i in
4233     let s'' = String.sub str (i+seplen) (len-i-seplen) in
4234     s' :: string_split sep s''
4235   )
4236
4237 let files_equal n1 n2 =
4238   let cmd = sprintf "cmp -s %s %s" (Filename.quote n1) (Filename.quote n2) in
4239   match Sys.command cmd with
4240   | 0 -> true
4241   | 1 -> false
4242   | i -> failwithf "%s: failed with error code %d" cmd i
4243
4244 let rec filter_map f = function
4245   | [] -> []
4246   | x :: xs ->
4247       match f x with
4248       | Some y -> y :: filter_map f xs
4249       | None -> filter_map f xs
4250
4251 let rec find_map f = function
4252   | [] -> raise Not_found
4253   | x :: xs ->
4254       match f x with
4255       | Some y -> y
4256       | None -> find_map f xs
4257
4258 let iteri f xs =
4259   let rec loop i = function
4260     | [] -> ()
4261     | x :: xs -> f i x; loop (i+1) xs
4262   in
4263   loop 0 xs
4264
4265 let mapi f xs =
4266   let rec loop i = function
4267     | [] -> []
4268     | x :: xs -> let r = f i x in r :: loop (i+1) xs
4269   in
4270   loop 0 xs
4271
4272 let name_of_argt = function
4273   | Pathname n | Device n | Dev_or_Path n | String n | OptString n
4274   | StringList n | DeviceList n | Bool n | Int n | Int64 n
4275   | FileIn n | FileOut n -> n
4276
4277 let java_name_of_struct typ =
4278   try List.assoc typ java_structs
4279   with Not_found ->
4280     failwithf
4281       "java_name_of_struct: no java_structs entry corresponding to %s" typ
4282
4283 let cols_of_struct typ =
4284   try List.assoc typ structs
4285   with Not_found ->
4286     failwithf "cols_of_struct: unknown struct %s" typ
4287
4288 let seq_of_test = function
4289   | TestRun s | TestOutput (s, _) | TestOutputList (s, _)
4290   | TestOutputListOfDevices (s, _)
4291   | TestOutputInt (s, _) | TestOutputIntOp (s, _, _)
4292   | TestOutputTrue s | TestOutputFalse s
4293   | TestOutputLength (s, _) | TestOutputBuffer (s, _)
4294   | TestOutputStruct (s, _)
4295   | TestLastFail s -> s
4296
4297 (* Handling for function flags. *)
4298 let protocol_limit_warning =
4299   "Because of the message protocol, there is a transfer limit
4300 of somewhere between 2MB and 4MB.  To transfer large files you should use
4301 FTP."
4302
4303 let danger_will_robinson =
4304   "B<This command is dangerous.  Without careful use you
4305 can easily destroy all your data>."
4306
4307 let deprecation_notice flags =
4308   try
4309     let alt =
4310       find_map (function DeprecatedBy str -> Some str | _ -> None) flags in
4311     let txt =
4312       sprintf "This function is deprecated.
4313 In new code, use the C<%s> call instead.
4314
4315 Deprecated functions will not be removed from the API, but the
4316 fact that they are deprecated indicates that there are problems
4317 with correct use of these functions." alt in
4318     Some txt
4319   with
4320     Not_found -> None
4321
4322 (* Check function names etc. for consistency. *)
4323 let check_functions () =
4324   let contains_uppercase str =
4325     let len = String.length str in
4326     let rec loop i =
4327       if i >= len then false
4328       else (
4329         let c = str.[i] in
4330         if c >= 'A' && c <= 'Z' then true
4331         else loop (i+1)
4332       )
4333     in
4334     loop 0
4335   in
4336
4337   (* Check function names. *)
4338   List.iter (
4339     fun (name, _, _, _, _, _, _) ->
4340       if String.length name >= 7 && String.sub name 0 7 = "guestfs" then
4341         failwithf "function name %s does not need 'guestfs' prefix" name;
4342       if name = "" then
4343         failwithf "function name is empty";
4344       if name.[0] < 'a' || name.[0] > 'z' then
4345         failwithf "function name %s must start with lowercase a-z" name;
4346       if String.contains name '-' then
4347         failwithf "function name %s should not contain '-', use '_' instead."
4348           name
4349   ) all_functions;
4350
4351   (* Check function parameter/return names. *)
4352   List.iter (
4353     fun (name, style, _, _, _, _, _) ->
4354       let check_arg_ret_name n =
4355         if contains_uppercase n then
4356           failwithf "%s param/ret %s should not contain uppercase chars"
4357             name n;
4358         if String.contains n '-' || String.contains n '_' then
4359           failwithf "%s param/ret %s should not contain '-' or '_'"
4360             name n;
4361         if n = "value" then
4362           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;
4363         if n = "int" || n = "char" || n = "short" || n = "long" then
4364           failwithf "%s has a param/ret which conflicts with a C type (eg. 'int', 'char' etc.)" name;
4365         if n = "i" || n = "n" then
4366           failwithf "%s has a param/ret called 'i' or 'n', which will cause some conflicts in the generated code" name;
4367         if n = "argv" || n = "args" then
4368           failwithf "%s has a param/ret called 'argv' or 'args', which will cause some conflicts in the generated code" name;
4369
4370         (* List Haskell, OCaml and C keywords here.
4371          * http://www.haskell.org/haskellwiki/Keywords
4372          * http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#operator-char
4373          * http://en.wikipedia.org/wiki/C_syntax#Reserved_keywords
4374          * Formatted via: cat c haskell ocaml|sort -u|grep -vE '_|^val$' \
4375          *   |perl -pe 's/(.+)/"$1";/'|fmt -70
4376          * Omitting _-containing words, since they're handled above.
4377          * Omitting the OCaml reserved word, "val", is ok,
4378          * and saves us from renaming several parameters.
4379          *)
4380         let reserved = [
4381           "and"; "as"; "asr"; "assert"; "auto"; "begin"; "break"; "case";
4382           "char"; "class"; "const"; "constraint"; "continue"; "data";
4383           "default"; "deriving"; "do"; "done"; "double"; "downto"; "else";
4384           "end"; "enum"; "exception"; "extern"; "external"; "false"; "float";
4385           "for"; "forall"; "foreign"; "fun"; "function"; "functor"; "goto";
4386           "hiding"; "if"; "import"; "in"; "include"; "infix"; "infixl";
4387           "infixr"; "inherit"; "initializer"; "inline"; "instance"; "int";
4388           "land"; "lazy"; "let"; "long"; "lor"; "lsl"; "lsr"; "lxor";
4389           "match"; "mdo"; "method"; "mod"; "module"; "mutable"; "new";
4390           "newtype"; "object"; "of"; "open"; "or"; "private"; "qualified";
4391           "rec"; "register"; "restrict"; "return"; "short"; "sig"; "signed";
4392           "sizeof"; "static"; "struct"; "switch"; "then"; "to"; "true"; "try";
4393           "type"; "typedef"; "union"; "unsigned"; "virtual"; "void";
4394           "volatile"; "when"; "where"; "while";
4395           ] in
4396         if List.mem n reserved then
4397           failwithf "%s has param/ret using reserved word %s" name n;
4398       in
4399
4400       (match fst style with
4401        | RErr -> ()
4402        | RInt n | RInt64 n | RBool n
4403        | RConstString n | RConstOptString n | RString n
4404        | RStringList n | RStruct (n, _) | RStructList (n, _)
4405        | RHashtable n | RBufferOut n ->
4406            check_arg_ret_name n
4407       );
4408       List.iter (fun arg -> check_arg_ret_name (name_of_argt arg)) (snd style)
4409   ) all_functions;
4410
4411   (* Check short descriptions. *)
4412   List.iter (
4413     fun (name, _, _, _, _, shortdesc, _) ->
4414       if shortdesc.[0] <> Char.lowercase shortdesc.[0] then
4415         failwithf "short description of %s should begin with lowercase." name;
4416       let c = shortdesc.[String.length shortdesc-1] in
4417       if c = '\n' || c = '.' then
4418         failwithf "short description of %s should not end with . or \\n." name
4419   ) all_functions;
4420
4421   (* Check long dscriptions. *)
4422   List.iter (
4423     fun (name, _, _, _, _, _, longdesc) ->
4424       if longdesc.[String.length longdesc-1] = '\n' then
4425         failwithf "long description of %s should not end with \\n." name
4426   ) all_functions;
4427
4428   (* Check proc_nrs. *)
4429   List.iter (
4430     fun (name, _, proc_nr, _, _, _, _) ->
4431       if proc_nr <= 0 then
4432         failwithf "daemon function %s should have proc_nr > 0" name
4433   ) daemon_functions;
4434
4435   List.iter (
4436     fun (name, _, proc_nr, _, _, _, _) ->
4437       if proc_nr <> -1 then
4438         failwithf "non-daemon function %s should have proc_nr -1" name
4439   ) non_daemon_functions;
4440
4441   let proc_nrs =
4442     List.map (fun (name, _, proc_nr, _, _, _, _) -> name, proc_nr)
4443       daemon_functions in
4444   let proc_nrs =
4445     List.sort (fun (_,nr1) (_,nr2) -> compare nr1 nr2) proc_nrs in
4446   let rec loop = function
4447     | [] -> ()
4448     | [_] -> ()
4449     | (name1,nr1) :: ((name2,nr2) :: _ as rest) when nr1 < nr2 ->
4450         loop rest
4451     | (name1,nr1) :: (name2,nr2) :: _ ->
4452         failwithf "%s and %s have conflicting procedure numbers (%d, %d)"
4453           name1 name2 nr1 nr2
4454   in
4455   loop proc_nrs;
4456
4457   (* Check tests. *)
4458   List.iter (
4459     function
4460       (* Ignore functions that have no tests.  We generate a
4461        * warning when the user does 'make check' instead.
4462        *)
4463     | name, _, _, _, [], _, _ -> ()
4464     | name, _, _, _, tests, _, _ ->
4465         let funcs =
4466           List.map (
4467             fun (_, _, test) ->
4468               match seq_of_test test with
4469               | [] ->
4470                   failwithf "%s has a test containing an empty sequence" name
4471               | cmds -> List.map List.hd cmds
4472           ) tests in
4473         let funcs = List.flatten funcs in
4474
4475         let tested = List.mem name funcs in
4476
4477         if not tested then
4478           failwithf "function %s has tests but does not test itself" name
4479   ) all_functions
4480
4481 (* 'pr' prints to the current output file. *)
4482 let chan = ref stdout
4483 let pr fs = ksprintf (output_string !chan) fs
4484
4485 (* Generate a header block in a number of standard styles. *)
4486 type comment_style = CStyle | HashStyle | OCamlStyle | HaskellStyle
4487 type license = GPLv2 | LGPLv2
4488
4489 let generate_header comment license =
4490   let c = match comment with
4491     | CStyle ->     pr "/* "; " *"
4492     | HashStyle ->  pr "# ";  "#"
4493     | OCamlStyle -> pr "(* "; " *"
4494     | HaskellStyle -> pr "{- "; "  " in
4495   pr "libguestfs generated file\n";
4496   pr "%s WARNING: THIS FILE IS GENERATED BY 'src/generator.ml'.\n" c;
4497   pr "%s ANY CHANGES YOU MAKE TO THIS FILE WILL BE LOST.\n" c;
4498   pr "%s\n" c;
4499   pr "%s Copyright (C) 2009 Red Hat Inc.\n" c;
4500   pr "%s\n" c;
4501   (match license with
4502    | GPLv2 ->
4503        pr "%s This program is free software; you can redistribute it and/or modify\n" c;
4504        pr "%s it under the terms of the GNU General Public License as published by\n" c;
4505        pr "%s the Free Software Foundation; either version 2 of the License, or\n" c;
4506        pr "%s (at your option) any later version.\n" c;
4507        pr "%s\n" c;
4508        pr "%s This program is distributed in the hope that it will be useful,\n" c;
4509        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
4510        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" c;
4511        pr "%s GNU General Public License for more details.\n" c;
4512        pr "%s\n" c;
4513        pr "%s You should have received a copy of the GNU General Public License along\n" c;
4514        pr "%s with this program; if not, write to the Free Software Foundation, Inc.,\n" c;
4515        pr "%s 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n" c;
4516
4517    | LGPLv2 ->
4518        pr "%s This library is free software; you can redistribute it and/or\n" c;
4519        pr "%s modify it under the terms of the GNU Lesser General Public\n" c;
4520        pr "%s License as published by the Free Software Foundation; either\n" c;
4521        pr "%s version 2 of the License, or (at your option) any later version.\n" c;
4522        pr "%s\n" c;
4523        pr "%s This library is distributed in the hope that it will be useful,\n" c;
4524        pr "%s but WITHOUT ANY WARRANTY; without even the implied warranty of\n" c;
4525        pr "%s MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n" c;
4526        pr "%s Lesser General Public License for more details.\n" c;
4527        pr "%s\n" c;
4528        pr "%s You should have received a copy of the GNU Lesser General Public\n" c;
4529        pr "%s License along with this library; if not, write to the Free Software\n" c;
4530        pr "%s Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n" c;
4531   );
4532   (match comment with
4533    | CStyle -> pr " */\n"
4534    | HashStyle -> ()
4535    | OCamlStyle -> pr " *)\n"
4536    | HaskellStyle -> pr "-}\n"
4537   );
4538   pr "\n"
4539
4540 (* Start of main code generation functions below this line. *)
4541
4542 (* Generate the pod documentation for the C API. *)
4543 let rec generate_actions_pod () =
4544   List.iter (
4545     fun (shortname, style, _, flags, _, _, longdesc) ->
4546       if not (List.mem NotInDocs flags) then (
4547         let name = "guestfs_" ^ shortname in
4548         pr "=head2 %s\n\n" name;
4549         pr " ";
4550         generate_prototype ~extern:false ~handle:"handle" name style;
4551         pr "\n\n";
4552         pr "%s\n\n" longdesc;
4553         (match fst style with
4554          | RErr ->
4555              pr "This function returns 0 on success or -1 on error.\n\n"
4556          | RInt _ ->
4557              pr "On error this function returns -1.\n\n"
4558          | RInt64 _ ->
4559              pr "On error this function returns -1.\n\n"
4560          | RBool _ ->
4561              pr "This function returns a C truth value on success or -1 on error.\n\n"
4562          | RConstString _ ->
4563              pr "This function returns a string, or NULL on error.
4564 The string is owned by the guest handle and must I<not> be freed.\n\n"
4565          | RConstOptString _ ->
4566              pr "This function returns a string which may be NULL.
4567 There is way to return an error from this function.
4568 The string is owned by the guest handle and must I<not> be freed.\n\n"
4569          | RString _ ->
4570              pr "This function returns a string, or NULL on error.
4571 I<The caller must free the returned string after use>.\n\n"
4572          | RStringList _ ->
4573              pr "This function returns a NULL-terminated array of strings
4574 (like L<environ(3)>), or NULL if there was an error.
4575 I<The caller must free the strings and the array after use>.\n\n"
4576          | RStruct (_, typ) ->
4577              pr "This function returns a C<struct guestfs_%s *>,
4578 or NULL if there was an error.
4579 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
4580          | RStructList (_, typ) ->
4581              pr "This function returns a C<struct guestfs_%s_list *>
4582 (see E<lt>guestfs-structs.hE<gt>),
4583 or NULL if there was an error.
4584 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
4585          | RHashtable _ ->
4586              pr "This function returns a NULL-terminated array of
4587 strings, or NULL if there was an error.
4588 The array of strings will always have length C<2n+1>, where
4589 C<n> keys and values alternate, followed by the trailing NULL entry.
4590 I<The caller must free the strings and the array after use>.\n\n"
4591          | RBufferOut _ ->
4592              pr "This function returns a buffer, or NULL on error.
4593 The size of the returned buffer is written to C<*size_r>.
4594 I<The caller must free the returned buffer after use>.\n\n"
4595         );
4596         if List.mem ProtocolLimitWarning flags then
4597           pr "%s\n\n" protocol_limit_warning;
4598         if List.mem DangerWillRobinson flags then
4599           pr "%s\n\n" danger_will_robinson;
4600         match deprecation_notice flags with
4601         | None -> ()
4602         | Some txt -> pr "%s\n\n" txt
4603       )
4604   ) all_functions_sorted
4605
4606 and generate_structs_pod () =
4607   (* Structs documentation. *)
4608   List.iter (
4609     fun (typ, cols) ->
4610       pr "=head2 guestfs_%s\n" typ;
4611       pr "\n";
4612       pr " struct guestfs_%s {\n" typ;
4613       List.iter (
4614         function
4615         | name, FChar -> pr "   char %s;\n" name
4616         | name, FUInt32 -> pr "   uint32_t %s;\n" name
4617         | name, FInt32 -> pr "   int32_t %s;\n" name
4618         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
4619         | name, FInt64 -> pr "   int64_t %s;\n" name
4620         | name, FString -> pr "   char *%s;\n" name
4621         | name, FBuffer ->
4622             pr "   /* The next two fields describe a byte array. */\n";
4623             pr "   uint32_t %s_len;\n" name;
4624             pr "   char *%s;\n" name
4625         | name, FUUID ->
4626             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
4627             pr "   char %s[32];\n" name
4628         | name, FOptPercent ->
4629             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
4630             pr "   float %s;\n" name
4631       ) cols;
4632       pr " };\n";
4633       pr " \n";
4634       pr " struct guestfs_%s_list {\n" typ;
4635       pr "   uint32_t len; /* Number of elements in list. */\n";
4636       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
4637       pr " };\n";
4638       pr " \n";
4639       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
4640       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
4641         typ typ;
4642       pr "\n"
4643   ) structs
4644
4645 (* Generate the protocol (XDR) file, 'guestfs_protocol.x' and
4646  * indirectly 'guestfs_protocol.h' and 'guestfs_protocol.c'.
4647  *
4648  * We have to use an underscore instead of a dash because otherwise
4649  * rpcgen generates incorrect code.
4650  *
4651  * This header is NOT exported to clients, but see also generate_structs_h.
4652  *)
4653 and generate_xdr () =
4654   generate_header CStyle LGPLv2;
4655
4656   (* This has to be defined to get around a limitation in Sun's rpcgen. *)
4657   pr "typedef string str<>;\n";
4658   pr "\n";
4659
4660   (* Internal structures. *)
4661   List.iter (
4662     function
4663     | typ, cols ->
4664         pr "struct guestfs_int_%s {\n" typ;
4665         List.iter (function
4666                    | name, FChar -> pr "  char %s;\n" name
4667                    | name, FString -> pr "  string %s<>;\n" name
4668                    | name, FBuffer -> pr "  opaque %s<>;\n" name
4669                    | name, FUUID -> pr "  opaque %s[32];\n" name
4670                    | name, (FInt32|FUInt32) -> pr "  int %s;\n" name
4671                    | name, (FInt64|FUInt64|FBytes) -> pr "  hyper %s;\n" name
4672                    | name, FOptPercent -> pr "  float %s;\n" name
4673                   ) cols;
4674         pr "};\n";
4675         pr "\n";
4676         pr "typedef struct guestfs_int_%s guestfs_int_%s_list<>;\n" typ typ;
4677         pr "\n";
4678   ) structs;
4679
4680   List.iter (
4681     fun (shortname, style, _, _, _, _, _) ->
4682       let name = "guestfs_" ^ shortname in
4683
4684       (match snd style with
4685        | [] -> ()
4686        | args ->
4687            pr "struct %s_args {\n" name;
4688            List.iter (
4689              function
4690              | Pathname n | Device n | Dev_or_Path n | String n ->
4691                  pr "  string %s<>;\n" n
4692              | OptString n -> pr "  str *%s;\n" n
4693              | StringList n | DeviceList n -> pr "  str %s<>;\n" n
4694              | Bool n -> pr "  bool %s;\n" n
4695              | Int n -> pr "  int %s;\n" n
4696              | Int64 n -> pr "  hyper %s;\n" n
4697              | FileIn _ | FileOut _ -> ()
4698            ) args;
4699            pr "};\n\n"
4700       );
4701       (match fst style with
4702        | RErr -> ()
4703        | RInt n ->
4704            pr "struct %s_ret {\n" name;
4705            pr "  int %s;\n" n;
4706            pr "};\n\n"
4707        | RInt64 n ->
4708            pr "struct %s_ret {\n" name;
4709            pr "  hyper %s;\n" n;
4710            pr "};\n\n"
4711        | RBool n ->
4712            pr "struct %s_ret {\n" name;
4713            pr "  bool %s;\n" n;
4714            pr "};\n\n"
4715        | RConstString _ | RConstOptString _ ->
4716            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
4717        | RString n ->
4718            pr "struct %s_ret {\n" name;
4719            pr "  string %s<>;\n" n;
4720            pr "};\n\n"
4721        | RStringList n ->
4722            pr "struct %s_ret {\n" name;
4723            pr "  str %s<>;\n" n;
4724            pr "};\n\n"
4725        | RStruct (n, typ) ->
4726            pr "struct %s_ret {\n" name;
4727            pr "  guestfs_int_%s %s;\n" typ n;
4728            pr "};\n\n"
4729        | RStructList (n, typ) ->
4730            pr "struct %s_ret {\n" name;
4731            pr "  guestfs_int_%s_list %s;\n" typ n;
4732            pr "};\n\n"
4733        | RHashtable n ->
4734            pr "struct %s_ret {\n" name;
4735            pr "  str %s<>;\n" n;
4736            pr "};\n\n"
4737        | RBufferOut n ->
4738            pr "struct %s_ret {\n" name;
4739            pr "  opaque %s<>;\n" n;
4740            pr "};\n\n"
4741       );
4742   ) daemon_functions;
4743
4744   (* Table of procedure numbers. *)
4745   pr "enum guestfs_procedure {\n";
4746   List.iter (
4747     fun (shortname, _, proc_nr, _, _, _, _) ->
4748       pr "  GUESTFS_PROC_%s = %d,\n" (String.uppercase shortname) proc_nr
4749   ) daemon_functions;
4750   pr "  GUESTFS_PROC_NR_PROCS\n";
4751   pr "};\n";
4752   pr "\n";
4753
4754   (* Having to choose a maximum message size is annoying for several
4755    * reasons (it limits what we can do in the API), but it (a) makes
4756    * the protocol a lot simpler, and (b) provides a bound on the size
4757    * of the daemon which operates in limited memory space.  For large
4758    * file transfers you should use FTP.
4759    *)
4760   pr "const GUESTFS_MESSAGE_MAX = %d;\n" (4 * 1024 * 1024);
4761   pr "\n";
4762
4763   (* Message header, etc. *)
4764   pr "\
4765 /* The communication protocol is now documented in the guestfs(3)
4766  * manpage.
4767  */
4768
4769 const GUESTFS_PROGRAM = 0x2000F5F5;
4770 const GUESTFS_PROTOCOL_VERSION = 1;
4771
4772 /* These constants must be larger than any possible message length. */
4773 const GUESTFS_LAUNCH_FLAG = 0xf5f55ff5;
4774 const GUESTFS_CANCEL_FLAG = 0xffffeeee;
4775
4776 enum guestfs_message_direction {
4777   GUESTFS_DIRECTION_CALL = 0,        /* client -> daemon */
4778   GUESTFS_DIRECTION_REPLY = 1        /* daemon -> client */
4779 };
4780
4781 enum guestfs_message_status {
4782   GUESTFS_STATUS_OK = 0,
4783   GUESTFS_STATUS_ERROR = 1
4784 };
4785
4786 const GUESTFS_ERROR_LEN = 256;
4787
4788 struct guestfs_message_error {
4789   string error_message<GUESTFS_ERROR_LEN>;
4790 };
4791
4792 struct guestfs_message_header {
4793   unsigned prog;                     /* GUESTFS_PROGRAM */
4794   unsigned vers;                     /* GUESTFS_PROTOCOL_VERSION */
4795   guestfs_procedure proc;            /* GUESTFS_PROC_x */
4796   guestfs_message_direction direction;
4797   unsigned serial;                   /* message serial number */
4798   guestfs_message_status status;
4799 };
4800
4801 const GUESTFS_MAX_CHUNK_SIZE = 8192;
4802
4803 struct guestfs_chunk {
4804   int cancel;                        /* if non-zero, transfer is cancelled */
4805   /* data size is 0 bytes if the transfer has finished successfully */
4806   opaque data<GUESTFS_MAX_CHUNK_SIZE>;
4807 };
4808 "
4809
4810 (* Generate the guestfs-structs.h file. *)
4811 and generate_structs_h () =
4812   generate_header CStyle LGPLv2;
4813
4814   (* This is a public exported header file containing various
4815    * structures.  The structures are carefully written to have
4816    * exactly the same in-memory format as the XDR structures that
4817    * we use on the wire to the daemon.  The reason for creating
4818    * copies of these structures here is just so we don't have to
4819    * export the whole of guestfs_protocol.h (which includes much
4820    * unrelated and XDR-dependent stuff that we don't want to be
4821    * public, or required by clients).
4822    *
4823    * To reiterate, we will pass these structures to and from the
4824    * client with a simple assignment or memcpy, so the format
4825    * must be identical to what rpcgen / the RFC defines.
4826    *)
4827
4828   (* Public structures. *)
4829   List.iter (
4830     fun (typ, cols) ->
4831       pr "struct guestfs_%s {\n" typ;
4832       List.iter (
4833         function
4834         | name, FChar -> pr "  char %s;\n" name
4835         | name, FString -> pr "  char *%s;\n" name
4836         | name, FBuffer ->
4837             pr "  uint32_t %s_len;\n" name;
4838             pr "  char *%s;\n" name
4839         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
4840         | name, FUInt32 -> pr "  uint32_t %s;\n" name
4841         | name, FInt32 -> pr "  int32_t %s;\n" name
4842         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
4843         | name, FInt64 -> pr "  int64_t %s;\n" name
4844         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
4845       ) cols;
4846       pr "};\n";
4847       pr "\n";
4848       pr "struct guestfs_%s_list {\n" typ;
4849       pr "  uint32_t len;\n";
4850       pr "  struct guestfs_%s *val;\n" typ;
4851       pr "};\n";
4852       pr "\n";
4853       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
4854       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
4855       pr "\n"
4856   ) structs
4857
4858 (* Generate the guestfs-actions.h file. *)
4859 and generate_actions_h () =
4860   generate_header CStyle LGPLv2;
4861   List.iter (
4862     fun (shortname, style, _, _, _, _, _) ->
4863       let name = "guestfs_" ^ shortname in
4864       generate_prototype ~single_line:true ~newline:true ~handle:"handle"
4865         name style
4866   ) all_functions
4867
4868 (* Generate the guestfs-internal-actions.h file. *)
4869 and generate_internal_actions_h () =
4870   generate_header CStyle LGPLv2;
4871   List.iter (
4872     fun (shortname, style, _, _, _, _, _) ->
4873       let name = "guestfs__" ^ shortname in
4874       generate_prototype ~single_line:true ~newline:true ~handle:"handle"
4875         name style
4876   ) non_daemon_functions
4877
4878 (* Generate the client-side dispatch stubs. *)
4879 and generate_client_actions () =
4880   generate_header CStyle LGPLv2;
4881
4882   pr "\
4883 #include <stdio.h>
4884 #include <stdlib.h>
4885 #include <stdint.h>
4886 #include <inttypes.h>
4887
4888 #include \"guestfs.h\"
4889 #include \"guestfs-internal-actions.h\"
4890 #include \"guestfs_protocol.h\"
4891
4892 #define error guestfs_error
4893 //#define perrorf guestfs_perrorf
4894 //#define safe_malloc guestfs_safe_malloc
4895 #define safe_realloc guestfs_safe_realloc
4896 //#define safe_strdup guestfs_safe_strdup
4897 #define safe_memdup guestfs_safe_memdup
4898
4899 /* Check the return message from a call for validity. */
4900 static int
4901 check_reply_header (guestfs_h *g,
4902                     const struct guestfs_message_header *hdr,
4903                     unsigned int proc_nr, unsigned int serial)
4904 {
4905   if (hdr->prog != GUESTFS_PROGRAM) {
4906     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
4907     return -1;
4908   }
4909   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
4910     error (g, \"wrong protocol version (%%d/%%d)\",
4911            hdr->vers, GUESTFS_PROTOCOL_VERSION);
4912     return -1;
4913   }
4914   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
4915     error (g, \"unexpected message direction (%%d/%%d)\",
4916            hdr->direction, GUESTFS_DIRECTION_REPLY);
4917     return -1;
4918   }
4919   if (hdr->proc != proc_nr) {
4920     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
4921     return -1;
4922   }
4923   if (hdr->serial != serial) {
4924     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
4925     return -1;
4926   }
4927
4928   return 0;
4929 }
4930
4931 /* Check we are in the right state to run a high-level action. */
4932 static int
4933 check_state (guestfs_h *g, const char *caller)
4934 {
4935   if (!guestfs__is_ready (g)) {
4936     if (guestfs__is_config (g) || guestfs__is_launching (g))
4937       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
4938         caller);
4939     else
4940       error (g, \"%%s called from the wrong state, %%d != READY\",
4941         caller, guestfs__get_state (g));
4942     return -1;
4943   }
4944   return 0;
4945 }
4946
4947 ";
4948
4949   (* Generate code to generate guestfish call traces. *)
4950   let trace_call shortname style =
4951     pr "  if (guestfs__get_trace (g)) {\n";
4952
4953     let needs_i =
4954       List.exists (function
4955                    | StringList _ | DeviceList _ -> true
4956                    | _ -> false) (snd style) in
4957     if needs_i then (
4958       pr "    int i;\n";
4959       pr "\n"
4960     );
4961
4962     pr "    printf (\"%s\");\n" shortname;
4963     List.iter (
4964       function
4965       | String n                        (* strings *)
4966       | Device n
4967       | Pathname n
4968       | Dev_or_Path n
4969       | FileIn n
4970       | FileOut n ->
4971           (* guestfish doesn't support string escaping, so neither do we *)
4972           pr "    printf (\" \\\"%%s\\\"\", %s);\n" n
4973       | OptString n ->                  (* string option *)
4974           pr "    if (%s) printf (\" \\\"%%s\\\"\", %s);\n" n n;
4975           pr "    else printf (\" null\");\n"
4976       | StringList n
4977       | DeviceList n ->                 (* string list *)
4978           pr "    putchar (' ');\n";
4979           pr "    putchar ('\"');\n";
4980           pr "    for (i = 0; %s[i]; ++i) {\n" n;
4981           pr "      if (i > 0) putchar (' ');\n";
4982           pr "      fputs (%s[i], stdout);\n" n;
4983           pr "    }\n";
4984           pr "    putchar ('\"');\n";
4985       | Bool n ->                       (* boolean *)
4986           pr "    fputs (%s ? \" true\" : \" false\", stdout);\n" n
4987       | Int n ->                        (* int *)
4988           pr "    printf (\" %%d\", %s);\n" n
4989       | Int64 n ->
4990           pr "    printf (\" %%\" PRIi64, %s);\n" n
4991     ) (snd style);
4992     pr "    putchar ('\\n');\n";
4993     pr "  }\n";
4994     pr "\n";
4995   in
4996
4997   (* For non-daemon functions, generate a wrapper around each function. *)
4998   List.iter (
4999     fun (shortname, style, _, _, _, _, _) ->
5000       let name = "guestfs_" ^ shortname in
5001
5002       generate_prototype ~extern:false ~semicolon:false ~newline:true
5003         ~handle:"g" name style;
5004       pr "{\n";
5005       trace_call shortname style;
5006       pr "  return guestfs__%s " shortname;
5007       generate_c_call_args ~handle:"g" style;
5008       pr ";\n";
5009       pr "}\n";
5010       pr "\n"
5011   ) non_daemon_functions;
5012
5013   (* Client-side stubs for each function. *)
5014   List.iter (
5015     fun (shortname, style, _, _, _, _, _) ->
5016       let name = "guestfs_" ^ shortname in
5017
5018       (* Generate the action stub. *)
5019       generate_prototype ~extern:false ~semicolon:false ~newline:true
5020         ~handle:"g" name style;
5021
5022       let error_code =
5023         match fst style with
5024         | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
5025         | RConstString _ | RConstOptString _ ->
5026             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5027         | RString _ | RStringList _
5028         | RStruct _ | RStructList _
5029         | RHashtable _ | RBufferOut _ ->
5030             "NULL" in
5031
5032       pr "{\n";
5033
5034       (match snd style with
5035        | [] -> ()
5036        | _ -> pr "  struct %s_args args;\n" name
5037       );
5038
5039       pr "  guestfs_message_header hdr;\n";
5040       pr "  guestfs_message_error err;\n";
5041       let has_ret =
5042         match fst style with
5043         | RErr -> false
5044         | RConstString _ | RConstOptString _ ->
5045             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5046         | RInt _ | RInt64 _
5047         | RBool _ | RString _ | RStringList _
5048         | RStruct _ | RStructList _
5049         | RHashtable _ | RBufferOut _ ->
5050             pr "  struct %s_ret ret;\n" name;
5051             true in
5052
5053       pr "  int serial;\n";
5054       pr "  int r;\n";
5055       pr "\n";
5056       trace_call shortname style;
5057       pr "  if (check_state (g, \"%s\") == -1) return %s;\n" name error_code;
5058       pr "  guestfs___set_busy (g);\n";
5059       pr "\n";
5060
5061       (* Send the main header and arguments. *)
5062       (match snd style with
5063        | [] ->
5064            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
5065              (String.uppercase shortname)
5066        | args ->
5067            List.iter (
5068              function
5069              | Pathname n | Device n | Dev_or_Path n | String n ->
5070                  pr "  args.%s = (char *) %s;\n" n n
5071              | OptString n ->
5072                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
5073              | StringList n | DeviceList n ->
5074                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
5075                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
5076              | Bool n ->
5077                  pr "  args.%s = %s;\n" n n
5078              | Int n ->
5079                  pr "  args.%s = %s;\n" n n
5080              | Int64 n ->
5081                  pr "  args.%s = %s;\n" n n
5082              | FileIn _ | FileOut _ -> ()
5083            ) args;
5084            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
5085              (String.uppercase shortname);
5086            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
5087              name;
5088       );
5089       pr "  if (serial == -1) {\n";
5090       pr "    guestfs___end_busy (g);\n";
5091       pr "    return %s;\n" error_code;
5092       pr "  }\n";
5093       pr "\n";
5094
5095       (* Send any additional files (FileIn) requested. *)
5096       let need_read_reply_label = ref false in
5097       List.iter (
5098         function
5099         | FileIn n ->
5100             pr "  r = guestfs___send_file (g, %s);\n" n;
5101             pr "  if (r == -1) {\n";
5102             pr "    guestfs___end_busy (g);\n";
5103             pr "    return %s;\n" error_code;
5104             pr "  }\n";
5105             pr "  if (r == -2) /* daemon cancelled */\n";
5106             pr "    goto read_reply;\n";
5107             need_read_reply_label := true;
5108             pr "\n";
5109         | _ -> ()
5110       ) (snd style);
5111
5112       (* Wait for the reply from the remote end. *)
5113       if !need_read_reply_label then pr " read_reply:\n";
5114       pr "  memset (&hdr, 0, sizeof hdr);\n";
5115       pr "  memset (&err, 0, sizeof err);\n";
5116       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
5117       pr "\n";
5118       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
5119       if not has_ret then
5120         pr "NULL, NULL"
5121       else
5122         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
5123       pr ");\n";
5124
5125       pr "  if (r == -1) {\n";
5126       pr "    guestfs___end_busy (g);\n";
5127       pr "    return %s;\n" error_code;
5128       pr "  }\n";
5129       pr "\n";
5130
5131       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
5132         (String.uppercase shortname);
5133       pr "    guestfs___end_busy (g);\n";
5134       pr "    return %s;\n" error_code;
5135       pr "  }\n";
5136       pr "\n";
5137
5138       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
5139       pr "    error (g, \"%%s: %%s\", \"%s\", err.error_message);\n" shortname;
5140       pr "    free (err.error_message);\n";
5141       pr "    guestfs___end_busy (g);\n";
5142       pr "    return %s;\n" error_code;
5143       pr "  }\n";
5144       pr "\n";
5145
5146       (* Expecting to receive further files (FileOut)? *)
5147       List.iter (
5148         function
5149         | FileOut n ->
5150             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
5151             pr "    guestfs___end_busy (g);\n";
5152             pr "    return %s;\n" error_code;
5153             pr "  }\n";
5154             pr "\n";
5155         | _ -> ()
5156       ) (snd style);
5157
5158       pr "  guestfs___end_busy (g);\n";
5159
5160       (match fst style with
5161        | RErr -> pr "  return 0;\n"
5162        | RInt n | RInt64 n | RBool n ->
5163            pr "  return ret.%s;\n" n
5164        | RConstString _ | RConstOptString _ ->
5165            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5166        | RString n ->
5167            pr "  return ret.%s; /* caller will free */\n" n
5168        | RStringList n | RHashtable n ->
5169            pr "  /* caller will free this, but we need to add a NULL entry */\n";
5170            pr "  ret.%s.%s_val =\n" n n;
5171            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
5172            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
5173              n n;
5174            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
5175            pr "  return ret.%s.%s_val;\n" n n
5176        | RStruct (n, _) ->
5177            pr "  /* caller will free this */\n";
5178            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
5179        | RStructList (n, _) ->
5180            pr "  /* caller will free this */\n";
5181            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
5182        | RBufferOut n ->
5183            pr "  *size_r = ret.%s.%s_len;\n" n n;
5184            pr "  return ret.%s.%s_val; /* caller will free */\n" n n
5185       );
5186
5187       pr "}\n\n"
5188   ) daemon_functions;
5189
5190   (* Functions to free structures. *)
5191   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
5192   pr " * structure format is identical to the XDR format.  See note in\n";
5193   pr " * generator.ml.\n";
5194   pr " */\n";
5195   pr "\n";
5196
5197   List.iter (
5198     fun (typ, _) ->
5199       pr "void\n";
5200       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
5201       pr "{\n";
5202       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
5203       pr "  free (x);\n";
5204       pr "}\n";
5205       pr "\n";
5206
5207       pr "void\n";
5208       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
5209       pr "{\n";
5210       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
5211       pr "  free (x);\n";
5212       pr "}\n";
5213       pr "\n";
5214
5215   ) structs;
5216
5217 (* Generate daemon/actions.h. *)
5218 and generate_daemon_actions_h () =
5219   generate_header CStyle GPLv2;
5220
5221   pr "#include \"../src/guestfs_protocol.h\"\n";
5222   pr "\n";
5223
5224   List.iter (
5225     fun (name, style, _, _, _, _, _) ->
5226       generate_prototype
5227         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
5228         name style;
5229   ) daemon_functions
5230
5231 (* Generate the server-side stubs. *)
5232 and generate_daemon_actions () =
5233   generate_header CStyle GPLv2;
5234
5235   pr "#include <config.h>\n";
5236   pr "\n";
5237   pr "#include <stdio.h>\n";
5238   pr "#include <stdlib.h>\n";
5239   pr "#include <string.h>\n";
5240   pr "#include <inttypes.h>\n";
5241   pr "#include <rpc/types.h>\n";
5242   pr "#include <rpc/xdr.h>\n";
5243   pr "\n";
5244   pr "#include \"daemon.h\"\n";
5245   pr "#include \"c-ctype.h\"\n";
5246   pr "#include \"../src/guestfs_protocol.h\"\n";
5247   pr "#include \"actions.h\"\n";
5248   pr "\n";
5249
5250   List.iter (
5251     fun (name, style, _, _, _, _, _) ->
5252       (* Generate server-side stubs. *)
5253       pr "static void %s_stub (XDR *xdr_in)\n" name;
5254       pr "{\n";
5255       let error_code =
5256         match fst style with
5257         | RErr | RInt _ -> pr "  int r;\n"; "-1"
5258         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
5259         | RBool _ -> pr "  int r;\n"; "-1"
5260         | RConstString _ | RConstOptString _ ->
5261             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5262         | RString _ -> pr "  char *r;\n"; "NULL"
5263         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
5264         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
5265         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
5266         | RBufferOut _ ->
5267             pr "  size_t size;\n";
5268             pr "  char *r;\n";
5269             "NULL" in
5270
5271       (match snd style with
5272        | [] -> ()
5273        | args ->
5274            pr "  struct guestfs_%s_args args;\n" name;
5275            List.iter (
5276              function
5277              | Device n | Dev_or_Path n
5278              | Pathname n
5279              | String n -> ()
5280              | OptString n -> pr "  char *%s;\n" n
5281              | StringList n | DeviceList n -> pr "  char **%s;\n" n
5282              | Bool n -> pr "  int %s;\n" n
5283              | Int n -> pr "  int %s;\n" n
5284              | Int64 n -> pr "  int64_t %s;\n" n
5285              | FileIn _ | FileOut _ -> ()
5286            ) args
5287       );
5288       pr "\n";
5289
5290       (match snd style with
5291        | [] -> ()
5292        | args ->
5293            pr "  memset (&args, 0, sizeof args);\n";
5294            pr "\n";
5295            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
5296            pr "    reply_with_error (\"%%s: daemon failed to decode procedure arguments\", \"%s\");\n" name;
5297            pr "    return;\n";
5298            pr "  }\n";
5299            let pr_args n =
5300              pr "  char *%s = args.%s;\n" n n
5301            in
5302            let pr_list_handling_code n =
5303              pr "  %s = realloc (args.%s.%s_val,\n" n n n;
5304              pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
5305              pr "  if (%s == NULL) {\n" n;
5306              pr "    reply_with_perror (\"realloc\");\n";
5307              pr "    goto done;\n";
5308              pr "  }\n";
5309              pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
5310              pr "  args.%s.%s_val = %s;\n" n n n;
5311            in
5312            List.iter (
5313              function
5314              | Pathname n ->
5315                  pr_args n;
5316                  pr "  ABS_PATH (%s, goto done);\n" n;
5317              | Device n ->
5318                  pr_args n;
5319                  pr "  RESOLVE_DEVICE (%s, goto done);\n" n;
5320              | Dev_or_Path n ->
5321                  pr_args n;
5322                  pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, goto done);\n" n;
5323              | String n -> pr_args n
5324              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
5325              | StringList n ->
5326                  pr_list_handling_code n;
5327              | DeviceList n ->
5328                  pr_list_handling_code n;
5329                  pr "  /* Ensure that each is a device,\n";
5330                  pr "   * and perform device name translation. */\n";
5331                  pr "  { int pvi; for (pvi = 0; physvols[pvi] != NULL; ++pvi)\n";
5332                  pr "    RESOLVE_DEVICE (physvols[pvi], goto done);\n";
5333                  pr "  }\n";
5334              | Bool n -> pr "  %s = args.%s;\n" n n
5335              | Int n -> pr "  %s = args.%s;\n" n n
5336              | Int64 n -> pr "  %s = args.%s;\n" n n
5337              | FileIn _ | FileOut _ -> ()
5338            ) args;
5339            pr "\n"
5340       );
5341
5342
5343       (* this is used at least for do_equal *)
5344       if List.exists (function Pathname _ -> true | _ -> false) (snd style) then (
5345         (* Emit NEED_ROOT just once, even when there are two or
5346            more Pathname args *)
5347         pr "  NEED_ROOT (goto done);\n";
5348       );
5349
5350       (* Don't want to call the impl with any FileIn or FileOut
5351        * parameters, since these go "outside" the RPC protocol.
5352        *)
5353       let args' =
5354         List.filter (function FileIn _ | FileOut _ -> false | _ -> true)
5355           (snd style) in
5356       pr "  r = do_%s " name;
5357       generate_c_call_args (fst style, args');
5358       pr ";\n";
5359
5360       pr "  if (r == %s)\n" error_code;
5361       pr "    /* do_%s has already called reply_with_error */\n" name;
5362       pr "    goto done;\n";
5363       pr "\n";
5364
5365       (* If there are any FileOut parameters, then the impl must
5366        * send its own reply.
5367        *)
5368       let no_reply =
5369         List.exists (function FileOut _ -> true | _ -> false) (snd style) in
5370       if no_reply then
5371         pr "  /* do_%s has already sent a reply */\n" name
5372       else (
5373         match fst style with
5374         | RErr -> pr "  reply (NULL, NULL);\n"
5375         | RInt n | RInt64 n | RBool n ->
5376             pr "  struct guestfs_%s_ret ret;\n" name;
5377             pr "  ret.%s = r;\n" n;
5378             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5379               name
5380         | RConstString _ | RConstOptString _ ->
5381             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
5382         | RString n ->
5383             pr "  struct guestfs_%s_ret ret;\n" name;
5384             pr "  ret.%s = r;\n" n;
5385             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5386               name;
5387             pr "  free (r);\n"
5388         | RStringList n | RHashtable n ->
5389             pr "  struct guestfs_%s_ret ret;\n" name;
5390             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
5391             pr "  ret.%s.%s_val = r;\n" n n;
5392             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5393               name;
5394             pr "  free_strings (r);\n"
5395         | RStruct (n, _) ->
5396             pr "  struct guestfs_%s_ret ret;\n" name;
5397             pr "  ret.%s = *r;\n" n;
5398             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5399               name;
5400             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5401               name
5402         | RStructList (n, _) ->
5403             pr "  struct guestfs_%s_ret ret;\n" name;
5404             pr "  ret.%s = *r;\n" n;
5405             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5406               name;
5407             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
5408               name
5409         | RBufferOut n ->
5410             pr "  struct guestfs_%s_ret ret;\n" name;
5411             pr "  ret.%s.%s_val = r;\n" n n;
5412             pr "  ret.%s.%s_len = size;\n" n n;
5413             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
5414               name;
5415             pr "  free (r);\n"
5416       );
5417
5418       (* Free the args. *)
5419       (match snd style with
5420        | [] ->
5421            pr "done: ;\n";
5422        | _ ->
5423            pr "done:\n";
5424            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
5425              name
5426       );
5427
5428       pr "}\n\n";
5429   ) daemon_functions;
5430
5431   (* Dispatch function. *)
5432   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
5433   pr "{\n";
5434   pr "  switch (proc_nr) {\n";
5435
5436   List.iter (
5437     fun (name, style, _, _, _, _, _) ->
5438       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
5439       pr "      %s_stub (xdr_in);\n" name;
5440       pr "      break;\n"
5441   ) daemon_functions;
5442
5443   pr "    default:\n";
5444   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";
5445   pr "  }\n";
5446   pr "}\n";
5447   pr "\n";
5448
5449   (* LVM columns and tokenization functions. *)
5450   (* XXX This generates crap code.  We should rethink how we
5451    * do this parsing.
5452    *)
5453   List.iter (
5454     function
5455     | typ, cols ->
5456         pr "static const char *lvm_%s_cols = \"%s\";\n"
5457           typ (String.concat "," (List.map fst cols));
5458         pr "\n";
5459
5460         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
5461         pr "{\n";
5462         pr "  char *tok, *p, *next;\n";
5463         pr "  int i, j;\n";
5464         pr "\n";
5465         (*
5466           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
5467           pr "\n";
5468         *)
5469         pr "  if (!str) {\n";
5470         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
5471         pr "    return -1;\n";
5472         pr "  }\n";
5473         pr "  if (!*str || c_isspace (*str)) {\n";
5474         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
5475         pr "    return -1;\n";
5476         pr "  }\n";
5477         pr "  tok = str;\n";
5478         List.iter (
5479           fun (name, coltype) ->
5480             pr "  if (!tok) {\n";
5481             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
5482             pr "    return -1;\n";
5483             pr "  }\n";
5484             pr "  p = strchrnul (tok, ',');\n";
5485             pr "  if (*p) next = p+1; else next = NULL;\n";
5486             pr "  *p = '\\0';\n";
5487             (match coltype with
5488              | FString ->
5489                  pr "  r->%s = strdup (tok);\n" name;
5490                  pr "  if (r->%s == NULL) {\n" name;
5491                  pr "    perror (\"strdup\");\n";
5492                  pr "    return -1;\n";
5493                  pr "  }\n"
5494              | FUUID ->
5495                  pr "  for (i = j = 0; i < 32; ++j) {\n";
5496                  pr "    if (tok[j] == '\\0') {\n";
5497                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
5498                  pr "      return -1;\n";
5499                  pr "    } else if (tok[j] != '-')\n";
5500                  pr "      r->%s[i++] = tok[j];\n" name;
5501                  pr "  }\n";
5502              | FBytes ->
5503                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
5504                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
5505                  pr "    return -1;\n";
5506                  pr "  }\n";
5507              | FInt64 ->
5508                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
5509                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
5510                  pr "    return -1;\n";
5511                  pr "  }\n";
5512              | FOptPercent ->
5513                  pr "  if (tok[0] == '\\0')\n";
5514                  pr "    r->%s = -1;\n" name;
5515                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
5516                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
5517                  pr "    return -1;\n";
5518                  pr "  }\n";
5519              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
5520                  assert false (* can never be an LVM column *)
5521             );
5522             pr "  tok = next;\n";
5523         ) cols;
5524
5525         pr "  if (tok != NULL) {\n";
5526         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
5527         pr "    return -1;\n";
5528         pr "  }\n";
5529         pr "  return 0;\n";
5530         pr "}\n";
5531         pr "\n";
5532
5533         pr "guestfs_int_lvm_%s_list *\n" typ;
5534         pr "parse_command_line_%ss (void)\n" typ;
5535         pr "{\n";
5536         pr "  char *out, *err;\n";
5537         pr "  char *p, *pend;\n";
5538         pr "  int r, i;\n";
5539         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
5540         pr "  void *newp;\n";
5541         pr "\n";
5542         pr "  ret = malloc (sizeof *ret);\n";
5543         pr "  if (!ret) {\n";
5544         pr "    reply_with_perror (\"malloc\");\n";
5545         pr "    return NULL;\n";
5546         pr "  }\n";
5547         pr "\n";
5548         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
5549         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
5550         pr "\n";
5551         pr "  r = command (&out, &err,\n";
5552         pr "           \"/sbin/lvm\", \"%ss\",\n" typ;
5553         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
5554         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
5555         pr "  if (r == -1) {\n";
5556         pr "    reply_with_error (\"%%s\", err);\n";
5557         pr "    free (out);\n";
5558         pr "    free (err);\n";
5559         pr "    free (ret);\n";
5560         pr "    return NULL;\n";
5561         pr "  }\n";
5562         pr "\n";
5563         pr "  free (err);\n";
5564         pr "\n";
5565         pr "  /* Tokenize each line of the output. */\n";
5566         pr "  p = out;\n";
5567         pr "  i = 0;\n";
5568         pr "  while (p) {\n";
5569         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
5570         pr "    if (pend) {\n";
5571         pr "      *pend = '\\0';\n";
5572         pr "      pend++;\n";
5573         pr "    }\n";
5574         pr "\n";
5575         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
5576         pr "      p++;\n";
5577         pr "\n";
5578         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
5579         pr "      p = pend;\n";
5580         pr "      continue;\n";
5581         pr "    }\n";
5582         pr "\n";
5583         pr "    /* Allocate some space to store this next entry. */\n";
5584         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
5585         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
5586         pr "    if (newp == NULL) {\n";
5587         pr "      reply_with_perror (\"realloc\");\n";
5588         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
5589         pr "      free (ret);\n";
5590         pr "      free (out);\n";
5591         pr "      return NULL;\n";
5592         pr "    }\n";
5593         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
5594         pr "\n";
5595         pr "    /* Tokenize the next entry. */\n";
5596         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
5597         pr "    if (r == -1) {\n";
5598         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
5599         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
5600         pr "      free (ret);\n";
5601         pr "      free (out);\n";
5602         pr "      return NULL;\n";
5603         pr "    }\n";
5604         pr "\n";
5605         pr "    ++i;\n";
5606         pr "    p = pend;\n";
5607         pr "  }\n";
5608         pr "\n";
5609         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
5610         pr "\n";
5611         pr "  free (out);\n";
5612         pr "  return ret;\n";
5613         pr "}\n"
5614
5615   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
5616
5617 (* Generate a list of function names, for debugging in the daemon.. *)
5618 and generate_daemon_names () =
5619   generate_header CStyle GPLv2;
5620
5621   pr "#include <config.h>\n";
5622   pr "\n";
5623   pr "#include \"daemon.h\"\n";
5624   pr "\n";
5625
5626   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
5627   pr "const char *function_names[] = {\n";
5628   List.iter (
5629     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
5630   ) daemon_functions;
5631   pr "};\n";
5632
5633 (* Generate the tests. *)
5634 and generate_tests () =
5635   generate_header CStyle GPLv2;
5636
5637   pr "\
5638 #include <stdio.h>
5639 #include <stdlib.h>
5640 #include <string.h>
5641 #include <unistd.h>
5642 #include <sys/types.h>
5643 #include <fcntl.h>
5644
5645 #include \"guestfs.h\"
5646
5647 static guestfs_h *g;
5648 static int suppress_error = 0;
5649
5650 static void print_error (guestfs_h *g, void *data, const char *msg)
5651 {
5652   if (!suppress_error)
5653     fprintf (stderr, \"%%s\\n\", msg);
5654 }
5655
5656 /* FIXME: nearly identical code appears in fish.c */
5657 static void print_strings (char *const *argv)
5658 {
5659   int argc;
5660
5661   for (argc = 0; argv[argc] != NULL; ++argc)
5662     printf (\"\\t%%s\\n\", argv[argc]);
5663 }
5664
5665 /*
5666 static void print_table (char const *const *argv)
5667 {
5668   int i;
5669
5670   for (i = 0; argv[i] != NULL; i += 2)
5671     printf (\"%%s: %%s\\n\", argv[i], argv[i+1]);
5672 }
5673 */
5674
5675 ";
5676
5677   (* Generate a list of commands which are not tested anywhere. *)
5678   pr "static void no_test_warnings (void)\n";
5679   pr "{\n";
5680
5681   let hash : (string, bool) Hashtbl.t = Hashtbl.create 13 in
5682   List.iter (
5683     fun (_, _, _, _, tests, _, _) ->
5684       let tests = filter_map (
5685         function
5686         | (_, (Always|If _|Unless _), test) -> Some test
5687         | (_, Disabled, _) -> None
5688       ) tests in
5689       let seq = List.concat (List.map seq_of_test tests) in
5690       let cmds_tested = List.map List.hd seq in
5691       List.iter (fun cmd -> Hashtbl.replace hash cmd true) cmds_tested
5692   ) all_functions;
5693
5694   List.iter (
5695     fun (name, _, _, _, _, _, _) ->
5696       if not (Hashtbl.mem hash name) then
5697         pr "  fprintf (stderr, \"warning: \\\"guestfs_%s\\\" has no tests\\n\");\n" name
5698   ) all_functions;
5699
5700   pr "}\n";
5701   pr "\n";
5702
5703   (* Generate the actual tests.  Note that we generate the tests
5704    * in reverse order, deliberately, so that (in general) the
5705    * newest tests run first.  This makes it quicker and easier to
5706    * debug them.
5707    *)
5708   let test_names =
5709     List.map (
5710       fun (name, _, _, _, tests, _, _) ->
5711         mapi (generate_one_test name) tests
5712     ) (List.rev all_functions) in
5713   let test_names = List.concat test_names in
5714   let nr_tests = List.length test_names in
5715
5716   pr "\
5717 int main (int argc, char *argv[])
5718 {
5719   char c = 0;
5720   unsigned long int n_failed = 0;
5721   const char *filename;
5722   int fd;
5723   int nr_tests, test_num = 0;
5724
5725   setbuf (stdout, NULL);
5726
5727   no_test_warnings ();
5728
5729   g = guestfs_create ();
5730   if (g == NULL) {
5731     printf (\"guestfs_create FAILED\\n\");
5732     exit (1);
5733   }
5734
5735   guestfs_set_error_handler (g, print_error, NULL);
5736
5737   guestfs_set_path (g, \"../appliance\");
5738
5739   filename = \"test1.img\";
5740   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
5741   if (fd == -1) {
5742     perror (filename);
5743     exit (1);
5744   }
5745   if (lseek (fd, %d, SEEK_SET) == -1) {
5746     perror (\"lseek\");
5747     close (fd);
5748     unlink (filename);
5749     exit (1);
5750   }
5751   if (write (fd, &c, 1) == -1) {
5752     perror (\"write\");
5753     close (fd);
5754     unlink (filename);
5755     exit (1);
5756   }
5757   if (close (fd) == -1) {
5758     perror (filename);
5759     unlink (filename);
5760     exit (1);
5761   }
5762   if (guestfs_add_drive (g, filename) == -1) {
5763     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
5764     exit (1);
5765   }
5766
5767   filename = \"test2.img\";
5768   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
5769   if (fd == -1) {
5770     perror (filename);
5771     exit (1);
5772   }
5773   if (lseek (fd, %d, SEEK_SET) == -1) {
5774     perror (\"lseek\");
5775     close (fd);
5776     unlink (filename);
5777     exit (1);
5778   }
5779   if (write (fd, &c, 1) == -1) {
5780     perror (\"write\");
5781     close (fd);
5782     unlink (filename);
5783     exit (1);
5784   }
5785   if (close (fd) == -1) {
5786     perror (filename);
5787     unlink (filename);
5788     exit (1);
5789   }
5790   if (guestfs_add_drive (g, filename) == -1) {
5791     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
5792     exit (1);
5793   }
5794
5795   filename = \"test3.img\";
5796   fd = open (filename, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_TRUNC, 0666);
5797   if (fd == -1) {
5798     perror (filename);
5799     exit (1);
5800   }
5801   if (lseek (fd, %d, SEEK_SET) == -1) {
5802     perror (\"lseek\");
5803     close (fd);
5804     unlink (filename);
5805     exit (1);
5806   }
5807   if (write (fd, &c, 1) == -1) {
5808     perror (\"write\");
5809     close (fd);
5810     unlink (filename);
5811     exit (1);
5812   }
5813   if (close (fd) == -1) {
5814     perror (filename);
5815     unlink (filename);
5816     exit (1);
5817   }
5818   if (guestfs_add_drive (g, filename) == -1) {
5819     printf (\"guestfs_add_drive %%s FAILED\\n\", filename);
5820     exit (1);
5821   }
5822
5823   if (guestfs_add_drive_ro (g, \"../images/test.iso\") == -1) {
5824     printf (\"guestfs_add_drive_ro ../images/test.iso FAILED\\n\");
5825     exit (1);
5826   }
5827
5828   if (guestfs_launch (g) == -1) {
5829     printf (\"guestfs_launch FAILED\\n\");
5830     exit (1);
5831   }
5832
5833   /* Set a timeout in case qemu hangs during launch (RHBZ#505329). */
5834   alarm (600);
5835
5836   /* Cancel previous alarm. */
5837   alarm (0);
5838
5839   nr_tests = %d;
5840
5841 " (500 * 1024 * 1024) (50 * 1024 * 1024) (10 * 1024 * 1024) nr_tests;
5842
5843   iteri (
5844     fun i test_name ->
5845       pr "  test_num++;\n";
5846       pr "  printf (\"%%3d/%%3d %s\\n\", test_num, nr_tests);\n" test_name;
5847       pr "  if (%s () == -1) {\n" test_name;
5848       pr "    printf (\"%s FAILED\\n\");\n" test_name;
5849       pr "    n_failed++;\n";
5850       pr "  }\n";
5851   ) test_names;
5852   pr "\n";
5853
5854   pr "  guestfs_close (g);\n";
5855   pr "  unlink (\"test1.img\");\n";
5856   pr "  unlink (\"test2.img\");\n";
5857   pr "  unlink (\"test3.img\");\n";
5858   pr "\n";
5859
5860   pr "  if (n_failed > 0) {\n";
5861   pr "    printf (\"***** %%lu / %%d tests FAILED *****\\n\", n_failed, nr_tests);\n";
5862   pr "    exit (1);\n";
5863   pr "  }\n";
5864   pr "\n";
5865
5866   pr "  exit (0);\n";
5867   pr "}\n"
5868
5869 and generate_one_test name i (init, prereq, test) =
5870   let test_name = sprintf "test_%s_%d" name i in
5871
5872   pr "\
5873 static int %s_skip (void)
5874 {
5875   const char *str;
5876
5877   str = getenv (\"TEST_ONLY\");
5878   if (str)
5879     return strstr (str, \"%s\") == NULL;
5880   str = getenv (\"SKIP_%s\");
5881   if (str && STREQ (str, \"1\")) return 1;
5882   str = getenv (\"SKIP_TEST_%s\");
5883   if (str && STREQ (str, \"1\")) return 1;
5884   return 0;
5885 }
5886
5887 " test_name name (String.uppercase test_name) (String.uppercase name);
5888
5889   (match prereq with
5890    | Disabled | Always -> ()
5891    | If code | Unless code ->
5892        pr "static int %s_prereq (void)\n" test_name;
5893        pr "{\n";
5894        pr "  %s\n" code;
5895        pr "}\n";
5896        pr "\n";
5897   );
5898
5899   pr "\
5900 static int %s (void)
5901 {
5902   if (%s_skip ()) {
5903     printf (\"        %%s skipped (reason: environment variable set)\\n\", \"%s\");
5904     return 0;
5905   }
5906
5907 " test_name test_name test_name;
5908
5909   (match prereq with
5910    | Disabled ->
5911        pr "  printf (\"        %%s skipped (reason: test disabled in generator)\\n\", \"%s\");\n" test_name
5912    | If _ ->
5913        pr "  if (! %s_prereq ()) {\n" test_name;
5914        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
5915        pr "    return 0;\n";
5916        pr "  }\n";
5917        pr "\n";
5918        generate_one_test_body name i test_name init test;
5919    | Unless _ ->
5920        pr "  if (%s_prereq ()) {\n" test_name;
5921        pr "    printf (\"        %%s skipped (reason: test prerequisite)\\n\", \"%s\");\n" test_name;
5922        pr "    return 0;\n";
5923        pr "  }\n";
5924        pr "\n";
5925        generate_one_test_body name i test_name init test;
5926    | Always ->
5927        generate_one_test_body name i test_name init test
5928   );
5929
5930   pr "  return 0;\n";
5931   pr "}\n";
5932   pr "\n";
5933   test_name
5934
5935 and generate_one_test_body name i test_name init test =
5936   (match init with
5937    | InitNone (* XXX at some point, InitNone and InitEmpty became
5938                * folded together as the same thing.  Really we should
5939                * make InitNone do nothing at all, but the tests may
5940                * need to be checked to make sure this is OK.
5941                *)
5942    | InitEmpty ->
5943        pr "  /* InitNone|InitEmpty for %s */\n" test_name;
5944        List.iter (generate_test_command_call test_name)
5945          [["blockdev_setrw"; "/dev/sda"];
5946           ["umount_all"];
5947           ["lvm_remove_all"]]
5948    | InitPartition ->
5949        pr "  /* InitPartition for %s: create /dev/sda1 */\n" test_name;
5950        List.iter (generate_test_command_call test_name)
5951          [["blockdev_setrw"; "/dev/sda"];
5952           ["umount_all"];
5953           ["lvm_remove_all"];
5954           ["sfdiskM"; "/dev/sda"; ","]]
5955    | InitBasicFS ->
5956        pr "  /* InitBasicFS for %s: create ext2 on /dev/sda1 */\n" test_name;
5957        List.iter (generate_test_command_call test_name)
5958          [["blockdev_setrw"; "/dev/sda"];
5959           ["umount_all"];
5960           ["lvm_remove_all"];
5961           ["sfdiskM"; "/dev/sda"; ","];
5962           ["mkfs"; "ext2"; "/dev/sda1"];
5963           ["mount"; "/dev/sda1"; "/"]]
5964    | InitBasicFSonLVM ->
5965        pr "  /* InitBasicFSonLVM for %s: create ext2 on /dev/VG/LV */\n"
5966          test_name;
5967        List.iter (generate_test_command_call test_name)
5968          [["blockdev_setrw"; "/dev/sda"];
5969           ["umount_all"];
5970           ["lvm_remove_all"];
5971           ["sfdiskM"; "/dev/sda"; ","];
5972           ["pvcreate"; "/dev/sda1"];
5973           ["vgcreate"; "VG"; "/dev/sda1"];
5974           ["lvcreate"; "LV"; "VG"; "8"];
5975           ["mkfs"; "ext2"; "/dev/VG/LV"];
5976           ["mount"; "/dev/VG/LV"; "/"]]
5977    | InitISOFS ->
5978        pr "  /* InitISOFS for %s */\n" test_name;
5979        List.iter (generate_test_command_call test_name)
5980          [["blockdev_setrw"; "/dev/sda"];
5981           ["umount_all"];
5982           ["lvm_remove_all"];
5983           ["mount_ro"; "/dev/sdd"; "/"]]
5984   );
5985
5986   let get_seq_last = function
5987     | [] ->
5988         failwithf "%s: you cannot use [] (empty list) when expecting a command"
5989           test_name
5990     | seq ->
5991         let seq = List.rev seq in
5992         List.rev (List.tl seq), List.hd seq
5993   in
5994
5995   match test with
5996   | TestRun seq ->
5997       pr "  /* TestRun for %s (%d) */\n" name i;
5998       List.iter (generate_test_command_call test_name) seq
5999   | TestOutput (seq, expected) ->
6000       pr "  /* TestOutput for %s (%d) */\n" name i;
6001       pr "  const char *expected = \"%s\";\n" (c_quote expected);
6002       let seq, last = get_seq_last seq in
6003       let test () =
6004         pr "    if (STRNEQ (r, expected)) {\n";
6005         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
6006         pr "      return -1;\n";
6007         pr "    }\n"
6008       in
6009       List.iter (generate_test_command_call test_name) seq;
6010       generate_test_command_call ~test test_name last
6011   | TestOutputList (seq, expected) ->
6012       pr "  /* TestOutputList for %s (%d) */\n" name i;
6013       let seq, last = get_seq_last seq in
6014       let test () =
6015         iteri (
6016           fun i str ->
6017             pr "    if (!r[%d]) {\n" i;
6018             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
6019             pr "      print_strings (r);\n";
6020             pr "      return -1;\n";
6021             pr "    }\n";
6022             pr "    {\n";
6023             pr "      const char *expected = \"%s\";\n" (c_quote str);
6024             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
6025             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
6026             pr "        return -1;\n";
6027             pr "      }\n";
6028             pr "    }\n"
6029         ) expected;
6030         pr "    if (r[%d] != NULL) {\n" (List.length expected);
6031         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
6032           test_name;
6033         pr "      print_strings (r);\n";
6034         pr "      return -1;\n";
6035         pr "    }\n"
6036       in
6037       List.iter (generate_test_command_call test_name) seq;
6038       generate_test_command_call ~test test_name last
6039   | TestOutputListOfDevices (seq, expected) ->
6040       pr "  /* TestOutputListOfDevices for %s (%d) */\n" name i;
6041       let seq, last = get_seq_last seq in
6042       let test () =
6043         iteri (
6044           fun i str ->
6045             pr "    if (!r[%d]) {\n" i;
6046             pr "      fprintf (stderr, \"%s: short list returned from command\\n\");\n" test_name;
6047             pr "      print_strings (r);\n";
6048             pr "      return -1;\n";
6049             pr "    }\n";
6050             pr "    {\n";
6051             pr "      const char *expected = \"%s\";\n" (c_quote str);
6052             pr "      r[%d][5] = 's';\n" i;
6053             pr "      if (STRNEQ (r[%d], expected)) {\n" i;
6054             pr "        fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r[%d]);\n" test_name i;
6055             pr "        return -1;\n";
6056             pr "      }\n";
6057             pr "    }\n"
6058         ) expected;
6059         pr "    if (r[%d] != NULL) {\n" (List.length expected);
6060         pr "      fprintf (stderr, \"%s: extra elements returned from command\\n\");\n"
6061           test_name;
6062         pr "      print_strings (r);\n";
6063         pr "      return -1;\n";
6064         pr "    }\n"
6065       in
6066       List.iter (generate_test_command_call test_name) seq;
6067       generate_test_command_call ~test test_name last
6068   | TestOutputInt (seq, expected) ->
6069       pr "  /* TestOutputInt for %s (%d) */\n" name i;
6070       let seq, last = get_seq_last seq in
6071       let test () =
6072         pr "    if (r != %d) {\n" expected;
6073         pr "      fprintf (stderr, \"%s: expected %d but got %%d\\n\","
6074           test_name expected;
6075         pr "               (int) r);\n";
6076         pr "      return -1;\n";
6077         pr "    }\n"
6078       in
6079       List.iter (generate_test_command_call test_name) seq;
6080       generate_test_command_call ~test test_name last
6081   | TestOutputIntOp (seq, op, expected) ->
6082       pr "  /* TestOutputIntOp for %s (%d) */\n" name i;
6083       let seq, last = get_seq_last seq in
6084       let test () =
6085         pr "    if (! (r %s %d)) {\n" op expected;
6086         pr "      fprintf (stderr, \"%s: expected %s %d but got %%d\\n\","
6087           test_name op expected;
6088         pr "               (int) r);\n";
6089         pr "      return -1;\n";
6090         pr "    }\n"
6091       in
6092       List.iter (generate_test_command_call test_name) seq;
6093       generate_test_command_call ~test test_name last
6094   | TestOutputTrue seq ->
6095       pr "  /* TestOutputTrue for %s (%d) */\n" name i;
6096       let seq, last = get_seq_last seq in
6097       let test () =
6098         pr "    if (!r) {\n";
6099         pr "      fprintf (stderr, \"%s: expected true, got false\\n\");\n"
6100           test_name;
6101         pr "      return -1;\n";
6102         pr "    }\n"
6103       in
6104       List.iter (generate_test_command_call test_name) seq;
6105       generate_test_command_call ~test test_name last
6106   | TestOutputFalse seq ->
6107       pr "  /* TestOutputFalse for %s (%d) */\n" name i;
6108       let seq, last = get_seq_last seq in
6109       let test () =
6110         pr "    if (r) {\n";
6111         pr "      fprintf (stderr, \"%s: expected false, got true\\n\");\n"
6112           test_name;
6113         pr "      return -1;\n";
6114         pr "    }\n"
6115       in
6116       List.iter (generate_test_command_call test_name) seq;
6117       generate_test_command_call ~test test_name last
6118   | TestOutputLength (seq, expected) ->
6119       pr "  /* TestOutputLength for %s (%d) */\n" name i;
6120       let seq, last = get_seq_last seq in
6121       let test () =
6122         pr "    int j;\n";
6123         pr "    for (j = 0; j < %d; ++j)\n" expected;
6124         pr "      if (r[j] == NULL) {\n";
6125         pr "        fprintf (stderr, \"%s: short list returned\\n\");\n"
6126           test_name;
6127         pr "        print_strings (r);\n";
6128         pr "        return -1;\n";
6129         pr "      }\n";
6130         pr "    if (r[j] != NULL) {\n";
6131         pr "      fprintf (stderr, \"%s: long list returned\\n\");\n"
6132           test_name;
6133         pr "      print_strings (r);\n";
6134         pr "      return -1;\n";
6135         pr "    }\n"
6136       in
6137       List.iter (generate_test_command_call test_name) seq;
6138       generate_test_command_call ~test test_name last
6139   | TestOutputBuffer (seq, expected) ->
6140       pr "  /* TestOutputBuffer for %s (%d) */\n" name i;
6141       pr "  const char *expected = \"%s\";\n" (c_quote expected);
6142       let seq, last = get_seq_last seq in
6143       let len = String.length expected in
6144       let test () =
6145         pr "    if (size != %d) {\n" len;
6146         pr "      fprintf (stderr, \"%s: returned size of buffer wrong, expected %d but got %%zu\\n\", size);\n" test_name len;
6147         pr "      return -1;\n";
6148         pr "    }\n";
6149         pr "    if (STRNEQLEN (r, expected, size)) {\n";
6150         pr "      fprintf (stderr, \"%s: expected \\\"%%s\\\" but got \\\"%%s\\\"\\n\", expected, r);\n" test_name;
6151         pr "      return -1;\n";
6152         pr "    }\n"
6153       in
6154       List.iter (generate_test_command_call test_name) seq;
6155       generate_test_command_call ~test test_name last
6156   | TestOutputStruct (seq, checks) ->
6157       pr "  /* TestOutputStruct for %s (%d) */\n" name i;
6158       let seq, last = get_seq_last seq in
6159       let test () =
6160         List.iter (
6161           function
6162           | CompareWithInt (field, expected) ->
6163               pr "    if (r->%s != %d) {\n" field expected;
6164               pr "      fprintf (stderr, \"%s: %s was %%d, expected %d\\n\",\n"
6165                 test_name field expected;
6166               pr "               (int) r->%s);\n" field;
6167               pr "      return -1;\n";
6168               pr "    }\n"
6169           | CompareWithIntOp (field, op, expected) ->
6170               pr "    if (!(r->%s %s %d)) {\n" field op expected;
6171               pr "      fprintf (stderr, \"%s: %s was %%d, expected %s %d\\n\",\n"
6172                 test_name field op expected;
6173               pr "               (int) r->%s);\n" field;
6174               pr "      return -1;\n";
6175               pr "    }\n"
6176           | CompareWithString (field, expected) ->
6177               pr "    if (STRNEQ (r->%s, \"%s\")) {\n" field expected;
6178               pr "      fprintf (stderr, \"%s: %s was \"%%s\", expected \"%s\"\\n\",\n"
6179                 test_name field expected;
6180               pr "               r->%s);\n" field;
6181               pr "      return -1;\n";
6182               pr "    }\n"
6183           | CompareFieldsIntEq (field1, field2) ->
6184               pr "    if (r->%s != r->%s) {\n" field1 field2;
6185               pr "      fprintf (stderr, \"%s: %s (%%d) <> %s (%%d)\\n\",\n"
6186                 test_name field1 field2;
6187               pr "               (int) r->%s, (int) r->%s);\n" field1 field2;
6188               pr "      return -1;\n";
6189               pr "    }\n"
6190           | CompareFieldsStrEq (field1, field2) ->
6191               pr "    if (STRNEQ (r->%s, r->%s)) {\n" field1 field2;
6192               pr "      fprintf (stderr, \"%s: %s (\"%%s\") <> %s (\"%%s\")\\n\",\n"
6193                 test_name field1 field2;
6194               pr "               r->%s, r->%s);\n" field1 field2;
6195               pr "      return -1;\n";
6196               pr "    }\n"
6197         ) checks
6198       in
6199       List.iter (generate_test_command_call test_name) seq;
6200       generate_test_command_call ~test test_name last
6201   | TestLastFail seq ->
6202       pr "  /* TestLastFail for %s (%d) */\n" name i;
6203       let seq, last = get_seq_last seq in
6204       List.iter (generate_test_command_call test_name) seq;
6205       generate_test_command_call test_name ~expect_error:true last
6206
6207 (* Generate the code to run a command, leaving the result in 'r'.
6208  * If you expect to get an error then you should set expect_error:true.
6209  *)
6210 and generate_test_command_call ?(expect_error = false) ?test test_name cmd =
6211   match cmd with
6212   | [] -> assert false
6213   | name :: args ->
6214       (* Look up the command to find out what args/ret it has. *)
6215       let style =
6216         try
6217           let _, style, _, _, _, _, _ =
6218             List.find (fun (n, _, _, _, _, _, _) -> n = name) all_functions in
6219           style
6220         with Not_found ->
6221           failwithf "%s: in test, command %s was not found" test_name name in
6222
6223       if List.length (snd style) <> List.length args then
6224         failwithf "%s: in test, wrong number of args given to %s"
6225           test_name name;
6226
6227       pr "  {\n";
6228
6229       List.iter (
6230         function
6231         | OptString n, "NULL" -> ()
6232         | Pathname n, arg
6233         | Device n, arg
6234         | Dev_or_Path n, arg
6235         | String n, arg
6236         | OptString n, arg ->
6237             pr "    const char *%s = \"%s\";\n" n (c_quote arg);
6238         | Int _, _
6239         | Int64 _, _
6240         | Bool _, _
6241         | FileIn _, _ | FileOut _, _ -> ()
6242         | StringList n, arg | DeviceList n, arg ->
6243             let strs = string_split " " arg in
6244             iteri (
6245               fun i str ->
6246                 pr "    const char *%s_%d = \"%s\";\n" n i (c_quote str);
6247             ) strs;
6248             pr "    const char *const %s[] = {\n" n;
6249             iteri (
6250               fun i _ -> pr "      %s_%d,\n" n i
6251             ) strs;
6252             pr "      NULL\n";
6253             pr "    };\n";
6254       ) (List.combine (snd style) args);
6255
6256       let error_code =
6257         match fst style with
6258         | RErr | RInt _ | RBool _ -> pr "    int r;\n"; "-1"
6259         | RInt64 _ -> pr "    int64_t r;\n"; "-1"
6260         | RConstString _ | RConstOptString _ ->
6261             pr "    const char *r;\n"; "NULL"
6262         | RString _ -> pr "    char *r;\n"; "NULL"
6263         | RStringList _ | RHashtable _ ->
6264             pr "    char **r;\n";
6265             pr "    int i;\n";
6266             "NULL"
6267         | RStruct (_, typ) ->
6268             pr "    struct guestfs_%s *r;\n" typ; "NULL"
6269         | RStructList (_, typ) ->
6270             pr "    struct guestfs_%s_list *r;\n" typ; "NULL"
6271         | RBufferOut _ ->
6272             pr "    char *r;\n";
6273             pr "    size_t size;\n";
6274             "NULL" in
6275
6276       pr "    suppress_error = %d;\n" (if expect_error then 1 else 0);
6277       pr "    r = guestfs_%s (g" name;
6278
6279       (* Generate the parameters. *)
6280       List.iter (
6281         function
6282         | OptString _, "NULL" -> pr ", NULL"
6283         | Pathname n, _
6284         | Device n, _ | Dev_or_Path n, _
6285         | String n, _
6286         | OptString n, _ ->
6287             pr ", %s" n
6288         | FileIn _, arg | FileOut _, arg ->
6289             pr ", \"%s\"" (c_quote arg)
6290         | StringList n, _ | DeviceList n, _ ->
6291             pr ", (char **) %s" n
6292         | Int _, arg ->
6293             let i =
6294               try int_of_string arg
6295               with Failure "int_of_string" ->
6296                 failwithf "%s: expecting an int, but got '%s'" test_name arg in
6297             pr ", %d" i
6298         | Int64 _, arg ->
6299             let i =
6300               try Int64.of_string arg
6301               with Failure "int_of_string" ->
6302                 failwithf "%s: expecting an int64, but got '%s'" test_name arg in
6303             pr ", %Ld" i
6304         | Bool _, arg ->
6305             let b = bool_of_string arg in pr ", %d" (if b then 1 else 0)
6306       ) (List.combine (snd style) args);
6307
6308       (match fst style with
6309        | RBufferOut _ -> pr ", &size"
6310        | _ -> ()
6311       );
6312
6313       pr ");\n";
6314
6315       if not expect_error then
6316         pr "    if (r == %s)\n" error_code
6317       else
6318         pr "    if (r != %s)\n" error_code;
6319       pr "      return -1;\n";
6320
6321       (* Insert the test code. *)
6322       (match test with
6323        | None -> ()
6324        | Some f -> f ()
6325       );
6326
6327       (match fst style with
6328        | RErr | RInt _ | RInt64 _ | RBool _
6329        | RConstString _ | RConstOptString _ -> ()
6330        | RString _ | RBufferOut _ -> pr "    free (r);\n"
6331        | RStringList _ | RHashtable _ ->
6332            pr "    for (i = 0; r[i] != NULL; ++i)\n";
6333            pr "      free (r[i]);\n";
6334            pr "    free (r);\n"
6335        | RStruct (_, typ) ->
6336            pr "    guestfs_free_%s (r);\n" typ
6337        | RStructList (_, typ) ->
6338            pr "    guestfs_free_%s_list (r);\n" typ
6339       );
6340
6341       pr "  }\n"
6342
6343 and c_quote str =
6344   let str = replace_str str "\r" "\\r" in
6345   let str = replace_str str "\n" "\\n" in
6346   let str = replace_str str "\t" "\\t" in
6347   let str = replace_str str "\000" "\\0" in
6348   str
6349
6350 (* Generate a lot of different functions for guestfish. *)
6351 and generate_fish_cmds () =
6352   generate_header CStyle GPLv2;
6353
6354   let all_functions =
6355     List.filter (
6356       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
6357     ) all_functions in
6358   let all_functions_sorted =
6359     List.filter (
6360       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
6361     ) all_functions_sorted in
6362
6363   pr "#include <stdio.h>\n";
6364   pr "#include <stdlib.h>\n";
6365   pr "#include <string.h>\n";
6366   pr "#include <inttypes.h>\n";
6367   pr "\n";
6368   pr "#include <guestfs.h>\n";
6369   pr "#include \"c-ctype.h\"\n";
6370   pr "#include \"fish.h\"\n";
6371   pr "\n";
6372
6373   (* list_commands function, which implements guestfish -h *)
6374   pr "void list_commands (void)\n";
6375   pr "{\n";
6376   pr "  printf (\"    %%-16s     %%s\\n\", _(\"Command\"), _(\"Description\"));\n";
6377   pr "  list_builtin_commands ();\n";
6378   List.iter (
6379     fun (name, _, _, flags, _, shortdesc, _) ->
6380       let name = replace_char name '_' '-' in
6381       pr "  printf (\"%%-20s %%s\\n\", \"%s\", _(\"%s\"));\n"
6382         name shortdesc
6383   ) all_functions_sorted;
6384   pr "  printf (\"    %%s\\n\",";
6385   pr "          _(\"Use -h <cmd> / help <cmd> to show detailed help for a command.\"));\n";
6386   pr "}\n";
6387   pr "\n";
6388
6389   (* display_command function, which implements guestfish -h cmd *)
6390   pr "void display_command (const char *cmd)\n";
6391   pr "{\n";
6392   List.iter (
6393     fun (name, style, _, flags, _, shortdesc, longdesc) ->
6394       let name2 = replace_char name '_' '-' in
6395       let alias =
6396         try find_map (function FishAlias n -> Some n | _ -> None) flags
6397         with Not_found -> name in
6398       let longdesc = replace_str longdesc "C<guestfs_" "C<" in
6399       let synopsis =
6400         match snd style with
6401         | [] -> name2
6402         | args ->
6403             sprintf "%s <%s>"
6404               name2 (String.concat "> <" (List.map name_of_argt args)) in
6405
6406       let warnings =
6407         if List.mem ProtocolLimitWarning flags then
6408           ("\n\n" ^ protocol_limit_warning)
6409         else "" in
6410
6411       (* For DangerWillRobinson commands, we should probably have
6412        * guestfish prompt before allowing you to use them (especially
6413        * in interactive mode). XXX
6414        *)
6415       let warnings =
6416         warnings ^
6417           if List.mem DangerWillRobinson flags then
6418             ("\n\n" ^ danger_will_robinson)
6419           else "" in
6420
6421       let warnings =
6422         warnings ^
6423           match deprecation_notice flags with
6424           | None -> ""
6425           | Some txt -> "\n\n" ^ txt in
6426
6427       let describe_alias =
6428         if name <> alias then
6429           sprintf "\n\nYou can use '%s' as an alias for this command." alias
6430         else "" in
6431
6432       pr "  if (";
6433       pr "STRCASEEQ (cmd, \"%s\")" name;
6434       if name <> name2 then
6435         pr " || STRCASEEQ (cmd, \"%s\")" name2;
6436       if name <> alias then
6437         pr " || STRCASEEQ (cmd, \"%s\")" alias;
6438       pr ")\n";
6439       pr "    pod2text (\"%s\", _(\"%s\"), %S);\n"
6440         name2 shortdesc
6441         (" " ^ synopsis ^ "\n\n" ^ longdesc ^ warnings ^ describe_alias);
6442       pr "  else\n"
6443   ) all_functions;
6444   pr "    display_builtin_command (cmd);\n";
6445   pr "}\n";
6446   pr "\n";
6447
6448   let emit_print_list_function typ =
6449     pr "static void print_%s_list (struct guestfs_%s_list *%ss)\n"
6450       typ typ typ;
6451     pr "{\n";
6452     pr "  unsigned int i;\n";
6453     pr "\n";
6454     pr "  for (i = 0; i < %ss->len; ++i) {\n" typ;
6455     pr "    printf (\"[%%d] = {\\n\", i);\n";
6456     pr "    print_%s_indent (&%ss->val[i], \"  \");\n" typ typ;
6457     pr "    printf (\"}\\n\");\n";
6458     pr "  }\n";
6459     pr "}\n";
6460     pr "\n";
6461   in
6462
6463   (* print_* functions *)
6464   List.iter (
6465     fun (typ, cols) ->
6466       let needs_i =
6467         List.exists (function (_, (FUUID|FBuffer)) -> true | _ -> false) cols in
6468
6469       pr "static void print_%s_indent (struct guestfs_%s *%s, const char *indent)\n" typ typ typ;
6470       pr "{\n";
6471       if needs_i then (
6472         pr "  unsigned int i;\n";
6473         pr "\n"
6474       );
6475       List.iter (
6476         function
6477         | name, FString ->
6478             pr "  printf (\"%%s%s: %%s\\n\", indent, %s->%s);\n" name typ name
6479         | name, FUUID ->
6480             pr "  printf (\"%%s%s: \", indent);\n" name;
6481             pr "  for (i = 0; i < 32; ++i)\n";
6482             pr "    printf (\"%%c\", %s->%s[i]);\n" typ name;
6483             pr "  printf (\"\\n\");\n"
6484         | name, FBuffer ->
6485             pr "  printf (\"%%s%s: \", indent);\n" name;
6486             pr "  for (i = 0; i < %s->%s_len; ++i)\n" typ name;
6487             pr "    if (c_isprint (%s->%s[i]))\n" typ name;
6488             pr "      printf (\"%%c\", %s->%s[i]);\n" typ name;
6489             pr "    else\n";
6490             pr "      printf (\"\\\\x%%02x\", %s->%s[i]);\n" typ name;
6491             pr "  printf (\"\\n\");\n"
6492         | name, (FUInt64|FBytes) ->
6493             pr "  printf (\"%%s%s: %%\" PRIu64 \"\\n\", indent, %s->%s);\n"
6494               name typ name
6495         | name, FInt64 ->
6496             pr "  printf (\"%%s%s: %%\" PRIi64 \"\\n\", indent, %s->%s);\n"
6497               name typ name
6498         | name, FUInt32 ->
6499             pr "  printf (\"%%s%s: %%\" PRIu32 \"\\n\", indent, %s->%s);\n"
6500               name typ name
6501         | name, FInt32 ->
6502             pr "  printf (\"%%s%s: %%\" PRIi32 \"\\n\", indent, %s->%s);\n"
6503               name typ name
6504         | name, FChar ->
6505             pr "  printf (\"%%s%s: %%c\\n\", indent, %s->%s);\n"
6506               name typ name
6507         | name, FOptPercent ->
6508             pr "  if (%s->%s >= 0) printf (\"%%s%s: %%g %%%%\\n\", indent, %s->%s);\n"
6509               typ name name typ name;
6510             pr "  else printf (\"%%s%s: \\n\", indent);\n" name
6511       ) cols;
6512       pr "}\n";
6513       pr "\n";
6514   ) structs;
6515
6516   (* Emit a print_TYPE_list function definition only if that function is used. *)
6517   List.iter (
6518     function
6519     | typ, (RStructListOnly | RStructAndList) ->
6520         (* generate the function for typ *)
6521         emit_print_list_function typ
6522     | typ, _ -> () (* empty *)
6523   ) (rstructs_used_by all_functions);
6524
6525   (* Emit a print_TYPE function definition only if that function is used. *)
6526   List.iter (
6527     function
6528     | typ, (RStructOnly | RStructAndList) ->
6529         pr "static void print_%s (struct guestfs_%s *%s)\n" typ typ typ;
6530         pr "{\n";
6531         pr "  print_%s_indent (%s, \"\");\n" typ typ;
6532         pr "}\n";
6533         pr "\n";
6534     | typ, _ -> () (* empty *)
6535   ) (rstructs_used_by all_functions);
6536
6537   (* run_<action> actions *)
6538   List.iter (
6539     fun (name, style, _, flags, _, _, _) ->
6540       pr "static int run_%s (const char *cmd, int argc, char *argv[])\n" name;
6541       pr "{\n";
6542       (match fst style with
6543        | RErr
6544        | RInt _
6545        | RBool _ -> pr "  int r;\n"
6546        | RInt64 _ -> pr "  int64_t r;\n"
6547        | RConstString _ | RConstOptString _ -> pr "  const char *r;\n"
6548        | RString _ -> pr "  char *r;\n"
6549        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
6550        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
6551        | RStructList (_, typ) -> pr "  struct guestfs_%s_list *r;\n" typ
6552        | RBufferOut _ ->
6553            pr "  char *r;\n";
6554            pr "  size_t size;\n";
6555       );
6556       List.iter (
6557         function
6558         | Device n
6559         | String n
6560         | OptString n
6561         | FileIn n
6562         | FileOut n -> pr "  const char *%s;\n" n
6563         | Pathname n
6564         | Dev_or_Path n -> pr "  char *%s;\n" n
6565         | StringList n | DeviceList n -> pr "  char **%s;\n" n
6566         | Bool n -> pr "  int %s;\n" n
6567         | Int n -> pr "  int %s;\n" n
6568         | Int64 n -> pr "  int64_t %s;\n" n
6569       ) (snd style);
6570
6571       (* Check and convert parameters. *)
6572       let argc_expected = List.length (snd style) in
6573       pr "  if (argc != %d) {\n" argc_expected;
6574       pr "    fprintf (stderr, _(\"%%s should have %%d parameter(s)\\n\"), cmd, %d);\n"
6575         argc_expected;
6576       pr "    fprintf (stderr, _(\"type 'help %%s' for help on %%s\\n\"), cmd, cmd);\n";
6577       pr "    return -1;\n";
6578       pr "  }\n";
6579       iteri (
6580         fun i ->
6581           function
6582           | Device name
6583           | String name ->
6584               pr "  %s = argv[%d];\n" name i
6585           | Pathname name
6586           | Dev_or_Path name ->
6587               pr "  %s = resolve_win_path (argv[%d]);\n" name i;
6588               pr "  if (%s == NULL) return -1;\n" name
6589           | OptString name ->
6590               pr "  %s = STRNEQ (argv[%d], \"\") ? argv[%d] : NULL;\n"
6591                 name i i
6592           | FileIn name ->
6593               pr "  %s = STRNEQ (argv[%d], \"-\") ? argv[%d] : \"/dev/stdin\";\n"
6594                 name i i
6595           | FileOut name ->
6596               pr "  %s = STRNEQ (argv[%d], \"-\") ? argv[%d] : \"/dev/stdout\";\n"
6597                 name i i
6598           | StringList name | DeviceList name ->
6599               pr "  %s = parse_string_list (argv[%d]);\n" name i;
6600               pr "  if (%s == NULL) return -1;\n" name;
6601           | Bool name ->
6602               pr "  %s = is_true (argv[%d]) ? 1 : 0;\n" name i
6603           | Int name ->
6604               pr "  %s = atoi (argv[%d]);\n" name i
6605           | Int64 name ->
6606               pr "  %s = atoll (argv[%d]);\n" name i
6607       ) (snd style);
6608
6609       (* Call C API function. *)
6610       let fn =
6611         try find_map (function FishAction n -> Some n | _ -> None) flags
6612         with Not_found -> sprintf "guestfs_%s" name in
6613       pr "  r = %s " fn;
6614       generate_c_call_args ~handle:"g" style;
6615       pr ";\n";
6616
6617       List.iter (
6618         function
6619         | Device name | String name
6620         | OptString name | FileIn name | FileOut name | Bool name
6621         | Int name | Int64 name -> ()
6622         | Pathname name | Dev_or_Path name ->
6623             pr "  free (%s);\n" name
6624         | StringList name | DeviceList name ->
6625             pr "  free_strings (%s);\n" name
6626       ) (snd style);
6627
6628       (* Check return value for errors and display command results. *)
6629       (match fst style with
6630        | RErr -> pr "  return r;\n"
6631        | RInt _ ->
6632            pr "  if (r == -1) return -1;\n";
6633            pr "  printf (\"%%d\\n\", r);\n";
6634            pr "  return 0;\n"
6635        | RInt64 _ ->
6636            pr "  if (r == -1) return -1;\n";
6637            pr "  printf (\"%%\" PRIi64 \"\\n\", r);\n";
6638            pr "  return 0;\n"
6639        | RBool _ ->
6640            pr "  if (r == -1) return -1;\n";
6641            pr "  if (r) printf (\"true\\n\"); else printf (\"false\\n\");\n";
6642            pr "  return 0;\n"
6643        | RConstString _ ->
6644            pr "  if (r == NULL) return -1;\n";
6645            pr "  printf (\"%%s\\n\", r);\n";
6646            pr "  return 0;\n"
6647        | RConstOptString _ ->
6648            pr "  printf (\"%%s\\n\", r ? : \"(null)\");\n";
6649            pr "  return 0;\n"
6650        | RString _ ->
6651            pr "  if (r == NULL) return -1;\n";
6652            pr "  printf (\"%%s\\n\", r);\n";
6653            pr "  free (r);\n";
6654            pr "  return 0;\n"
6655        | RStringList _ ->
6656            pr "  if (r == NULL) return -1;\n";
6657            pr "  print_strings (r);\n";
6658            pr "  free_strings (r);\n";
6659            pr "  return 0;\n"
6660        | RStruct (_, typ) ->
6661            pr "  if (r == NULL) return -1;\n";
6662            pr "  print_%s (r);\n" typ;
6663            pr "  guestfs_free_%s (r);\n" typ;
6664            pr "  return 0;\n"
6665        | RStructList (_, typ) ->
6666            pr "  if (r == NULL) return -1;\n";
6667            pr "  print_%s_list (r);\n" typ;
6668            pr "  guestfs_free_%s_list (r);\n" typ;
6669            pr "  return 0;\n"
6670        | RHashtable _ ->
6671            pr "  if (r == NULL) return -1;\n";
6672            pr "  print_table (r);\n";
6673            pr "  free_strings (r);\n";
6674            pr "  return 0;\n"
6675        | RBufferOut _ ->
6676            pr "  if (r == NULL) return -1;\n";
6677            pr "  fwrite (r, size, 1, stdout);\n";
6678            pr "  free (r);\n";
6679            pr "  return 0;\n"
6680       );
6681       pr "}\n";
6682       pr "\n"
6683   ) all_functions;
6684
6685   (* run_action function *)
6686   pr "int run_action (const char *cmd, int argc, char *argv[])\n";
6687   pr "{\n";
6688   List.iter (
6689     fun (name, _, _, flags, _, _, _) ->
6690       let name2 = replace_char name '_' '-' in
6691       let alias =
6692         try find_map (function FishAlias n -> Some n | _ -> None) flags
6693         with Not_found -> name in
6694       pr "  if (";
6695       pr "STRCASEEQ (cmd, \"%s\")" name;
6696       if name <> name2 then
6697         pr " || STRCASEEQ (cmd, \"%s\")" name2;
6698       if name <> alias then
6699         pr " || STRCASEEQ (cmd, \"%s\")" alias;
6700       pr ")\n";
6701       pr "    return run_%s (cmd, argc, argv);\n" name;
6702       pr "  else\n";
6703   ) all_functions;
6704   pr "    {\n";
6705   pr "      fprintf (stderr, _(\"%%s: unknown command\\n\"), cmd);\n";
6706   pr "      return -1;\n";
6707   pr "    }\n";
6708   pr "  return 0;\n";
6709   pr "}\n";
6710   pr "\n"
6711
6712 (* Readline completion for guestfish. *)
6713 and generate_fish_completion () =
6714   generate_header CStyle GPLv2;
6715
6716   let all_functions =
6717     List.filter (
6718       fun (_, _, _, flags, _, _, _) -> not (List.mem NotInFish flags)
6719     ) all_functions in
6720
6721   pr "\
6722 #include <config.h>
6723
6724 #include <stdio.h>
6725 #include <stdlib.h>
6726 #include <string.h>
6727
6728 #ifdef HAVE_LIBREADLINE
6729 #include <readline/readline.h>
6730 #endif
6731
6732 #include \"fish.h\"
6733
6734 #ifdef HAVE_LIBREADLINE
6735
6736 static const char *const commands[] = {
6737   BUILTIN_COMMANDS_FOR_COMPLETION,
6738 ";
6739
6740   (* Get the commands, including the aliases.  They don't need to be
6741    * sorted - the generator() function just does a dumb linear search.
6742    *)
6743   let commands =
6744     List.map (
6745       fun (name, _, _, flags, _, _, _) ->
6746         let name2 = replace_char name '_' '-' in
6747         let alias =
6748           try find_map (function FishAlias n -> Some n | _ -> None) flags
6749           with Not_found -> name in
6750
6751         if name <> alias then [name2; alias] else [name2]
6752     ) all_functions in
6753   let commands = List.flatten commands in
6754
6755   List.iter (pr "  \"%s\",\n") commands;
6756
6757   pr "  NULL
6758 };
6759
6760 static char *
6761 generator (const char *text, int state)
6762 {
6763   static int index, len;
6764   const char *name;
6765
6766   if (!state) {
6767     index = 0;
6768     len = strlen (text);
6769   }
6770
6771   rl_attempted_completion_over = 1;
6772
6773   while ((name = commands[index]) != NULL) {
6774     index++;
6775     if (strncasecmp (name, text, len) == 0)
6776       return strdup (name);
6777   }
6778
6779   return NULL;
6780 }
6781
6782 #endif /* HAVE_LIBREADLINE */
6783
6784 char **do_completion (const char *text, int start, int end)
6785 {
6786   char **matches = NULL;
6787
6788 #ifdef HAVE_LIBREADLINE
6789   rl_completion_append_character = ' ';
6790
6791   if (start == 0)
6792     matches = rl_completion_matches (text, generator);
6793   else if (complete_dest_paths)
6794     matches = rl_completion_matches (text, complete_dest_paths_generator);
6795 #endif
6796
6797   return matches;
6798 }
6799 ";
6800
6801 (* Generate the POD documentation for guestfish. *)
6802 and generate_fish_actions_pod () =
6803   let all_functions_sorted =
6804     List.filter (
6805       fun (_, _, _, flags, _, _, _) ->
6806         not (List.mem NotInFish flags || List.mem NotInDocs flags)
6807     ) all_functions_sorted in
6808
6809   let rex = Str.regexp "C<guestfs_\\([^>]+\\)>" in
6810
6811   List.iter (
6812     fun (name, style, _, flags, _, _, longdesc) ->
6813       let longdesc =
6814         Str.global_substitute rex (
6815           fun s ->
6816             let sub =
6817               try Str.matched_group 1 s
6818               with Not_found ->
6819                 failwithf "error substituting C<guestfs_...> in longdesc of function %s" name in
6820             "C<" ^ replace_char sub '_' '-' ^ ">"
6821         ) longdesc in
6822       let name = replace_char name '_' '-' in
6823       let alias =
6824         try find_map (function FishAlias n -> Some n | _ -> None) flags
6825         with Not_found -> name in
6826
6827       pr "=head2 %s" name;
6828       if name <> alias then
6829         pr " | %s" alias;
6830       pr "\n";
6831       pr "\n";
6832       pr " %s" name;
6833       List.iter (
6834         function
6835         | Pathname n | Device n | Dev_or_Path n | String n -> pr " %s" n
6836         | OptString n -> pr " %s" n
6837         | StringList n | DeviceList n -> pr " '%s ...'" n
6838         | Bool _ -> pr " true|false"
6839         | Int n -> pr " %s" n
6840         | Int64 n -> pr " %s" n
6841         | FileIn n | FileOut n -> pr " (%s|-)" n
6842       ) (snd style);
6843       pr "\n";
6844       pr "\n";
6845       pr "%s\n\n" longdesc;
6846
6847       if List.exists (function FileIn _ | FileOut _ -> true
6848                       | _ -> false) (snd style) then
6849         pr "Use C<-> instead of a filename to read/write from stdin/stdout.\n\n";
6850
6851       if List.mem ProtocolLimitWarning flags then
6852         pr "%s\n\n" protocol_limit_warning;
6853
6854       if List.mem DangerWillRobinson flags then
6855         pr "%s\n\n" danger_will_robinson;
6856
6857       match deprecation_notice flags with
6858       | None -> ()
6859       | Some txt -> pr "%s\n\n" txt
6860   ) all_functions_sorted
6861
6862 (* Generate a C function prototype. *)
6863 and generate_prototype ?(extern = true) ?(static = false) ?(semicolon = true)
6864     ?(single_line = false) ?(newline = false) ?(in_daemon = false)
6865     ?(prefix = "")
6866     ?handle name style =
6867   if extern then pr "extern ";
6868   if static then pr "static ";
6869   (match fst style with
6870    | RErr -> pr "int "
6871    | RInt _ -> pr "int "
6872    | RInt64 _ -> pr "int64_t "
6873    | RBool _ -> pr "int "
6874    | RConstString _ | RConstOptString _ -> pr "const char *"
6875    | RString _ | RBufferOut _ -> pr "char *"
6876    | RStringList _ | RHashtable _ -> pr "char **"
6877    | RStruct (_, typ) ->
6878        if not in_daemon then pr "struct guestfs_%s *" typ
6879        else pr "guestfs_int_%s *" typ
6880    | RStructList (_, typ) ->
6881        if not in_daemon then pr "struct guestfs_%s_list *" typ
6882        else pr "guestfs_int_%s_list *" typ
6883   );
6884   let is_RBufferOut = match fst style with RBufferOut _ -> true | _ -> false in
6885   pr "%s%s (" prefix name;
6886   if handle = None && List.length (snd style) = 0 && not is_RBufferOut then
6887     pr "void"
6888   else (
6889     let comma = ref false in
6890     (match handle with
6891      | None -> ()
6892      | Some handle -> pr "guestfs_h *%s" handle; comma := true
6893     );
6894     let next () =
6895       if !comma then (
6896         if single_line then pr ", " else pr ",\n\t\t"
6897       );
6898       comma := true
6899     in
6900     List.iter (
6901       function
6902       | Pathname n
6903       | Device n | Dev_or_Path n
6904       | String n
6905       | OptString n ->
6906           next ();
6907           pr "const char *%s" n
6908       | StringList n | DeviceList n ->
6909           next ();
6910           pr "char *const *%s" n
6911       | Bool n -> next (); pr "int %s" n
6912       | Int n -> next (); pr "int %s" n
6913       | Int64 n -> next (); pr "int64_t %s" n
6914       | FileIn n
6915       | FileOut n ->
6916           if not in_daemon then (next (); pr "const char *%s" n)
6917     ) (snd style);
6918     if is_RBufferOut then (next (); pr "size_t *size_r");
6919   );
6920   pr ")";
6921   if semicolon then pr ";";
6922   if newline then pr "\n"
6923
6924 (* Generate C call arguments, eg "(handle, foo, bar)" *)
6925 and generate_c_call_args ?handle ?(decl = false) style =
6926   pr "(";
6927   let comma = ref false in
6928   let next () =
6929     if !comma then pr ", ";
6930     comma := true
6931   in
6932   (match handle with
6933    | None -> ()
6934    | Some handle -> pr "%s" handle; comma := true
6935   );
6936   List.iter (
6937     fun arg ->
6938       next ();
6939       pr "%s" (name_of_argt arg)
6940   ) (snd style);
6941   (* For RBufferOut calls, add implicit &size parameter. *)
6942   if not decl then (
6943     match fst style with
6944     | RBufferOut _ ->
6945         next ();
6946         pr "&size"
6947     | _ -> ()
6948   );
6949   pr ")"
6950
6951 (* Generate the OCaml bindings interface. *)
6952 and generate_ocaml_mli () =
6953   generate_header OCamlStyle LGPLv2;
6954
6955   pr "\
6956 (** For API documentation you should refer to the C API
6957     in the guestfs(3) manual page.  The OCaml API uses almost
6958     exactly the same calls. *)
6959
6960 type t
6961 (** A [guestfs_h] handle. *)
6962
6963 exception Error of string
6964 (** This exception is raised when there is an error. *)
6965
6966 exception Handle_closed of string
6967 (** This exception is raised if you use a {!Guestfs.t} handle
6968     after calling {!close} on it.  The string is the name of
6969     the function. *)
6970
6971 val create : unit -> t
6972 (** Create a {!Guestfs.t} handle. *)
6973
6974 val close : t -> unit
6975 (** Close the {!Guestfs.t} handle and free up all resources used
6976     by it immediately.
6977
6978     Handles are closed by the garbage collector when they become
6979     unreferenced, but callers can call this in order to provide
6980     predictable cleanup. *)
6981
6982 ";
6983   generate_ocaml_structure_decls ();
6984
6985   (* The actions. *)
6986   List.iter (
6987     fun (name, style, _, _, _, shortdesc, _) ->
6988       generate_ocaml_prototype name style;
6989       pr "(** %s *)\n" shortdesc;
6990       pr "\n"
6991   ) all_functions_sorted
6992
6993 (* Generate the OCaml bindings implementation. *)
6994 and generate_ocaml_ml () =
6995   generate_header OCamlStyle LGPLv2;
6996
6997   pr "\
6998 type t
6999
7000 exception Error of string
7001 exception Handle_closed of string
7002
7003 external create : unit -> t = \"ocaml_guestfs_create\"
7004 external close : t -> unit = \"ocaml_guestfs_close\"
7005
7006 (* Give the exceptions names, so they can be raised from the C code. *)
7007 let () =
7008   Callback.register_exception \"ocaml_guestfs_error\" (Error \"\");
7009   Callback.register_exception \"ocaml_guestfs_closed\" (Handle_closed \"\")
7010
7011 ";
7012
7013   generate_ocaml_structure_decls ();
7014
7015   (* The actions. *)
7016   List.iter (
7017     fun (name, style, _, _, _, shortdesc, _) ->
7018       generate_ocaml_prototype ~is_external:true name style;
7019   ) all_functions_sorted
7020
7021 (* Generate the OCaml bindings C implementation. *)
7022 and generate_ocaml_c () =
7023   generate_header CStyle LGPLv2;
7024
7025   pr "\
7026 #include <stdio.h>
7027 #include <stdlib.h>
7028 #include <string.h>
7029
7030 #include <caml/config.h>
7031 #include <caml/alloc.h>
7032 #include <caml/callback.h>
7033 #include <caml/fail.h>
7034 #include <caml/memory.h>
7035 #include <caml/mlvalues.h>
7036 #include <caml/signals.h>
7037
7038 #include <guestfs.h>
7039
7040 #include \"guestfs_c.h\"
7041
7042 /* Copy a hashtable of string pairs into an assoc-list.  We return
7043  * the list in reverse order, but hashtables aren't supposed to be
7044  * ordered anyway.
7045  */
7046 static CAMLprim value
7047 copy_table (char * const * argv)
7048 {
7049   CAMLparam0 ();
7050   CAMLlocal5 (rv, pairv, kv, vv, cons);
7051   int i;
7052
7053   rv = Val_int (0);
7054   for (i = 0; argv[i] != NULL; i += 2) {
7055     kv = caml_copy_string (argv[i]);
7056     vv = caml_copy_string (argv[i+1]);
7057     pairv = caml_alloc (2, 0);
7058     Store_field (pairv, 0, kv);
7059     Store_field (pairv, 1, vv);
7060     cons = caml_alloc (2, 0);
7061     Store_field (cons, 1, rv);
7062     rv = cons;
7063     Store_field (cons, 0, pairv);
7064   }
7065
7066   CAMLreturn (rv);
7067 }
7068
7069 ";
7070
7071   (* Struct copy functions. *)
7072
7073   let emit_ocaml_copy_list_function typ =
7074     pr "static CAMLprim value\n";
7075     pr "copy_%s_list (const struct guestfs_%s_list *%ss)\n" typ typ typ;
7076     pr "{\n";
7077     pr "  CAMLparam0 ();\n";
7078     pr "  CAMLlocal2 (rv, v);\n";
7079     pr "  unsigned int i;\n";
7080     pr "\n";
7081     pr "  if (%ss->len == 0)\n" typ;
7082     pr "    CAMLreturn (Atom (0));\n";
7083     pr "  else {\n";
7084     pr "    rv = caml_alloc (%ss->len, 0);\n" typ;
7085     pr "    for (i = 0; i < %ss->len; ++i) {\n" typ;
7086     pr "      v = copy_%s (&%ss->val[i]);\n" typ typ;
7087     pr "      caml_modify (&Field (rv, i), v);\n";
7088     pr "    }\n";
7089     pr "    CAMLreturn (rv);\n";
7090     pr "  }\n";
7091     pr "}\n";
7092     pr "\n";
7093   in
7094
7095   List.iter (
7096     fun (typ, cols) ->
7097       let has_optpercent_col =
7098         List.exists (function (_, FOptPercent) -> true | _ -> false) cols in
7099
7100       pr "static CAMLprim value\n";
7101       pr "copy_%s (const struct guestfs_%s *%s)\n" typ typ typ;
7102       pr "{\n";
7103       pr "  CAMLparam0 ();\n";
7104       if has_optpercent_col then
7105         pr "  CAMLlocal3 (rv, v, v2);\n"
7106       else
7107         pr "  CAMLlocal2 (rv, v);\n";
7108       pr "\n";
7109       pr "  rv = caml_alloc (%d, 0);\n" (List.length cols);
7110       iteri (
7111         fun i col ->
7112           (match col with
7113            | name, FString ->
7114                pr "  v = caml_copy_string (%s->%s);\n" typ name
7115            | name, FBuffer ->
7116                pr "  v = caml_alloc_string (%s->%s_len);\n" typ name;
7117                pr "  memcpy (String_val (v), %s->%s, %s->%s_len);\n"
7118                  typ name typ name
7119            | name, FUUID ->
7120                pr "  v = caml_alloc_string (32);\n";
7121                pr "  memcpy (String_val (v), %s->%s, 32);\n" typ name
7122            | name, (FBytes|FInt64|FUInt64) ->
7123                pr "  v = caml_copy_int64 (%s->%s);\n" typ name
7124            | name, (FInt32|FUInt32) ->
7125                pr "  v = caml_copy_int32 (%s->%s);\n" typ name
7126            | name, FOptPercent ->
7127                pr "  if (%s->%s >= 0) { /* Some %s */\n" typ name name;
7128                pr "    v2 = caml_copy_double (%s->%s);\n" typ name;
7129                pr "    v = caml_alloc (1, 0);\n";
7130                pr "    Store_field (v, 0, v2);\n";
7131                pr "  } else /* None */\n";
7132                pr "    v = Val_int (0);\n";
7133            | name, FChar ->
7134                pr "  v = Val_int (%s->%s);\n" typ name
7135           );
7136           pr "  Store_field (rv, %d, v);\n" i
7137       ) cols;
7138       pr "  CAMLreturn (rv);\n";
7139       pr "}\n";
7140       pr "\n";
7141   ) structs;
7142
7143   (* Emit a copy_TYPE_list function definition only if that function is used. *)
7144   List.iter (
7145     function
7146     | typ, (RStructListOnly | RStructAndList) ->
7147         (* generate the function for typ *)
7148         emit_ocaml_copy_list_function typ
7149     | typ, _ -> () (* empty *)
7150   ) (rstructs_used_by all_functions);
7151
7152   (* The wrappers. *)
7153   List.iter (
7154     fun (name, style, _, _, _, _, _) ->
7155       pr "/* Automatically generated wrapper for function\n";
7156       pr " * ";
7157       generate_ocaml_prototype name style;
7158       pr " */\n";
7159       pr "\n";
7160
7161       let params =
7162         "gv" :: List.map (fun arg -> name_of_argt arg ^ "v") (snd style) in
7163
7164       let needs_extra_vs =
7165         match fst style with RConstOptString _ -> true | _ -> false in
7166
7167       pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
7168       pr "CAMLprim value ocaml_guestfs_%s (value %s" name (List.hd params);
7169       List.iter (pr ", value %s") (List.tl params); pr ");\n";
7170       pr "\n";
7171
7172       pr "CAMLprim value\n";
7173       pr "ocaml_guestfs_%s (value %s" name (List.hd params);
7174       List.iter (pr ", value %s") (List.tl params);
7175       pr ")\n";
7176       pr "{\n";
7177
7178       (match params with
7179        | [p1; p2; p3; p4; p5] ->
7180            pr "  CAMLparam5 (%s);\n" (String.concat ", " params)
7181        | p1 :: p2 :: p3 :: p4 :: p5 :: rest ->
7182            pr "  CAMLparam5 (%s);\n" (String.concat ", " [p1; p2; p3; p4; p5]);
7183            pr "  CAMLxparam%d (%s);\n"
7184              (List.length rest) (String.concat ", " rest)
7185        | ps ->
7186            pr "  CAMLparam%d (%s);\n" (List.length ps) (String.concat ", " ps)
7187       );
7188       if not needs_extra_vs then
7189         pr "  CAMLlocal1 (rv);\n"
7190       else
7191         pr "  CAMLlocal3 (rv, v, v2);\n";
7192       pr "\n";
7193
7194       pr "  guestfs_h *g = Guestfs_val (gv);\n";
7195       pr "  if (g == NULL)\n";
7196       pr "    ocaml_guestfs_raise_closed (\"%s\");\n" name;
7197       pr "\n";
7198
7199       List.iter (
7200         function
7201         | Pathname n
7202         | Device n | Dev_or_Path n
7203         | String n
7204         | FileIn n
7205         | FileOut n ->
7206             pr "  const char *%s = String_val (%sv);\n" n n
7207         | OptString n ->
7208             pr "  const char *%s =\n" n;
7209             pr "    %sv != Val_int (0) ? String_val (Field (%sv, 0)) : NULL;\n"
7210               n n
7211         | StringList n | DeviceList n ->
7212             pr "  char **%s = ocaml_guestfs_strings_val (g, %sv);\n" n n
7213         | Bool n ->
7214             pr "  int %s = Bool_val (%sv);\n" n n
7215         | Int n ->
7216             pr "  int %s = Int_val (%sv);\n" n n
7217         | Int64 n ->
7218             pr "  int64_t %s = Int64_val (%sv);\n" n n
7219       ) (snd style);
7220       let error_code =
7221         match fst style with
7222         | RErr -> pr "  int r;\n"; "-1"
7223         | RInt _ -> pr "  int r;\n"; "-1"
7224         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
7225         | RBool _ -> pr "  int r;\n"; "-1"
7226         | RConstString _ | RConstOptString _ ->
7227             pr "  const char *r;\n"; "NULL"
7228         | RString _ -> pr "  char *r;\n"; "NULL"
7229         | RStringList _ ->
7230             pr "  int i;\n";
7231             pr "  char **r;\n";
7232             "NULL"
7233         | RStruct (_, typ) ->
7234             pr "  struct guestfs_%s *r;\n" typ; "NULL"
7235         | RStructList (_, typ) ->
7236             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
7237         | RHashtable _ ->
7238             pr "  int i;\n";
7239             pr "  char **r;\n";
7240             "NULL"
7241         | RBufferOut _ ->
7242             pr "  char *r;\n";
7243             pr "  size_t size;\n";
7244             "NULL" in
7245       pr "\n";
7246
7247       pr "  caml_enter_blocking_section ();\n";
7248       pr "  r = guestfs_%s " name;
7249       generate_c_call_args ~handle:"g" style;
7250       pr ";\n";
7251       pr "  caml_leave_blocking_section ();\n";
7252
7253       List.iter (
7254         function
7255         | StringList n | DeviceList n ->
7256             pr "  ocaml_guestfs_free_strings (%s);\n" n;
7257         | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
7258         | Bool _ | Int _ | Int64 _
7259         | FileIn _ | FileOut _ -> ()
7260       ) (snd style);
7261
7262       pr "  if (r == %s)\n" error_code;
7263       pr "    ocaml_guestfs_raise_error (g, \"%s\");\n" name;
7264       pr "\n";
7265
7266       (match fst style with
7267        | RErr -> pr "  rv = Val_unit;\n"
7268        | RInt _ -> pr "  rv = Val_int (r);\n"
7269        | RInt64 _ ->
7270            pr "  rv = caml_copy_int64 (r);\n"
7271        | RBool _ -> pr "  rv = Val_bool (r);\n"
7272        | RConstString _ ->
7273            pr "  rv = caml_copy_string (r);\n"
7274        | RConstOptString _ ->
7275            pr "  if (r) { /* Some string */\n";
7276            pr "    v = caml_alloc (1, 0);\n";
7277            pr "    v2 = caml_copy_string (r);\n";
7278            pr "    Store_field (v, 0, v2);\n";
7279            pr "  } else /* None */\n";
7280            pr "    v = Val_int (0);\n";
7281        | RString _ ->
7282            pr "  rv = caml_copy_string (r);\n";
7283            pr "  free (r);\n"
7284        | RStringList _ ->
7285            pr "  rv = caml_copy_string_array ((const char **) r);\n";
7286            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
7287            pr "  free (r);\n"
7288        | RStruct (_, typ) ->
7289            pr "  rv = copy_%s (r);\n" typ;
7290            pr "  guestfs_free_%s (r);\n" typ;
7291        | RStructList (_, typ) ->
7292            pr "  rv = copy_%s_list (r);\n" typ;
7293            pr "  guestfs_free_%s_list (r);\n" typ;
7294        | RHashtable _ ->
7295            pr "  rv = copy_table (r);\n";
7296            pr "  for (i = 0; r[i] != NULL; ++i) free (r[i]);\n";
7297            pr "  free (r);\n";
7298        | RBufferOut _ ->
7299            pr "  rv = caml_alloc_string (size);\n";
7300            pr "  memcpy (String_val (rv), r, size);\n";
7301       );
7302
7303       pr "  CAMLreturn (rv);\n";
7304       pr "}\n";
7305       pr "\n";
7306
7307       if List.length params > 5 then (
7308         pr "/* Emit prototype to appease gcc's -Wmissing-prototypes. */\n";
7309         pr "CAMLprim value ";
7310         pr "ocaml_guestfs_%s_byte (value *argv, int argn);\n" name;
7311         pr "CAMLprim value\n";
7312         pr "ocaml_guestfs_%s_byte (value *argv, int argn)\n" name;
7313         pr "{\n";
7314         pr "  return ocaml_guestfs_%s (argv[0]" name;
7315         iteri (fun i _ -> pr ", argv[%d]" i) (List.tl params);
7316         pr ");\n";
7317         pr "}\n";
7318         pr "\n"
7319       )
7320   ) all_functions_sorted
7321
7322 and generate_ocaml_structure_decls () =
7323   List.iter (
7324     fun (typ, cols) ->
7325       pr "type %s = {\n" typ;
7326       List.iter (
7327         function
7328         | name, FString -> pr "  %s : string;\n" name
7329         | name, FBuffer -> pr "  %s : string;\n" name
7330         | name, FUUID -> pr "  %s : string;\n" name
7331         | name, (FBytes|FInt64|FUInt64) -> pr "  %s : int64;\n" name
7332         | name, (FInt32|FUInt32) -> pr "  %s : int32;\n" name
7333         | name, FChar -> pr "  %s : char;\n" name
7334         | name, FOptPercent -> pr "  %s : float option;\n" name
7335       ) cols;
7336       pr "}\n";
7337       pr "\n"
7338   ) structs
7339
7340 and generate_ocaml_prototype ?(is_external = false) name style =
7341   if is_external then pr "external " else pr "val ";
7342   pr "%s : t -> " name;
7343   List.iter (
7344     function
7345     | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _ -> pr "string -> "
7346     | OptString _ -> pr "string option -> "
7347     | StringList _ | DeviceList _ -> pr "string array -> "
7348     | Bool _ -> pr "bool -> "
7349     | Int _ -> pr "int -> "
7350     | Int64 _ -> pr "int64 -> "
7351   ) (snd style);
7352   (match fst style with
7353    | RErr -> pr "unit" (* all errors are turned into exceptions *)
7354    | RInt _ -> pr "int"
7355    | RInt64 _ -> pr "int64"
7356    | RBool _ -> pr "bool"
7357    | RConstString _ -> pr "string"
7358    | RConstOptString _ -> pr "string option"
7359    | RString _ | RBufferOut _ -> pr "string"
7360    | RStringList _ -> pr "string array"
7361    | RStruct (_, typ) -> pr "%s" typ
7362    | RStructList (_, typ) -> pr "%s array" typ
7363    | RHashtable _ -> pr "(string * string) list"
7364   );
7365   if is_external then (
7366     pr " = ";
7367     if List.length (snd style) + 1 > 5 then
7368       pr "\"ocaml_guestfs_%s_byte\" " name;
7369     pr "\"ocaml_guestfs_%s\"" name
7370   );
7371   pr "\n"
7372
7373 (* Generate Perl xs code, a sort of crazy variation of C with macros. *)
7374 and generate_perl_xs () =
7375   generate_header CStyle LGPLv2;
7376
7377   pr "\
7378 #include \"EXTERN.h\"
7379 #include \"perl.h\"
7380 #include \"XSUB.h\"
7381
7382 #include <guestfs.h>
7383
7384 #ifndef PRId64
7385 #define PRId64 \"lld\"
7386 #endif
7387
7388 static SV *
7389 my_newSVll(long long val) {
7390 #ifdef USE_64_BIT_ALL
7391   return newSViv(val);
7392 #else
7393   char buf[100];
7394   int len;
7395   len = snprintf(buf, 100, \"%%\" PRId64, val);
7396   return newSVpv(buf, len);
7397 #endif
7398 }
7399
7400 #ifndef PRIu64
7401 #define PRIu64 \"llu\"
7402 #endif
7403
7404 static SV *
7405 my_newSVull(unsigned long long val) {
7406 #ifdef USE_64_BIT_ALL
7407   return newSVuv(val);
7408 #else
7409   char buf[100];
7410   int len;
7411   len = snprintf(buf, 100, \"%%\" PRIu64, val);
7412   return newSVpv(buf, len);
7413 #endif
7414 }
7415
7416 /* http://www.perlmonks.org/?node_id=680842 */
7417 static char **
7418 XS_unpack_charPtrPtr (SV *arg) {
7419   char **ret;
7420   AV *av;
7421   I32 i;
7422
7423   if (!arg || !SvOK (arg) || !SvROK (arg) || SvTYPE (SvRV (arg)) != SVt_PVAV)
7424     croak (\"array reference expected\");
7425
7426   av = (AV *)SvRV (arg);
7427   ret = malloc ((av_len (av) + 1 + 1) * sizeof (char *));
7428   if (!ret)
7429     croak (\"malloc failed\");
7430
7431   for (i = 0; i <= av_len (av); i++) {
7432     SV **elem = av_fetch (av, i, 0);
7433
7434     if (!elem || !*elem)
7435       croak (\"missing element in list\");
7436
7437     ret[i] = SvPV_nolen (*elem);
7438   }
7439
7440   ret[i] = NULL;
7441
7442   return ret;
7443 }
7444
7445 MODULE = Sys::Guestfs  PACKAGE = Sys::Guestfs
7446
7447 PROTOTYPES: ENABLE
7448
7449 guestfs_h *
7450 _create ()
7451    CODE:
7452       RETVAL = guestfs_create ();
7453       if (!RETVAL)
7454         croak (\"could not create guestfs handle\");
7455       guestfs_set_error_handler (RETVAL, NULL, NULL);
7456  OUTPUT:
7457       RETVAL
7458
7459 void
7460 DESTROY (g)
7461       guestfs_h *g;
7462  PPCODE:
7463       guestfs_close (g);
7464
7465 ";
7466
7467   List.iter (
7468     fun (name, style, _, _, _, _, _) ->
7469       (match fst style with
7470        | RErr -> pr "void\n"
7471        | RInt _ -> pr "SV *\n"
7472        | RInt64 _ -> pr "SV *\n"
7473        | RBool _ -> pr "SV *\n"
7474        | RConstString _ -> pr "SV *\n"
7475        | RConstOptString _ -> pr "SV *\n"
7476        | RString _ -> pr "SV *\n"
7477        | RBufferOut _ -> pr "SV *\n"
7478        | RStringList _
7479        | RStruct _ | RStructList _
7480        | RHashtable _ ->
7481            pr "void\n" (* all lists returned implictly on the stack *)
7482       );
7483       (* Call and arguments. *)
7484       pr "%s " name;
7485       generate_c_call_args ~handle:"g" ~decl:true style;
7486       pr "\n";
7487       pr "      guestfs_h *g;\n";
7488       iteri (
7489         fun i ->
7490           function
7491           | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
7492               pr "      char *%s;\n" n
7493           | OptString n ->
7494               (* http://www.perlmonks.org/?node_id=554277
7495                * Note that the implicit handle argument means we have
7496                * to add 1 to the ST(x) operator.
7497                *)
7498               pr "      char *%s = SvOK(ST(%d)) ? SvPV_nolen(ST(%d)) : NULL;\n" n (i+1) (i+1)
7499           | StringList n | DeviceList n -> pr "      char **%s;\n" n
7500           | Bool n -> pr "      int %s;\n" n
7501           | Int n -> pr "      int %s;\n" n
7502           | Int64 n -> pr "      int64_t %s;\n" n
7503       ) (snd style);
7504
7505       let do_cleanups () =
7506         List.iter (
7507           function
7508           | Pathname _ | Device _ | Dev_or_Path _ | String _ | OptString _
7509           | Bool _ | Int _ | Int64 _
7510           | FileIn _ | FileOut _ -> ()
7511           | StringList n | DeviceList n -> pr "      free (%s);\n" n
7512         ) (snd style)
7513       in
7514
7515       (* Code. *)
7516       (match fst style with
7517        | RErr ->
7518            pr "PREINIT:\n";
7519            pr "      int r;\n";
7520            pr " PPCODE:\n";
7521            pr "      r = guestfs_%s " name;
7522            generate_c_call_args ~handle:"g" style;
7523            pr ";\n";
7524            do_cleanups ();
7525            pr "      if (r == -1)\n";
7526            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7527        | RInt n
7528        | RBool n ->
7529            pr "PREINIT:\n";
7530            pr "      int %s;\n" n;
7531            pr "   CODE:\n";
7532            pr "      %s = guestfs_%s " n name;
7533            generate_c_call_args ~handle:"g" style;
7534            pr ";\n";
7535            do_cleanups ();
7536            pr "      if (%s == -1)\n" n;
7537            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7538            pr "      RETVAL = newSViv (%s);\n" n;
7539            pr " OUTPUT:\n";
7540            pr "      RETVAL\n"
7541        | RInt64 n ->
7542            pr "PREINIT:\n";
7543            pr "      int64_t %s;\n" n;
7544            pr "   CODE:\n";
7545            pr "      %s = guestfs_%s " n name;
7546            generate_c_call_args ~handle:"g" style;
7547            pr ";\n";
7548            do_cleanups ();
7549            pr "      if (%s == -1)\n" n;
7550            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7551            pr "      RETVAL = my_newSVll (%s);\n" n;
7552            pr " OUTPUT:\n";
7553            pr "      RETVAL\n"
7554        | RConstString n ->
7555            pr "PREINIT:\n";
7556            pr "      const char *%s;\n" n;
7557            pr "   CODE:\n";
7558            pr "      %s = guestfs_%s " n name;
7559            generate_c_call_args ~handle:"g" style;
7560            pr ";\n";
7561            do_cleanups ();
7562            pr "      if (%s == NULL)\n" n;
7563            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7564            pr "      RETVAL = newSVpv (%s, 0);\n" n;
7565            pr " OUTPUT:\n";
7566            pr "      RETVAL\n"
7567        | RConstOptString n ->
7568            pr "PREINIT:\n";
7569            pr "      const char *%s;\n" n;
7570            pr "   CODE:\n";
7571            pr "      %s = guestfs_%s " n name;
7572            generate_c_call_args ~handle:"g" style;
7573            pr ";\n";
7574            do_cleanups ();
7575            pr "      if (%s == NULL)\n" n;
7576            pr "        RETVAL = &PL_sv_undef;\n";
7577            pr "      else\n";
7578            pr "        RETVAL = newSVpv (%s, 0);\n" n;
7579            pr " OUTPUT:\n";
7580            pr "      RETVAL\n"
7581        | RString n ->
7582            pr "PREINIT:\n";
7583            pr "      char *%s;\n" n;
7584            pr "   CODE:\n";
7585            pr "      %s = guestfs_%s " n name;
7586            generate_c_call_args ~handle:"g" style;
7587            pr ";\n";
7588            do_cleanups ();
7589            pr "      if (%s == NULL)\n" n;
7590            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7591            pr "      RETVAL = newSVpv (%s, 0);\n" n;
7592            pr "      free (%s);\n" n;
7593            pr " OUTPUT:\n";
7594            pr "      RETVAL\n"
7595        | RStringList n | RHashtable n ->
7596            pr "PREINIT:\n";
7597            pr "      char **%s;\n" n;
7598            pr "      int i, n;\n";
7599            pr " PPCODE:\n";
7600            pr "      %s = guestfs_%s " n name;
7601            generate_c_call_args ~handle:"g" style;
7602            pr ";\n";
7603            do_cleanups ();
7604            pr "      if (%s == NULL)\n" n;
7605            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7606            pr "      for (n = 0; %s[n] != NULL; ++n) /**/;\n" n;
7607            pr "      EXTEND (SP, n);\n";
7608            pr "      for (i = 0; i < n; ++i) {\n";
7609            pr "        PUSHs (sv_2mortal (newSVpv (%s[i], 0)));\n" n;
7610            pr "        free (%s[i]);\n" n;
7611            pr "      }\n";
7612            pr "      free (%s);\n" n;
7613        | RStruct (n, typ) ->
7614            let cols = cols_of_struct typ in
7615            generate_perl_struct_code typ cols name style n do_cleanups
7616        | RStructList (n, typ) ->
7617            let cols = cols_of_struct typ in
7618            generate_perl_struct_list_code typ cols name style n do_cleanups
7619        | RBufferOut n ->
7620            pr "PREINIT:\n";
7621            pr "      char *%s;\n" n;
7622            pr "      size_t size;\n";
7623            pr "   CODE:\n";
7624            pr "      %s = guestfs_%s " n name;
7625            generate_c_call_args ~handle:"g" style;
7626            pr ";\n";
7627            do_cleanups ();
7628            pr "      if (%s == NULL)\n" n;
7629            pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7630            pr "      RETVAL = newSVpv (%s, size);\n" n;
7631            pr "      free (%s);\n" n;
7632            pr " OUTPUT:\n";
7633            pr "      RETVAL\n"
7634       );
7635
7636       pr "\n"
7637   ) all_functions
7638
7639 and generate_perl_struct_list_code typ cols name style n do_cleanups =
7640   pr "PREINIT:\n";
7641   pr "      struct guestfs_%s_list *%s;\n" typ n;
7642   pr "      int i;\n";
7643   pr "      HV *hv;\n";
7644   pr " PPCODE:\n";
7645   pr "      %s = guestfs_%s " n name;
7646   generate_c_call_args ~handle:"g" style;
7647   pr ";\n";
7648   do_cleanups ();
7649   pr "      if (%s == NULL)\n" n;
7650   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7651   pr "      EXTEND (SP, %s->len);\n" n;
7652   pr "      for (i = 0; i < %s->len; ++i) {\n" n;
7653   pr "        hv = newHV ();\n";
7654   List.iter (
7655     function
7656     | name, FString ->
7657         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 0), 0);\n"
7658           name (String.length name) n name
7659     | name, FUUID ->
7660         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, 32), 0);\n"
7661           name (String.length name) n name
7662     | name, FBuffer ->
7663         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (%s->val[i].%s, %s->val[i].%s_len), 0);\n"
7664           name (String.length name) n name n name
7665     | name, (FBytes|FUInt64) ->
7666         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVull (%s->val[i].%s), 0);\n"
7667           name (String.length name) n name
7668     | name, FInt64 ->
7669         pr "        (void) hv_store (hv, \"%s\", %d, my_newSVll (%s->val[i].%s), 0);\n"
7670           name (String.length name) n name
7671     | name, (FInt32|FUInt32) ->
7672         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
7673           name (String.length name) n name
7674     | name, FChar ->
7675         pr "        (void) hv_store (hv, \"%s\", %d, newSVpv (&%s->val[i].%s, 1), 0);\n"
7676           name (String.length name) n name
7677     | name, FOptPercent ->
7678         pr "        (void) hv_store (hv, \"%s\", %d, newSVnv (%s->val[i].%s), 0);\n"
7679           name (String.length name) n name
7680   ) cols;
7681   pr "        PUSHs (sv_2mortal (newRV ((SV *) hv)));\n";
7682   pr "      }\n";
7683   pr "      guestfs_free_%s_list (%s);\n" typ n
7684
7685 and generate_perl_struct_code typ cols name style n do_cleanups =
7686   pr "PREINIT:\n";
7687   pr "      struct guestfs_%s *%s;\n" typ n;
7688   pr " PPCODE:\n";
7689   pr "      %s = guestfs_%s " n name;
7690   generate_c_call_args ~handle:"g" style;
7691   pr ";\n";
7692   do_cleanups ();
7693   pr "      if (%s == NULL)\n" n;
7694   pr "        croak (\"%s: %%s\", guestfs_last_error (g));\n" name;
7695   pr "      EXTEND (SP, 2 * %d);\n" (List.length cols);
7696   List.iter (
7697     fun ((name, _) as col) ->
7698       pr "      PUSHs (sv_2mortal (newSVpv (\"%s\", 0)));\n" name;
7699
7700       match col with
7701       | name, FString ->
7702           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 0)));\n"
7703             n name
7704       | name, FBuffer ->
7705           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, %s->%s_len)));\n"
7706             n name n name
7707       | name, FUUID ->
7708           pr "      PUSHs (sv_2mortal (newSVpv (%s->%s, 32)));\n"
7709             n name
7710       | name, (FBytes|FUInt64) ->
7711           pr "      PUSHs (sv_2mortal (my_newSVull (%s->%s)));\n"
7712             n name
7713       | name, FInt64 ->
7714           pr "      PUSHs (sv_2mortal (my_newSVll (%s->%s)));\n"
7715             n name
7716       | name, (FInt32|FUInt32) ->
7717           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
7718             n name
7719       | name, FChar ->
7720           pr "      PUSHs (sv_2mortal (newSVpv (&%s->%s, 1)));\n"
7721             n name
7722       | name, FOptPercent ->
7723           pr "      PUSHs (sv_2mortal (newSVnv (%s->%s)));\n"
7724             n name
7725   ) cols;
7726   pr "      free (%s);\n" n
7727
7728 (* Generate Sys/Guestfs.pm. *)
7729 and generate_perl_pm () =
7730   generate_header HashStyle LGPLv2;
7731
7732   pr "\
7733 =pod
7734
7735 =head1 NAME
7736
7737 Sys::Guestfs - Perl bindings for libguestfs
7738
7739 =head1 SYNOPSIS
7740
7741  use Sys::Guestfs;
7742
7743  my $h = Sys::Guestfs->new ();
7744  $h->add_drive ('guest.img');
7745  $h->launch ();
7746  $h->mount ('/dev/sda1', '/');
7747  $h->touch ('/hello');
7748  $h->sync ();
7749
7750 =head1 DESCRIPTION
7751
7752 The C<Sys::Guestfs> module provides a Perl XS binding to the
7753 libguestfs API for examining and modifying virtual machine
7754 disk images.
7755
7756 Amongst the things this is good for: making batch configuration
7757 changes to guests, getting disk used/free statistics (see also:
7758 virt-df), migrating between virtualization systems (see also:
7759 virt-p2v), performing partial backups, performing partial guest
7760 clones, cloning guests and changing registry/UUID/hostname info, and
7761 much else besides.
7762
7763 Libguestfs uses Linux kernel and qemu code, and can access any type of
7764 guest filesystem that Linux and qemu can, including but not limited
7765 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
7766 schemes, qcow, qcow2, vmdk.
7767
7768 Libguestfs provides ways to enumerate guest storage (eg. partitions,
7769 LVs, what filesystem is in each LV, etc.).  It can also run commands
7770 in the context of the guest.  Also you can access filesystems over FTP.
7771
7772 See also L<Sys::Guestfs::Lib(3)> for a set of useful library
7773 functions for using libguestfs from Perl, including integration
7774 with libvirt.
7775
7776 =head1 ERRORS
7777
7778 All errors turn into calls to C<croak> (see L<Carp(3)>).
7779
7780 =head1 METHODS
7781
7782 =over 4
7783
7784 =cut
7785
7786 package Sys::Guestfs;
7787
7788 use strict;
7789 use warnings;
7790
7791 require XSLoader;
7792 XSLoader::load ('Sys::Guestfs');
7793
7794 =item $h = Sys::Guestfs->new ();
7795
7796 Create a new guestfs handle.
7797
7798 =cut
7799
7800 sub new {
7801   my $proto = shift;
7802   my $class = ref ($proto) || $proto;
7803
7804   my $self = Sys::Guestfs::_create ();
7805   bless $self, $class;
7806   return $self;
7807 }
7808
7809 ";
7810
7811   (* Actions.  We only need to print documentation for these as
7812    * they are pulled in from the XS code automatically.
7813    *)
7814   List.iter (
7815     fun (name, style, _, flags, _, _, longdesc) ->
7816       if not (List.mem NotInDocs flags) then (
7817         let longdesc = replace_str longdesc "C<guestfs_" "C<$h-E<gt>" in
7818         pr "=item ";
7819         generate_perl_prototype name style;
7820         pr "\n\n";
7821         pr "%s\n\n" longdesc;
7822         if List.mem ProtocolLimitWarning flags then
7823           pr "%s\n\n" protocol_limit_warning;
7824         if List.mem DangerWillRobinson flags then
7825           pr "%s\n\n" danger_will_robinson;
7826         match deprecation_notice flags with
7827         | None -> ()
7828         | Some txt -> pr "%s\n\n" txt
7829       )
7830   ) all_functions_sorted;
7831
7832   (* End of file. *)
7833   pr "\
7834 =cut
7835
7836 1;
7837
7838 =back
7839
7840 =head1 COPYRIGHT
7841
7842 Copyright (C) 2009 Red Hat Inc.
7843
7844 =head1 LICENSE
7845
7846 Please see the file COPYING.LIB for the full license.
7847
7848 =head1 SEE ALSO
7849
7850 L<guestfs(3)>,
7851 L<guestfish(1)>,
7852 L<http://libguestfs.org>,
7853 L<Sys::Guestfs::Lib(3)>.
7854
7855 =cut
7856 "
7857
7858 and generate_perl_prototype name style =
7859   (match fst style with
7860    | RErr -> ()
7861    | RBool n
7862    | RInt n
7863    | RInt64 n
7864    | RConstString n
7865    | RConstOptString n
7866    | RString n
7867    | RBufferOut n -> pr "$%s = " n
7868    | RStruct (n,_)
7869    | RHashtable n -> pr "%%%s = " n
7870    | RStringList n
7871    | RStructList (n,_) -> pr "@%s = " n
7872   );
7873   pr "$h->%s (" name;
7874   let comma = ref false in
7875   List.iter (
7876     fun arg ->
7877       if !comma then pr ", ";
7878       comma := true;
7879       match arg with
7880       | Pathname n | Device n | Dev_or_Path n | String n
7881       | OptString n | Bool n | Int n | Int64 n | FileIn n | FileOut n ->
7882           pr "$%s" n
7883       | StringList n | DeviceList n ->
7884           pr "\\@%s" n
7885   ) (snd style);
7886   pr ");"
7887
7888 (* Generate Python C module. *)
7889 and generate_python_c () =
7890   generate_header CStyle LGPLv2;
7891
7892   pr "\
7893 #include <Python.h>
7894
7895 #include <stdio.h>
7896 #include <stdlib.h>
7897 #include <assert.h>
7898
7899 #include \"guestfs.h\"
7900
7901 typedef struct {
7902   PyObject_HEAD
7903   guestfs_h *g;
7904 } Pyguestfs_Object;
7905
7906 static guestfs_h *
7907 get_handle (PyObject *obj)
7908 {
7909   assert (obj);
7910   assert (obj != Py_None);
7911   return ((Pyguestfs_Object *) obj)->g;
7912 }
7913
7914 static PyObject *
7915 put_handle (guestfs_h *g)
7916 {
7917   assert (g);
7918   return
7919     PyCObject_FromVoidPtrAndDesc ((void *) g, (char *) \"guestfs_h\", NULL);
7920 }
7921
7922 /* This list should be freed (but not the strings) after use. */
7923 static char **
7924 get_string_list (PyObject *obj)
7925 {
7926   int i, len;
7927   char **r;
7928
7929   assert (obj);
7930
7931   if (!PyList_Check (obj)) {
7932     PyErr_SetString (PyExc_RuntimeError, \"expecting a list parameter\");
7933     return NULL;
7934   }
7935
7936   len = PyList_Size (obj);
7937   r = malloc (sizeof (char *) * (len+1));
7938   if (r == NULL) {
7939     PyErr_SetString (PyExc_RuntimeError, \"get_string_list: out of memory\");
7940     return NULL;
7941   }
7942
7943   for (i = 0; i < len; ++i)
7944     r[i] = PyString_AsString (PyList_GetItem (obj, i));
7945   r[len] = NULL;
7946
7947   return r;
7948 }
7949
7950 static PyObject *
7951 put_string_list (char * const * const argv)
7952 {
7953   PyObject *list;
7954   int argc, i;
7955
7956   for (argc = 0; argv[argc] != NULL; ++argc)
7957     ;
7958
7959   list = PyList_New (argc);
7960   for (i = 0; i < argc; ++i)
7961     PyList_SetItem (list, i, PyString_FromString (argv[i]));
7962
7963   return list;
7964 }
7965
7966 static PyObject *
7967 put_table (char * const * const argv)
7968 {
7969   PyObject *list, *item;
7970   int argc, i;
7971
7972   for (argc = 0; argv[argc] != NULL; ++argc)
7973     ;
7974
7975   list = PyList_New (argc >> 1);
7976   for (i = 0; i < argc; i += 2) {
7977     item = PyTuple_New (2);
7978     PyTuple_SetItem (item, 0, PyString_FromString (argv[i]));
7979     PyTuple_SetItem (item, 1, PyString_FromString (argv[i+1]));
7980     PyList_SetItem (list, i >> 1, item);
7981   }
7982
7983   return list;
7984 }
7985
7986 static void
7987 free_strings (char **argv)
7988 {
7989   int argc;
7990
7991   for (argc = 0; argv[argc] != NULL; ++argc)
7992     free (argv[argc]);
7993   free (argv);
7994 }
7995
7996 static PyObject *
7997 py_guestfs_create (PyObject *self, PyObject *args)
7998 {
7999   guestfs_h *g;
8000
8001   g = guestfs_create ();
8002   if (g == NULL) {
8003     PyErr_SetString (PyExc_RuntimeError,
8004                      \"guestfs.create: failed to allocate handle\");
8005     return NULL;
8006   }
8007   guestfs_set_error_handler (g, NULL, NULL);
8008   return put_handle (g);
8009 }
8010
8011 static PyObject *
8012 py_guestfs_close (PyObject *self, PyObject *args)
8013 {
8014   PyObject *py_g;
8015   guestfs_h *g;
8016
8017   if (!PyArg_ParseTuple (args, (char *) \"O:guestfs_close\", &py_g))
8018     return NULL;
8019   g = get_handle (py_g);
8020
8021   guestfs_close (g);
8022
8023   Py_INCREF (Py_None);
8024   return Py_None;
8025 }
8026
8027 ";
8028
8029   let emit_put_list_function typ =
8030     pr "static PyObject *\n";
8031     pr "put_%s_list (struct guestfs_%s_list *%ss)\n" typ typ typ;
8032     pr "{\n";
8033     pr "  PyObject *list;\n";
8034     pr "  int i;\n";
8035     pr "\n";
8036     pr "  list = PyList_New (%ss->len);\n" typ;
8037     pr "  for (i = 0; i < %ss->len; ++i)\n" typ;
8038     pr "    PyList_SetItem (list, i, put_%s (&%ss->val[i]));\n" typ typ;
8039     pr "  return list;\n";
8040     pr "};\n";
8041     pr "\n"
8042   in
8043
8044   (* Structures, turned into Python dictionaries. *)
8045   List.iter (
8046     fun (typ, cols) ->
8047       pr "static PyObject *\n";
8048       pr "put_%s (struct guestfs_%s *%s)\n" typ typ typ;
8049       pr "{\n";
8050       pr "  PyObject *dict;\n";
8051       pr "\n";
8052       pr "  dict = PyDict_New ();\n";
8053       List.iter (
8054         function
8055         | name, FString ->
8056             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8057             pr "                        PyString_FromString (%s->%s));\n"
8058               typ name
8059         | name, FBuffer ->
8060             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8061             pr "                        PyString_FromStringAndSize (%s->%s, %s->%s_len));\n"
8062               typ name typ name
8063         | name, FUUID ->
8064             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8065             pr "                        PyString_FromStringAndSize (%s->%s, 32));\n"
8066               typ name
8067         | name, (FBytes|FUInt64) ->
8068             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8069             pr "                        PyLong_FromUnsignedLongLong (%s->%s));\n"
8070               typ name
8071         | name, FInt64 ->
8072             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8073             pr "                        PyLong_FromLongLong (%s->%s));\n"
8074               typ name
8075         | name, FUInt32 ->
8076             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8077             pr "                        PyLong_FromUnsignedLong (%s->%s));\n"
8078               typ name
8079         | name, FInt32 ->
8080             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8081             pr "                        PyLong_FromLong (%s->%s));\n"
8082               typ name
8083         | name, FOptPercent ->
8084             pr "  if (%s->%s >= 0)\n" typ name;
8085             pr "    PyDict_SetItemString (dict, \"%s\",\n" name;
8086             pr "                          PyFloat_FromDouble ((double) %s->%s));\n"
8087               typ name;
8088             pr "  else {\n";
8089             pr "    Py_INCREF (Py_None);\n";
8090             pr "    PyDict_SetItemString (dict, \"%s\", Py_None);\n" name;
8091             pr "  }\n"
8092         | name, FChar ->
8093             pr "  PyDict_SetItemString (dict, \"%s\",\n" name;
8094             pr "                        PyString_FromStringAndSize (&dirent->%s, 1));\n" name
8095       ) cols;
8096       pr "  return dict;\n";
8097       pr "};\n";
8098       pr "\n";
8099
8100   ) structs;
8101
8102   (* Emit a put_TYPE_list function definition only if that function is used. *)
8103   List.iter (
8104     function
8105     | typ, (RStructListOnly | RStructAndList) ->
8106         (* generate the function for typ *)
8107         emit_put_list_function typ
8108     | typ, _ -> () (* empty *)
8109   ) (rstructs_used_by all_functions);
8110
8111   (* Python wrapper functions. *)
8112   List.iter (
8113     fun (name, style, _, _, _, _, _) ->
8114       pr "static PyObject *\n";
8115       pr "py_guestfs_%s (PyObject *self, PyObject *args)\n" name;
8116       pr "{\n";
8117
8118       pr "  PyObject *py_g;\n";
8119       pr "  guestfs_h *g;\n";
8120       pr "  PyObject *py_r;\n";
8121
8122       let error_code =
8123         match fst style with
8124         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
8125         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
8126         | RConstString _ | RConstOptString _ ->
8127             pr "  const char *r;\n"; "NULL"
8128         | RString _ -> pr "  char *r;\n"; "NULL"
8129         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
8130         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
8131         | RStructList (_, typ) ->
8132             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
8133         | RBufferOut _ ->
8134             pr "  char *r;\n";
8135             pr "  size_t size;\n";
8136             "NULL" in
8137
8138       List.iter (
8139         function
8140         | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
8141             pr "  const char *%s;\n" n
8142         | OptString n -> pr "  const char *%s;\n" n
8143         | StringList n | DeviceList n ->
8144             pr "  PyObject *py_%s;\n" n;
8145             pr "  char **%s;\n" n
8146         | Bool n -> pr "  int %s;\n" n
8147         | Int n -> pr "  int %s;\n" n
8148         | Int64 n -> pr "  long long %s;\n" n
8149       ) (snd style);
8150
8151       pr "\n";
8152
8153       (* Convert the parameters. *)
8154       pr "  if (!PyArg_ParseTuple (args, (char *) \"O";
8155       List.iter (
8156         function
8157         | Pathname _ | Device _ | Dev_or_Path _ | String _ | FileIn _ | FileOut _ -> pr "s"
8158         | OptString _ -> pr "z"
8159         | StringList _ | DeviceList _ -> pr "O"
8160         | Bool _ -> pr "i" (* XXX Python has booleans? *)
8161         | Int _ -> pr "i"
8162         | Int64 _ -> pr "L" (* XXX Whoever thought it was a good idea to
8163                              * emulate C's int/long/long long in Python?
8164                              *)
8165       ) (snd style);
8166       pr ":guestfs_%s\",\n" name;
8167       pr "                         &py_g";
8168       List.iter (
8169         function
8170         | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n -> pr ", &%s" n
8171         | OptString n -> pr ", &%s" n
8172         | StringList n | DeviceList n -> pr ", &py_%s" n
8173         | Bool n -> pr ", &%s" n
8174         | Int n -> pr ", &%s" n
8175         | Int64 n -> pr ", &%s" n
8176       ) (snd style);
8177
8178       pr "))\n";
8179       pr "    return NULL;\n";
8180
8181       pr "  g = get_handle (py_g);\n";
8182       List.iter (
8183         function
8184         | Pathname _ | Device _ | Dev_or_Path _ | String _
8185         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
8186         | StringList n | DeviceList n ->
8187             pr "  %s = get_string_list (py_%s);\n" n n;
8188             pr "  if (!%s) return NULL;\n" n
8189       ) (snd style);
8190
8191       pr "\n";
8192
8193       pr "  r = guestfs_%s " name;
8194       generate_c_call_args ~handle:"g" style;
8195       pr ";\n";
8196
8197       List.iter (
8198         function
8199         | Pathname _ | Device _ | Dev_or_Path _ | String _
8200         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
8201         | StringList n | DeviceList n ->
8202             pr "  free (%s);\n" n
8203       ) (snd style);
8204
8205       pr "  if (r == %s) {\n" error_code;
8206       pr "    PyErr_SetString (PyExc_RuntimeError, guestfs_last_error (g));\n";
8207       pr "    return NULL;\n";
8208       pr "  }\n";
8209       pr "\n";
8210
8211       (match fst style with
8212        | RErr ->
8213            pr "  Py_INCREF (Py_None);\n";
8214            pr "  py_r = Py_None;\n"
8215        | RInt _
8216        | RBool _ -> pr "  py_r = PyInt_FromLong ((long) r);\n"
8217        | RInt64 _ -> pr "  py_r = PyLong_FromLongLong (r);\n"
8218        | RConstString _ -> pr "  py_r = PyString_FromString (r);\n"
8219        | RConstOptString _ ->
8220            pr "  if (r)\n";
8221            pr "    py_r = PyString_FromString (r);\n";
8222            pr "  else {\n";
8223            pr "    Py_INCREF (Py_None);\n";
8224            pr "    py_r = Py_None;\n";
8225            pr "  }\n"
8226        | RString _ ->
8227            pr "  py_r = PyString_FromString (r);\n";
8228            pr "  free (r);\n"
8229        | RStringList _ ->
8230            pr "  py_r = put_string_list (r);\n";
8231            pr "  free_strings (r);\n"
8232        | RStruct (_, typ) ->
8233            pr "  py_r = put_%s (r);\n" typ;
8234            pr "  guestfs_free_%s (r);\n" typ
8235        | RStructList (_, typ) ->
8236            pr "  py_r = put_%s_list (r);\n" typ;
8237            pr "  guestfs_free_%s_list (r);\n" typ
8238        | RHashtable n ->
8239            pr "  py_r = put_table (r);\n";
8240            pr "  free_strings (r);\n"
8241        | RBufferOut _ ->
8242            pr "  py_r = PyString_FromStringAndSize (r, size);\n";
8243            pr "  free (r);\n"
8244       );
8245
8246       pr "  return py_r;\n";
8247       pr "}\n";
8248       pr "\n"
8249   ) all_functions;
8250
8251   (* Table of functions. *)
8252   pr "static PyMethodDef methods[] = {\n";
8253   pr "  { (char *) \"create\", py_guestfs_create, METH_VARARGS, NULL },\n";
8254   pr "  { (char *) \"close\", py_guestfs_close, METH_VARARGS, NULL },\n";
8255   List.iter (
8256     fun (name, _, _, _, _, _, _) ->
8257       pr "  { (char *) \"%s\", py_guestfs_%s, METH_VARARGS, NULL },\n"
8258         name name
8259   ) all_functions;
8260   pr "  { NULL, NULL, 0, NULL }\n";
8261   pr "};\n";
8262   pr "\n";
8263
8264   (* Init function. *)
8265   pr "\
8266 void
8267 initlibguestfsmod (void)
8268 {
8269   static int initialized = 0;
8270
8271   if (initialized) return;
8272   Py_InitModule ((char *) \"libguestfsmod\", methods);
8273   initialized = 1;
8274 }
8275 "
8276
8277 (* Generate Python module. *)
8278 and generate_python_py () =
8279   generate_header HashStyle LGPLv2;
8280
8281   pr "\
8282 u\"\"\"Python bindings for libguestfs
8283
8284 import guestfs
8285 g = guestfs.GuestFS ()
8286 g.add_drive (\"guest.img\")
8287 g.launch ()
8288 parts = g.list_partitions ()
8289
8290 The guestfs module provides a Python binding to the libguestfs API
8291 for examining and modifying virtual machine disk images.
8292
8293 Amongst the things this is good for: making batch configuration
8294 changes to guests, getting disk used/free statistics (see also:
8295 virt-df), migrating between virtualization systems (see also:
8296 virt-p2v), performing partial backups, performing partial guest
8297 clones, cloning guests and changing registry/UUID/hostname info, and
8298 much else besides.
8299
8300 Libguestfs uses Linux kernel and qemu code, and can access any type of
8301 guest filesystem that Linux and qemu can, including but not limited
8302 to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition
8303 schemes, qcow, qcow2, vmdk.
8304
8305 Libguestfs provides ways to enumerate guest storage (eg. partitions,
8306 LVs, what filesystem is in each LV, etc.).  It can also run commands
8307 in the context of the guest.  Also you can access filesystems over FTP.
8308
8309 Errors which happen while using the API are turned into Python
8310 RuntimeError exceptions.
8311
8312 To create a guestfs handle you usually have to perform the following
8313 sequence of calls:
8314
8315 # Create the handle, call add_drive at least once, and possibly
8316 # several times if the guest has multiple block devices:
8317 g = guestfs.GuestFS ()
8318 g.add_drive (\"guest.img\")
8319
8320 # Launch the qemu subprocess and wait for it to become ready:
8321 g.launch ()
8322
8323 # Now you can issue commands, for example:
8324 logvols = g.lvs ()
8325
8326 \"\"\"
8327
8328 import libguestfsmod
8329
8330 class GuestFS:
8331     \"\"\"Instances of this class are libguestfs API handles.\"\"\"
8332
8333     def __init__ (self):
8334         \"\"\"Create a new libguestfs handle.\"\"\"
8335         self._o = libguestfsmod.create ()
8336
8337     def __del__ (self):
8338         libguestfsmod.close (self._o)
8339
8340 ";
8341
8342   List.iter (
8343     fun (name, style, _, flags, _, _, longdesc) ->
8344       pr "    def %s " name;
8345       generate_py_call_args ~handle:"self" (snd style);
8346       pr ":\n";
8347
8348       if not (List.mem NotInDocs flags) then (
8349         let doc = replace_str longdesc "C<guestfs_" "C<g." in
8350         let doc =
8351           match fst style with
8352           | RErr | RInt _ | RInt64 _ | RBool _
8353           | RConstOptString _ | RConstString _
8354           | RString _ | RBufferOut _ -> doc
8355           | RStringList _ ->
8356               doc ^ "\n\nThis function returns a list of strings."
8357           | RStruct (_, typ) ->
8358               doc ^ sprintf "\n\nThis function returns a dictionary, with keys matching the various fields in the guestfs_%s structure." typ
8359           | RStructList (_, typ) ->
8360               doc ^ sprintf "\n\nThis function returns a list of %ss.  Each %s is represented as a dictionary." typ typ
8361           | RHashtable _ ->
8362               doc ^ "\n\nThis function returns a dictionary." in
8363         let doc =
8364           if List.mem ProtocolLimitWarning flags then
8365             doc ^ "\n\n" ^ protocol_limit_warning
8366           else doc in
8367         let doc =
8368           if List.mem DangerWillRobinson flags then
8369             doc ^ "\n\n" ^ danger_will_robinson
8370           else doc in
8371         let doc =
8372           match deprecation_notice flags with
8373           | None -> doc
8374           | Some txt -> doc ^ "\n\n" ^ txt in
8375         let doc = pod2text ~width:60 name doc in
8376         let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in
8377         let doc = String.concat "\n        " doc in
8378         pr "        u\"\"\"%s\"\"\"\n" doc;
8379       );
8380       pr "        return libguestfsmod.%s " name;
8381       generate_py_call_args ~handle:"self._o" (snd style);
8382       pr "\n";
8383       pr "\n";
8384   ) all_functions
8385
8386 (* Generate Python call arguments, eg "(handle, foo, bar)" *)
8387 and generate_py_call_args ~handle args =
8388   pr "(%s" handle;
8389   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
8390   pr ")"
8391
8392 (* Useful if you need the longdesc POD text as plain text.  Returns a
8393  * list of lines.
8394  *
8395  * Because this is very slow (the slowest part of autogeneration),
8396  * we memoize the results.
8397  *)
8398 and pod2text ~width name longdesc =
8399   let key = width, name, longdesc in
8400   try Hashtbl.find pod2text_memo key
8401   with Not_found ->
8402     let filename, chan = Filename.open_temp_file "gen" ".tmp" in
8403     fprintf chan "=head1 %s\n\n%s\n" name longdesc;
8404     close_out chan;
8405     let cmd = sprintf "pod2text -w %d %s" width (Filename.quote filename) in
8406     let chan = Unix.open_process_in cmd in
8407     let lines = ref [] in
8408     let rec loop i =
8409       let line = input_line chan in
8410       if i = 1 then             (* discard the first line of output *)
8411         loop (i+1)
8412       else (
8413         let line = triml line in
8414         lines := line :: !lines;
8415         loop (i+1)
8416       ) in
8417     let lines = try loop 1 with End_of_file -> List.rev !lines in
8418     Unix.unlink filename;
8419     (match Unix.close_process_in chan with
8420      | Unix.WEXITED 0 -> ()
8421      | Unix.WEXITED i ->
8422          failwithf "pod2text: process exited with non-zero status (%d)" i
8423      | Unix.WSIGNALED i | Unix.WSTOPPED i ->
8424          failwithf "pod2text: process signalled or stopped by signal %d" i
8425     );
8426     Hashtbl.add pod2text_memo key lines;
8427     pod2text_memo_updated ();
8428     lines
8429
8430 (* Generate ruby bindings. *)
8431 and generate_ruby_c () =
8432   generate_header CStyle LGPLv2;
8433
8434   pr "\
8435 #include <stdio.h>
8436 #include <stdlib.h>
8437
8438 #include <ruby.h>
8439
8440 #include \"guestfs.h\"
8441
8442 #include \"extconf.h\"
8443
8444 /* For Ruby < 1.9 */
8445 #ifndef RARRAY_LEN
8446 #define RARRAY_LEN(r) (RARRAY((r))->len)
8447 #endif
8448
8449 static VALUE m_guestfs;                 /* guestfs module */
8450 static VALUE c_guestfs;                 /* guestfs_h handle */
8451 static VALUE e_Error;                   /* used for all errors */
8452
8453 static void ruby_guestfs_free (void *p)
8454 {
8455   if (!p) return;
8456   guestfs_close ((guestfs_h *) p);
8457 }
8458
8459 static VALUE ruby_guestfs_create (VALUE m)
8460 {
8461   guestfs_h *g;
8462
8463   g = guestfs_create ();
8464   if (!g)
8465     rb_raise (e_Error, \"failed to create guestfs handle\");
8466
8467   /* Don't print error messages to stderr by default. */
8468   guestfs_set_error_handler (g, NULL, NULL);
8469
8470   /* Wrap it, and make sure the close function is called when the
8471    * handle goes away.
8472    */
8473   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
8474 }
8475
8476 static VALUE ruby_guestfs_close (VALUE gv)
8477 {
8478   guestfs_h *g;
8479   Data_Get_Struct (gv, guestfs_h, g);
8480
8481   ruby_guestfs_free (g);
8482   DATA_PTR (gv) = NULL;
8483
8484   return Qnil;
8485 }
8486
8487 ";
8488
8489   List.iter (
8490     fun (name, style, _, _, _, _, _) ->
8491       pr "static VALUE ruby_guestfs_%s (VALUE gv" name;
8492       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) (snd style);
8493       pr ")\n";
8494       pr "{\n";
8495       pr "  guestfs_h *g;\n";
8496       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
8497       pr "  if (!g)\n";
8498       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
8499         name;
8500       pr "\n";
8501
8502       List.iter (
8503         function
8504         | Pathname n | Device n | Dev_or_Path n | String n | FileIn n | FileOut n ->
8505             pr "  Check_Type (%sv, T_STRING);\n" n;
8506             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
8507             pr "  if (!%s)\n" n;
8508             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
8509             pr "              \"%s\", \"%s\");\n" n name
8510         | OptString n ->
8511             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
8512         | StringList n | DeviceList n ->
8513             pr "  char **%s;\n" n;
8514             pr "  Check_Type (%sv, T_ARRAY);\n" n;
8515             pr "  {\n";
8516             pr "    int i, len;\n";
8517             pr "    len = RARRAY_LEN (%sv);\n" n;
8518             pr "    %s = guestfs_safe_malloc (g, sizeof (char *) * (len+1));\n"
8519               n;
8520             pr "    for (i = 0; i < len; ++i) {\n";
8521             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
8522             pr "      %s[i] = StringValueCStr (v);\n" n;
8523             pr "    }\n";
8524             pr "    %s[len] = NULL;\n" n;
8525             pr "  }\n";
8526         | Bool n ->
8527             pr "  int %s = RTEST (%sv);\n" n n
8528         | Int n ->
8529             pr "  int %s = NUM2INT (%sv);\n" n n
8530         | Int64 n ->
8531             pr "  long long %s = NUM2LL (%sv);\n" n n
8532       ) (snd style);
8533       pr "\n";
8534
8535       let error_code =
8536         match fst style with
8537         | RErr | RInt _ | RBool _ -> pr "  int r;\n"; "-1"
8538         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
8539         | RConstString _ | RConstOptString _ ->
8540             pr "  const char *r;\n"; "NULL"
8541         | RString _ -> pr "  char *r;\n"; "NULL"
8542         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
8543         | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ; "NULL"
8544         | RStructList (_, typ) ->
8545             pr "  struct guestfs_%s_list *r;\n" typ; "NULL"
8546         | RBufferOut _ ->
8547             pr "  char *r;\n";
8548             pr "  size_t size;\n";
8549             "NULL" in
8550       pr "\n";
8551
8552       pr "  r = guestfs_%s " name;
8553       generate_c_call_args ~handle:"g" style;
8554       pr ";\n";
8555
8556       List.iter (
8557         function
8558         | Pathname _ | Device _ | Dev_or_Path _ | String _
8559         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ -> ()
8560         | StringList n | DeviceList n ->
8561             pr "  free (%s);\n" n
8562       ) (snd style);
8563
8564       pr "  if (r == %s)\n" error_code;
8565       pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n";
8566       pr "\n";
8567
8568       (match fst style with
8569        | RErr ->
8570            pr "  return Qnil;\n"
8571        | RInt _ | RBool _ ->
8572            pr "  return INT2NUM (r);\n"
8573        | RInt64 _ ->
8574            pr "  return ULL2NUM (r);\n"
8575        | RConstString _ ->
8576            pr "  return rb_str_new2 (r);\n";
8577        | RConstOptString _ ->
8578            pr "  if (r)\n";
8579            pr "    return rb_str_new2 (r);\n";
8580            pr "  else\n";
8581            pr "    return Qnil;\n";
8582        | RString _ ->
8583            pr "  VALUE rv = rb_str_new2 (r);\n";
8584            pr "  free (r);\n";
8585            pr "  return rv;\n";
8586        | RStringList _ ->
8587            pr "  int i, len = 0;\n";
8588            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
8589            pr "  VALUE rv = rb_ary_new2 (len);\n";
8590            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
8591            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
8592            pr "    free (r[i]);\n";
8593            pr "  }\n";
8594            pr "  free (r);\n";
8595            pr "  return rv;\n"
8596        | RStruct (_, typ) ->
8597            let cols = cols_of_struct typ in
8598            generate_ruby_struct_code typ cols
8599        | RStructList (_, typ) ->
8600            let cols = cols_of_struct typ in
8601            generate_ruby_struct_list_code typ cols
8602        | RHashtable _ ->
8603            pr "  VALUE rv = rb_hash_new ();\n";
8604            pr "  int i;\n";
8605            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
8606            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
8607            pr "    free (r[i]);\n";
8608            pr "    free (r[i+1]);\n";
8609            pr "  }\n";
8610            pr "  free (r);\n";
8611            pr "  return rv;\n"
8612        | RBufferOut _ ->
8613            pr "  VALUE rv = rb_str_new (r, size);\n";
8614            pr "  free (r);\n";
8615            pr "  return rv;\n";
8616       );
8617
8618       pr "}\n";
8619       pr "\n"
8620   ) all_functions;
8621
8622   pr "\
8623 /* Initialize the module. */
8624 void Init__guestfs ()
8625 {
8626   m_guestfs = rb_define_module (\"Guestfs\");
8627   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
8628   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
8629
8630   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
8631   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
8632
8633 ";
8634   (* Define the rest of the methods. *)
8635   List.iter (
8636     fun (name, style, _, _, _, _, _) ->
8637       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
8638       pr "        ruby_guestfs_%s, %d);\n" name (List.length (snd style))
8639   ) all_functions;
8640
8641   pr "}\n"
8642
8643 (* Ruby code to return a struct. *)
8644 and generate_ruby_struct_code typ cols =
8645   pr "  VALUE rv = rb_hash_new ();\n";
8646   List.iter (
8647     function
8648     | name, FString ->
8649         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
8650     | name, FBuffer ->
8651         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
8652     | name, FUUID ->
8653         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
8654     | name, (FBytes|FUInt64) ->
8655         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
8656     | name, FInt64 ->
8657         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
8658     | name, FUInt32 ->
8659         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
8660     | name, FInt32 ->
8661         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
8662     | name, FOptPercent ->
8663         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
8664     | name, FChar -> (* XXX wrong? *)
8665         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
8666   ) cols;
8667   pr "  guestfs_free_%s (r);\n" typ;
8668   pr "  return rv;\n"
8669
8670 (* Ruby code to return a struct list. *)
8671 and generate_ruby_struct_list_code typ cols =
8672   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
8673   pr "  int i;\n";
8674   pr "  for (i = 0; i < r->len; ++i) {\n";
8675   pr "    VALUE hv = rb_hash_new ();\n";
8676   List.iter (
8677     function
8678     | name, FString ->
8679         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
8680     | name, FBuffer ->
8681         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
8682     | name, FUUID ->
8683         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
8684     | name, (FBytes|FUInt64) ->
8685         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
8686     | name, FInt64 ->
8687         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
8688     | name, FUInt32 ->
8689         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
8690     | name, FInt32 ->
8691         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
8692     | name, FOptPercent ->
8693         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
8694     | name, FChar -> (* XXX wrong? *)
8695         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
8696   ) cols;
8697   pr "    rb_ary_push (rv, hv);\n";
8698   pr "  }\n";
8699   pr "  guestfs_free_%s_list (r);\n" typ;
8700   pr "  return rv;\n"
8701
8702 (* Generate Java bindings GuestFS.java file. *)
8703 and generate_java_java () =
8704   generate_header CStyle LGPLv2;
8705
8706   pr "\
8707 package com.redhat.et.libguestfs;
8708
8709 import java.util.HashMap;
8710 import com.redhat.et.libguestfs.LibGuestFSException;
8711 import com.redhat.et.libguestfs.PV;
8712 import com.redhat.et.libguestfs.VG;
8713 import com.redhat.et.libguestfs.LV;
8714 import com.redhat.et.libguestfs.Stat;
8715 import com.redhat.et.libguestfs.StatVFS;
8716 import com.redhat.et.libguestfs.IntBool;
8717 import com.redhat.et.libguestfs.Dirent;
8718
8719 /**
8720  * The GuestFS object is a libguestfs handle.
8721  *
8722  * @author rjones
8723  */
8724 public class GuestFS {
8725   // Load the native code.
8726   static {
8727     System.loadLibrary (\"guestfs_jni\");
8728   }
8729
8730   /**
8731    * The native guestfs_h pointer.
8732    */
8733   long g;
8734
8735   /**
8736    * Create a libguestfs handle.
8737    *
8738    * @throws LibGuestFSException
8739    */
8740   public GuestFS () throws LibGuestFSException
8741   {
8742     g = _create ();
8743   }
8744   private native long _create () throws LibGuestFSException;
8745
8746   /**
8747    * Close a libguestfs handle.
8748    *
8749    * You can also leave handles to be collected by the garbage
8750    * collector, but this method ensures that the resources used
8751    * by the handle are freed up immediately.  If you call any
8752    * other methods after closing the handle, you will get an
8753    * exception.
8754    *
8755    * @throws LibGuestFSException
8756    */
8757   public void close () throws LibGuestFSException
8758   {
8759     if (g != 0)
8760       _close (g);
8761     g = 0;
8762   }
8763   private native void _close (long g) throws LibGuestFSException;
8764
8765   public void finalize () throws LibGuestFSException
8766   {
8767     close ();
8768   }
8769
8770 ";
8771
8772   List.iter (
8773     fun (name, style, _, flags, _, shortdesc, longdesc) ->
8774       if not (List.mem NotInDocs flags); then (
8775         let doc = replace_str longdesc "C<guestfs_" "C<g." in
8776         let doc =
8777           if List.mem ProtocolLimitWarning flags then
8778             doc ^ "\n\n" ^ protocol_limit_warning
8779           else doc in
8780         let doc =
8781           if List.mem DangerWillRobinson flags then
8782             doc ^ "\n\n" ^ danger_will_robinson
8783           else doc in
8784         let doc =
8785           match deprecation_notice flags with
8786           | None -> doc
8787           | Some txt -> doc ^ "\n\n" ^ txt in
8788         let doc = pod2text ~width:60 name doc in
8789         let doc = List.map (            (* RHBZ#501883 *)
8790           function
8791           | "" -> "<p>"
8792           | nonempty -> nonempty
8793         ) doc in
8794         let doc = String.concat "\n   * " doc in
8795
8796         pr "  /**\n";
8797         pr "   * %s\n" shortdesc;
8798         pr "   * <p>\n";
8799         pr "   * %s\n" doc;
8800         pr "   * @throws LibGuestFSException\n";
8801         pr "   */\n";
8802         pr "  ";
8803       );
8804       generate_java_prototype ~public:true ~semicolon:false name style;
8805       pr "\n";
8806       pr "  {\n";
8807       pr "    if (g == 0)\n";
8808       pr "      throw new LibGuestFSException (\"%s: handle is closed\");\n"
8809         name;
8810       pr "    ";
8811       if fst style <> RErr then pr "return ";
8812       pr "_%s " name;
8813       generate_java_call_args ~handle:"g" (snd style);
8814       pr ";\n";
8815       pr "  }\n";
8816       pr "  ";
8817       generate_java_prototype ~privat:true ~native:true name style;
8818       pr "\n";
8819       pr "\n";
8820   ) all_functions;
8821
8822   pr "}\n"
8823
8824 (* Generate Java call arguments, eg "(handle, foo, bar)" *)
8825 and generate_java_call_args ~handle args =
8826   pr "(%s" handle;
8827   List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args;
8828   pr ")"
8829
8830 and generate_java_prototype ?(public=false) ?(privat=false) ?(native=false)
8831     ?(semicolon=true) name style =
8832   if privat then pr "private ";
8833   if public then pr "public ";
8834   if native then pr "native ";
8835
8836   (* return type *)
8837   (match fst style with
8838    | RErr -> pr "void ";
8839    | RInt _ -> pr "int ";
8840    | RInt64 _ -> pr "long ";
8841    | RBool _ -> pr "boolean ";
8842    | RConstString _ | RConstOptString _ | RString _
8843    | RBufferOut _ -> pr "String ";
8844    | RStringList _ -> pr "String[] ";
8845    | RStruct (_, typ) ->
8846        let name = java_name_of_struct typ in
8847        pr "%s " name;
8848    | RStructList (_, typ) ->
8849        let name = java_name_of_struct typ in
8850        pr "%s[] " name;
8851    | RHashtable _ -> pr "HashMap<String,String> ";
8852   );
8853
8854   if native then pr "_%s " name else pr "%s " name;
8855   pr "(";
8856   let needs_comma = ref false in
8857   if native then (
8858     pr "long g";
8859     needs_comma := true
8860   );
8861
8862   (* args *)
8863   List.iter (
8864     fun arg ->
8865       if !needs_comma then pr ", ";
8866       needs_comma := true;
8867
8868       match arg with
8869       | Pathname n
8870       | Device n | Dev_or_Path n
8871       | String n
8872       | OptString n
8873       | FileIn n
8874       | FileOut n ->
8875           pr "String %s" n
8876       | StringList n | DeviceList n ->
8877           pr "String[] %s" n
8878       | Bool n ->
8879           pr "boolean %s" n
8880       | Int n ->
8881           pr "int %s" n
8882       | Int64 n ->
8883           pr "long %s" n
8884   ) (snd style);
8885
8886   pr ")\n";
8887   pr "    throws LibGuestFSException";
8888   if semicolon then pr ";"
8889
8890 and generate_java_struct jtyp cols =
8891   generate_header CStyle LGPLv2;
8892
8893   pr "\
8894 package com.redhat.et.libguestfs;
8895
8896 /**
8897  * Libguestfs %s structure.
8898  *
8899  * @author rjones
8900  * @see GuestFS
8901  */
8902 public class %s {
8903 " jtyp jtyp;
8904
8905   List.iter (
8906     function
8907     | name, FString
8908     | name, FUUID
8909     | name, FBuffer -> pr "  public String %s;\n" name
8910     | name, (FBytes|FUInt64|FInt64) -> pr "  public long %s;\n" name
8911     | name, (FUInt32|FInt32) -> pr "  public int %s;\n" name
8912     | name, FChar -> pr "  public char %s;\n" name
8913     | name, FOptPercent ->
8914         pr "  /* The next field is [0..100] or -1 meaning 'not present': */\n";
8915         pr "  public float %s;\n" name
8916   ) cols;
8917
8918   pr "}\n"
8919
8920 and generate_java_c () =
8921   generate_header CStyle LGPLv2;
8922
8923   pr "\
8924 #include <stdio.h>
8925 #include <stdlib.h>
8926 #include <string.h>
8927
8928 #include \"com_redhat_et_libguestfs_GuestFS.h\"
8929 #include \"guestfs.h\"
8930
8931 /* Note that this function returns.  The exception is not thrown
8932  * until after the wrapper function returns.
8933  */
8934 static void
8935 throw_exception (JNIEnv *env, const char *msg)
8936 {
8937   jclass cl;
8938   cl = (*env)->FindClass (env,
8939                           \"com/redhat/et/libguestfs/LibGuestFSException\");
8940   (*env)->ThrowNew (env, cl, msg);
8941 }
8942
8943 JNIEXPORT jlong JNICALL
8944 Java_com_redhat_et_libguestfs_GuestFS__1create
8945   (JNIEnv *env, jobject obj)
8946 {
8947   guestfs_h *g;
8948
8949   g = guestfs_create ();
8950   if (g == NULL) {
8951     throw_exception (env, \"GuestFS.create: failed to allocate handle\");
8952     return 0;
8953   }
8954   guestfs_set_error_handler (g, NULL, NULL);
8955   return (jlong) (long) g;
8956 }
8957
8958 JNIEXPORT void JNICALL
8959 Java_com_redhat_et_libguestfs_GuestFS__1close
8960   (JNIEnv *env, jobject obj, jlong jg)
8961 {
8962   guestfs_h *g = (guestfs_h *) (long) jg;
8963   guestfs_close (g);
8964 }
8965
8966 ";
8967
8968   List.iter (
8969     fun (name, style, _, _, _, _, _) ->
8970       pr "JNIEXPORT ";
8971       (match fst style with
8972        | RErr -> pr "void ";
8973        | RInt _ -> pr "jint ";
8974        | RInt64 _ -> pr "jlong ";
8975        | RBool _ -> pr "jboolean ";
8976        | RConstString _ | RConstOptString _ | RString _
8977        | RBufferOut _ -> pr "jstring ";
8978        | RStruct _ | RHashtable _ ->
8979            pr "jobject ";
8980        | RStringList _ | RStructList _ ->
8981            pr "jobjectArray ";
8982       );
8983       pr "JNICALL\n";
8984       pr "Java_com_redhat_et_libguestfs_GuestFS_";
8985       pr "%s" (replace_str ("_" ^ name) "_" "_1");
8986       pr "\n";
8987       pr "  (JNIEnv *env, jobject obj, jlong jg";
8988       List.iter (
8989         function
8990         | Pathname n
8991         | Device n | Dev_or_Path n
8992         | String n
8993         | OptString n
8994         | FileIn n
8995         | FileOut n ->
8996             pr ", jstring j%s" n
8997         | StringList n | DeviceList n ->
8998             pr ", jobjectArray j%s" n
8999         | Bool n ->
9000             pr ", jboolean j%s" n
9001         | Int n ->
9002             pr ", jint j%s" n
9003         | Int64 n ->
9004             pr ", jlong j%s" n
9005       ) (snd style);
9006       pr ")\n";
9007       pr "{\n";
9008       pr "  guestfs_h *g = (guestfs_h *) (long) jg;\n";
9009       let error_code, no_ret =
9010         match fst style with
9011         | RErr -> pr "  int r;\n"; "-1", ""
9012         | RBool _
9013         | RInt _ -> pr "  int r;\n"; "-1", "0"
9014         | RInt64 _ -> pr "  int64_t r;\n"; "-1", "0"
9015         | RConstString _ -> pr "  const char *r;\n"; "NULL", "NULL"
9016         | RConstOptString _ -> pr "  const char *r;\n"; "NULL", "NULL"
9017         | RString _ ->
9018             pr "  jstring jr;\n";
9019             pr "  char *r;\n"; "NULL", "NULL"
9020         | RStringList _ ->
9021             pr "  jobjectArray jr;\n";
9022             pr "  int r_len;\n";
9023             pr "  jclass cl;\n";
9024             pr "  jstring jstr;\n";
9025             pr "  char **r;\n"; "NULL", "NULL"
9026         | RStruct (_, typ) ->
9027             pr "  jobject jr;\n";
9028             pr "  jclass cl;\n";
9029             pr "  jfieldID fl;\n";
9030             pr "  struct guestfs_%s *r;\n" typ; "NULL", "NULL"
9031         | RStructList (_, typ) ->
9032             pr "  jobjectArray jr;\n";
9033             pr "  jclass cl;\n";
9034             pr "  jfieldID fl;\n";
9035             pr "  jobject jfl;\n";
9036             pr "  struct guestfs_%s_list *r;\n" typ; "NULL", "NULL"
9037         | RHashtable _ -> pr "  char **r;\n"; "NULL", "NULL"
9038         | RBufferOut _ ->
9039             pr "  jstring jr;\n";
9040             pr "  char *r;\n";
9041             pr "  size_t size;\n";
9042             "NULL", "NULL" in
9043       List.iter (
9044         function
9045         | Pathname n
9046         | Device n | Dev_or_Path n
9047         | String n
9048         | OptString n
9049         | FileIn n
9050         | FileOut n ->
9051             pr "  const char *%s;\n" n
9052         | StringList n | DeviceList n ->
9053             pr "  int %s_len;\n" n;
9054             pr "  const char **%s;\n" n
9055         | Bool n
9056         | Int n ->
9057             pr "  int %s;\n" n
9058         | Int64 n ->
9059             pr "  int64_t %s;\n" n
9060       ) (snd style);
9061
9062       let needs_i =
9063         (match fst style with
9064          | RStringList _ | RStructList _ -> true
9065          | RErr | RBool _ | RInt _ | RInt64 _ | RConstString _
9066          | RConstOptString _
9067          | RString _ | RBufferOut _ | RStruct _ | RHashtable _ -> false) ||
9068           List.exists (function
9069                        | StringList _ -> true
9070                        | DeviceList _ -> true
9071                        | _ -> false) (snd style) in
9072       if needs_i then
9073         pr "  int i;\n";
9074
9075       pr "\n";
9076
9077       (* Get the parameters. *)
9078       List.iter (
9079         function
9080         | Pathname n
9081         | Device n | Dev_or_Path n
9082         | String n
9083         | FileIn n
9084         | FileOut n ->
9085             pr "  %s = (*env)->GetStringUTFChars (env, j%s, NULL);\n" n n
9086         | OptString n ->
9087             (* This is completely undocumented, but Java null becomes
9088              * a NULL parameter.
9089              *)
9090             pr "  %s = j%s ? (*env)->GetStringUTFChars (env, j%s, NULL) : NULL;\n" n n n
9091         | StringList n | DeviceList n ->
9092             pr "  %s_len = (*env)->GetArrayLength (env, j%s);\n" n n;
9093             pr "  %s = guestfs_safe_malloc (g, sizeof (char *) * (%s_len+1));\n" n n;
9094             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
9095             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
9096               n;
9097             pr "    %s[i] = (*env)->GetStringUTFChars (env, o, NULL);\n" n;
9098             pr "  }\n";
9099             pr "  %s[%s_len] = NULL;\n" n n;
9100         | Bool n
9101         | Int n
9102         | Int64 n ->
9103             pr "  %s = j%s;\n" n n
9104       ) (snd style);
9105
9106       (* Make the call. *)
9107       pr "  r = guestfs_%s " name;
9108       generate_c_call_args ~handle:"g" style;
9109       pr ";\n";
9110
9111       (* Release the parameters. *)
9112       List.iter (
9113         function
9114         | Pathname n
9115         | Device n | Dev_or_Path n
9116         | String n
9117         | FileIn n
9118         | FileOut n ->
9119             pr "  (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
9120         | OptString n ->
9121             pr "  if (j%s)\n" n;
9122             pr "    (*env)->ReleaseStringUTFChars (env, j%s, %s);\n" n n
9123         | StringList n | DeviceList n ->
9124             pr "  for (i = 0; i < %s_len; ++i) {\n" n;
9125             pr "    jobject o = (*env)->GetObjectArrayElement (env, j%s, i);\n"
9126               n;
9127             pr "    (*env)->ReleaseStringUTFChars (env, o, %s[i]);\n" n;
9128             pr "  }\n";
9129             pr "  free (%s);\n" n
9130         | Bool n
9131         | Int n
9132         | Int64 n -> ()
9133       ) (snd style);
9134
9135       (* Check for errors. *)
9136       pr "  if (r == %s) {\n" error_code;
9137       pr "    throw_exception (env, guestfs_last_error (g));\n";
9138       pr "    return %s;\n" no_ret;
9139       pr "  }\n";
9140
9141       (* Return value. *)
9142       (match fst style with
9143        | RErr -> ()
9144        | RInt _ -> pr "  return (jint) r;\n"
9145        | RBool _ -> pr "  return (jboolean) r;\n"
9146        | RInt64 _ -> pr "  return (jlong) r;\n"
9147        | RConstString _ -> pr "  return (*env)->NewStringUTF (env, r);\n"
9148        | RConstOptString _ ->
9149            pr "  return (*env)->NewStringUTF (env, r); /* XXX r NULL? */\n"
9150        | RString _ ->
9151            pr "  jr = (*env)->NewStringUTF (env, r);\n";
9152            pr "  free (r);\n";
9153            pr "  return jr;\n"
9154        | RStringList _ ->
9155            pr "  for (r_len = 0; r[r_len] != NULL; ++r_len) ;\n";
9156            pr "  cl = (*env)->FindClass (env, \"java/lang/String\");\n";
9157            pr "  jstr = (*env)->NewStringUTF (env, \"\");\n";
9158            pr "  jr = (*env)->NewObjectArray (env, r_len, cl, jstr);\n";
9159            pr "  for (i = 0; i < r_len; ++i) {\n";
9160            pr "    jstr = (*env)->NewStringUTF (env, r[i]);\n";
9161            pr "    (*env)->SetObjectArrayElement (env, jr, i, jstr);\n";
9162            pr "    free (r[i]);\n";
9163            pr "  }\n";
9164            pr "  free (r);\n";
9165            pr "  return jr;\n"
9166        | RStruct (_, typ) ->
9167            let jtyp = java_name_of_struct typ in
9168            let cols = cols_of_struct typ in
9169            generate_java_struct_return typ jtyp cols
9170        | RStructList (_, typ) ->
9171            let jtyp = java_name_of_struct typ in
9172            let cols = cols_of_struct typ in
9173            generate_java_struct_list_return typ jtyp cols
9174        | RHashtable _ ->
9175            (* XXX *)
9176            pr "  throw_exception (env, \"%s: internal error: please let us know how to make a Java HashMap from JNI bindings!\");\n" name;
9177            pr "  return NULL;\n"
9178        | RBufferOut _ ->
9179            pr "  jr = (*env)->NewStringUTF (env, r); /* XXX size */\n";
9180            pr "  free (r);\n";
9181            pr "  return jr;\n"
9182       );
9183
9184       pr "}\n";
9185       pr "\n"
9186   ) all_functions
9187
9188 and generate_java_struct_return typ jtyp cols =
9189   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
9190   pr "  jr = (*env)->AllocObject (env, cl);\n";
9191   List.iter (
9192     function
9193     | name, FString ->
9194         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9195         pr "  (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, r->%s));\n" name;
9196     | name, FUUID ->
9197         pr "  {\n";
9198         pr "    char s[33];\n";
9199         pr "    memcpy (s, r->%s, 32);\n" name;
9200         pr "    s[32] = 0;\n";
9201         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9202         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
9203         pr "  }\n";
9204     | name, FBuffer ->
9205         pr "  {\n";
9206         pr "    int len = r->%s_len;\n" name;
9207         pr "    char s[len+1];\n";
9208         pr "    memcpy (s, r->%s, len);\n" name;
9209         pr "    s[len] = 0;\n";
9210         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9211         pr "    (*env)->SetObjectField (env, jr, fl, (*env)->NewStringUTF (env, s));\n";
9212         pr "  }\n";
9213     | name, (FBytes|FUInt64|FInt64) ->
9214         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
9215         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9216     | name, (FUInt32|FInt32) ->
9217         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
9218         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9219     | name, FOptPercent ->
9220         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
9221         pr "  (*env)->SetFloatField (env, jr, fl, r->%s);\n" name;
9222     | name, FChar ->
9223         pr "  fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
9224         pr "  (*env)->SetLongField (env, jr, fl, r->%s);\n" name;
9225   ) cols;
9226   pr "  free (r);\n";
9227   pr "  return jr;\n"
9228
9229 and generate_java_struct_list_return typ jtyp cols =
9230   pr "  cl = (*env)->FindClass (env, \"com/redhat/et/libguestfs/%s\");\n" jtyp;
9231   pr "  jr = (*env)->NewObjectArray (env, r->len, cl, NULL);\n";
9232   pr "  for (i = 0; i < r->len; ++i) {\n";
9233   pr "    jfl = (*env)->AllocObject (env, cl);\n";
9234   List.iter (
9235     function
9236     | name, FString ->
9237         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9238         pr "    (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, r->val[i].%s));\n" name;
9239     | name, FUUID ->
9240         pr "    {\n";
9241         pr "      char s[33];\n";
9242         pr "      memcpy (s, r->val[i].%s, 32);\n" name;
9243         pr "      s[32] = 0;\n";
9244         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9245         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
9246         pr "    }\n";
9247     | name, FBuffer ->
9248         pr "    {\n";
9249         pr "      int len = r->val[i].%s_len;\n" name;
9250         pr "      char s[len+1];\n";
9251         pr "      memcpy (s, r->val[i].%s, len);\n" name;
9252         pr "      s[len] = 0;\n";
9253         pr "      fl = (*env)->GetFieldID (env, cl, \"%s\", \"Ljava/lang/String;\");\n" name;
9254         pr "      (*env)->SetObjectField (env, jfl, fl, (*env)->NewStringUTF (env, s));\n";
9255         pr "    }\n";
9256     | name, (FBytes|FUInt64|FInt64) ->
9257         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"J\");\n" name;
9258         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9259     | name, (FUInt32|FInt32) ->
9260         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"I\");\n" name;
9261         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9262     | name, FOptPercent ->
9263         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"F\");\n" name;
9264         pr "    (*env)->SetFloatField (env, jfl, fl, r->val[i].%s);\n" name;
9265     | name, FChar ->
9266         pr "    fl = (*env)->GetFieldID (env, cl, \"%s\", \"C\");\n" name;
9267         pr "    (*env)->SetLongField (env, jfl, fl, r->val[i].%s);\n" name;
9268   ) cols;
9269   pr "    (*env)->SetObjectArrayElement (env, jfl, i, jfl);\n";
9270   pr "  }\n";
9271   pr "  guestfs_free_%s_list (r);\n" typ;
9272   pr "  return jr;\n"
9273
9274 and generate_java_makefile_inc () =
9275   generate_header HashStyle GPLv2;
9276
9277   pr "java_built_sources = \\\n";
9278   List.iter (
9279     fun (typ, jtyp) ->
9280         pr "\tcom/redhat/et/libguestfs/%s.java \\\n" jtyp;
9281   ) java_structs;
9282   pr "\tcom/redhat/et/libguestfs/GuestFS.java\n"
9283
9284 and generate_haskell_hs () =
9285   generate_header HaskellStyle LGPLv2;
9286
9287   (* XXX We only know how to generate partial FFI for Haskell
9288    * at the moment.  Please help out!
9289    *)
9290   let can_generate style =
9291     match style with
9292     | RErr, _
9293     | RInt _, _
9294     | RInt64 _, _ -> true
9295     | RBool _, _
9296     | RConstString _, _
9297     | RConstOptString _, _
9298     | RString _, _
9299     | RStringList _, _
9300     | RStruct _, _
9301     | RStructList _, _
9302     | RHashtable _, _
9303     | RBufferOut _, _ -> false in
9304
9305   pr "\
9306 {-# INCLUDE <guestfs.h> #-}
9307 {-# LANGUAGE ForeignFunctionInterface #-}
9308
9309 module Guestfs (
9310   create";
9311
9312   (* List out the names of the actions we want to export. *)
9313   List.iter (
9314     fun (name, style, _, _, _, _, _) ->
9315       if can_generate style then pr ",\n  %s" name
9316   ) all_functions;
9317
9318   pr "
9319   ) where
9320
9321 -- Unfortunately some symbols duplicate ones already present
9322 -- in Prelude.  We don't know which, so we hard-code a list
9323 -- here.
9324 import Prelude hiding (truncate)
9325
9326 import Foreign
9327 import Foreign.C
9328 import Foreign.C.Types
9329 import IO
9330 import Control.Exception
9331 import Data.Typeable
9332
9333 data GuestfsS = GuestfsS            -- represents the opaque C struct
9334 type GuestfsP = Ptr GuestfsS        -- guestfs_h *
9335 type GuestfsH = ForeignPtr GuestfsS -- guestfs_h * with attached finalizer
9336
9337 -- XXX define properly later XXX
9338 data PV = PV
9339 data VG = VG
9340 data LV = LV
9341 data IntBool = IntBool
9342 data Stat = Stat
9343 data StatVFS = StatVFS
9344 data Hashtable = Hashtable
9345
9346 foreign import ccall unsafe \"guestfs_create\" c_create
9347   :: IO GuestfsP
9348 foreign import ccall unsafe \"&guestfs_close\" c_close
9349   :: FunPtr (GuestfsP -> IO ())
9350 foreign import ccall unsafe \"guestfs_set_error_handler\" c_set_error_handler
9351   :: GuestfsP -> Ptr CInt -> Ptr CInt -> IO ()
9352
9353 create :: IO GuestfsH
9354 create = do
9355   p <- c_create
9356   c_set_error_handler p nullPtr nullPtr
9357   h <- newForeignPtr c_close p
9358   return h
9359
9360 foreign import ccall unsafe \"guestfs_last_error\" c_last_error
9361   :: GuestfsP -> IO CString
9362
9363 -- last_error :: GuestfsH -> IO (Maybe String)
9364 -- last_error h = do
9365 --   str <- withForeignPtr h (\\p -> c_last_error p)
9366 --   maybePeek peekCString str
9367
9368 last_error :: GuestfsH -> IO (String)
9369 last_error h = do
9370   str <- withForeignPtr h (\\p -> c_last_error p)
9371   if (str == nullPtr)
9372     then return \"no error\"
9373     else peekCString str
9374
9375 ";
9376
9377   (* Generate wrappers for each foreign function. *)
9378   List.iter (
9379     fun (name, style, _, _, _, _, _) ->
9380       if can_generate style then (
9381         pr "foreign import ccall unsafe \"guestfs_%s\" c_%s\n" name name;
9382         pr "  :: ";
9383         generate_haskell_prototype ~handle:"GuestfsP" style;
9384         pr "\n";
9385         pr "\n";
9386         pr "%s :: " name;
9387         generate_haskell_prototype ~handle:"GuestfsH" ~hs:true style;
9388         pr "\n";
9389         pr "%s %s = do\n" name
9390           (String.concat " " ("h" :: List.map name_of_argt (snd style)));
9391         pr "  r <- ";
9392         (* Convert pointer arguments using with* functions. *)
9393         List.iter (
9394           function
9395           | FileIn n
9396           | FileOut n
9397           | Pathname n | Device n | Dev_or_Path n | String n -> pr "withCString %s $ \\%s -> " n n
9398           | OptString n -> pr "maybeWith withCString %s $ \\%s -> " n n
9399           | StringList n | DeviceList n -> pr "withMany withCString %s $ \\%s -> withArray0 nullPtr %s $ \\%s -> " n n n n
9400           | Bool _ | Int _ | Int64 _ -> ()
9401         ) (snd style);
9402         (* Convert integer arguments. *)
9403         let args =
9404           List.map (
9405             function
9406             | Bool n -> sprintf "(fromBool %s)" n
9407             | Int n -> sprintf "(fromIntegral %s)" n
9408             | Int64 n -> sprintf "(fromIntegral %s)" n
9409             | FileIn n | FileOut n
9410             | Pathname n | Device n | Dev_or_Path n | String n | OptString n | StringList n | DeviceList n -> n
9411           ) (snd style) in
9412         pr "withForeignPtr h (\\p -> c_%s %s)\n" name
9413           (String.concat " " ("p" :: args));
9414         (match fst style with
9415          | RErr | RInt _ | RInt64 _ | RBool _ ->
9416              pr "  if (r == -1)\n";
9417              pr "    then do\n";
9418              pr "      err <- last_error h\n";
9419              pr "      fail err\n";
9420          | RConstString _ | RConstOptString _ | RString _
9421          | RStringList _ | RStruct _
9422          | RStructList _ | RHashtable _ | RBufferOut _ ->
9423              pr "  if (r == nullPtr)\n";
9424              pr "    then do\n";
9425              pr "      err <- last_error h\n";
9426              pr "      fail err\n";
9427         );
9428         (match fst style with
9429          | RErr ->
9430              pr "    else return ()\n"
9431          | RInt _ ->
9432              pr "    else return (fromIntegral r)\n"
9433          | RInt64 _ ->
9434              pr "    else return (fromIntegral r)\n"
9435          | RBool _ ->
9436              pr "    else return (toBool r)\n"
9437          | RConstString _
9438          | RConstOptString _
9439          | RString _
9440          | RStringList _
9441          | RStruct _
9442          | RStructList _
9443          | RHashtable _
9444          | RBufferOut _ ->
9445              pr "    else return ()\n" (* XXXXXXXXXXXXXXXXXXXX *)
9446         );
9447         pr "\n";
9448       )
9449   ) all_functions
9450
9451 and generate_haskell_prototype ~handle ?(hs = false) style =
9452   pr "%s -> " handle;
9453   let string = if hs then "String" else "CString" in
9454   let int = if hs then "Int" else "CInt" in
9455   let bool = if hs then "Bool" else "CInt" in
9456   let int64 = if hs then "Integer" else "Int64" in
9457   List.iter (
9458     fun arg ->
9459       (match arg with
9460        | Pathname _ | Device _ | Dev_or_Path _ | String _ -> pr "%s" string
9461        | OptString _ -> if hs then pr "Maybe String" else pr "CString"
9462        | StringList _ | DeviceList _ -> if hs then pr "[String]" else pr "Ptr CString"
9463        | Bool _ -> pr "%s" bool
9464        | Int _ -> pr "%s" int
9465        | Int64 _ -> pr "%s" int
9466        | FileIn _ -> pr "%s" string
9467        | FileOut _ -> pr "%s" string
9468       );
9469       pr " -> ";
9470   ) (snd style);
9471   pr "IO (";
9472   (match fst style with
9473    | RErr -> if not hs then pr "CInt"
9474    | RInt _ -> pr "%s" int
9475    | RInt64 _ -> pr "%s" int64
9476    | RBool _ -> pr "%s" bool
9477    | RConstString _ -> pr "%s" string
9478    | RConstOptString _ -> pr "Maybe %s" string
9479    | RString _ -> pr "%s" string
9480    | RStringList _ -> pr "[%s]" string
9481    | RStruct (_, typ) ->
9482        let name = java_name_of_struct typ in
9483        pr "%s" name
9484    | RStructList (_, typ) ->
9485        let name = java_name_of_struct typ in
9486        pr "[%s]" name
9487    | RHashtable _ -> pr "Hashtable"
9488    | RBufferOut _ -> pr "%s" string
9489   );
9490   pr ")"
9491
9492 and generate_bindtests () =
9493   generate_header CStyle LGPLv2;
9494
9495   pr "\
9496 #include <stdio.h>
9497 #include <stdlib.h>
9498 #include <inttypes.h>
9499 #include <string.h>
9500
9501 #include \"guestfs.h\"
9502 #include \"guestfs-internal-actions.h\"
9503 #include \"guestfs_protocol.h\"
9504
9505 #define error guestfs_error
9506 #define safe_calloc guestfs_safe_calloc
9507 #define safe_malloc guestfs_safe_malloc
9508
9509 static void
9510 print_strings (char *const *argv)
9511 {
9512   int argc;
9513
9514   printf (\"[\");
9515   for (argc = 0; argv[argc] != NULL; ++argc) {
9516     if (argc > 0) printf (\", \");
9517     printf (\"\\\"%%s\\\"\", argv[argc]);
9518   }
9519   printf (\"]\\n\");
9520 }
9521
9522 /* The test0 function prints its parameters to stdout. */
9523 ";
9524
9525   let test0, tests =
9526     match test_functions with
9527     | [] -> assert false
9528     | test0 :: tests -> test0, tests in
9529
9530   let () =
9531     let (name, style, _, _, _, _, _) = test0 in
9532     generate_prototype ~extern:false ~semicolon:false ~newline:true
9533       ~handle:"g" ~prefix:"guestfs__" name style;
9534     pr "{\n";
9535     List.iter (
9536       function
9537       | Pathname n
9538       | Device n | Dev_or_Path n
9539       | String n
9540       | FileIn n
9541       | FileOut n -> pr "  printf (\"%%s\\n\", %s);\n" n
9542       | OptString n -> pr "  printf (\"%%s\\n\", %s ? %s : \"null\");\n" n n
9543       | StringList n | DeviceList n -> pr "  print_strings (%s);\n" n
9544       | Bool n -> pr "  printf (\"%%s\\n\", %s ? \"true\" : \"false\");\n" n
9545       | Int n -> pr "  printf (\"%%d\\n\", %s);\n" n
9546       | Int64 n -> pr "  printf (\"%%\" PRIi64 \"\\n\", %s);\n" n
9547     ) (snd style);
9548     pr "  /* Java changes stdout line buffering so we need this: */\n";
9549     pr "  fflush (stdout);\n";
9550     pr "  return 0;\n";
9551     pr "}\n";
9552     pr "\n" in
9553
9554   List.iter (
9555     fun (name, style, _, _, _, _, _) ->
9556       if String.sub name (String.length name - 3) 3 <> "err" then (
9557         pr "/* Test normal return. */\n";
9558         generate_prototype ~extern:false ~semicolon:false ~newline:true
9559           ~handle:"g" ~prefix:"guestfs__" name style;
9560         pr "{\n";
9561         (match fst style with
9562          | RErr ->
9563              pr "  return 0;\n"
9564          | RInt _ ->
9565              pr "  int r;\n";
9566              pr "  sscanf (val, \"%%d\", &r);\n";
9567              pr "  return r;\n"
9568          | RInt64 _ ->
9569              pr "  int64_t r;\n";
9570              pr "  sscanf (val, \"%%\" SCNi64, &r);\n";
9571              pr "  return r;\n"
9572          | RBool _ ->
9573              pr "  return STREQ (val, \"true\");\n"
9574          | RConstString _
9575          | RConstOptString _ ->
9576              (* Can't return the input string here.  Return a static
9577               * string so we ensure we get a segfault if the caller
9578               * tries to free it.
9579               *)
9580              pr "  return \"static string\";\n"
9581          | RString _ ->
9582              pr "  return strdup (val);\n"
9583          | RStringList _ ->
9584              pr "  char **strs;\n";
9585              pr "  int n, i;\n";
9586              pr "  sscanf (val, \"%%d\", &n);\n";
9587              pr "  strs = safe_malloc (g, (n+1) * sizeof (char *));\n";
9588              pr "  for (i = 0; i < n; ++i) {\n";
9589              pr "    strs[i] = safe_malloc (g, 16);\n";
9590              pr "    snprintf (strs[i], 16, \"%%d\", i);\n";
9591              pr "  }\n";
9592              pr "  strs[n] = NULL;\n";
9593              pr "  return strs;\n"
9594          | RStruct (_, typ) ->
9595              pr "  struct guestfs_%s *r;\n" typ;
9596              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
9597              pr "  return r;\n"
9598          | RStructList (_, typ) ->
9599              pr "  struct guestfs_%s_list *r;\n" typ;
9600              pr "  r = safe_calloc (g, sizeof *r, 1);\n";
9601              pr "  sscanf (val, \"%%d\", &r->len);\n";
9602              pr "  r->val = safe_calloc (g, r->len, sizeof *r->val);\n";
9603              pr "  return r;\n"
9604          | RHashtable _ ->
9605              pr "  char **strs;\n";
9606              pr "  int n, i;\n";
9607              pr "  sscanf (val, \"%%d\", &n);\n";
9608              pr "  strs = safe_malloc (g, (n*2+1) * sizeof (*strs));\n";
9609              pr "  for (i = 0; i < n; ++i) {\n";
9610              pr "    strs[i*2] = safe_malloc (g, 16);\n";
9611              pr "    strs[i*2+1] = safe_malloc (g, 16);\n";
9612              pr "    snprintf (strs[i*2], 16, \"%%d\", i);\n";
9613              pr "    snprintf (strs[i*2+1], 16, \"%%d\", i);\n";
9614              pr "  }\n";
9615              pr "  strs[n*2] = NULL;\n";
9616              pr "  return strs;\n"
9617          | RBufferOut _ ->
9618              pr "  return strdup (val);\n"
9619         );
9620         pr "}\n";
9621         pr "\n"
9622       ) else (
9623         pr "/* Test error return. */\n";
9624         generate_prototype ~extern:false ~semicolon:false ~newline:true
9625           ~handle:"g" ~prefix:"guestfs__" name style;
9626         pr "{\n";
9627         pr "  error (g, \"error\");\n";
9628         (match fst style with
9629          | RErr | RInt _ | RInt64 _ | RBool _ ->
9630              pr "  return -1;\n"
9631          | RConstString _ | RConstOptString _
9632          | RString _ | RStringList _ | RStruct _
9633          | RStructList _
9634          | RHashtable _
9635          | RBufferOut _ ->
9636              pr "  return NULL;\n"
9637         );
9638         pr "}\n";
9639         pr "\n"
9640       )
9641   ) tests
9642
9643 and generate_ocaml_bindtests () =
9644   generate_header OCamlStyle GPLv2;
9645
9646   pr "\
9647 let () =
9648   let g = Guestfs.create () in
9649 ";
9650
9651   let mkargs args =
9652     String.concat " " (
9653       List.map (
9654         function
9655         | CallString s -> "\"" ^ s ^ "\""
9656         | CallOptString None -> "None"
9657         | CallOptString (Some s) -> sprintf "(Some \"%s\")" s
9658         | CallStringList xs ->
9659             "[|" ^ String.concat ";" (List.map (sprintf "\"%s\"") xs) ^ "|]"
9660         | CallInt i when i >= 0 -> string_of_int i
9661         | CallInt i (* when i < 0 *) -> "(" ^ string_of_int i ^ ")"
9662         | CallInt64 i when i >= 0L -> Int64.to_string i ^ "L"
9663         | CallInt64 i (* when i < 0L *) -> "(" ^ Int64.to_string i ^ "L)"
9664         | CallBool b -> string_of_bool b
9665       ) args
9666     )
9667   in
9668
9669   generate_lang_bindtests (
9670     fun f args -> pr "  Guestfs.%s g %s;\n" f (mkargs args)
9671   );
9672
9673   pr "print_endline \"EOF\"\n"
9674
9675 and generate_perl_bindtests () =
9676   pr "#!/usr/bin/perl -w\n";
9677   generate_header HashStyle GPLv2;
9678
9679   pr "\
9680 use strict;
9681
9682 use Sys::Guestfs;
9683
9684 my $g = Sys::Guestfs->new ();
9685 ";
9686
9687   let mkargs args =
9688     String.concat ", " (
9689       List.map (
9690         function
9691         | CallString s -> "\"" ^ s ^ "\""
9692         | CallOptString None -> "undef"
9693         | CallOptString (Some s) -> sprintf "\"%s\"" s
9694         | CallStringList xs ->
9695             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
9696         | CallInt i -> string_of_int i
9697         | CallInt64 i -> Int64.to_string i
9698         | CallBool b -> if b then "1" else "0"
9699       ) args
9700     )
9701   in
9702
9703   generate_lang_bindtests (
9704     fun f args -> pr "$g->%s (%s);\n" f (mkargs args)
9705   );
9706
9707   pr "print \"EOF\\n\"\n"
9708
9709 and generate_python_bindtests () =
9710   generate_header HashStyle GPLv2;
9711
9712   pr "\
9713 import guestfs
9714
9715 g = guestfs.GuestFS ()
9716 ";
9717
9718   let mkargs args =
9719     String.concat ", " (
9720       List.map (
9721         function
9722         | CallString s -> "\"" ^ s ^ "\""
9723         | CallOptString None -> "None"
9724         | CallOptString (Some s) -> sprintf "\"%s\"" s
9725         | CallStringList xs ->
9726             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
9727         | CallInt i -> string_of_int i
9728         | CallInt64 i -> Int64.to_string i
9729         | CallBool b -> if b then "1" else "0"
9730       ) args
9731     )
9732   in
9733
9734   generate_lang_bindtests (
9735     fun f args -> pr "g.%s (%s)\n" f (mkargs args)
9736   );
9737
9738   pr "print \"EOF\"\n"
9739
9740 and generate_ruby_bindtests () =
9741   generate_header HashStyle GPLv2;
9742
9743   pr "\
9744 require 'guestfs'
9745
9746 g = Guestfs::create()
9747 ";
9748
9749   let mkargs args =
9750     String.concat ", " (
9751       List.map (
9752         function
9753         | CallString s -> "\"" ^ s ^ "\""
9754         | CallOptString None -> "nil"
9755         | CallOptString (Some s) -> sprintf "\"%s\"" s
9756         | CallStringList xs ->
9757             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
9758         | CallInt i -> string_of_int i
9759         | CallInt64 i -> Int64.to_string i
9760         | CallBool b -> string_of_bool b
9761       ) args
9762     )
9763   in
9764
9765   generate_lang_bindtests (
9766     fun f args -> pr "g.%s(%s)\n" f (mkargs args)
9767   );
9768
9769   pr "print \"EOF\\n\"\n"
9770
9771 and generate_java_bindtests () =
9772   generate_header CStyle GPLv2;
9773
9774   pr "\
9775 import com.redhat.et.libguestfs.*;
9776
9777 public class Bindtests {
9778     public static void main (String[] argv)
9779     {
9780         try {
9781             GuestFS g = new GuestFS ();
9782 ";
9783
9784   let mkargs args =
9785     String.concat ", " (
9786       List.map (
9787         function
9788         | CallString s -> "\"" ^ s ^ "\""
9789         | CallOptString None -> "null"
9790         | CallOptString (Some s) -> sprintf "\"%s\"" s
9791         | CallStringList xs ->
9792             "new String[]{" ^
9793               String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "}"
9794         | CallInt i -> string_of_int i
9795         | CallInt64 i -> Int64.to_string i
9796         | CallBool b -> string_of_bool b
9797       ) args
9798     )
9799   in
9800
9801   generate_lang_bindtests (
9802     fun f args -> pr "            g.%s (%s);\n" f (mkargs args)
9803   );
9804
9805   pr "
9806             System.out.println (\"EOF\");
9807         }
9808         catch (Exception exn) {
9809             System.err.println (exn);
9810             System.exit (1);
9811         }
9812     }
9813 }
9814 "
9815
9816 and generate_haskell_bindtests () =
9817   generate_header HaskellStyle GPLv2;
9818
9819   pr "\
9820 module Bindtests where
9821 import qualified Guestfs
9822
9823 main = do
9824   g <- Guestfs.create
9825 ";
9826
9827   let mkargs args =
9828     String.concat " " (
9829       List.map (
9830         function
9831         | CallString s -> "\"" ^ s ^ "\""
9832         | CallOptString None -> "Nothing"
9833         | CallOptString (Some s) -> sprintf "(Just \"%s\")" s
9834         | CallStringList xs ->
9835             "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]"
9836         | CallInt i when i < 0 -> "(" ^ string_of_int i ^ ")"
9837         | CallInt i -> string_of_int i
9838         | CallInt64 i when i < 0L -> "(" ^ Int64.to_string i ^ ")"
9839         | CallInt64 i -> Int64.to_string i
9840         | CallBool true -> "True"
9841         | CallBool false -> "False"
9842       ) args
9843     )
9844   in
9845
9846   generate_lang_bindtests (
9847     fun f args -> pr "  Guestfs.%s g %s\n" f (mkargs args)
9848   );
9849
9850   pr "  putStrLn \"EOF\"\n"
9851
9852 (* Language-independent bindings tests - we do it this way to
9853  * ensure there is parity in testing bindings across all languages.
9854  *)
9855 and generate_lang_bindtests call =
9856   call "test0" [CallString "abc"; CallOptString (Some "def");
9857                 CallStringList []; CallBool false;
9858                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9859   call "test0" [CallString "abc"; CallOptString None;
9860                 CallStringList []; CallBool false;
9861                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9862   call "test0" [CallString ""; CallOptString (Some "def");
9863                 CallStringList []; CallBool false;
9864                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9865   call "test0" [CallString ""; CallOptString (Some "");
9866                 CallStringList []; CallBool false;
9867                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9868   call "test0" [CallString "abc"; CallOptString (Some "def");
9869                 CallStringList ["1"]; CallBool false;
9870                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9871   call "test0" [CallString "abc"; CallOptString (Some "def");
9872                 CallStringList ["1"; "2"]; CallBool false;
9873                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9874   call "test0" [CallString "abc"; CallOptString (Some "def");
9875                 CallStringList ["1"]; CallBool true;
9876                 CallInt 0; CallInt64 0L; CallString "123"; CallString "456"];
9877   call "test0" [CallString "abc"; CallOptString (Some "def");
9878                 CallStringList ["1"]; CallBool false;
9879                 CallInt (-1); CallInt64 (-1L); CallString "123"; CallString "456"];
9880   call "test0" [CallString "abc"; CallOptString (Some "def");
9881                 CallStringList ["1"]; CallBool false;
9882                 CallInt (-2); CallInt64 (-2L); CallString "123"; CallString "456"];
9883   call "test0" [CallString "abc"; CallOptString (Some "def");
9884                 CallStringList ["1"]; CallBool false;
9885                 CallInt 1; CallInt64 1L; CallString "123"; CallString "456"];
9886   call "test0" [CallString "abc"; CallOptString (Some "def");
9887                 CallStringList ["1"]; CallBool false;
9888                 CallInt 2; CallInt64 2L; CallString "123"; CallString "456"];
9889   call "test0" [CallString "abc"; CallOptString (Some "def");
9890                 CallStringList ["1"]; CallBool false;
9891                 CallInt 4095; CallInt64 4095L; CallString "123"; CallString "456"];
9892   call "test0" [CallString "abc"; CallOptString (Some "def");
9893                 CallStringList ["1"]; CallBool false;
9894                 CallInt 0; CallInt64 0L; CallString ""; CallString ""]
9895
9896 (* XXX Add here tests of the return and error functions. *)
9897
9898 (* This is used to generate the src/MAX_PROC_NR file which
9899  * contains the maximum procedure number, a surrogate for the
9900  * ABI version number.  See src/Makefile.am for the details.
9901  *)
9902 and generate_max_proc_nr () =
9903   let proc_nrs = List.map (
9904     fun (_, _, proc_nr, _, _, _, _) -> proc_nr
9905   ) daemon_functions in
9906
9907   let max_proc_nr = List.fold_left max 0 proc_nrs in
9908
9909   pr "%d\n" max_proc_nr
9910
9911 let output_to filename =
9912   let filename_new = filename ^ ".new" in
9913   chan := open_out filename_new;
9914   let close () =
9915     close_out !chan;
9916     chan := stdout;
9917
9918     (* Is the new file different from the current file? *)
9919     if Sys.file_exists filename && files_equal filename filename_new then
9920       Unix.unlink filename_new          (* same, so skip it *)
9921     else (
9922       (* different, overwrite old one *)
9923       (try Unix.chmod filename 0o644 with Unix.Unix_error _ -> ());
9924       Unix.rename filename_new filename;
9925       Unix.chmod filename 0o444;
9926       printf "written %s\n%!" filename;
9927     )
9928   in
9929   close
9930
9931 (* Main program. *)
9932 let () =
9933   check_functions ();
9934
9935   if not (Sys.file_exists "HACKING") then (
9936     eprintf "\
9937 You are probably running this from the wrong directory.
9938 Run it from the top source directory using the command
9939   src/generator.ml
9940 ";
9941     exit 1
9942   );
9943
9944   let close = output_to "src/guestfs_protocol.x" in
9945   generate_xdr ();
9946   close ();
9947
9948   let close = output_to "src/guestfs-structs.h" in
9949   generate_structs_h ();
9950   close ();
9951
9952   let close = output_to "src/guestfs-actions.h" in
9953   generate_actions_h ();
9954   close ();
9955
9956   let close = output_to "src/guestfs-internal-actions.h" in
9957   generate_internal_actions_h ();
9958   close ();
9959
9960   let close = output_to "src/guestfs-actions.c" in
9961   generate_client_actions ();
9962   close ();
9963
9964   let close = output_to "daemon/actions.h" in
9965   generate_daemon_actions_h ();
9966   close ();
9967
9968   let close = output_to "daemon/stubs.c" in
9969   generate_daemon_actions ();
9970   close ();
9971
9972   let close = output_to "daemon/names.c" in
9973   generate_daemon_names ();
9974   close ();
9975
9976   let close = output_to "capitests/tests.c" in
9977   generate_tests ();
9978   close ();
9979
9980   let close = output_to "src/guestfs-bindtests.c" in
9981   generate_bindtests ();
9982   close ();
9983
9984   let close = output_to "fish/cmds.c" in
9985   generate_fish_cmds ();
9986   close ();
9987
9988   let close = output_to "fish/completion.c" in
9989   generate_fish_completion ();
9990   close ();
9991
9992   let close = output_to "guestfs-structs.pod" in
9993   generate_structs_pod ();
9994   close ();
9995
9996   let close = output_to "guestfs-actions.pod" in
9997   generate_actions_pod ();
9998   close ();
9999
10000   let close = output_to "guestfish-actions.pod" in
10001   generate_fish_actions_pod ();
10002   close ();
10003
10004   let close = output_to "ocaml/guestfs.mli" in
10005   generate_ocaml_mli ();
10006   close ();
10007
10008   let close = output_to "ocaml/guestfs.ml" in
10009   generate_ocaml_ml ();
10010   close ();
10011
10012   let close = output_to "ocaml/guestfs_c_actions.c" in
10013   generate_ocaml_c ();
10014   close ();
10015
10016   let close = output_to "ocaml/bindtests.ml" in
10017   generate_ocaml_bindtests ();
10018   close ();
10019
10020   let close = output_to "perl/Guestfs.xs" in
10021   generate_perl_xs ();
10022   close ();
10023
10024   let close = output_to "perl/lib/Sys/Guestfs.pm" in
10025   generate_perl_pm ();
10026   close ();
10027
10028   let close = output_to "perl/bindtests.pl" in
10029   generate_perl_bindtests ();
10030   close ();
10031
10032   let close = output_to "python/guestfs-py.c" in
10033   generate_python_c ();
10034   close ();
10035
10036   let close = output_to "python/guestfs.py" in
10037   generate_python_py ();
10038   close ();
10039
10040   let close = output_to "python/bindtests.py" in
10041   generate_python_bindtests ();
10042   close ();
10043
10044   let close = output_to "ruby/ext/guestfs/_guestfs.c" in
10045   generate_ruby_c ();
10046   close ();
10047
10048   let close = output_to "ruby/bindtests.rb" in
10049   generate_ruby_bindtests ();
10050   close ();
10051
10052   let close = output_to "java/com/redhat/et/libguestfs/GuestFS.java" in
10053   generate_java_java ();
10054   close ();
10055
10056   List.iter (
10057     fun (typ, jtyp) ->
10058       let cols = cols_of_struct typ in
10059       let filename = sprintf "java/com/redhat/et/libguestfs/%s.java" jtyp in
10060       let close = output_to filename in
10061       generate_java_struct jtyp cols;
10062       close ();
10063   ) java_structs;
10064
10065   let close = output_to "java/Makefile.inc" in
10066   generate_java_makefile_inc ();
10067   close ();
10068
10069   let close = output_to "java/com_redhat_et_libguestfs_GuestFS.c" in
10070   generate_java_c ();
10071   close ();
10072
10073   let close = output_to "java/Bindtests.java" in
10074   generate_java_bindtests ();
10075   close ();
10076
10077   let close = output_to "haskell/Guestfs.hs" in
10078   generate_haskell_hs ();
10079   close ();
10080
10081   let close = output_to "haskell/Bindtests.hs" in
10082   generate_haskell_bindtests ();
10083   close ();
10084
10085   let close = output_to "src/MAX_PROC_NR" in
10086   generate_max_proc_nr ();
10087   close ();
10088
10089   (* Always generate this file last, and unconditionally.  It's used
10090    * by the Makefile to know when we must re-run the generator.
10091    *)
10092   let chan = open_out "src/stamp-generator" in
10093   fprintf chan "1\n";
10094   close_out chan