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