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