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