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