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