generator: Fix functions with both RBufferOut and optional args.
[libguestfs.git] / generator / generator_c.ml
1 (* libguestfs
2  * Copyright (C) 2009-2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 (* Please read generator/README first. *)
20
21 open Printf
22
23 open Generator_types
24 open Generator_utils
25 open Generator_pr
26 open Generator_docstrings
27 open Generator_api_versions
28 open Generator_optgroups
29 open Generator_actions
30 open Generator_structs
31 open Generator_events
32
33 (* Generate C API. *)
34
35 type optarg_proto = Dots | VA | Argv
36
37 (* Generate a C function prototype. *)
38 let rec generate_prototype ?(extern = true) ?(static = false)
39     ?(semicolon = true)
40     ?(single_line = false) ?(indent = "") ?(newline = false)
41     ?(in_daemon = false)
42     ?(prefix = "") ?(suffix = "")
43     ?handle
44     ?(optarg_proto = Dots)
45     name (ret, args, optargs) =
46   pr "%s" indent;
47   if extern then pr "extern ";
48   if static then pr "static ";
49   (match ret with
50    | RErr
51    | RInt _
52    | RBool _ ->
53        pr "int";
54        if single_line then pr " " else pr "\n%s" indent
55    | RInt64 _ ->
56        pr "int64_t";
57        if single_line then pr " " else pr "\n%s" indent
58    | RConstString _ | RConstOptString _ ->
59        pr "const char *";
60        if not single_line then pr "\n%s" indent
61    | RString _ | RBufferOut _ ->
62        pr "char *";
63        if not single_line then pr "\n%s" indent
64    | RStringList _ | RHashtable _ ->
65        pr "char **";
66        if not single_line then pr "\n%s" indent
67    | RStruct (_, typ) ->
68        if not in_daemon then pr "struct guestfs_%s *" typ
69        else pr "guestfs_int_%s *" typ;
70        if not single_line then pr "\n%s" indent
71    | RStructList (_, typ) ->
72        if not in_daemon then pr "struct guestfs_%s_list *" typ
73        else pr "guestfs_int_%s_list *" typ;
74        if not single_line then pr "\n%s" indent
75   );
76   let is_RBufferOut = match ret with RBufferOut _ -> true | _ -> false in
77   pr "%s%s%s (" prefix name suffix;
78   if handle = None && args = [] && optargs = [] && not is_RBufferOut then
79       pr "void"
80   else (
81     let comma = ref false in
82     (match handle with
83      | None -> ()
84      | Some handle -> pr "guestfs_h *%s" handle; comma := true
85     );
86     let next () =
87       if !comma then (
88         if single_line then pr ", "
89         else (
90           let namelen = String.length prefix + String.length name +
91                         String.length suffix + 2 in
92           pr ",\n%s%s" indent (spaces namelen)
93         )
94       );
95       comma := true
96     in
97     List.iter (
98       function
99       | Pathname n
100       | Device n | Dev_or_Path n
101       | String n
102       | OptString n
103       | Key n ->
104           next ();
105           pr "const char *%s" n
106       | StringList n | DeviceList n ->
107           next ();
108           pr "char *const *%s" n
109       | Bool n -> next (); pr "int %s" n
110       | Int n -> next (); pr "int %s" n
111       | Int64 n -> next (); pr "int64_t %s" n
112       | FileIn n
113       | FileOut n ->
114           if not in_daemon then (next (); pr "const char *%s" n)
115       | BufferIn n ->
116           next ();
117           pr "const char *%s" n;
118           next ();
119           pr "size_t %s_size" n
120       | Pointer (t, n) ->
121           next ();
122           pr "%s %s" t n
123     ) args;
124     if is_RBufferOut then (next (); pr "size_t *size_r");
125     if optargs <> [] then (
126       next ();
127       match optarg_proto with
128       | Dots -> pr "..."
129       | VA -> pr "va_list args"
130       | Argv -> pr "const struct guestfs_%s_argv *optargs" name
131     );
132   );
133   pr ")";
134   if semicolon then pr ";";
135   if newline then pr "\n"
136
137 (* Generate C call arguments, eg "(handle, foo, bar)" *)
138 and generate_c_call_args ?handle ?(implicit_size_ptr = "&size")
139     (ret, args, optargs) =
140   pr "(";
141   let comma = ref false in
142   let next () =
143     if !comma then pr ", ";
144     comma := true
145   in
146   (match handle with
147    | None -> ()
148    | Some handle -> pr "%s" handle; comma := true
149   );
150   List.iter (
151     function
152     | BufferIn n ->
153         next ();
154         pr "%s, %s_size" n n
155     | arg ->
156         next ();
157         pr "%s" (name_of_argt arg)
158   ) args;
159   (* For RBufferOut calls, add implicit size pointer parameter. *)
160   (match ret with
161    | RBufferOut _ ->
162        next ();
163        pr "%s" implicit_size_ptr
164    | _ -> ()
165   );
166   (* For calls with optional arguments, add implicit optargs parameter. *)
167   if optargs <> [] then (
168     next ();
169     pr "optargs"
170   );
171   pr ")"
172
173 (* Generate the pod documentation for the C API. *)
174 and generate_actions_pod () =
175   List.iter (
176     fun (shortname, (ret, args, optargs as style), _, flags, _, _, longdesc) ->
177       if not (List.mem NotInDocs flags) then (
178         let name = "guestfs_" ^ shortname in
179         pr "=head2 %s\n\n" name;
180         generate_prototype ~extern:false ~indent:" " ~handle:"g" name style;
181         pr "\n\n";
182
183         let uc_shortname = String.uppercase shortname in
184         if optargs <> [] then (
185           pr "You may supply a list of optional arguments to this call.\n";
186           pr "Use zero or more of the following pairs of parameters,\n";
187           pr "and terminate the list with C<-1> on its own.\n";
188           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
189           List.iter (
190             fun argt ->
191               let n = name_of_argt argt in
192               let uc_n = String.uppercase n in
193               pr " GUESTFS_%s_%s, " uc_shortname uc_n;
194               match argt with
195               | Bool n -> pr "int %s,\n" n
196               | Int n -> pr "int %s,\n" n
197               | Int64 n -> pr "int64_t %s,\n" n
198               | String n -> pr "const char *%s,\n" n
199               | _ -> assert false
200           ) optargs;
201           pr "\n";
202         );
203
204         pr "%s\n\n" longdesc;
205         let ret, args, optargs = style in
206         (match ret with
207          | RErr ->
208              pr "This function returns 0 on success or -1 on error.\n\n"
209          | RInt _ ->
210              pr "On error this function returns -1.\n\n"
211          | RInt64 _ ->
212              pr "On error this function returns -1.\n\n"
213          | RBool _ ->
214              pr "This function returns a C truth value on success or -1 on error.\n\n"
215          | RConstString _ ->
216              pr "This function returns a string, or NULL on error.
217 The string is owned by the guest handle and must I<not> be freed.\n\n"
218          | RConstOptString _ ->
219              pr "This function returns a string which may be NULL.
220 There is no way to return an error from this function.
221 The string is owned by the guest handle and must I<not> be freed.\n\n"
222          | RString _ ->
223              pr "This function returns a string, or NULL on error.
224 I<The caller must free the returned string after use>.\n\n"
225          | RStringList _ ->
226              pr "This function returns a NULL-terminated array of strings
227 (like L<environ(3)>), or NULL if there was an error.
228 I<The caller must free the strings and the array after use>.\n\n"
229          | RStruct (_, typ) ->
230              pr "This function returns a C<struct guestfs_%s *>,
231 or NULL if there was an error.
232 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
233          | RStructList (_, typ) ->
234              pr "This function returns a C<struct guestfs_%s_list *>,
235 or NULL if there was an error.
236 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
237          | RHashtable _ ->
238              pr "This function returns a NULL-terminated array of
239 strings, or NULL if there was an error.
240 The array of strings will always have length C<2n+1>, where
241 C<n> keys and values alternate, followed by the trailing NULL entry.
242 I<The caller must free the strings and the array after use>.\n\n"
243          | RBufferOut _ ->
244              pr "This function returns a buffer, or NULL on error.
245 The size of the returned buffer is written to C<*size_r>.
246 I<The caller must free the returned buffer after use>.\n\n"
247         );
248         if List.mem Progress flags then
249           pr "%s\n\n" progress_message;
250         if List.mem ProtocolLimitWarning flags then
251           pr "%s\n\n" protocol_limit_warning;
252         if List.mem DangerWillRobinson flags then
253           pr "%s\n\n" danger_will_robinson;
254         if List.exists (function Key _ -> true | _ -> false) (args@optargs) then
255           pr "This function takes a key or passphrase parameter which
256 could contain sensitive material.  Read the section
257 L</KEYS AND PASSPHRASES> for more information.\n\n";
258         (match deprecation_notice flags with
259          | None -> ()
260          | Some txt -> pr "%s\n\n" txt
261         );
262         (match lookup_api_version name with
263          | Some version -> pr "(Added in %s)\n\n" version
264          | None -> ()
265         );
266
267         (* Handling of optional argument variants. *)
268         if optargs <> [] then (
269           pr "=head2 %s_va\n\n" name;
270           generate_prototype ~extern:false ~indent:" " ~handle:"g"
271             ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
272             shortname style;
273           pr "\n\n";
274           pr "This is the \"va_list variant\" of L</%s>.\n\n" name;
275           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
276           pr "=head2 %s_argv\n\n" name;
277           generate_prototype ~extern:false ~indent:" " ~handle:"g"
278             ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
279             shortname style;
280           pr "\n\n";
281           pr "This is the \"argv variant\" of L</%s>.\n\n" name;
282           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
283         );
284       )
285   ) all_functions_sorted
286
287 and generate_structs_pod () =
288   (* Structs documentation. *)
289   List.iter (
290     fun (typ, cols) ->
291       pr "=head2 guestfs_%s\n" typ;
292       pr "\n";
293       pr " struct guestfs_%s {\n" typ;
294       List.iter (
295         function
296         | name, FChar -> pr "   char %s;\n" name
297         | name, FUInt32 -> pr "   uint32_t %s;\n" name
298         | name, FInt32 -> pr "   int32_t %s;\n" name
299         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
300         | name, FInt64 -> pr "   int64_t %s;\n" name
301         | name, FString -> pr "   char *%s;\n" name
302         | name, FBuffer ->
303             pr "   /* The next two fields describe a byte array. */\n";
304             pr "   uint32_t %s_len;\n" name;
305             pr "   char *%s;\n" name
306         | name, FUUID ->
307             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
308             pr "   char %s[32];\n" name
309         | name, FOptPercent ->
310             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
311             pr "   float %s;\n" name
312       ) cols;
313       pr " };\n";
314       pr " \n";
315       pr " struct guestfs_%s_list {\n" typ;
316       pr "   uint32_t len; /* Number of elements in list. */\n";
317       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
318       pr " };\n";
319       pr " \n";
320       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
321       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
322         typ typ;
323       pr "\n"
324   ) structs
325
326 and generate_availability_pod () =
327   (* Availability documentation. *)
328   pr "=over 4\n";
329   pr "\n";
330   List.iter (
331     fun (group, functions) ->
332       pr "=item B<%s>\n" group;
333       pr "\n";
334       pr "The following functions:\n";
335       List.iter (pr "L</guestfs_%s>\n") functions;
336       pr "\n"
337   ) optgroups;
338   pr "=back\n";
339   pr "\n"
340
341 (* Generate the guestfs.h file. *)
342 and generate_guestfs_h () =
343   generate_header CStyle LGPLv2plus;
344
345   pr "\
346 /* ---------- IMPORTANT NOTE ----------
347  *
348  * All API documentation is in the manpage, 'guestfs(3)'.
349  * To read it, type:           man 3 guestfs
350  * Or read it online here:     http://libguestfs.org/guestfs.3.html
351  *
352  * Go and read it now, I'll be right here waiting for you
353  * when you come back.
354  *
355  * ------------------------------------
356  */
357
358 #ifndef GUESTFS_H_
359 #define GUESTFS_H_
360
361 #ifdef __cplusplus
362 extern \"C\" {
363 #endif
364
365 #include <stddef.h>
366 #include <stdint.h>
367 #include <stdarg.h>
368
369 #ifdef __GNUC__
370 # define GUESTFS_GCC_VERSION \\
371     (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
372 #endif
373
374 /* Define GUESTFS_WARN_DEPRECATED=1 to warn about deprecated API functions. */
375 #define GUESTFS_DEPRECATED_BY(s)
376 #if GUESTFS_WARN_DEPRECATED
377 #  if defined(__GNUC__) && GUESTFS_GCC_VERSION >= 40500 /* gcc >= 4.5 */
378 #    undef GUESTFS_DEPRECATED_BY
379 #    define GUESTFS_DEPRECATED_BY(s) __attribute__((__deprecated__(\"change the program to use guestfs_\" s \" instead of this deprecated function\")))
380 #  endif
381 #endif /* GUESTFS_WARN_DEPRECATED */
382
383 /* The handle. */
384 #ifndef GUESTFS_TYPEDEF_H
385 #define GUESTFS_TYPEDEF_H 1
386 typedef struct guestfs_h guestfs_h;
387 #endif
388
389 /* Connection management. */
390 extern guestfs_h *guestfs_create (void);
391 extern void guestfs_close (guestfs_h *g);
392
393 /* Error handling. */
394 extern const char *guestfs_last_error (guestfs_h *g);
395 #define LIBGUESTFS_HAVE_LAST_ERRNO 1
396 extern int guestfs_last_errno (guestfs_h *g);
397
398 #ifndef GUESTFS_TYPEDEF_ERROR_HANDLER_CB
399 #define GUESTFS_TYPEDEF_ERROR_HANDLER_CB 1
400 typedef void (*guestfs_error_handler_cb) (guestfs_h *g, void *opaque, const char *msg);
401 #endif
402
403 #ifndef GUESTFS_TYPEDEF_ABORT_CB
404 #define GUESTFS_TYPEDEF_ABORT_CB 1
405 typedef void (*guestfs_abort_cb) (void) __attribute__((__noreturn__));
406 #endif
407
408 extern void guestfs_set_error_handler (guestfs_h *g, guestfs_error_handler_cb cb, void *opaque);
409 extern guestfs_error_handler_cb guestfs_get_error_handler (guestfs_h *g, void **opaque_rtn);
410
411 extern void guestfs_set_out_of_memory_handler (guestfs_h *g, guestfs_abort_cb);
412 extern guestfs_abort_cb guestfs_get_out_of_memory_handler (guestfs_h *g);
413
414 /* Events. */
415 ";
416
417   List.iter (
418     fun (name, bitmask) ->
419       pr "#define GUESTFS_EVENT_%-16s 0x%04x\n"
420         (String.uppercase name) bitmask
421   ) events;
422   pr "#define GUESTFS_EVENT_%-16s UINT64_MAX\n" "ALL";
423   pr "\n";
424
425   pr "\
426 #ifndef GUESTFS_TYPEDEF_EVENT_CALLBACK
427 #define GUESTFS_TYPEDEF_EVENT_CALLBACK 1
428 typedef void (*guestfs_event_callback) (
429                         guestfs_h *g,
430                         void *opaque,
431                         uint64_t event,
432                         int event_handle,
433                         int flags,
434                         const char *buf, size_t buf_len,
435                         const uint64_t *array, size_t array_len);
436 #endif
437
438 #define LIBGUESTFS_HAVE_SET_EVENT_CALLBACK 1
439 int guestfs_set_event_callback (guestfs_h *g,
440                                 guestfs_event_callback cb,
441                                 uint64_t event_bitmask,
442                                 int flags,
443                                 void *opaque);
444 #define LIBGUESTFS_HAVE_DELETE_EVENT_CALLBACK 1
445 void guestfs_delete_event_callback (guestfs_h *g, int event_handle);
446
447 /* Old-style event handling. */
448 #ifndef GUESTFS_TYPEDEF_LOG_MESSAGE_CB
449 #define GUESTFS_TYPEDEF_LOG_MESSAGE_CB 1
450 typedef void (*guestfs_log_message_cb) (guestfs_h *g, void *opaque, char *buf, int len);
451 #endif
452
453 #ifndef GUESTFS_TYPEDEF_SUBPROCESS_QUIT_CB
454 #define GUESTFS_TYPEDEF_SUBPROCESS_QUIT_CB 1
455 typedef void (*guestfs_subprocess_quit_cb) (guestfs_h *g, void *opaque);
456 #endif
457
458 #ifndef GUESTFS_TYPEDEF_LAUNCH_DONE_CB
459 #define GUESTFS_TYPEDEF_LAUNCH_DONE_CB 1
460 typedef void (*guestfs_launch_done_cb) (guestfs_h *g, void *opaque);
461 #endif
462
463 #ifndef GUESTFS_TYPEDEF_CLOSE_CB
464 #define GUESTFS_TYPEDEF_CLOSE_CB 1
465 typedef void (*guestfs_close_cb) (guestfs_h *g, void *opaque);
466 #endif
467
468 #ifndef GUESTFS_TYPEDEF_PROGRESS_CB
469 #define GUESTFS_TYPEDEF_PROGRESS_CB 1
470 typedef void (*guestfs_progress_cb) (guestfs_h *g, void *opaque, int proc_nr, int serial, uint64_t position, uint64_t total);
471 #endif
472
473 extern void guestfs_set_log_message_callback (guestfs_h *g, guestfs_log_message_cb cb, void *opaque)
474   GUESTFS_DEPRECATED_BY(\"set_event_callback\");
475 extern void guestfs_set_subprocess_quit_callback (guestfs_h *g, guestfs_subprocess_quit_cb cb, void *opaque)
476   GUESTFS_DEPRECATED_BY(\"set_event_callback\");
477 extern void guestfs_set_launch_done_callback (guestfs_h *g, guestfs_launch_done_cb cb, void *opaque)
478   GUESTFS_DEPRECATED_BY(\"set_event_callback\");
479 #define LIBGUESTFS_HAVE_SET_CLOSE_CALLBACK 1
480 extern void guestfs_set_close_callback (guestfs_h *g, guestfs_close_cb cb, void *opaque)
481   GUESTFS_DEPRECATED_BY(\"set_event_callback\");
482 #define LIBGUESTFS_HAVE_SET_PROGRESS_CALLBACK 1
483 extern void guestfs_set_progress_callback (guestfs_h *g, guestfs_progress_cb cb, void *opaque)
484   GUESTFS_DEPRECATED_BY(\"set_event_callback\");
485
486 /* Private data area. */
487 #define LIBGUESTFS_HAVE_SET_PRIVATE 1
488 extern void guestfs_set_private (guestfs_h *g, const char *key, void *data);
489 #define LIBGUESTFS_HAVE_GET_PRIVATE 1
490 extern void *guestfs_get_private (guestfs_h *g, const char *key);
491 #define LIBGUESTFS_HAVE_FIRST_PRIVATE 1
492 extern void *guestfs_first_private (guestfs_h *g, const char **key_rtn);
493 #define LIBGUESTFS_HAVE_NEXT_PRIVATE 1
494 extern void *guestfs_next_private (guestfs_h *g, const char **key_rtn);
495
496 /* Structures. */
497 ";
498
499   (* The structures are carefully written to have exactly the same
500    * in-memory format as the XDR structures that we use on the wire to
501    * the daemon.  The reason for creating copies of these structures
502    * here is just so we don't have to export the whole of
503    * guestfs_protocol.h (which includes much unrelated and
504    * XDR-dependent stuff that we don't want to be public, or required
505    * by clients).
506    * 
507    * To reiterate, we will pass these structures to and from the client
508    * with a simple assignment or memcpy, so the format must be
509    * identical to what rpcgen / the RFC defines.
510    *)
511
512   (* Public structures. *)
513   List.iter (
514     fun (typ, cols) ->
515       pr "struct guestfs_%s {\n" typ;
516       List.iter (
517         function
518         | name, FChar -> pr "  char %s;\n" name
519         | name, FString -> pr "  char *%s;\n" name
520         | name, FBuffer ->
521             pr "  uint32_t %s_len;\n" name;
522             pr "  char *%s;\n" name
523         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
524         | name, FUInt32 -> pr "  uint32_t %s;\n" name
525         | name, FInt32 -> pr "  int32_t %s;\n" name
526         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
527         | name, FInt64 -> pr "  int64_t %s;\n" name
528         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
529       ) cols;
530       pr "};\n";
531       pr "\n";
532       pr "struct guestfs_%s_list {\n" typ;
533       pr "  uint32_t len;\n";
534       pr "  struct guestfs_%s *val;\n" typ;
535       pr "};\n";
536       pr "\n";
537       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
538       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
539       pr "\n"
540   ) structs;
541
542   pr "\
543 /* Actions. */
544 ";
545
546   List.iter (
547     fun (shortname, (ret, args, optargs as style), _, flags, _, _, _) ->
548       let deprecated =
549         try
550           Some (find_map (function DeprecatedBy fn -> Some fn | _ -> None)
551                   flags)
552         with Not_found -> None in
553       let test0 =
554         String.length shortname >= 5 && String.sub shortname 0 5 = "test0" in
555       let debug =
556         String.length shortname >= 5 && String.sub shortname 0 5 = "debug" in
557       if deprecated = None && not test0 && not debug then
558         pr "#define LIBGUESTFS_HAVE_%s 1\n" (String.uppercase shortname);
559
560       if optargs <> [] then (
561         iteri (
562           fun i argt ->
563             let uc_shortname = String.uppercase shortname in
564             let n = name_of_argt argt in
565             let uc_n = String.uppercase n in
566             pr "#define GUESTFS_%s_%s %d\n" uc_shortname uc_n i;
567         ) optargs;
568       );
569
570       generate_prototype ~single_line:true ~semicolon:false
571         ~handle:"g" ~prefix:"guestfs_" shortname style;
572       (match deprecated with
573        | Some fn -> pr "\n  GUESTFS_DEPRECATED_BY (%S);\n" fn
574        | None -> pr ";\n"
575       );
576
577       if optargs <> [] then (
578         generate_prototype ~single_line:true ~newline:true ~handle:"g"
579           ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
580           shortname style;
581
582         pr "\n";
583         pr "struct guestfs_%s_argv {\n" shortname;
584         pr "  uint64_t bitmask;\n";
585         iteri (
586           fun i argt ->
587             let c_type =
588               match argt with
589               | Bool n -> "int "
590               | Int n -> "int "
591               | Int64 n -> "int64_t "
592               | String n -> "const char *"
593               | _ -> assert false (* checked in generator_checks *) in
594             let uc_shortname = String.uppercase shortname in
595             let n = name_of_argt argt in
596             let uc_n = String.uppercase n in
597             pr "\n";
598             pr "# define GUESTFS_%s_%s_BITMASK (UINT64_C(1)<<%d)\n" uc_shortname uc_n i;
599             pr "  /* The field below is only valid in this struct if the\n";
600             pr "   * GUESTFS_%s_%s_BITMASK bit is set\n" uc_shortname uc_n;
601             pr "   * in the bitmask above.  If not, the field is ignored.\n";
602             pr "   */\n";
603             pr "  %s%s;\n" c_type n
604         ) optargs;
605         pr "};\n";
606         pr "\n";
607
608         generate_prototype ~single_line:true ~newline:true ~handle:"g"
609           ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
610           shortname style;
611       );
612
613       pr "\n";
614   ) all_functions_sorted;
615
616   pr "\
617
618 /* Private functions.
619  *
620  * These are NOT part of the public, stable API, and can change at any
621  * time!  We export them because they are used by some of the language
622  * bindings.
623  */
624 extern void *guestfs_safe_malloc (guestfs_h *g, size_t nbytes);
625 extern void *guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s);
626 extern const char *guestfs_tmpdir (void);
627 #ifdef GUESTFS_PRIVATE_FOR_EACH_DISK
628 extern int guestfs___for_each_disk (guestfs_h *g, virDomainPtr dom, int (*)(guestfs_h *g, const char *filename, const char *format, void *data), void *data);
629 #endif
630 /* End of private functions. */
631
632 #ifdef __cplusplus
633 }
634 #endif
635
636 #endif /* GUESTFS_H_ */
637 "
638
639 (* Generate the guestfs-internal-actions.h file. *)
640 and generate_internal_actions_h () =
641   generate_header CStyle LGPLv2plus;
642   List.iter (
643     fun (shortname, style, _, _, _, _, _) ->
644       generate_prototype ~single_line:true ~newline:true ~handle:"g"
645         ~prefix:"guestfs__" ~optarg_proto:Argv
646         shortname style
647   ) non_daemon_functions
648
649 (* Generate the client-side dispatch stubs. *)
650 and generate_client_actions () =
651   generate_header CStyle LGPLv2plus;
652
653   pr "\
654 #include <stdio.h>
655 #include <stdlib.h>
656 #include <stdint.h>
657 #include <string.h>
658 #include <inttypes.h>
659 #include <unistd.h>
660 #include <sys/types.h>
661 #include <sys/stat.h>
662 #include <assert.h>
663
664 #include \"guestfs.h\"
665 #include \"guestfs-internal.h\"
666 #include \"guestfs-internal-actions.h\"
667 #include \"guestfs_protocol.h\"
668 #include \"errnostring.h\"
669
670 /* Check the return message from a call for validity. */
671 static int
672 check_reply_header (guestfs_h *g,
673                     const struct guestfs_message_header *hdr,
674                     unsigned int proc_nr, unsigned int serial)
675 {
676   if (hdr->prog != GUESTFS_PROGRAM) {
677     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
678     return -1;
679   }
680   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
681     error (g, \"wrong protocol version (%%d/%%d)\",
682            hdr->vers, GUESTFS_PROTOCOL_VERSION);
683     return -1;
684   }
685   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
686     error (g, \"unexpected message direction (%%d/%%d)\",
687            hdr->direction, GUESTFS_DIRECTION_REPLY);
688     return -1;
689   }
690   if (hdr->proc != proc_nr) {
691     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
692     return -1;
693   }
694   if (hdr->serial != serial) {
695     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
696     return -1;
697   }
698
699   return 0;
700 }
701
702 /* Check we are in the right state to run a high-level action. */
703 static int
704 check_state (guestfs_h *g, const char *caller)
705 {
706   if (!guestfs__is_ready (g)) {
707     if (guestfs__is_config (g) || guestfs__is_launching (g))
708       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
709         caller);
710     else
711       error (g, \"%%s called from the wrong state, %%d != READY\",
712         caller, guestfs__get_state (g));
713     return -1;
714   }
715   return 0;
716 }
717
718 /* Convenience wrapper for tracing. */
719 static FILE *
720 trace_open (guestfs_h *g)
721 {
722   assert (g->trace_fp == NULL);
723   g->trace_buf = NULL;
724   g->trace_len = 0;
725   g->trace_fp = open_memstream (&g->trace_buf, &g->trace_len);
726   if (g->trace_fp)
727     return g->trace_fp;
728   else
729     return stderr;
730 }
731
732 static void
733 trace_send_line (guestfs_h *g)
734 {
735   char *buf;
736   size_t len;
737
738   if (g->trace_fp) {
739     fclose (g->trace_fp);
740     g->trace_fp = NULL;
741
742     /* The callback might invoke other libguestfs calls, so keep
743      * a copy of the pointer to the buffer and length.
744      */
745     buf = g->trace_buf;
746     len = g->trace_len;
747     g->trace_buf = NULL;
748     guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE, buf, len);
749
750     free (buf);
751   }
752 }
753
754 ";
755
756   (* Generate code to check String-like parameters are not passed in
757    * as NULL (returning an error if they are).
758    *)
759   let check_null_strings shortname (ret, args, optargs) =
760     let pr_newline = ref false in
761     List.iter (
762       function
763       (* parameters which should not be NULL *)
764       | String n
765       | Device n
766       | Pathname n
767       | Dev_or_Path n
768       | FileIn n
769       | FileOut n
770       | BufferIn n
771       | StringList n
772       | DeviceList n
773       | Key n
774       | Pointer (_, n) ->
775           pr "  if (%s == NULL) {\n" n;
776           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
777           pr "           \"%s\", \"%s\");\n" shortname n;
778           let errcode =
779             match errcode_of_ret ret with
780             | `CannotReturnError ->
781                 if shortname = "test0rconstoptstring" then (* XXX hack *)
782                   `ErrorIsNULL
783                 else
784                   failwithf
785                     "%s: RConstOptString function has invalid parameter '%s'"
786                     shortname n
787             | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
788           pr "    return %s;\n" (string_of_errcode errcode);
789           pr "  }\n";
790           pr_newline := true
791
792       (* can be NULL *)
793       | OptString _
794
795       (* not applicable *)
796       | Bool _
797       | Int _
798       | Int64 _ -> ()
799     ) args;
800
801     (* For optional arguments. *)
802     List.iter (
803       function
804       | String n ->
805           pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK) &&\n"
806             (String.uppercase shortname) (String.uppercase n);
807           pr "      optargs->%s == NULL) {\n" n;
808           pr "    error (g, \"%%s: %%s: optional parameter cannot be NULL\",\n";
809           pr "           \"%s\", \"%s\");\n" shortname n;
810           let errcode =
811             match errcode_of_ret ret with
812             | `CannotReturnError -> assert false
813             | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
814           pr "    return %s;\n" (string_of_errcode errcode);
815           pr "  }\n";
816           pr_newline := true
817
818       (* not applicable *)
819       | Bool _ | Int _ | Int64 _ -> ()
820
821       | _ -> assert false
822     ) optargs;
823
824     if !pr_newline then pr "\n";
825   in
826
827   (* Generate code to reject optargs we don't know about. *)
828   let reject_unknown_optargs shortname = function
829     | _, _, [] -> ()
830     | ret, _, optargs ->
831         let len = List.length optargs in
832         let mask = Int64.lognot (Int64.pred (Int64.shift_left 1L len)) in
833         pr "  if (optargs->bitmask & UINT64_C(0x%Lx)) {\n" mask;
834         pr "    error (g, \"%%s: unknown option in guestfs_%%s_argv->bitmask (this can happen if a program is compiled against a newer version of libguestfs, then dynamically linked to an older version)\",\n";
835         pr "           \"%s\", \"%s\");\n" shortname shortname;
836         let errcode =
837           match errcode_of_ret ret with
838           | `CannotReturnError -> assert false
839           | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
840         pr "    return %s;\n" (string_of_errcode errcode);
841         pr "  }\n";
842         pr "\n";
843   in
844
845   (* Generate code to generate guestfish call traces. *)
846   let trace_call shortname (ret, args, optargs) =
847     pr "  if (trace_flag) {\n";
848
849     let needs_i =
850       List.exists (function
851                    | StringList _ | DeviceList _ -> true
852                    | _ -> false) args in
853     if needs_i then (
854       pr "    size_t i;\n";
855       pr "\n"
856     );
857
858     pr "    trace_fp = trace_open (g);\n";
859
860     pr "    fprintf (trace_fp, \"%%s\", \"%s\");\n" shortname;
861
862     (* Required arguments. *)
863     List.iter (
864       function
865       | String n                        (* strings *)
866       | Device n
867       | Pathname n
868       | Dev_or_Path n
869       | FileIn n
870       | FileOut n ->
871           (* guestfish doesn't support string escaping, so neither do we *)
872           pr "    fprintf (trace_fp, \" \\\"%%s\\\"\", %s);\n" n
873       | Key n ->
874           (* don't print keys *)
875           pr "    fprintf (trace_fp, \" \\\"***\\\"\");\n"
876       | OptString n ->                  (* string option *)
877           pr "    if (%s) fprintf (trace_fp, \" \\\"%%s\\\"\", %s);\n" n n;
878           pr "    else fprintf (trace_fp, \" null\");\n"
879       | StringList n
880       | DeviceList n ->                 (* string list *)
881           pr "    fputc (' ', trace_fp);\n";
882           pr "    fputc ('\"', trace_fp);\n";
883           pr "    for (i = 0; %s[i]; ++i) {\n" n;
884           pr "      if (i > 0) fputc (' ', trace_fp);\n";
885           pr "      fputs (%s[i], trace_fp);\n" n;
886           pr "    }\n";
887           pr "    fputc ('\"', trace_fp);\n";
888       | Bool n ->                       (* boolean *)
889           pr "    fputs (%s ? \" true\" : \" false\", trace_fp);\n" n
890       | Int n ->                        (* int *)
891           pr "    fprintf (trace_fp, \" %%d\", %s);\n" n
892       | Int64 n ->
893           pr "    fprintf (trace_fp, \" %%\" PRIi64, %s);\n" n
894       | BufferIn n ->                   (* RHBZ#646822 *)
895           pr "    fputc (' ', trace_fp);\n";
896           pr "    guestfs___print_BufferIn (trace_fp, %s, %s_size);\n" n n
897       | Pointer (t, n) ->
898           pr "    fprintf (trace_fp, \" (%s)%%p\", %s);\n" t n
899     ) args;
900
901     (* Optional arguments. *)
902     List.iter (
903       fun argt ->
904         let n = name_of_argt argt in
905         let uc_shortname = String.uppercase shortname in
906         let uc_n = String.uppercase n in
907         pr "    if (optargs->bitmask & GUESTFS_%s_%s_BITMASK)\n"
908           uc_shortname uc_n;
909         (match argt with
910          | String n ->
911              pr "      fprintf (trace_fp, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s);\n" n n
912          | Bool n ->
913              pr "      fprintf (trace_fp, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s ? \"true\" : \"false\");\n" n n
914          | Int n ->
915              pr "      fprintf (trace_fp, \" \\\"%%s:%%d\\\"\", \"%s\", optargs->%s);\n" n n
916          | Int64 n ->
917              pr "      fprintf (trace_fp, \" \\\"%%s:%%\" PRIi64 \"\\\"\", \"%s\", optargs->%s);\n" n n
918          | _ -> assert false
919         );
920     ) optargs;
921
922     pr "    trace_send_line (g);\n";
923     pr "  }\n";
924     pr "\n";
925   in
926
927   let trace_return ?(indent = 2) shortname (ret, _, _) rv =
928     let indent = spaces indent in
929
930     pr "%sif (trace_flag) {\n" indent;
931
932     let needs_i =
933       match ret with
934       | RStringList _ | RHashtable _ -> true
935       | _ -> false in
936     if needs_i then (
937       pr "%s  size_t i;\n" indent;
938       pr "\n"
939     );
940
941     pr "%s  trace_fp = trace_open (g);\n" indent;
942
943     pr "%s  fprintf (trace_fp, \"%%s = \", \"%s\");\n" indent shortname;
944
945     (match ret with
946      | RErr | RInt _ | RBool _ ->
947          pr "%s  fprintf (trace_fp, \"%%d\", %s);\n" indent rv
948      | RInt64 _ ->
949          pr "%s  fprintf (trace_fp, \"%%\" PRIi64, %s);\n" indent rv
950      | RConstString _ | RString _ ->
951          pr "%s  fprintf (trace_fp, \"\\\"%%s\\\"\", %s);\n" indent rv
952      | RConstOptString _ ->
953          pr "%s  fprintf (trace_fp, \"\\\"%%s\\\"\", %s != NULL ? %s : \"NULL\");\n"
954            indent rv rv
955      | RBufferOut _ ->
956          pr "%s  guestfs___print_BufferOut (trace_fp, %s, *size_r);\n" indent rv
957      | RStringList _ | RHashtable _ ->
958          pr "%s  fputs (\"[\", trace_fp);\n" indent;
959          pr "%s  for (i = 0; %s[i]; ++i) {\n" indent rv;
960          pr "%s    if (i > 0) fputs (\", \", trace_fp);\n" indent;
961          pr "%s    fputs (\"\\\"\", trace_fp);\n" indent;
962          pr "%s    fputs (%s[i], trace_fp);\n" indent rv;
963          pr "%s    fputs (\"\\\"\", trace_fp);\n" indent;
964          pr "%s  }\n" indent;
965          pr "%s  fputs (\"]\", trace_fp);\n" indent;
966      | RStruct (_, typ) ->
967          (* XXX There is code generated for guestfish for printing
968           * these structures.  We need to make it generally available
969           * for all callers
970           *)
971          pr "%s  fprintf (trace_fp, \"<struct guestfs_%s *>\");\n"
972            indent typ (* XXX *)
973      | RStructList (_, typ) ->
974          pr "%s  fprintf (trace_fp, \"<struct guestfs_%s_list *>\");\n"
975            indent typ (* XXX *)
976     );
977     pr "%s  trace_send_line (g);\n" indent;
978     pr "%s}\n" indent;
979     pr "\n";
980   in
981
982   let trace_return_error ?(indent = 2) shortname (ret, _, _) errcode =
983     let indent = spaces indent in
984
985     pr "%sif (trace_flag)\n" indent;
986
987     pr "%s  guestfs___trace (g, \"%%s = %%s (error)\",\n" indent;
988     pr "%s                   \"%s\", \"%s\");\n"
989       indent shortname (string_of_errcode errcode)
990   in
991
992   (* For non-daemon functions, generate a wrapper around each function. *)
993   List.iter (
994     fun (shortname, (ret, _, optargs as style), _, _, _, _, _) ->
995       if optargs = [] then
996         generate_prototype ~extern:false ~semicolon:false ~newline:true
997           ~handle:"g" ~prefix:"guestfs_"
998           shortname style
999       else
1000         generate_prototype ~extern:false ~semicolon:false ~newline:true
1001           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
1002           shortname style;
1003       pr "{\n";
1004       pr "  int trace_flag = g->trace;\n";
1005       pr "  FILE *trace_fp;\n";
1006       (match ret with
1007        | RErr | RInt _ | RBool _ ->
1008            pr "  int r;\n"
1009        | RInt64 _ ->
1010            pr "  int64_t r;\n"
1011        | RConstString _ ->
1012            pr "  const char *r;\n"
1013        | RConstOptString _ ->
1014            pr "  const char *r;\n"
1015        | RString _ | RBufferOut _ ->
1016            pr "  char *r;\n"
1017        | RStringList _ | RHashtable _ ->
1018            pr "  char **r;\n"
1019        | RStruct (_, typ) ->
1020            pr "  struct guestfs_%s *r;\n" typ
1021        | RStructList (_, typ) ->
1022            pr "  struct guestfs_%s_list *r;\n" typ
1023       );
1024       pr "\n";
1025       check_null_strings shortname style;
1026       reject_unknown_optargs shortname style;
1027       trace_call shortname style;
1028       pr "  r = guestfs__%s " shortname;
1029       generate_c_call_args ~handle:"g" ~implicit_size_ptr:"size_r" style;
1030       pr ";\n";
1031       pr "\n";
1032       (match errcode_of_ret ret with
1033        | (`ErrorIsMinusOne | `ErrorIsNULL) as errcode ->
1034            pr "  if (r != %s) {\n" (string_of_errcode errcode);
1035            trace_return ~indent:4 shortname style "r";
1036            pr "  } else {\n";
1037            trace_return_error ~indent:4 shortname style errcode;
1038            pr "  }\n";
1039        | `CannotReturnError ->
1040            trace_return shortname style "r";
1041       );
1042       pr "\n";
1043       pr "  return r;\n";
1044       pr "}\n";
1045       pr "\n"
1046   ) non_daemon_functions;
1047
1048   (* Client-side stubs for each function. *)
1049   List.iter (
1050     fun (shortname, (ret, args, optargs as style), _, _, _, _, _) ->
1051       let name = "guestfs_" ^ shortname in
1052       let errcode =
1053         match errcode_of_ret ret with
1054         | `CannotReturnError -> assert false
1055         | (`ErrorIsMinusOne | `ErrorIsNULL) as e -> e in
1056
1057       (* Generate the action stub. *)
1058       if optargs = [] then
1059         generate_prototype ~extern:false ~semicolon:false ~newline:true
1060           ~handle:"g" ~prefix:"guestfs_" shortname style
1061       else
1062         generate_prototype ~extern:false ~semicolon:false ~newline:true
1063           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv"
1064           ~optarg_proto:Argv shortname style;
1065
1066       pr "{\n";
1067
1068       (match args with
1069        | [] -> ()
1070        | _ -> pr "  struct %s_args args;\n" name
1071       );
1072
1073       pr "  guestfs_message_header hdr;\n";
1074       pr "  guestfs_message_error err;\n";
1075       let has_ret =
1076         match ret with
1077         | RErr -> false
1078         | RConstString _ | RConstOptString _ ->
1079             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
1080         | RInt _ | RInt64 _
1081         | RBool _ | RString _ | RStringList _
1082         | RStruct _ | RStructList _
1083         | RHashtable _ | RBufferOut _ ->
1084             pr "  struct %s_ret ret;\n" name;
1085             true in
1086
1087       pr "  int serial;\n";
1088       pr "  int r;\n";
1089       pr "  int trace_flag = g->trace;\n";
1090       pr "  FILE *trace_fp;\n";
1091       (match ret with
1092        | RErr | RInt _ | RBool _ ->
1093            pr "  int ret_v;\n"
1094        | RInt64 _ ->
1095            pr "  int64_t ret_v;\n"
1096        | RConstString _ | RConstOptString _ ->
1097            pr "  const char *ret_v;\n"
1098        | RString _ | RBufferOut _ ->
1099            pr "  char *ret_v;\n"
1100        | RStringList _ | RHashtable _ ->
1101            pr "  char **ret_v;\n"
1102        | RStruct (_, typ) ->
1103            pr "  struct guestfs_%s *ret_v;\n" typ
1104        | RStructList (_, typ) ->
1105            pr "  struct guestfs_%s_list *ret_v;\n" typ
1106       );
1107
1108       let has_filein =
1109         List.exists (function FileIn _ -> true | _ -> false) args in
1110       if has_filein then (
1111         pr "  uint64_t progress_hint = 0;\n";
1112         pr "  struct stat progress_stat;\n";
1113       ) else
1114         pr "  const uint64_t progress_hint = 0;\n";
1115
1116       pr "\n";
1117       check_null_strings shortname style;
1118       reject_unknown_optargs shortname style;
1119       trace_call shortname style;
1120
1121       (* Calculate the total size of all FileIn arguments to pass
1122        * as a progress bar hint.
1123        *)
1124       List.iter (
1125         function
1126         | FileIn n ->
1127             pr "  if (stat (%s, &progress_stat) == 0 &&\n" n;
1128             pr "      S_ISREG (progress_stat.st_mode))\n";
1129             pr "    progress_hint += progress_stat.st_size;\n";
1130             pr "\n";
1131         | _ -> ()
1132       ) args;
1133
1134       (* Check we are in the right state for sending a request. *)
1135       pr "  if (check_state (g, \"%s\") == -1) {\n" shortname;
1136       trace_return_error ~indent:4 shortname style errcode;
1137       pr "    return %s;\n" (string_of_errcode errcode);
1138       pr "  }\n";
1139       pr "  guestfs___set_busy (g);\n";
1140       pr "\n";
1141
1142       (* Send the main header and arguments. *)
1143       if args = [] && optargs = [] then (
1144         pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, progress_hint, 0,\n"
1145           (String.uppercase shortname);
1146         pr "                           NULL, NULL);\n"
1147       ) else (
1148         List.iter (
1149           function
1150           | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
1151               pr "  args.%s = (char *) %s;\n" n n
1152           | OptString n ->
1153               pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
1154           | StringList n | DeviceList n ->
1155               pr "  args.%s.%s_val = (char **) %s;\n" n n n;
1156               pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
1157           | Bool n ->
1158               pr "  args.%s = %s;\n" n n
1159           | Int n ->
1160               pr "  args.%s = %s;\n" n n
1161           | Int64 n ->
1162               pr "  args.%s = %s;\n" n n
1163           | FileIn _ | FileOut _ -> ()
1164           | BufferIn n ->
1165               pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
1166               pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
1167               trace_return_error ~indent:4 shortname style errcode;
1168               pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
1169                 shortname;
1170               pr "    guestfs___end_busy (g);\n";
1171               pr "    return %s;\n" (string_of_errcode errcode);
1172               pr "  }\n";
1173               pr "  args.%s.%s_val = (char *) %s;\n" n n n;
1174               pr "  args.%s.%s_len = %s_size;\n" n n n
1175           | Pointer _ -> assert false
1176         ) args;
1177
1178         List.iter (
1179           fun argt ->
1180             let n = name_of_argt argt in
1181             let uc_shortname = String.uppercase shortname in
1182             let uc_n = String.uppercase n in
1183             pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK))\n"
1184               uc_shortname uc_n;
1185             (match argt with
1186              | Bool n
1187              | Int n
1188              | Int64 n ->
1189                  pr "    args.%s = optargs->%s;\n" n n;
1190                  pr "  else\n";
1191                  pr "    args.%s = 0;\n" n
1192              | String n ->
1193                  pr "    args.%s = (char *) optargs->%s;\n" n n;
1194                  pr "  else\n";
1195                  pr "    args.%s = (char *) \"\";\n" n
1196              | _ -> assert false
1197             )
1198         ) optargs;
1199
1200         pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
1201           (String.uppercase shortname);
1202         pr "                           progress_hint, %s,\n"
1203           (if optargs <> [] then "optargs->bitmask" else "0");
1204         pr "                           (xdrproc_t) xdr_%s_args, (char *) &args);\n"
1205           name;
1206       );
1207       pr "  if (serial == -1) {\n";
1208       pr "    guestfs___end_busy (g);\n";
1209       trace_return_error ~indent:4 shortname style errcode;
1210       pr "    return %s;\n" (string_of_errcode errcode);
1211       pr "  }\n";
1212       pr "\n";
1213
1214       (* Send any additional files (FileIn) requested. *)
1215       let need_read_reply_label = ref false in
1216       List.iter (
1217         function
1218         | FileIn n ->
1219             pr "  r = guestfs___send_file (g, %s);\n" n;
1220             pr "  if (r == -1) {\n";
1221             pr "    guestfs___end_busy (g);\n";
1222             trace_return_error ~indent:4 shortname style errcode;
1223             pr "    /* daemon will send an error reply which we discard */\n";
1224             pr "    guestfs___recv_discard (g, \"%s\");\n" shortname;
1225             pr "    return %s;\n" (string_of_errcode errcode);
1226             pr "  }\n";
1227             pr "  if (r == -2) /* daemon cancelled */\n";
1228             pr "    goto read_reply;\n";
1229             need_read_reply_label := true;
1230             pr "\n";
1231         | _ -> ()
1232       ) args;
1233
1234       (* Wait for the reply from the remote end. *)
1235       if !need_read_reply_label then pr " read_reply:\n";
1236       pr "  memset (&hdr, 0, sizeof hdr);\n";
1237       pr "  memset (&err, 0, sizeof err);\n";
1238       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
1239       pr "\n";
1240       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
1241       if not has_ret then
1242         pr "NULL, NULL"
1243       else
1244         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
1245       pr ");\n";
1246
1247       pr "  if (r == -1) {\n";
1248       pr "    guestfs___end_busy (g);\n";
1249       trace_return_error ~indent:4 shortname style errcode;
1250       pr "    return %s;\n" (string_of_errcode errcode);
1251       pr "  }\n";
1252       pr "\n";
1253
1254       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
1255         (String.uppercase shortname);
1256       pr "    guestfs___end_busy (g);\n";
1257       trace_return_error ~indent:4 shortname style errcode;
1258       pr "    return %s;\n" (string_of_errcode errcode);
1259       pr "  }\n";
1260       pr "\n";
1261
1262       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
1263       trace_return_error ~indent:4 shortname style errcode;
1264       pr "    int errnum = 0;\n";
1265       pr "    if (err.errno_string[0] != '\\0')\n";
1266       pr "      errnum = guestfs___string_to_errno (err.errno_string);\n";
1267       pr "    if (errnum <= 0)\n";
1268       pr "      error (g, \"%%s: %%s\", \"%s\", err.error_message);\n"
1269         shortname;
1270       pr "    else\n";
1271       pr "      guestfs_error_errno (g, errnum, \"%%s: %%s\", \"%s\",\n"
1272         shortname;
1273       pr "                           err.error_message);\n";
1274       pr "    free (err.error_message);\n";
1275       pr "    free (err.errno_string);\n";
1276       pr "    guestfs___end_busy (g);\n";
1277       pr "    return %s;\n" (string_of_errcode errcode);
1278       pr "  }\n";
1279       pr "\n";
1280
1281       (* Expecting to receive further files (FileOut)? *)
1282       List.iter (
1283         function
1284         | FileOut n ->
1285             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
1286             pr "    guestfs___end_busy (g);\n";
1287             trace_return_error ~indent:4 shortname style errcode;
1288             pr "    return %s;\n" (string_of_errcode errcode);
1289             pr "  }\n";
1290             pr "\n";
1291         | _ -> ()
1292       ) args;
1293
1294       pr "  guestfs___end_busy (g);\n";
1295
1296       (match ret with
1297        | RErr ->
1298            pr "  ret_v = 0;\n"
1299        | RInt n | RInt64 n | RBool n ->
1300            pr "  ret_v = ret.%s;\n" n
1301        | RConstString _ | RConstOptString _ ->
1302            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
1303        | RString n ->
1304            pr "  ret_v = ret.%s; /* caller will free */\n" n
1305        | RStringList n | RHashtable n ->
1306            pr "  /* caller will free this, but we need to add a NULL entry */\n";
1307            pr "  ret.%s.%s_val =\n" n n;
1308            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
1309            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
1310              n n;
1311            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
1312            pr "  ret_v = ret.%s.%s_val;\n" n n
1313        | RStruct (n, _) ->
1314            pr "  /* caller will free this */\n";
1315            pr "  ret_v = safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
1316        | RStructList (n, _) ->
1317            pr "  /* caller will free this */\n";
1318            pr "  ret_v = safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
1319        | RBufferOut n ->
1320            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
1321            pr "   * _val might be NULL here.  To make the API saner for\n";
1322            pr "   * callers, we turn this case into a unique pointer (using\n";
1323            pr "   * malloc(1)).\n";
1324            pr "   */\n";
1325            pr "  if (ret.%s.%s_len > 0) {\n" n n;
1326            pr "    *size_r = ret.%s.%s_len;\n" n n;
1327            pr "    ret_v = ret.%s.%s_val; /* caller will free */\n" n n;
1328            pr "  } else {\n";
1329            pr "    free (ret.%s.%s_val);\n" n n;
1330            pr "    char *p = safe_malloc (g, 1);\n";
1331            pr "    *size_r = ret.%s.%s_len;\n" n n;
1332            pr "    ret_v = p;\n";
1333            pr "  }\n";
1334       );
1335       trace_return shortname style "ret_v";
1336       pr "  return ret_v;\n";
1337       pr "}\n\n"
1338   ) daemon_functions;
1339
1340   (* Functions to free structures. *)
1341   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
1342   pr " * structure format is identical to the XDR format.  See note in\n";
1343   pr " * generator.ml.\n";
1344   pr " */\n";
1345   pr "\n";
1346
1347   List.iter (
1348     fun (typ, _) ->
1349       pr "void\n";
1350       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
1351       pr "{\n";
1352       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
1353       pr "  free (x);\n";
1354       pr "}\n";
1355       pr "\n";
1356
1357       pr "void\n";
1358       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
1359       pr "{\n";
1360       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
1361       pr "  free (x);\n";
1362       pr "}\n";
1363       pr "\n";
1364
1365   ) structs;
1366
1367   (* Functions which have optional arguments have two generated variants. *)
1368   List.iter (
1369     function
1370     | shortname, (ret, args, (_::_ as optargs) as style), _, _, _, _, _ ->
1371         let uc_shortname = String.uppercase shortname in
1372
1373         (* Get the name of the last regular argument. *)
1374         let last_arg =
1375           match ret with
1376           | RBufferOut _ -> "size_r"
1377           | _ ->
1378               match args with
1379               | [] -> "g"
1380               | args -> name_of_argt (List.hd (List.rev args)) in
1381
1382         let rtype =
1383           match ret with
1384           | RErr | RInt _ | RBool _ -> "int "
1385           | RInt64 _ -> "int64_t "
1386           | RConstString _ | RConstOptString _ -> "const char *"
1387           | RString _ | RBufferOut _ -> "char *"
1388           | RStringList _ | RHashtable _ -> "char **"
1389           | RStruct (_, typ) -> sprintf "struct guestfs_%s *" typ
1390           | RStructList (_, typ) ->
1391               sprintf "struct guestfs_%s_list *" typ in
1392
1393         (* The regular variable args function, just calls the _va variant. *)
1394         generate_prototype ~extern:false ~semicolon:false ~newline:true
1395           ~handle:"g" ~prefix:"guestfs_" shortname style;
1396         pr "{\n";
1397         pr "  va_list optargs;\n";
1398         pr "\n";
1399         pr "  va_start (optargs, %s);\n" last_arg;
1400         pr "  %sr = guestfs_%s_va " rtype shortname;
1401         generate_c_call_args ~handle:"g" ~implicit_size_ptr:"size_r" style;
1402         pr ";\n";
1403         pr "  va_end (optargs);\n";
1404         pr "\n";
1405         pr "  return r;\n";
1406         pr "}\n\n";
1407
1408         generate_prototype ~extern:false ~semicolon:false ~newline:true
1409           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
1410           shortname style;
1411         pr "{\n";
1412         pr "  struct guestfs_%s_argv optargs_s;\n" shortname;
1413         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" shortname;
1414         pr "  int i;\n";
1415         pr "\n";
1416         pr "  optargs_s.bitmask = 0;\n";
1417         pr "\n";
1418         pr "  while ((i = va_arg (args, int)) >= 0) {\n";
1419         pr "    switch (i) {\n";
1420
1421         List.iter (
1422           fun argt ->
1423             let n = name_of_argt argt in
1424             let uc_n = String.uppercase n in
1425             pr "    case GUESTFS_%s_%s:\n" uc_shortname uc_n;
1426             pr "      optargs_s.%s = va_arg (args, " n;
1427             (match argt with
1428              | Bool _ | Int _ -> pr "int"
1429              | Int64 _ -> pr "int64_t"
1430              | String _ -> pr "const char *"
1431              | _ -> assert false
1432             );
1433             pr ");\n";
1434             pr "      break;\n";
1435         ) optargs;
1436
1437         let errcode =
1438           match errcode_of_ret ret with
1439           | `CannotReturnError -> assert false
1440           | (`ErrorIsMinusOne | `ErrorIsNULL) as e -> e in
1441
1442         pr "    default:\n";
1443         pr "      error (g, \"%%s: unknown option %%d (this can happen if a program is compiled against a newer version of libguestfs, then dynamically linked to an older version)\",\n";
1444         pr "             \"%s\", i);\n" shortname;
1445         pr "      return %s;\n" (string_of_errcode errcode);
1446         pr "    }\n";
1447         pr "\n";
1448         pr "    uint64_t i_mask = UINT64_C(1) << i;\n";
1449         pr "    if (optargs_s.bitmask & i_mask) {\n";
1450         pr "      error (g, \"%%s: same optional argument specified more than once\",\n";
1451         pr "             \"%s\");\n" shortname;
1452         pr "      return %s;\n" (string_of_errcode errcode);
1453         pr "    }\n";
1454         pr "    optargs_s.bitmask |= i_mask;\n";
1455         pr "  }\n";
1456         pr "\n";
1457         pr "  return guestfs_%s_argv " shortname;
1458         generate_c_call_args ~handle:"g" ~implicit_size_ptr:"size_r" style;
1459         pr ";\n";
1460         pr "}\n\n"
1461     | _ -> ()
1462   ) all_functions_sorted
1463
1464 (* Generate the linker script which controls the visibility of
1465  * symbols in the public ABI and ensures no other symbols get
1466  * exported accidentally.
1467  *)
1468 and generate_linker_script () =
1469   generate_header HashStyle GPLv2plus;
1470
1471   let globals = [
1472     "guestfs_create";
1473     "guestfs_close";
1474     "guestfs_delete_event_callback";
1475     "guestfs_first_private";
1476     "guestfs_get_error_handler";
1477     "guestfs_get_out_of_memory_handler";
1478     "guestfs_get_private";
1479     "guestfs_last_errno";
1480     "guestfs_last_error";
1481     "guestfs_next_private";
1482     "guestfs_set_close_callback";
1483     "guestfs_set_error_handler";
1484     "guestfs_set_event_callback";
1485     "guestfs_set_launch_done_callback";
1486     "guestfs_set_log_message_callback";
1487     "guestfs_set_out_of_memory_handler";
1488     "guestfs_set_private";
1489     "guestfs_set_progress_callback";
1490     "guestfs_set_subprocess_quit_callback";
1491
1492     (* Unofficial parts of the API: the bindings code use these
1493      * functions, so it is useful to export them.
1494      *)
1495     "guestfs_safe_calloc";
1496     "guestfs_safe_malloc";
1497     "guestfs_safe_strdup";
1498     "guestfs_safe_memdup";
1499     "guestfs_tmpdir";
1500     "guestfs___for_each_disk";
1501   ] in
1502   let functions =
1503     List.flatten (
1504       List.map (
1505         function
1506         | name, (_, _, []), _, _, _, _, _ -> ["guestfs_" ^ name]
1507         | name, (_, _, _), _, _, _, _, _ ->
1508             ["guestfs_" ^ name;
1509              "guestfs_" ^ name ^ "_va";
1510              "guestfs_" ^ name ^ "_argv"]
1511       ) all_functions
1512     ) in
1513   let structs =
1514     List.concat (
1515       List.map (fun (typ, _) ->
1516                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
1517         structs
1518     ) in
1519   let globals = List.sort compare (globals @ functions @ structs) in
1520
1521   pr "{\n";
1522   pr "    global:\n";
1523   List.iter (pr "        %s;\n") globals;
1524   pr "\n";
1525
1526   pr "    local:\n";
1527   pr "        *;\n";
1528   pr "};\n"
1529
1530 and generate_max_proc_nr () =
1531   pr "%d\n" max_proc_nr