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