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