guestfs.h: Tidy up *_argv structs and other #defines.
[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       if optargs <> [] then (
560         iteri (
561           fun i argt ->
562             let uc_shortname = String.uppercase shortname in
563             let n = name_of_argt argt in
564             let uc_n = String.uppercase n in
565             pr "#define GUESTFS_%s_%s %d\n" uc_shortname uc_n i;
566         ) optargs;
567       );
568
569       generate_prototype ~single_line:true ~semicolon:false
570         ~handle:"g" ~prefix:"guestfs_" shortname style;
571       (match deprecated with
572        | Some fn -> pr "\n  GUESTFS_DEPRECATED_BY (%S);\n" fn
573        | None -> pr ";\n"
574       );
575
576       if optargs <> [] then (
577         generate_prototype ~single_line:true ~newline:true ~handle:"g"
578           ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
579           shortname style;
580
581         pr "\n";
582         pr "struct guestfs_%s_argv {\n" shortname;
583         pr "  uint64_t bitmask;\n";
584         iteri (
585           fun i argt ->
586             let c_type =
587               match argt with
588               | Bool n -> "int "
589               | Int n -> "int "
590               | Int64 n -> "int64_t "
591               | String n -> "const char *"
592               | _ -> assert false (* checked in generator_checks *) in
593             let uc_shortname = String.uppercase shortname in
594             let n = name_of_argt argt in
595             let uc_n = String.uppercase n in
596             pr "\n";
597             pr "# define GUESTFS_%s_%s_BITMASK (UINT64_C(1)<<%d)\n" uc_shortname uc_n i;
598             pr "  /* The field below is only valid in this struct if the\n";
599             pr "   * GUESTFS_%s_%s_BITMASK bit is set\n" uc_shortname uc_n;
600             pr "   * in the bitmask above.  If not, the field is ignored.\n";
601             pr "   */\n";
602             pr "  %s%s;\n" c_type n
603         ) optargs;
604         pr "};\n";
605         pr "\n";
606
607         generate_prototype ~single_line:true ~newline:true ~handle:"g"
608           ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
609           shortname style;
610       );
611
612       pr "\n";
613   ) all_functions_sorted;
614
615   pr "\
616
617 /* Private functions.
618  *
619  * These are NOT part of the public, stable API, and can change at any
620  * time!  We export them because they are used by some of the language
621  * bindings.
622  */
623 extern void *guestfs_safe_malloc (guestfs_h *g, size_t nbytes);
624 extern void *guestfs_safe_calloc (guestfs_h *g, size_t n, size_t s);
625 extern const char *guestfs_tmpdir (void);
626 #ifdef GUESTFS_PRIVATE_FOR_EACH_DISK
627 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);
628 #endif
629 /* End of private functions. */
630
631 #ifdef __cplusplus
632 }
633 #endif
634
635 #endif /* GUESTFS_H_ */
636 "
637
638 (* Generate the guestfs-internal-actions.h file. *)
639 and generate_internal_actions_h () =
640   generate_header CStyle LGPLv2plus;
641   List.iter (
642     fun (shortname, style, _, _, _, _, _) ->
643       generate_prototype ~single_line:true ~newline:true ~handle:"g"
644         ~prefix:"guestfs__" ~optarg_proto:Argv
645         shortname style
646   ) non_daemon_functions
647
648 (* Generate the client-side dispatch stubs. *)
649 and generate_client_actions () =
650   generate_header CStyle LGPLv2plus;
651
652   pr "\
653 #include <stdio.h>
654 #include <stdlib.h>
655 #include <stdint.h>
656 #include <string.h>
657 #include <inttypes.h>
658 #include <unistd.h>
659 #include <sys/types.h>
660 #include <sys/stat.h>
661 #include <assert.h>
662
663 #include \"guestfs.h\"
664 #include \"guestfs-internal.h\"
665 #include \"guestfs-internal-actions.h\"
666 #include \"guestfs_protocol.h\"
667 #include \"errnostring.h\"
668
669 /* Check the return message from a call for validity. */
670 static int
671 check_reply_header (guestfs_h *g,
672                     const struct guestfs_message_header *hdr,
673                     unsigned int proc_nr, unsigned int serial)
674 {
675   if (hdr->prog != GUESTFS_PROGRAM) {
676     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
677     return -1;
678   }
679   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
680     error (g, \"wrong protocol version (%%d/%%d)\",
681            hdr->vers, GUESTFS_PROTOCOL_VERSION);
682     return -1;
683   }
684   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
685     error (g, \"unexpected message direction (%%d/%%d)\",
686            hdr->direction, GUESTFS_DIRECTION_REPLY);
687     return -1;
688   }
689   if (hdr->proc != proc_nr) {
690     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
691     return -1;
692   }
693   if (hdr->serial != serial) {
694     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
695     return -1;
696   }
697
698   return 0;
699 }
700
701 /* Check we are in the right state to run a high-level action. */
702 static int
703 check_state (guestfs_h *g, const char *caller)
704 {
705   if (!guestfs__is_ready (g)) {
706     if (guestfs__is_config (g) || guestfs__is_launching (g))
707       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
708         caller);
709     else
710       error (g, \"%%s called from the wrong state, %%d != READY\",
711         caller, guestfs__get_state (g));
712     return -1;
713   }
714   return 0;
715 }
716
717 /* Convenience wrapper for tracing. */
718 static FILE *
719 trace_open (guestfs_h *g)
720 {
721   assert (g->trace_fp == NULL);
722   g->trace_buf = NULL;
723   g->trace_len = 0;
724   g->trace_fp = open_memstream (&g->trace_buf, &g->trace_len);
725   if (g->trace_fp)
726     return g->trace_fp;
727   else
728     return stderr;
729 }
730
731 static void
732 trace_send_line (guestfs_h *g)
733 {
734   char *buf;
735   size_t len;
736
737   if (g->trace_fp) {
738     fclose (g->trace_fp);
739     g->trace_fp = NULL;
740
741     /* The callback might invoke other libguestfs calls, so keep
742      * a copy of the pointer to the buffer and length.
743      */
744     buf = g->trace_buf;
745     len = g->trace_len;
746     g->trace_buf = NULL;
747     guestfs___call_callbacks_message (g, GUESTFS_EVENT_TRACE, buf, len);
748
749     free (buf);
750   }
751 }
752
753 ";
754
755   (* Generate code to check String-like parameters are not passed in
756    * as NULL (returning an error if they are).
757    *)
758   let check_null_strings shortname (ret, args, optargs) =
759     let pr_newline = ref false in
760     List.iter (
761       function
762       (* parameters which should not be NULL *)
763       | String n
764       | Device n
765       | Pathname n
766       | Dev_or_Path n
767       | FileIn n
768       | FileOut n
769       | BufferIn n
770       | StringList n
771       | DeviceList n
772       | Key n
773       | Pointer (_, n) ->
774           pr "  if (%s == NULL) {\n" n;
775           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
776           pr "           \"%s\", \"%s\");\n" shortname n;
777           let errcode =
778             match errcode_of_ret ret with
779             | `CannotReturnError ->
780                 if shortname = "test0rconstoptstring" then (* XXX hack *)
781                   `ErrorIsNULL
782                 else
783                   failwithf
784                     "%s: RConstOptString function has invalid parameter '%s'"
785                     shortname n
786             | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
787           pr "    return %s;\n" (string_of_errcode errcode);
788           pr "  }\n";
789           pr_newline := true
790
791       (* can be NULL *)
792       | OptString _
793
794       (* not applicable *)
795       | Bool _
796       | Int _
797       | Int64 _ -> ()
798     ) args;
799
800     (* For optional arguments. *)
801     List.iter (
802       function
803       | String n ->
804           pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK) &&\n"
805             (String.uppercase shortname) (String.uppercase n);
806           pr "      optargs->%s == NULL) {\n" n;
807           pr "    error (g, \"%%s: %%s: optional parameter cannot be NULL\",\n";
808           pr "           \"%s\", \"%s\");\n" shortname n;
809           let errcode =
810             match errcode_of_ret ret with
811             | `CannotReturnError -> assert false
812             | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
813           pr "    return %s;\n" (string_of_errcode errcode);
814           pr "  }\n";
815           pr_newline := true
816
817       (* not applicable *)
818       | Bool _ | Int _ | Int64 _ -> ()
819
820       | _ -> assert false
821     ) optargs;
822
823     if !pr_newline then pr "\n";
824   in
825
826   (* Generate code to reject optargs we don't know about. *)
827   let reject_unknown_optargs shortname = function
828     | _, _, [] -> ()
829     | ret, _, optargs ->
830         let len = List.length optargs in
831         let mask = Int64.lognot (Int64.pred (Int64.shift_left 1L len)) in
832         pr "  if (optargs->bitmask & UINT64_C(0x%Lx)) {\n" mask;
833         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";
834         pr "           \"%s\", \"%s\");\n" shortname shortname;
835         let errcode =
836           match errcode_of_ret ret with
837           | `CannotReturnError -> assert false
838           | (`ErrorIsMinusOne |`ErrorIsNULL) as e -> e in
839         pr "    return %s;\n" (string_of_errcode errcode);
840         pr "  }\n";
841         pr "\n";
842   in
843
844   (* Generate code to generate guestfish call traces. *)
845   let trace_call shortname (ret, args, optargs) =
846     pr "  if (trace_flag) {\n";
847
848     let needs_i =
849       List.exists (function
850                    | StringList _ | DeviceList _ -> true
851                    | _ -> false) args in
852     if needs_i then (
853       pr "    size_t i;\n";
854       pr "\n"
855     );
856
857     pr "    trace_fp = trace_open (g);\n";
858
859     pr "    fprintf (trace_fp, \"%%s\", \"%s\");\n" shortname;
860
861     (* Required arguments. *)
862     List.iter (
863       function
864       | String n                        (* strings *)
865       | Device n
866       | Pathname n
867       | Dev_or_Path n
868       | FileIn n
869       | FileOut n ->
870           (* guestfish doesn't support string escaping, so neither do we *)
871           pr "    fprintf (trace_fp, \" \\\"%%s\\\"\", %s);\n" n
872       | Key n ->
873           (* don't print keys *)
874           pr "    fprintf (trace_fp, \" \\\"***\\\"\");\n"
875       | OptString n ->                  (* string option *)
876           pr "    if (%s) fprintf (trace_fp, \" \\\"%%s\\\"\", %s);\n" n n;
877           pr "    else fprintf (trace_fp, \" null\");\n"
878       | StringList n
879       | DeviceList n ->                 (* string list *)
880           pr "    fputc (' ', trace_fp);\n";
881           pr "    fputc ('\"', trace_fp);\n";
882           pr "    for (i = 0; %s[i]; ++i) {\n" n;
883           pr "      if (i > 0) fputc (' ', trace_fp);\n";
884           pr "      fputs (%s[i], trace_fp);\n" n;
885           pr "    }\n";
886           pr "    fputc ('\"', trace_fp);\n";
887       | Bool n ->                       (* boolean *)
888           pr "    fputs (%s ? \" true\" : \" false\", trace_fp);\n" n
889       | Int n ->                        (* int *)
890           pr "    fprintf (trace_fp, \" %%d\", %s);\n" n
891       | Int64 n ->
892           pr "    fprintf (trace_fp, \" %%\" PRIi64, %s);\n" n
893       | BufferIn n ->                   (* RHBZ#646822 *)
894           pr "    fputc (' ', trace_fp);\n";
895           pr "    guestfs___print_BufferIn (trace_fp, %s, %s_size);\n" n n
896       | Pointer (t, n) ->
897           pr "    fprintf (trace_fp, \" (%s)%%p\", %s);\n" t n
898     ) args;
899
900     (* Optional arguments. *)
901     List.iter (
902       fun argt ->
903         let n = name_of_argt argt in
904         let uc_shortname = String.uppercase shortname in
905         let uc_n = String.uppercase n in
906         pr "    if (optargs->bitmask & GUESTFS_%s_%s_BITMASK)\n"
907           uc_shortname uc_n;
908         (match argt with
909          | String n ->
910              pr "      fprintf (trace_fp, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s);\n" n n
911          | Bool n ->
912              pr "      fprintf (trace_fp, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s ? \"true\" : \"false\");\n" n n
913          | Int n ->
914              pr "      fprintf (trace_fp, \" \\\"%%s:%%d\\\"\", \"%s\", optargs->%s);\n" n n
915          | Int64 n ->
916              pr "      fprintf (trace_fp, \" \\\"%%s:%%\" PRIi64 \"\\\"\", \"%s\", optargs->%s);\n" n n
917          | _ -> assert false
918         );
919     ) optargs;
920
921     pr "    trace_send_line (g);\n";
922     pr "  }\n";
923     pr "\n";
924   in
925
926   let trace_return ?(indent = 2) shortname (ret, _, _) rv =
927     let indent = spaces indent in
928
929     pr "%sif (trace_flag) {\n" indent;
930
931     let needs_i =
932       match ret with
933       | RStringList _ | RHashtable _ -> true
934       | _ -> false in
935     if needs_i then (
936       pr "%s  size_t i;\n" indent;
937       pr "\n"
938     );
939
940     pr "%s  trace_fp = trace_open (g);\n" indent;
941
942     pr "%s  fprintf (trace_fp, \"%%s = \", \"%s\");\n" indent shortname;
943
944     (match ret with
945      | RErr | RInt _ | RBool _ ->
946          pr "%s  fprintf (trace_fp, \"%%d\", %s);\n" indent rv
947      | RInt64 _ ->
948          pr "%s  fprintf (trace_fp, \"%%\" PRIi64, %s);\n" indent rv
949      | RConstString _ | RString _ ->
950          pr "%s  fprintf (trace_fp, \"\\\"%%s\\\"\", %s);\n" indent rv
951      | RConstOptString _ ->
952          pr "%s  fprintf (trace_fp, \"\\\"%%s\\\"\", %s != NULL ? %s : \"NULL\");\n"
953            indent rv rv
954      | RBufferOut _ ->
955          pr "%s  guestfs___print_BufferOut (trace_fp, %s, *size_r);\n" indent rv
956      | RStringList _ | RHashtable _ ->
957          pr "%s  fputs (\"[\", trace_fp);\n" indent;
958          pr "%s  for (i = 0; %s[i]; ++i) {\n" indent rv;
959          pr "%s    if (i > 0) fputs (\", \", trace_fp);\n" indent;
960          pr "%s    fputs (\"\\\"\", trace_fp);\n" indent;
961          pr "%s    fputs (%s[i], trace_fp);\n" indent rv;
962          pr "%s    fputs (\"\\\"\", trace_fp);\n" indent;
963          pr "%s  }\n" indent;
964          pr "%s  fputs (\"]\", trace_fp);\n" indent;
965      | RStruct (_, typ) ->
966          (* XXX There is code generated for guestfish for printing
967           * these structures.  We need to make it generally available
968           * for all callers
969           *)
970          pr "%s  fprintf (trace_fp, \"<struct guestfs_%s *>\");\n"
971            indent typ (* XXX *)
972      | RStructList (_, typ) ->
973          pr "%s  fprintf (trace_fp, \"<struct guestfs_%s_list *>\");\n"
974            indent typ (* XXX *)
975     );
976     pr "%s  trace_send_line (g);\n" indent;
977     pr "%s}\n" indent;
978     pr "\n";
979   in
980
981   let trace_return_error ?(indent = 2) shortname (ret, _, _) errcode =
982     let indent = spaces indent in
983
984     pr "%sif (trace_flag)\n" indent;
985
986     pr "%s  guestfs___trace (g, \"%%s = %%s (error)\",\n" indent;
987     pr "%s                   \"%s\", \"%s\");\n"
988       indent shortname (string_of_errcode errcode)
989   in
990
991   (* For non-daemon functions, generate a wrapper around each function. *)
992   List.iter (
993     fun (shortname, (ret, _, optargs as style), _, _, _, _, _) ->
994       if optargs = [] then
995         generate_prototype ~extern:false ~semicolon:false ~newline:true
996           ~handle:"g" ~prefix:"guestfs_"
997           shortname style
998       else
999         generate_prototype ~extern:false ~semicolon:false ~newline:true
1000           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
1001           shortname style;
1002       pr "{\n";
1003       pr "  int trace_flag = g->trace;\n";
1004       pr "  FILE *trace_fp;\n";
1005       (match ret with
1006        | RErr | RInt _ | RBool _ ->
1007            pr "  int r;\n"
1008        | RInt64 _ ->
1009            pr "  int64_t r;\n"
1010        | RConstString _ ->
1011            pr "  const char *r;\n"
1012        | RConstOptString _ ->
1013            pr "  const char *r;\n"
1014        | RString _ | RBufferOut _ ->
1015            pr "  char *r;\n"
1016        | RStringList _ | RHashtable _ ->
1017            pr "  char **r;\n"
1018        | RStruct (_, typ) ->
1019            pr "  struct guestfs_%s *r;\n" typ
1020        | RStructList (_, typ) ->
1021            pr "  struct guestfs_%s_list *r;\n" typ
1022       );
1023       pr "\n";
1024       check_null_strings shortname style;
1025       reject_unknown_optargs shortname style;
1026       trace_call shortname style;
1027       pr "  r = guestfs__%s " shortname;
1028       generate_c_call_args ~handle:"g" style;
1029       pr ";\n";
1030       pr "\n";
1031       (match errcode_of_ret ret with
1032        | (`ErrorIsMinusOne | `ErrorIsNULL) as errcode ->
1033            pr "  if (r != %s) {\n" (string_of_errcode errcode);
1034            trace_return ~indent:4 shortname style "r";
1035            pr "  } else {\n";
1036            trace_return_error ~indent:4 shortname style errcode;
1037            pr "  }\n";
1038        | `CannotReturnError ->
1039            trace_return shortname style "r";
1040       );
1041       pr "\n";
1042       pr "  return r;\n";
1043       pr "}\n";
1044       pr "\n"
1045   ) non_daemon_functions;
1046
1047   (* Client-side stubs for each function. *)
1048   List.iter (
1049     fun (shortname, (ret, args, optargs as style), _, _, _, _, _) ->
1050       let name = "guestfs_" ^ shortname in
1051       let errcode =
1052         match errcode_of_ret ret with
1053         | `CannotReturnError -> assert false
1054         | (`ErrorIsMinusOne | `ErrorIsNULL) as e -> e in
1055
1056       (* Generate the action stub. *)
1057       if optargs = [] then
1058         generate_prototype ~extern:false ~semicolon:false ~newline:true
1059           ~handle:"g" ~prefix:"guestfs_" shortname style
1060       else
1061         generate_prototype ~extern:false ~semicolon:false ~newline:true
1062           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv"
1063           ~optarg_proto:Argv shortname style;
1064
1065       pr "{\n";
1066
1067       (match args with
1068        | [] -> ()
1069        | _ -> pr "  struct %s_args args;\n" name
1070       );
1071
1072       pr "  guestfs_message_header hdr;\n";
1073       pr "  guestfs_message_error err;\n";
1074       let has_ret =
1075         match ret with
1076         | RErr -> false
1077         | RConstString _ | RConstOptString _ ->
1078             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
1079         | RInt _ | RInt64 _
1080         | RBool _ | RString _ | RStringList _
1081         | RStruct _ | RStructList _
1082         | RHashtable _ | RBufferOut _ ->
1083             pr "  struct %s_ret ret;\n" name;
1084             true in
1085
1086       pr "  int serial;\n";
1087       pr "  int r;\n";
1088       pr "  int trace_flag = g->trace;\n";
1089       pr "  FILE *trace_fp;\n";
1090       (match ret with
1091        | RErr | RInt _ | RBool _ ->
1092            pr "  int ret_v;\n"
1093        | RInt64 _ ->
1094            pr "  int64_t ret_v;\n"
1095        | RConstString _ | RConstOptString _ ->
1096            pr "  const char *ret_v;\n"
1097        | RString _ | RBufferOut _ ->
1098            pr "  char *ret_v;\n"
1099        | RStringList _ | RHashtable _ ->
1100            pr "  char **ret_v;\n"
1101        | RStruct (_, typ) ->
1102            pr "  struct guestfs_%s *ret_v;\n" typ
1103        | RStructList (_, typ) ->
1104            pr "  struct guestfs_%s_list *ret_v;\n" typ
1105       );
1106
1107       let has_filein =
1108         List.exists (function FileIn _ -> true | _ -> false) args in
1109       if has_filein then (
1110         pr "  uint64_t progress_hint = 0;\n";
1111         pr "  struct stat progress_stat;\n";
1112       ) else
1113         pr "  const uint64_t progress_hint = 0;\n";
1114
1115       pr "\n";
1116       check_null_strings shortname style;
1117       reject_unknown_optargs shortname style;
1118       trace_call shortname style;
1119
1120       (* Calculate the total size of all FileIn arguments to pass
1121        * as a progress bar hint.
1122        *)
1123       List.iter (
1124         function
1125         | FileIn n ->
1126             pr "  if (stat (%s, &progress_stat) == 0 &&\n" n;
1127             pr "      S_ISREG (progress_stat.st_mode))\n";
1128             pr "    progress_hint += progress_stat.st_size;\n";
1129             pr "\n";
1130         | _ -> ()
1131       ) args;
1132
1133       (* Check we are in the right state for sending a request. *)
1134       pr "  if (check_state (g, \"%s\") == -1) {\n" shortname;
1135       trace_return_error ~indent:4 shortname style errcode;
1136       pr "    return %s;\n" (string_of_errcode errcode);
1137       pr "  }\n";
1138       pr "  guestfs___set_busy (g);\n";
1139       pr "\n";
1140
1141       (* Send the main header and arguments. *)
1142       if args = [] && optargs = [] then (
1143         pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, progress_hint, 0,\n"
1144           (String.uppercase shortname);
1145         pr "                           NULL, NULL);\n"
1146       ) else (
1147         List.iter (
1148           function
1149           | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
1150               pr "  args.%s = (char *) %s;\n" n n
1151           | OptString n ->
1152               pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
1153           | StringList n | DeviceList n ->
1154               pr "  args.%s.%s_val = (char **) %s;\n" n n n;
1155               pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
1156           | Bool n ->
1157               pr "  args.%s = %s;\n" n n
1158           | Int n ->
1159               pr "  args.%s = %s;\n" n n
1160           | Int64 n ->
1161               pr "  args.%s = %s;\n" n n
1162           | FileIn _ | FileOut _ -> ()
1163           | BufferIn n ->
1164               pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
1165               pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
1166               trace_return_error ~indent:4 shortname style errcode;
1167               pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
1168                 shortname;
1169               pr "    guestfs___end_busy (g);\n";
1170               pr "    return %s;\n" (string_of_errcode errcode);
1171               pr "  }\n";
1172               pr "  args.%s.%s_val = (char *) %s;\n" n n n;
1173               pr "  args.%s.%s_len = %s_size;\n" n n n
1174           | Pointer _ -> assert false
1175         ) args;
1176
1177         List.iter (
1178           fun argt ->
1179             let n = name_of_argt argt in
1180             let uc_shortname = String.uppercase shortname in
1181             let uc_n = String.uppercase n in
1182             pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK))\n"
1183               uc_shortname uc_n;
1184             (match argt with
1185              | Bool n
1186              | Int n
1187              | Int64 n ->
1188                  pr "    args.%s = optargs->%s;\n" n n;
1189                  pr "  else\n";
1190                  pr "    args.%s = 0;\n" n
1191              | String n ->
1192                  pr "    args.%s = (char *) optargs->%s;\n" n n;
1193                  pr "  else\n";
1194                  pr "    args.%s = (char *) \"\";\n" n
1195              | _ -> assert false
1196             )
1197         ) optargs;
1198
1199         pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
1200           (String.uppercase shortname);
1201         pr "                           progress_hint, %s,\n"
1202           (if optargs <> [] then "optargs->bitmask" else "0");
1203         pr "                           (xdrproc_t) xdr_%s_args, (char *) &args);\n"
1204           name;
1205       );
1206       pr "  if (serial == -1) {\n";
1207       pr "    guestfs___end_busy (g);\n";
1208       trace_return_error ~indent:4 shortname style errcode;
1209       pr "    return %s;\n" (string_of_errcode errcode);
1210       pr "  }\n";
1211       pr "\n";
1212
1213       (* Send any additional files (FileIn) requested. *)
1214       let need_read_reply_label = ref false in
1215       List.iter (
1216         function
1217         | FileIn n ->
1218             pr "  r = guestfs___send_file (g, %s);\n" n;
1219             pr "  if (r == -1) {\n";
1220             pr "    guestfs___end_busy (g);\n";
1221             trace_return_error ~indent:4 shortname style errcode;
1222             pr "    /* daemon will send an error reply which we discard */\n";
1223             pr "    guestfs___recv_discard (g, \"%s\");\n" shortname;
1224             pr "    return %s;\n" (string_of_errcode errcode);
1225             pr "  }\n";
1226             pr "  if (r == -2) /* daemon cancelled */\n";
1227             pr "    goto read_reply;\n";
1228             need_read_reply_label := true;
1229             pr "\n";
1230         | _ -> ()
1231       ) args;
1232
1233       (* Wait for the reply from the remote end. *)
1234       if !need_read_reply_label then pr " read_reply:\n";
1235       pr "  memset (&hdr, 0, sizeof hdr);\n";
1236       pr "  memset (&err, 0, sizeof err);\n";
1237       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
1238       pr "\n";
1239       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
1240       if not has_ret then
1241         pr "NULL, NULL"
1242       else
1243         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
1244       pr ");\n";
1245
1246       pr "  if (r == -1) {\n";
1247       pr "    guestfs___end_busy (g);\n";
1248       trace_return_error ~indent:4 shortname style errcode;
1249       pr "    return %s;\n" (string_of_errcode errcode);
1250       pr "  }\n";
1251       pr "\n";
1252
1253       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
1254         (String.uppercase shortname);
1255       pr "    guestfs___end_busy (g);\n";
1256       trace_return_error ~indent:4 shortname style errcode;
1257       pr "    return %s;\n" (string_of_errcode errcode);
1258       pr "  }\n";
1259       pr "\n";
1260
1261       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
1262       trace_return_error ~indent:4 shortname style errcode;
1263       pr "    int errnum = 0;\n";
1264       pr "    if (err.errno_string[0] != '\\0')\n";
1265       pr "      errnum = guestfs___string_to_errno (err.errno_string);\n";
1266       pr "    if (errnum <= 0)\n";
1267       pr "      error (g, \"%%s: %%s\", \"%s\", err.error_message);\n"
1268         shortname;
1269       pr "    else\n";
1270       pr "      guestfs_error_errno (g, errnum, \"%%s: %%s\", \"%s\",\n"
1271         shortname;
1272       pr "                           err.error_message);\n";
1273       pr "    free (err.error_message);\n";
1274       pr "    free (err.errno_string);\n";
1275       pr "    guestfs___end_busy (g);\n";
1276       pr "    return %s;\n" (string_of_errcode errcode);
1277       pr "  }\n";
1278       pr "\n";
1279
1280       (* Expecting to receive further files (FileOut)? *)
1281       List.iter (
1282         function
1283         | FileOut n ->
1284             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
1285             pr "    guestfs___end_busy (g);\n";
1286             trace_return_error ~indent:4 shortname style errcode;
1287             pr "    return %s;\n" (string_of_errcode errcode);
1288             pr "  }\n";
1289             pr "\n";
1290         | _ -> ()
1291       ) args;
1292
1293       pr "  guestfs___end_busy (g);\n";
1294
1295       (match ret with
1296        | RErr ->
1297            pr "  ret_v = 0;\n"
1298        | RInt n | RInt64 n | RBool n ->
1299            pr "  ret_v = ret.%s;\n" n
1300        | RConstString _ | RConstOptString _ ->
1301            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
1302        | RString n ->
1303            pr "  ret_v = ret.%s; /* caller will free */\n" n
1304        | RStringList n | RHashtable n ->
1305            pr "  /* caller will free this, but we need to add a NULL entry */\n";
1306            pr "  ret.%s.%s_val =\n" n n;
1307            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
1308            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
1309              n n;
1310            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
1311            pr "  ret_v = ret.%s.%s_val;\n" n n
1312        | RStruct (n, _) ->
1313            pr "  /* caller will free this */\n";
1314            pr "  ret_v = safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
1315        | RStructList (n, _) ->
1316            pr "  /* caller will free this */\n";
1317            pr "  ret_v = safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
1318        | RBufferOut n ->
1319            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
1320            pr "   * _val might be NULL here.  To make the API saner for\n";
1321            pr "   * callers, we turn this case into a unique pointer (using\n";
1322            pr "   * malloc(1)).\n";
1323            pr "   */\n";
1324            pr "  if (ret.%s.%s_len > 0) {\n" n n;
1325            pr "    *size_r = ret.%s.%s_len;\n" n n;
1326            pr "    ret_v = ret.%s.%s_val; /* caller will free */\n" n n;
1327            pr "  } else {\n";
1328            pr "    free (ret.%s.%s_val);\n" n n;
1329            pr "    char *p = safe_malloc (g, 1);\n";
1330            pr "    *size_r = ret.%s.%s_len;\n" n n;
1331            pr "    ret_v = p;\n";
1332            pr "  }\n";
1333       );
1334       trace_return shortname style "ret_v";
1335       pr "  return ret_v;\n";
1336       pr "}\n\n"
1337   ) daemon_functions;
1338
1339   (* Functions to free structures. *)
1340   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
1341   pr " * structure format is identical to the XDR format.  See note in\n";
1342   pr " * generator.ml.\n";
1343   pr " */\n";
1344   pr "\n";
1345
1346   List.iter (
1347     fun (typ, _) ->
1348       pr "void\n";
1349       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
1350       pr "{\n";
1351       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
1352       pr "  free (x);\n";
1353       pr "}\n";
1354       pr "\n";
1355
1356       pr "void\n";
1357       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
1358       pr "{\n";
1359       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
1360       pr "  free (x);\n";
1361       pr "}\n";
1362       pr "\n";
1363
1364   ) structs;
1365
1366   (* Functions which have optional arguments have two generated variants. *)
1367   List.iter (
1368     function
1369     | shortname, (ret, args, (_::_ as optargs) as style), _, _, _, _, _ ->
1370         let uc_shortname = String.uppercase shortname in
1371
1372         (* Get the name of the last regular argument. *)
1373         let last_arg =
1374           match args with
1375           | [] -> "g"
1376           | args -> name_of_argt (List.hd (List.rev args)) in
1377
1378         let rtype =
1379           match ret with
1380           | RErr | RInt _ | RBool _ -> "int "
1381           | RInt64 _ -> "int64_t "
1382           | RConstString _ | RConstOptString _ -> "const char *"
1383           | RString _ | RBufferOut _ -> "char *"
1384           | RStringList _ | RHashtable _ -> "char **"
1385           | RStruct (_, typ) -> sprintf "struct guestfs_%s *" typ
1386           | RStructList (_, typ) ->
1387               sprintf "struct guestfs_%s_list *" typ in
1388
1389         (* The regular variable args function, just calls the _va variant. *)
1390         generate_prototype ~extern:false ~semicolon:false ~newline:true
1391           ~handle:"g" ~prefix:"guestfs_" shortname style;
1392         pr "{\n";
1393         pr "  va_list optargs;\n";
1394         pr "\n";
1395         pr "  va_start (optargs, %s);\n" last_arg;
1396         pr "  %sr = guestfs_%s_va " rtype shortname;
1397         generate_c_call_args ~handle:"g" style;
1398         pr ";\n";
1399         pr "  va_end (optargs);\n";
1400         pr "\n";
1401         pr "  return r;\n";
1402         pr "}\n\n";
1403
1404         generate_prototype ~extern:false ~semicolon:false ~newline:true
1405           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
1406           shortname style;
1407         pr "{\n";
1408         pr "  struct guestfs_%s_argv optargs_s;\n" shortname;
1409         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" shortname;
1410         pr "  int i;\n";
1411         pr "\n";
1412         pr "  optargs_s.bitmask = 0;\n";
1413         pr "\n";
1414         pr "  while ((i = va_arg (args, int)) >= 0) {\n";
1415         pr "    switch (i) {\n";
1416
1417         List.iter (
1418           fun argt ->
1419             let n = name_of_argt argt in
1420             let uc_n = String.uppercase n in
1421             pr "    case GUESTFS_%s_%s:\n" uc_shortname uc_n;
1422             pr "      optargs_s.%s = va_arg (args, " n;
1423             (match argt with
1424              | Bool _ | Int _ -> pr "int"
1425              | Int64 _ -> pr "int64_t"
1426              | String _ -> pr "const char *"
1427              | _ -> assert false
1428             );
1429             pr ");\n";
1430             pr "      break;\n";
1431         ) optargs;
1432
1433         let errcode =
1434           match errcode_of_ret ret with
1435           | `CannotReturnError -> assert false
1436           | (`ErrorIsMinusOne | `ErrorIsNULL) as e -> e in
1437
1438         pr "    default:\n";
1439         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";
1440         pr "             \"%s\", i);\n" shortname;
1441         pr "      return %s;\n" (string_of_errcode errcode);
1442         pr "    }\n";
1443         pr "\n";
1444         pr "    uint64_t i_mask = UINT64_C(1) << i;\n";
1445         pr "    if (optargs_s.bitmask & i_mask) {\n";
1446         pr "      error (g, \"%%s: same optional argument specified more than once\",\n";
1447         pr "             \"%s\");\n" shortname;
1448         pr "      return %s;\n" (string_of_errcode errcode);
1449         pr "    }\n";
1450         pr "    optargs_s.bitmask |= i_mask;\n";
1451         pr "  }\n";
1452         pr "\n";
1453         pr "  return guestfs_%s_argv " shortname;
1454         generate_c_call_args ~handle:"g" style;
1455         pr ";\n";
1456         pr "}\n\n"
1457     | _ -> ()
1458   ) all_functions_sorted
1459
1460 (* Generate the linker script which controls the visibility of
1461  * symbols in the public ABI and ensures no other symbols get
1462  * exported accidentally.
1463  *)
1464 and generate_linker_script () =
1465   generate_header HashStyle GPLv2plus;
1466
1467   let globals = [
1468     "guestfs_create";
1469     "guestfs_close";
1470     "guestfs_delete_event_callback";
1471     "guestfs_first_private";
1472     "guestfs_get_error_handler";
1473     "guestfs_get_out_of_memory_handler";
1474     "guestfs_get_private";
1475     "guestfs_last_errno";
1476     "guestfs_last_error";
1477     "guestfs_next_private";
1478     "guestfs_set_close_callback";
1479     "guestfs_set_error_handler";
1480     "guestfs_set_event_callback";
1481     "guestfs_set_launch_done_callback";
1482     "guestfs_set_log_message_callback";
1483     "guestfs_set_out_of_memory_handler";
1484     "guestfs_set_private";
1485     "guestfs_set_progress_callback";
1486     "guestfs_set_subprocess_quit_callback";
1487
1488     (* Unofficial parts of the API: the bindings code use these
1489      * functions, so it is useful to export them.
1490      *)
1491     "guestfs_safe_calloc";
1492     "guestfs_safe_malloc";
1493     "guestfs_safe_strdup";
1494     "guestfs_safe_memdup";
1495     "guestfs_tmpdir";
1496     "guestfs___for_each_disk";
1497   ] in
1498   let functions =
1499     List.flatten (
1500       List.map (
1501         function
1502         | name, (_, _, []), _, _, _, _, _ -> ["guestfs_" ^ name]
1503         | name, (_, _, _), _, _, _, _, _ ->
1504             ["guestfs_" ^ name;
1505              "guestfs_" ^ name ^ "_va";
1506              "guestfs_" ^ name ^ "_argv"]
1507       ) all_functions
1508     ) in
1509   let structs =
1510     List.concat (
1511       List.map (fun (typ, _) ->
1512                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
1513         structs
1514     ) in
1515   let globals = List.sort compare (globals @ functions @ structs) in
1516
1517   pr "{\n";
1518   pr "    global:\n";
1519   List.iter (pr "        %s;\n") globals;
1520   pr "\n";
1521
1522   pr "    local:\n";
1523   pr "        *;\n";
1524   pr "};\n"
1525
1526 and generate_max_proc_nr () =
1527   pr "%d\n" max_proc_nr