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