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