ocaml: Error on compiler warnings.
[libguestfs.git] / generator / generator_c.ml
1 (* libguestfs
2  * Copyright (C) 2009-2010 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     ) args;
120     if is_RBufferOut then (next (); pr "size_t *size_r");
121     if optargs <> [] then (
122       next ();
123       match optarg_proto with
124       | Dots -> pr "..."
125       | VA -> pr "va_list args"
126       | Argv -> pr "const struct guestfs_%s_argv *optargs" name
127     );
128   );
129   pr ")";
130   if semicolon then pr ";";
131   if newline then pr "\n"
132
133 (* Generate C call arguments, eg "(handle, foo, bar)" *)
134 and generate_c_call_args ?handle (ret, args, optargs) =
135   pr "(";
136   let comma = ref false in
137   let next () =
138     if !comma then pr ", ";
139     comma := true
140   in
141   (match handle with
142    | None -> ()
143    | Some handle -> pr "%s" handle; comma := true
144   );
145   List.iter (
146     function
147     | BufferIn n ->
148         next ();
149         pr "%s, %s_size" n n
150     | arg ->
151         next ();
152         pr "%s" (name_of_argt arg)
153   ) args;
154   (* For RBufferOut calls, add implicit &size parameter. *)
155   (match ret with
156    | RBufferOut _ ->
157        next ();
158        pr "&size"
159    | _ -> ()
160   );
161   (* For calls with optional arguments, add implicit optargs parameter. *)
162   if optargs <> [] then (
163     next ();
164     pr "optargs"
165   );
166   pr ")"
167
168 (* Generate the pod documentation for the C API. *)
169 and generate_actions_pod () =
170   List.iter (
171     fun (shortname, (ret, args, optargs as style), _, flags, _, _, longdesc) ->
172       if not (List.mem NotInDocs flags) then (
173         let name = "guestfs_" ^ shortname in
174         pr "=head2 %s\n\n" name;
175         generate_prototype ~extern:false ~indent:" " ~handle:"g" name style;
176         pr "\n\n";
177
178         let uc_shortname = String.uppercase shortname in
179         if optargs <> [] then (
180           pr "You may supply a list of optional arguments to this call.\n";
181           pr "Use zero or more of the following pairs of parameters,\n";
182           pr "and terminate the list with C<-1> on its own.\n";
183           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
184           List.iter (
185             fun argt ->
186               let n = name_of_argt argt in
187               let uc_n = String.uppercase n in
188               pr " GUESTFS_%s_%s, " uc_shortname uc_n;
189               match argt with
190               | Bool n -> pr "int %s,\n" n
191               | Int n -> pr "int %s,\n" n
192               | Int64 n -> pr "int64_t %s,\n" n
193               | String n -> pr "const char *%s,\n" n
194               | _ -> assert false
195           ) optargs;
196           pr "\n";
197         );
198
199         pr "%s\n\n" longdesc;
200         let ret, args, optargs = style in
201         (match ret with
202          | RErr ->
203              pr "This function returns 0 on success or -1 on error.\n\n"
204          | RInt _ ->
205              pr "On error this function returns -1.\n\n"
206          | RInt64 _ ->
207              pr "On error this function returns -1.\n\n"
208          | RBool _ ->
209              pr "This function returns a C truth value on success or -1 on error.\n\n"
210          | RConstString _ ->
211              pr "This function returns a string, or NULL on error.
212 The string is owned by the guest handle and must I<not> be freed.\n\n"
213          | RConstOptString _ ->
214              pr "This function returns a string which may be NULL.
215 There is no way to return an error from this function.
216 The string is owned by the guest handle and must I<not> be freed.\n\n"
217          | RString _ ->
218              pr "This function returns a string, or NULL on error.
219 I<The caller must free the returned string after use>.\n\n"
220          | RStringList _ ->
221              pr "This function returns a NULL-terminated array of strings
222 (like L<environ(3)>), or NULL if there was an error.
223 I<The caller must free the strings and the array after use>.\n\n"
224          | RStruct (_, typ) ->
225              pr "This function returns a C<struct guestfs_%s *>,
226 or NULL if there was an error.
227 I<The caller must call C<guestfs_free_%s> after use>.\n\n" typ typ
228          | RStructList (_, typ) ->
229              pr "This function returns a C<struct guestfs_%s_list *>
230 (see E<lt>guestfs-structs.hE<gt>),
231 or NULL if there was an error.
232 I<The caller must call C<guestfs_free_%s_list> after use>.\n\n" typ typ
233          | RHashtable _ ->
234              pr "This function returns a NULL-terminated array of
235 strings, or NULL if there was an error.
236 The array of strings will always have length C<2n+1>, where
237 C<n> keys and values alternate, followed by the trailing NULL entry.
238 I<The caller must free the strings and the array after use>.\n\n"
239          | RBufferOut _ ->
240              pr "This function returns a buffer, or NULL on error.
241 The size of the returned buffer is written to C<*size_r>.
242 I<The caller must free the returned buffer after use>.\n\n"
243         );
244         if List.mem Progress flags then
245           pr "%s\n\n" progress_message;
246         if List.mem ProtocolLimitWarning flags then
247           pr "%s\n\n" protocol_limit_warning;
248         if List.mem DangerWillRobinson flags then
249           pr "%s\n\n" danger_will_robinson;
250         if List.exists (function Key _ -> true | _ -> false) (args@optargs) then
251           pr "This function takes a key or passphrase parameter which
252 could contain sensitive material.  Read the section
253 L</KEYS AND PASSPHRASES> for more information.\n\n";
254         (match deprecation_notice flags with
255          | None -> ()
256          | Some txt -> pr "%s\n\n" txt
257         );
258         (match lookup_api_version name with
259          | Some version -> pr "(Added in %s)\n\n" version
260          | None -> ()
261         );
262
263         (* Handling of optional argument variants. *)
264         if optargs <> [] then (
265           pr "=head2 %s_va\n\n" name;
266           generate_prototype ~extern:false ~indent:" " ~handle:"g"
267             ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
268             shortname style;
269           pr "\n\n";
270           pr "This is the \"va_list variant\" of L</%s>.\n\n" name;
271           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
272           pr "=head2 %s_argv\n\n" name;
273           generate_prototype ~extern:false ~indent:" " ~handle:"g"
274             ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
275             shortname style;
276           pr "\n\n";
277           pr "This is the \"argv variant\" of L</%s>.\n\n" name;
278           pr "See L</CALLS WITH OPTIONAL ARGUMENTS>.\n\n";
279         );
280       )
281   ) all_functions_sorted
282
283 and generate_structs_pod () =
284   (* Structs documentation. *)
285   List.iter (
286     fun (typ, cols) ->
287       pr "=head2 guestfs_%s\n" typ;
288       pr "\n";
289       pr " struct guestfs_%s {\n" typ;
290       List.iter (
291         function
292         | name, FChar -> pr "   char %s;\n" name
293         | name, FUInt32 -> pr "   uint32_t %s;\n" name
294         | name, FInt32 -> pr "   int32_t %s;\n" name
295         | name, (FUInt64|FBytes) -> pr "   uint64_t %s;\n" name
296         | name, FInt64 -> pr "   int64_t %s;\n" name
297         | name, FString -> pr "   char *%s;\n" name
298         | name, FBuffer ->
299             pr "   /* The next two fields describe a byte array. */\n";
300             pr "   uint32_t %s_len;\n" name;
301             pr "   char *%s;\n" name
302         | name, FUUID ->
303             pr "   /* The next field is NOT nul-terminated, be careful when printing it: */\n";
304             pr "   char %s[32];\n" name
305         | name, FOptPercent ->
306             pr "   /* The next field is [0..100] or -1 meaning 'not present': */\n";
307             pr "   float %s;\n" name
308       ) cols;
309       pr " };\n";
310       pr " \n";
311       pr " struct guestfs_%s_list {\n" typ;
312       pr "   uint32_t len; /* Number of elements in list. */\n";
313       pr "   struct guestfs_%s *val; /* Elements. */\n" typ;
314       pr " };\n";
315       pr " \n";
316       pr " void guestfs_free_%s (struct guestfs_free_%s *);\n" typ typ;
317       pr " void guestfs_free_%s_list (struct guestfs_free_%s_list *);\n"
318         typ typ;
319       pr "\n"
320   ) structs
321
322 and generate_availability_pod () =
323   (* Availability documentation. *)
324   pr "=over 4\n";
325   pr "\n";
326   List.iter (
327     fun (group, functions) ->
328       pr "=item B<%s>\n" group;
329       pr "\n";
330       pr "The following functions:\n";
331       List.iter (pr "L</guestfs_%s>\n") functions;
332       pr "\n"
333   ) optgroups;
334   pr "=back\n";
335   pr "\n"
336
337 (* Generate the guestfs-structs.h file. *)
338 and generate_structs_h () =
339   generate_header CStyle LGPLv2plus;
340
341   (* This is a public exported header file containing various
342    * structures.  The structures are carefully written to have
343    * exactly the same in-memory format as the XDR structures that
344    * we use on the wire to the daemon.  The reason for creating
345    * copies of these structures here is just so we don't have to
346    * export the whole of guestfs_protocol.h (which includes much
347    * unrelated and XDR-dependent stuff that we don't want to be
348    * public, or required by clients).
349    *
350    * To reiterate, we will pass these structures to and from the
351    * client with a simple assignment or memcpy, so the format
352    * must be identical to what rpcgen / the RFC defines.
353    *)
354
355   (* Public structures. *)
356   List.iter (
357     fun (typ, cols) ->
358       pr "struct guestfs_%s {\n" typ;
359       List.iter (
360         function
361         | name, FChar -> pr "  char %s;\n" name
362         | name, FString -> pr "  char *%s;\n" name
363         | name, FBuffer ->
364             pr "  uint32_t %s_len;\n" name;
365             pr "  char *%s;\n" name
366         | name, FUUID -> pr "  char %s[32]; /* this is NOT nul-terminated, be careful when printing */\n" name
367         | name, FUInt32 -> pr "  uint32_t %s;\n" name
368         | name, FInt32 -> pr "  int32_t %s;\n" name
369         | name, (FUInt64|FBytes) -> pr "  uint64_t %s;\n" name
370         | name, FInt64 -> pr "  int64_t %s;\n" name
371         | name, FOptPercent -> pr "  float %s; /* [0..100] or -1 */\n" name
372       ) cols;
373       pr "};\n";
374       pr "\n";
375       pr "struct guestfs_%s_list {\n" typ;
376       pr "  uint32_t len;\n";
377       pr "  struct guestfs_%s *val;\n" typ;
378       pr "};\n";
379       pr "\n";
380       pr "extern void guestfs_free_%s (struct guestfs_%s *);\n" typ typ;
381       pr "extern void guestfs_free_%s_list (struct guestfs_%s_list *);\n" typ typ;
382       pr "\n"
383   ) structs
384
385 (* Generate the guestfs-actions.h file. *)
386 and generate_actions_h () =
387   generate_header CStyle LGPLv2plus;
388   List.iter (
389     fun (shortname, (ret, args, optargs as style), _, flags, _, _, _) ->
390       let deprecated =
391         List.exists (function DeprecatedBy _ -> true | _ -> false) flags in
392       let test0 =
393         String.length shortname >= 5 && String.sub shortname 0 5 = "test0" in
394       let debug =
395         String.length shortname >= 5 && String.sub shortname 0 5 = "debug" in
396       if not deprecated && not test0 && not debug then
397         pr "#define LIBGUESTFS_HAVE_%s 1\n" (String.uppercase shortname);
398
399       generate_prototype ~single_line:true ~newline:true ~handle:"g"
400         ~prefix:"guestfs_" shortname style;
401
402       if optargs <> [] then (
403         generate_prototype ~single_line:true ~newline:true ~handle:"g"
404           ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
405           shortname style;
406
407         pr "struct guestfs_%s_argv {\n" shortname;
408         pr "  uint64_t bitmask;\n";
409         iteri (
410           fun i argt ->
411             let c_type =
412               match argt with
413               | Bool n -> "int "
414               | Int n -> "int64_t "
415               | Int64 n -> "int "
416               | String n -> "const char *"
417               | _ -> assert false (* checked in generator_checks *) in
418             let uc_shortname = String.uppercase shortname in
419             let n = name_of_argt argt in
420             let uc_n = String.uppercase n in
421             pr "#define GUESTFS_%s_%s %d\n" uc_shortname uc_n i;
422             pr "#define GUESTFS_%s_%s_BITMASK (UINT64_C(1)<<%d)\n" uc_shortname uc_n i;
423             pr "/* The field below is only valid in this struct if the\n";
424             pr " * GUESTFS_%s_%s_BITMASK bit is set\n" uc_shortname uc_n;
425             pr " * in the bitmask above, otherwise the contents are ignored.\n";
426             pr " */\n";
427             pr "  %s%s;\n" c_type n
428         ) optargs;
429         pr "};\n";
430
431         generate_prototype ~single_line:true ~newline:true ~handle:"g"
432           ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
433           shortname style;
434       );
435   ) all_functions_sorted
436
437 (* Generate the guestfs-internal-actions.h file. *)
438 and generate_internal_actions_h () =
439   generate_header CStyle LGPLv2plus;
440   List.iter (
441     fun (shortname, style, _, _, _, _, _) ->
442       generate_prototype ~single_line:true ~newline:true ~handle:"g"
443         ~prefix:"guestfs__" ~optarg_proto:Argv
444         shortname style
445   ) non_daemon_functions
446
447 (* Generate the client-side dispatch stubs. *)
448 and generate_client_actions () =
449   generate_header CStyle LGPLv2plus;
450
451   pr "\
452 #include <stdio.h>
453 #include <stdlib.h>
454 #include <stdint.h>
455 #include <string.h>
456 #include <inttypes.h>
457
458 #include \"guestfs.h\"
459 #include \"guestfs-internal.h\"
460 #include \"guestfs-internal-actions.h\"
461 #include \"guestfs_protocol.h\"
462 #include \"errnostring.h\"
463
464 /* Check the return message from a call for validity. */
465 static int
466 check_reply_header (guestfs_h *g,
467                     const struct guestfs_message_header *hdr,
468                     unsigned int proc_nr, unsigned int serial)
469 {
470   if (hdr->prog != GUESTFS_PROGRAM) {
471     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
472     return -1;
473   }
474   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
475     error (g, \"wrong protocol version (%%d/%%d)\",
476            hdr->vers, GUESTFS_PROTOCOL_VERSION);
477     return -1;
478   }
479   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
480     error (g, \"unexpected message direction (%%d/%%d)\",
481            hdr->direction, GUESTFS_DIRECTION_REPLY);
482     return -1;
483   }
484   if (hdr->proc != proc_nr) {
485     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
486     return -1;
487   }
488   if (hdr->serial != serial) {
489     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
490     return -1;
491   }
492
493   return 0;
494 }
495
496 /* Check we are in the right state to run a high-level action. */
497 static int
498 check_state (guestfs_h *g, const char *caller)
499 {
500   if (!guestfs__is_ready (g)) {
501     if (guestfs__is_config (g) || guestfs__is_launching (g))
502       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
503         caller);
504     else
505       error (g, \"%%s called from the wrong state, %%d != READY\",
506         caller, guestfs__get_state (g));
507     return -1;
508   }
509   return 0;
510 }
511
512 ";
513
514   let error_code_of = function
515     | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
516     | RConstString _ | RConstOptString _
517     | RString _ | RStringList _
518     | RStruct _ | RStructList _
519     | RHashtable _ | RBufferOut _ -> "NULL"
520   in
521
522   (* Generate code to check String-like parameters are not passed in
523    * as NULL (returning an error if they are).
524    *)
525   let check_null_strings shortname (ret, args, optargs) =
526     let pr_newline = ref false in
527     List.iter (
528       function
529       (* parameters which should not be NULL *)
530       | String n
531       | Device n
532       | Pathname n
533       | Dev_or_Path n
534       | FileIn n
535       | FileOut n
536       | BufferIn n
537       | StringList n
538       | DeviceList n
539       | Key n ->
540           pr "  if (%s == NULL) {\n" n;
541           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
542           pr "           \"%s\", \"%s\");\n" shortname n;
543           pr "    return %s;\n" (error_code_of ret);
544           pr "  }\n";
545           pr_newline := true
546
547       (* can be NULL *)
548       | OptString _
549
550       (* not applicable *)
551       | Bool _
552       | Int _
553       | Int64 _ -> ()
554     ) args;
555
556     (* For optional arguments. *)
557     List.iter (
558       function
559       | String n ->
560           pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK) &&\n"
561             (String.uppercase shortname) (String.uppercase n);
562           pr "      optargs->%s == NULL) {\n" n;
563           pr "    error (g, \"%%s: %%s: optional parameter cannot be NULL\",\n";
564           pr "           \"%s\", \"%s\");\n" shortname n;
565           pr "    return %s;\n" (error_code_of ret);
566           pr "  }\n";
567           pr_newline := true
568
569       (* not applicable *)
570       | Bool _ | Int _ | Int64 _ -> ()
571
572       | _ -> assert false
573     ) optargs;
574
575     if !pr_newline then pr "\n";
576   in
577
578   (* Generate code to reject optargs we don't know about. *)
579   let reject_unknown_optargs shortname = function
580     | _, _, [] -> ()
581     | ret, _, optargs ->
582         let len = List.length optargs in
583         let mask = Int64.lognot (Int64.pred (Int64.shift_left 1L len)) in
584         pr "  if (optargs->bitmask & UINT64_C(0x%Lx)) {\n" mask;
585         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";
586         pr "           \"%s\", \"%s\");\n" shortname shortname;
587         pr "    return %s;\n" (error_code_of ret);
588         pr "  }\n";
589         pr "\n";
590   in
591
592   (* Generate code to generate guestfish call traces. *)
593   let trace_call shortname (ret, args, optargs) =
594     pr "  if (guestfs__get_trace (g)) {\n";
595
596     let needs_i =
597       List.exists (function
598                    | StringList _ | DeviceList _ -> true
599                    | _ -> false) args in
600     if needs_i then (
601       pr "    size_t i;\n";
602       pr "\n"
603     );
604
605     pr "    fprintf (stderr, \"%s\");\n" shortname;
606
607     (* Required arguments. *)
608     List.iter (
609       function
610       | String n                        (* strings *)
611       | Device n
612       | Pathname n
613       | Dev_or_Path n
614       | FileIn n
615       | FileOut n ->
616           (* guestfish doesn't support string escaping, so neither do we *)
617           pr "    fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
618       | Key n ->
619           (* don't print keys *)
620           pr "    fprintf (stderr, \" \\\"***\\\"\");\n"
621       | OptString n ->                  (* string option *)
622           pr "    if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
623           pr "    else fprintf (stderr, \" null\");\n"
624       | StringList n
625       | DeviceList n ->                 (* string list *)
626           pr "    fputc (' ', stderr);\n";
627           pr "    fputc ('\"', stderr);\n";
628           pr "    for (i = 0; %s[i]; ++i) {\n" n;
629           pr "      if (i > 0) fputc (' ', stderr);\n";
630           pr "      fputs (%s[i], stderr);\n" n;
631           pr "    }\n";
632           pr "    fputc ('\"', stderr);\n";
633       | Bool n ->                       (* boolean *)
634           pr "    fputs (%s ? \" true\" : \" false\", stderr);\n" n
635       | Int n ->                        (* int *)
636           pr "    fprintf (stderr, \" %%d\", %s);\n" n
637       | Int64 n ->
638           pr "    fprintf (stderr, \" %%\" PRIi64, %s);\n" n
639       | BufferIn n ->                   (* RHBZ#646822 *)
640           pr "    fputc (' ', stderr);\n";
641           pr "    guestfs___print_BufferIn (stderr, %s, %s_size);\n" n n
642     ) args;
643
644     (* Optional arguments. *)
645     List.iter (
646       fun argt ->
647         let n = name_of_argt argt in
648         let uc_shortname = String.uppercase shortname in
649         let uc_n = String.uppercase n in
650         pr "    if (optargs->bitmask & GUESTFS_%s_%s_BITMASK)\n"
651           uc_shortname uc_n;
652         (match argt with
653          | String n ->
654              pr "      fprintf (stderr, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s);\n" n n
655          | Bool n ->
656              pr "      fprintf (stderr, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s ? \"true\" : \"false\");\n" n n
657          | Int n ->
658              pr "      fprintf (stderr, \" \\\"%%s:%%d\\\"\", \"%s\", optargs->%s);\n" n n
659          | Int64 n ->
660              pr "      fprintf (stderr, \" \\\"%%s:%%\" PRIi64 \"\\\"\", \"%s\", optargs->%s);\n" n n
661          | _ -> assert false
662         );
663     ) optargs;
664
665     pr "    fputc ('\\n', stderr);\n";
666     pr "  }\n";
667     pr "\n";
668   in
669
670   (* For non-daemon functions, generate a wrapper around each function. *)
671   List.iter (
672     fun (shortname, (_, _, optargs as style), _, _, _, _, _) ->
673       if optargs = [] then
674         generate_prototype ~extern:false ~semicolon:false ~newline:true
675           ~handle:"g" ~prefix:"guestfs_"
676           shortname style
677       else
678         generate_prototype ~extern:false ~semicolon:false ~newline:true
679           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
680           shortname style;
681       pr "{\n";
682       check_null_strings shortname style;
683       reject_unknown_optargs shortname style;
684       trace_call shortname style;
685       pr "  return guestfs__%s " shortname;
686       generate_c_call_args ~handle:"g" style;
687       pr ";\n";
688       pr "}\n";
689       pr "\n"
690   ) non_daemon_functions;
691
692   (* Client-side stubs for each function. *)
693   List.iter (
694     fun (shortname, (ret, args, optargs as style), _, _, _, _, _) ->
695       if optargs <> [] then
696         failwithf "optargs not yet implemented for daemon functions";
697
698       let name = "guestfs_" ^ shortname in
699       let error_code = error_code_of ret in
700
701       (* Generate the action stub. *)
702       if optargs = [] then
703         generate_prototype ~extern:false ~semicolon:false ~newline:true
704           ~handle:"g" name style
705       else
706         generate_prototype ~extern:false ~semicolon:false ~newline:true
707           ~handle:"g" ~suffix:"_argv" ~optarg_proto:Argv name style;
708
709       pr "{\n";
710
711       (match args with
712        | [] -> ()
713        | _ -> pr "  struct %s_args args;\n" name
714       );
715
716       pr "  guestfs_message_header hdr;\n";
717       pr "  guestfs_message_error err;\n";
718       let has_ret =
719         match ret with
720         | RErr -> false
721         | RConstString _ | RConstOptString _ ->
722             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
723         | RInt _ | RInt64 _
724         | RBool _ | RString _ | RStringList _
725         | RStruct _ | RStructList _
726         | RHashtable _ | RBufferOut _ ->
727             pr "  struct %s_ret ret;\n" name;
728             true in
729
730       pr "  int serial;\n";
731       pr "  int r;\n";
732       pr "\n";
733       check_null_strings shortname style;
734       reject_unknown_optargs shortname style;
735       trace_call shortname style;
736       pr "  if (check_state (g, \"%s\") == -1) return %s;\n"
737         shortname error_code;
738       pr "  guestfs___set_busy (g);\n";
739       pr "\n";
740
741       (* Send the main header and arguments. *)
742       (match args with
743        | [] ->
744            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
745              (String.uppercase shortname)
746        | args ->
747            List.iter (
748              function
749              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
750                  pr "  args.%s = (char *) %s;\n" n n
751              | OptString n ->
752                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
753              | StringList n | DeviceList n ->
754                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
755                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
756              | Bool n ->
757                  pr "  args.%s = %s;\n" n n
758              | Int n ->
759                  pr "  args.%s = %s;\n" n n
760              | Int64 n ->
761                  pr "  args.%s = %s;\n" n n
762              | FileIn _ | FileOut _ -> ()
763              | BufferIn n ->
764                  pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
765                  pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
766                  pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
767                    shortname;
768                  pr "    guestfs___end_busy (g);\n";
769                  pr "    return %s;\n" error_code;
770                  pr "  }\n";
771                  pr "  args.%s.%s_val = (char *) %s;\n" n n n;
772                  pr "  args.%s.%s_len = %s_size;\n" n n n
773            ) args;
774            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
775              (String.uppercase shortname);
776            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
777              name;
778       );
779       pr "  if (serial == -1) {\n";
780       pr "    guestfs___end_busy (g);\n";
781       pr "    return %s;\n" error_code;
782       pr "  }\n";
783       pr "\n";
784
785       (* Send any additional files (FileIn) requested. *)
786       let need_read_reply_label = ref false in
787       List.iter (
788         function
789         | FileIn n ->
790             pr "  r = guestfs___send_file (g, %s);\n" n;
791             pr "  if (r == -1) {\n";
792             pr "    guestfs___end_busy (g);\n";
793             pr "    return %s;\n" error_code;
794             pr "  }\n";
795             pr "  if (r == -2) /* daemon cancelled */\n";
796             pr "    goto read_reply;\n";
797             need_read_reply_label := true;
798             pr "\n";
799         | _ -> ()
800       ) args;
801
802       (* Wait for the reply from the remote end. *)
803       if !need_read_reply_label then pr " read_reply:\n";
804       pr "  memset (&hdr, 0, sizeof hdr);\n";
805       pr "  memset (&err, 0, sizeof err);\n";
806       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
807       pr "\n";
808       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
809       if not has_ret then
810         pr "NULL, NULL"
811       else
812         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
813       pr ");\n";
814
815       pr "  if (r == -1) {\n";
816       pr "    guestfs___end_busy (g);\n";
817       pr "    return %s;\n" error_code;
818       pr "  }\n";
819       pr "\n";
820
821       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
822         (String.uppercase shortname);
823       pr "    guestfs___end_busy (g);\n";
824       pr "    return %s;\n" error_code;
825       pr "  }\n";
826       pr "\n";
827
828       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
829       pr "    int errnum = 0;\n";
830       pr "    if (err.errno_string[0] != '\\0')\n";
831       pr "      errnum = guestfs___string_to_errno (err.errno_string);\n";
832       pr "    if (errnum <= 0)\n";
833       pr "      error (g, \"%%s: %%s\", \"%s\", err.error_message);\n"
834         shortname;
835       pr "    else\n";
836       pr "      guestfs_error_errno (g, errnum, \"%%s: %%s\", \"%s\",\n"
837         shortname;
838       pr "                           err.error_message);\n";
839       pr "    free (err.error_message);\n";
840       pr "    free (err.errno_string);\n";
841       pr "    guestfs___end_busy (g);\n";
842       pr "    return %s;\n" error_code;
843       pr "  }\n";
844       pr "\n";
845
846       (* Expecting to receive further files (FileOut)? *)
847       List.iter (
848         function
849         | FileOut n ->
850             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
851             pr "    guestfs___end_busy (g);\n";
852             pr "    return %s;\n" error_code;
853             pr "  }\n";
854             pr "\n";
855         | _ -> ()
856       ) args;
857
858       pr "  guestfs___end_busy (g);\n";
859
860       (match ret with
861        | RErr -> pr "  return 0;\n"
862        | RInt n | RInt64 n | RBool n ->
863            pr "  return ret.%s;\n" n
864        | RConstString _ | RConstOptString _ ->
865            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
866        | RString n ->
867            pr "  return ret.%s; /* caller will free */\n" n
868        | RStringList n | RHashtable n ->
869            pr "  /* caller will free this, but we need to add a NULL entry */\n";
870            pr "  ret.%s.%s_val =\n" n n;
871            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
872            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
873              n n;
874            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
875            pr "  return ret.%s.%s_val;\n" n n
876        | RStruct (n, _) ->
877            pr "  /* caller will free this */\n";
878            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
879        | RStructList (n, _) ->
880            pr "  /* caller will free this */\n";
881            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
882        | RBufferOut n ->
883            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
884            pr "   * _val might be NULL here.  To make the API saner for\n";
885            pr "   * callers, we turn this case into a unique pointer (using\n";
886            pr "   * malloc(1)).\n";
887            pr "   */\n";
888            pr "  if (ret.%s.%s_len > 0) {\n" n n;
889            pr "    *size_r = ret.%s.%s_len;\n" n n;
890            pr "    return ret.%s.%s_val; /* caller will free */\n" n n;
891            pr "  } else {\n";
892            pr "    free (ret.%s.%s_val);\n" n n;
893            pr "    char *p = safe_malloc (g, 1);\n";
894            pr "    *size_r = ret.%s.%s_len;\n" n n;
895            pr "    return p;\n";
896            pr "  }\n";
897       );
898
899       pr "}\n\n"
900   ) daemon_functions;
901
902   (* Functions to free structures. *)
903   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
904   pr " * structure format is identical to the XDR format.  See note in\n";
905   pr " * generator.ml.\n";
906   pr " */\n";
907   pr "\n";
908
909   List.iter (
910     fun (typ, _) ->
911       pr "void\n";
912       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
913       pr "{\n";
914       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
915       pr "  free (x);\n";
916       pr "}\n";
917       pr "\n";
918
919       pr "void\n";
920       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
921       pr "{\n";
922       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
923       pr "  free (x);\n";
924       pr "}\n";
925       pr "\n";
926
927   ) structs;
928
929   (* Functions which have optional arguments have two generated variants. *)
930   List.iter (
931     function
932     | shortname, (ret, args, (_::_ as optargs) as style), _, _, _, _, _ ->
933         let uc_shortname = String.uppercase shortname in
934
935         (* Get the name of the last regular argument. *)
936         let last_arg =
937           match args with
938           | [] -> "g"
939           | args -> name_of_argt (List.hd (List.rev args)) in
940
941         let rerrcode, rtype =
942           match ret with
943           | RErr | RInt _ | RBool _ -> "-1", "int "
944           | RInt64 _ -> "-1", "int64_t "
945           | RConstString _ | RConstOptString _ -> "NULL", "const char *"
946           | RString _ | RBufferOut _ -> "NULL", "char *"
947           | RStringList _ | RHashtable _ -> "NULL", "char **"
948           | RStruct (_, typ) -> "NULL", sprintf "struct guestfs_%s *" typ
949           | RStructList (_, typ) ->
950               "NULL", sprintf "struct guestfs_%s_list *" typ in
951
952         (* The regular variable args function, just calls the _va variant. *)
953         generate_prototype ~extern:false ~semicolon:false ~newline:true
954           ~handle:"g" ~prefix:"guestfs_" shortname style;
955         pr "{\n";
956         pr "  va_list optargs;\n";
957         pr "\n";
958         pr "  va_start (optargs, %s);\n" last_arg;
959         pr "  %sr = guestfs_%s_va " rtype shortname;
960         generate_c_call_args ~handle:"g" style;
961         pr ";\n";
962         pr "  va_end (optargs);\n";
963         pr "\n";
964         pr "  return r;\n";
965         pr "}\n\n";
966
967         generate_prototype ~extern:false ~semicolon:false ~newline:true
968           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
969           shortname style;
970         pr "{\n";
971         pr "  struct guestfs_%s_argv optargs_s;\n" shortname;
972         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" shortname;
973         pr "  int i;\n";
974         pr "\n";
975         pr "  optargs_s.bitmask = 0;\n";
976         pr "\n";
977         pr "  while ((i = va_arg (args, int)) >= 0) {\n";
978         pr "    switch (i) {\n";
979
980         List.iter (
981           fun argt ->
982             let n = name_of_argt argt in
983             let uc_n = String.uppercase n in
984             pr "    case GUESTFS_%s_%s:\n" uc_shortname uc_n;
985             pr "      optargs_s.%s = va_arg (args, " n;
986             (match argt with
987              | Bool _ | Int _ -> pr "int"
988              | Int64 _ -> pr "int64_t"
989              | String _ -> pr "const char *"
990              | _ -> assert false
991             );
992             pr ");\n";
993             pr "      break;\n";
994         ) optargs;
995
996         pr "    default:\n";
997         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";
998         pr "             \"%s\", i);\n" shortname;
999         pr "      return %s;\n" rerrcode;
1000         pr "    }\n";
1001         pr "\n";
1002         pr "    uint64_t i_mask = UINT64_C(1) << i;\n";
1003         pr "    if (optargs_s.bitmask & i_mask) {\n";
1004         pr "      error (g, \"%%s: same optional argument specified more than once\",\n";
1005         pr "             \"%s\");\n" shortname;
1006         pr "      return %s;\n" rerrcode;
1007         pr "    }\n";
1008         pr "    optargs_s.bitmask |= i_mask;\n";
1009         pr "  }\n";
1010         pr "\n";
1011         pr "  return guestfs_%s_argv " shortname;
1012         generate_c_call_args ~handle:"g" style;
1013         pr ";\n";
1014         pr "}\n\n"
1015     | _ -> ()
1016   ) all_functions_sorted
1017
1018 (* Generate the linker script which controls the visibility of
1019  * symbols in the public ABI and ensures no other symbols get
1020  * exported accidentally.
1021  *)
1022 and generate_linker_script () =
1023   generate_header HashStyle GPLv2plus;
1024
1025   let globals = [
1026     "guestfs_create";
1027     "guestfs_close";
1028     "guestfs_get_error_handler";
1029     "guestfs_get_out_of_memory_handler";
1030     "guestfs_get_private";
1031     "guestfs_last_errno";
1032     "guestfs_last_error";
1033     "guestfs_set_close_callback";
1034     "guestfs_set_error_handler";
1035     "guestfs_set_launch_done_callback";
1036     "guestfs_set_log_message_callback";
1037     "guestfs_set_out_of_memory_handler";
1038     "guestfs_set_private";
1039     "guestfs_set_progress_callback";
1040     "guestfs_set_subprocess_quit_callback";
1041
1042     (* Unofficial parts of the API: the bindings code use these
1043      * functions, so it is useful to export them.
1044      *)
1045     "guestfs_safe_calloc";
1046     "guestfs_safe_malloc";
1047     "guestfs_safe_strdup";
1048     "guestfs_safe_memdup";
1049     "guestfs_tmpdir";
1050   ] in
1051   let functions =
1052     List.flatten (
1053       List.map (
1054         function
1055         | name, (_, _, []), _, _, _, _, _ -> ["guestfs_" ^ name]
1056         | name, (_, _, _), _, _, _, _, _ ->
1057             ["guestfs_" ^ name;
1058              "guestfs_" ^ name ^ "_va";
1059              "guestfs_" ^ name ^ "_argv"]
1060       ) all_functions
1061     ) in
1062   let structs =
1063     List.concat (
1064       List.map (fun (typ, _) ->
1065                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
1066         structs
1067     ) in
1068   let globals = List.sort compare (globals @ functions @ structs) in
1069
1070   pr "{\n";
1071   pr "    global:\n";
1072   List.iter (pr "        %s;\n") globals;
1073   pr "\n";
1074
1075   pr "    local:\n";
1076   pr "        *;\n";
1077   pr "};\n"
1078
1079 and generate_max_proc_nr () =
1080   pr "%d\n" max_proc_nr