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