generator: Properly lay out and indent multi-line C function decls.
[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 #include \"errnostring.h\"
458
459 /* Check the return message from a call for validity. */
460 static int
461 check_reply_header (guestfs_h *g,
462                     const struct guestfs_message_header *hdr,
463                     unsigned int proc_nr, unsigned int serial)
464 {
465   if (hdr->prog != GUESTFS_PROGRAM) {
466     error (g, \"wrong program (%%d/%%d)\", hdr->prog, GUESTFS_PROGRAM);
467     return -1;
468   }
469   if (hdr->vers != GUESTFS_PROTOCOL_VERSION) {
470     error (g, \"wrong protocol version (%%d/%%d)\",
471            hdr->vers, GUESTFS_PROTOCOL_VERSION);
472     return -1;
473   }
474   if (hdr->direction != GUESTFS_DIRECTION_REPLY) {
475     error (g, \"unexpected message direction (%%d/%%d)\",
476            hdr->direction, GUESTFS_DIRECTION_REPLY);
477     return -1;
478   }
479   if (hdr->proc != proc_nr) {
480     error (g, \"unexpected procedure number (%%d/%%d)\", hdr->proc, proc_nr);
481     return -1;
482   }
483   if (hdr->serial != serial) {
484     error (g, \"unexpected serial (%%d/%%d)\", hdr->serial, serial);
485     return -1;
486   }
487
488   return 0;
489 }
490
491 /* Check we are in the right state to run a high-level action. */
492 static int
493 check_state (guestfs_h *g, const char *caller)
494 {
495   if (!guestfs__is_ready (g)) {
496     if (guestfs__is_config (g) || guestfs__is_launching (g))
497       error (g, \"%%s: call launch before using this function\\n(in guestfish, don't forget to use the 'run' command)\",
498         caller);
499     else
500       error (g, \"%%s called from the wrong state, %%d != READY\",
501         caller, guestfs__get_state (g));
502     return -1;
503   }
504   return 0;
505 }
506
507 ";
508
509   let error_code_of = function
510     | RErr | RInt _ | RInt64 _ | RBool _ -> "-1"
511     | RConstString _ | RConstOptString _
512     | RString _ | RStringList _
513     | RStruct _ | RStructList _
514     | RHashtable _ | RBufferOut _ -> "NULL"
515   in
516
517   (* Generate code to check String-like parameters are not passed in
518    * as NULL (returning an error if they are).
519    *)
520   let check_null_strings shortname (ret, args, optargs) =
521     let pr_newline = ref false in
522     List.iter (
523       function
524       (* parameters which should not be NULL *)
525       | String n
526       | Device n
527       | Pathname n
528       | Dev_or_Path n
529       | FileIn n
530       | FileOut n
531       | BufferIn n
532       | StringList n
533       | DeviceList n
534       | Key n ->
535           pr "  if (%s == NULL) {\n" n;
536           pr "    error (g, \"%%s: %%s: parameter cannot be NULL\",\n";
537           pr "           \"%s\", \"%s\");\n" shortname n;
538           pr "    return %s;\n" (error_code_of ret);
539           pr "  }\n";
540           pr_newline := true
541
542       (* can be NULL *)
543       | OptString _
544
545       (* not applicable *)
546       | Bool _
547       | Int _
548       | Int64 _ -> ()
549     ) args;
550
551     (* For optional arguments. *)
552     List.iter (
553       function
554       | String n ->
555           pr "  if ((optargs->bitmask & GUESTFS_%s_%s_BITMASK) &&\n"
556             (String.uppercase shortname) (String.uppercase n);
557           pr "      optargs->%s == NULL) {\n" n;
558           pr "    error (g, \"%%s: %%s: optional parameter cannot be NULL\",\n";
559           pr "           \"%s\", \"%s\");\n" shortname n;
560           pr "    return %s;\n" (error_code_of ret);
561           pr "  }\n";
562           pr_newline := true
563
564       (* not applicable *)
565       | Bool _ | Int _ | Int64 _ -> ()
566
567       | _ -> assert false
568     ) optargs;
569
570     if !pr_newline then pr "\n";
571   in
572
573   (* Generate code to reject optargs we don't know about. *)
574   let reject_unknown_optargs shortname = function
575     | _, _, [] -> ()
576     | ret, _, optargs ->
577         let len = List.length optargs in
578         let mask = Int64.lognot (Int64.pred (Int64.shift_left 1L len)) in
579         pr "  if (optargs->bitmask & UINT64_C(0x%Lx)) {\n" mask;
580         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";
581         pr "           \"%s\", \"%s\");\n" shortname shortname;
582         pr "    return %s;\n" (error_code_of ret);
583         pr "  }\n";
584         pr "\n";
585   in
586
587   (* Generate code to generate guestfish call traces. *)
588   let trace_call shortname (ret, args, optargs) =
589     pr "  if (guestfs__get_trace (g)) {\n";
590
591     let needs_i =
592       List.exists (function
593                    | StringList _ | DeviceList _ -> true
594                    | _ -> false) args in
595     if needs_i then (
596       pr "    size_t i;\n";
597       pr "\n"
598     );
599
600     pr "    fprintf (stderr, \"%s\");\n" shortname;
601
602     (* Required arguments. *)
603     List.iter (
604       function
605       | String n                        (* strings *)
606       | Device n
607       | Pathname n
608       | Dev_or_Path n
609       | FileIn n
610       | FileOut n
611       | Key n ->
612           (* guestfish doesn't support string escaping, so neither do we *)
613           pr "    fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n
614       | OptString n ->                  (* string option *)
615           pr "    if (%s) fprintf (stderr, \" \\\"%%s\\\"\", %s);\n" n n;
616           pr "    else fprintf (stderr, \" null\");\n"
617       | StringList n
618       | DeviceList n ->                 (* string list *)
619           pr "    fputc (' ', stderr);\n";
620           pr "    fputc ('\"', stderr);\n";
621           pr "    for (i = 0; %s[i]; ++i) {\n" n;
622           pr "      if (i > 0) fputc (' ', stderr);\n";
623           pr "      fputs (%s[i], stderr);\n" n;
624           pr "    }\n";
625           pr "    fputc ('\"', stderr);\n";
626       | Bool n ->                       (* boolean *)
627           pr "    fputs (%s ? \" true\" : \" false\", stderr);\n" n
628       | Int n ->                        (* int *)
629           pr "    fprintf (stderr, \" %%d\", %s);\n" n
630       | Int64 n ->
631           pr "    fprintf (stderr, \" %%\" PRIi64, %s);\n" n
632       | BufferIn n ->                   (* RHBZ#646822 *)
633           pr "    fputc (' ', stderr);\n";
634           pr "    guestfs___print_BufferIn (stderr, %s, %s_size);\n" n n
635     ) args;
636
637     (* Optional arguments. *)
638     List.iter (
639       fun argt ->
640         let n = name_of_argt argt in
641         let uc_shortname = String.uppercase shortname in
642         let uc_n = String.uppercase n in
643         pr "    if (optargs->bitmask & GUESTFS_%s_%s_BITMASK)\n"
644           uc_shortname uc_n;
645         (match argt with
646          | String n ->
647              pr "      fprintf (stderr, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s);\n" n n
648          | Bool n ->
649              pr "      fprintf (stderr, \" \\\"%%s:%%s\\\"\", \"%s\", optargs->%s ? \"true\" : \"false\");\n" n n
650          | Int n ->
651              pr "      fprintf (stderr, \" \\\"%%s:%%d\\\"\", \"%s\", optargs->%s);\n" n n
652          | Int64 n ->
653              pr "      fprintf (stderr, \" \\\"%%s:%%\" PRIi64 \"\\\"\", \"%s\", optargs->%s);\n" n n
654          | _ -> assert false
655         );
656     ) optargs;
657
658     pr "    fputc ('\\n', stderr);\n";
659     pr "  }\n";
660     pr "\n";
661   in
662
663   (* For non-daemon functions, generate a wrapper around each function. *)
664   List.iter (
665     fun (shortname, (_, _, optargs as style), _, _, _, _, _) ->
666       if optargs = [] then
667         generate_prototype ~extern:false ~semicolon:false ~newline:true
668           ~handle:"g" ~prefix:"guestfs_"
669           shortname style
670       else
671         generate_prototype ~extern:false ~semicolon:false ~newline:true
672           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_argv" ~optarg_proto:Argv
673           shortname style;
674       pr "{\n";
675       check_null_strings shortname style;
676       reject_unknown_optargs shortname style;
677       trace_call shortname style;
678       pr "  return guestfs__%s " shortname;
679       generate_c_call_args ~handle:"g" style;
680       pr ";\n";
681       pr "}\n";
682       pr "\n"
683   ) non_daemon_functions;
684
685   (* Client-side stubs for each function. *)
686   List.iter (
687     fun (shortname, (ret, args, optargs as style), _, _, _, _, _) ->
688       if optargs <> [] then
689         failwithf "optargs not yet implemented for daemon functions";
690
691       let name = "guestfs_" ^ shortname in
692       let error_code = error_code_of ret in
693
694       (* Generate the action stub. *)
695       if optargs = [] then
696         generate_prototype ~extern:false ~semicolon:false ~newline:true
697           ~handle:"g" name style
698       else
699         generate_prototype ~extern:false ~semicolon:false ~newline:true
700           ~handle:"g" ~suffix:"_argv" ~optarg_proto:Argv name style;
701
702       pr "{\n";
703
704       (match args with
705        | [] -> ()
706        | _ -> pr "  struct %s_args args;\n" name
707       );
708
709       pr "  guestfs_message_header hdr;\n";
710       pr "  guestfs_message_error err;\n";
711       let has_ret =
712         match ret with
713         | RErr -> false
714         | RConstString _ | RConstOptString _ ->
715             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
716         | RInt _ | RInt64 _
717         | RBool _ | RString _ | RStringList _
718         | RStruct _ | RStructList _
719         | RHashtable _ | RBufferOut _ ->
720             pr "  struct %s_ret ret;\n" name;
721             true in
722
723       pr "  int serial;\n";
724       pr "  int r;\n";
725       pr "\n";
726       check_null_strings shortname style;
727       reject_unknown_optargs shortname style;
728       trace_call shortname style;
729       pr "  if (check_state (g, \"%s\") == -1) return %s;\n"
730         shortname error_code;
731       pr "  guestfs___set_busy (g);\n";
732       pr "\n";
733
734       (* Send the main header and arguments. *)
735       (match args with
736        | [] ->
737            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s, NULL, NULL);\n"
738              (String.uppercase shortname)
739        | args ->
740            List.iter (
741              function
742              | Pathname n | Device n | Dev_or_Path n | String n | Key n ->
743                  pr "  args.%s = (char *) %s;\n" n n
744              | OptString n ->
745                  pr "  args.%s = %s ? (char **) &%s : NULL;\n" n n n
746              | StringList n | DeviceList n ->
747                  pr "  args.%s.%s_val = (char **) %s;\n" n n n;
748                  pr "  for (args.%s.%s_len = 0; %s[args.%s.%s_len]; args.%s.%s_len++) ;\n" n n n n n n n;
749              | Bool n ->
750                  pr "  args.%s = %s;\n" n n
751              | Int n ->
752                  pr "  args.%s = %s;\n" n n
753              | Int64 n ->
754                  pr "  args.%s = %s;\n" n n
755              | FileIn _ | FileOut _ -> ()
756              | BufferIn n ->
757                  pr "  /* Just catch grossly large sizes. XDR encoding will make this precise. */\n";
758                  pr "  if (%s_size >= GUESTFS_MESSAGE_MAX) {\n" n;
759                  pr "    error (g, \"%%s: size of input buffer too large\", \"%s\");\n"
760                    shortname;
761                  pr "    guestfs___end_busy (g);\n";
762                  pr "    return %s;\n" error_code;
763                  pr "  }\n";
764                  pr "  args.%s.%s_val = (char *) %s;\n" n n n;
765                  pr "  args.%s.%s_len = %s_size;\n" n n n
766            ) args;
767            pr "  serial = guestfs___send (g, GUESTFS_PROC_%s,\n"
768              (String.uppercase shortname);
769            pr "        (xdrproc_t) xdr_%s_args, (char *) &args);\n"
770              name;
771       );
772       pr "  if (serial == -1) {\n";
773       pr "    guestfs___end_busy (g);\n";
774       pr "    return %s;\n" error_code;
775       pr "  }\n";
776       pr "\n";
777
778       (* Send any additional files (FileIn) requested. *)
779       let need_read_reply_label = ref false in
780       List.iter (
781         function
782         | FileIn n ->
783             pr "  r = guestfs___send_file (g, %s);\n" n;
784             pr "  if (r == -1) {\n";
785             pr "    guestfs___end_busy (g);\n";
786             pr "    return %s;\n" error_code;
787             pr "  }\n";
788             pr "  if (r == -2) /* daemon cancelled */\n";
789             pr "    goto read_reply;\n";
790             need_read_reply_label := true;
791             pr "\n";
792         | _ -> ()
793       ) args;
794
795       (* Wait for the reply from the remote end. *)
796       if !need_read_reply_label then pr " read_reply:\n";
797       pr "  memset (&hdr, 0, sizeof hdr);\n";
798       pr "  memset (&err, 0, sizeof err);\n";
799       if has_ret then pr "  memset (&ret, 0, sizeof ret);\n";
800       pr "\n";
801       pr "  r = guestfs___recv (g, \"%s\", &hdr, &err,\n        " shortname;
802       if not has_ret then
803         pr "NULL, NULL"
804       else
805         pr "(xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret" shortname;
806       pr ");\n";
807
808       pr "  if (r == -1) {\n";
809       pr "    guestfs___end_busy (g);\n";
810       pr "    return %s;\n" error_code;
811       pr "  }\n";
812       pr "\n";
813
814       pr "  if (check_reply_header (g, &hdr, GUESTFS_PROC_%s, serial) == -1) {\n"
815         (String.uppercase shortname);
816       pr "    guestfs___end_busy (g);\n";
817       pr "    return %s;\n" error_code;
818       pr "  }\n";
819       pr "\n";
820
821       pr "  if (hdr.status == GUESTFS_STATUS_ERROR) {\n";
822       pr "    int errnum = 0;\n";
823       pr "    if (err.errno_string[0] != '\\0')\n";
824       pr "      errnum = guestfs___string_to_errno (err.errno_string);\n";
825       pr "    if (errnum <= 0)\n";
826       pr "      error (g, \"%%s: %%s\", \"%s\", err.error_message);\n"
827         shortname;
828       pr "    else\n";
829       pr "      guestfs_error_errno (g, errnum, \"%%s: %%s\", \"%s\",\n"
830         shortname;
831       pr "                           err.error_message);\n";
832       pr "    free (err.error_message);\n";
833       pr "    free (err.errno_string);\n";
834       pr "    guestfs___end_busy (g);\n";
835       pr "    return %s;\n" error_code;
836       pr "  }\n";
837       pr "\n";
838
839       (* Expecting to receive further files (FileOut)? *)
840       List.iter (
841         function
842         | FileOut n ->
843             pr "  if (guestfs___recv_file (g, %s) == -1) {\n" n;
844             pr "    guestfs___end_busy (g);\n";
845             pr "    return %s;\n" error_code;
846             pr "  }\n";
847             pr "\n";
848         | _ -> ()
849       ) args;
850
851       pr "  guestfs___end_busy (g);\n";
852
853       (match ret with
854        | RErr -> pr "  return 0;\n"
855        | RInt n | RInt64 n | RBool n ->
856            pr "  return ret.%s;\n" n
857        | RConstString _ | RConstOptString _ ->
858            failwithf "RConstString|RConstOptString cannot be used by daemon functions"
859        | RString n ->
860            pr "  return ret.%s; /* caller will free */\n" n
861        | RStringList n | RHashtable n ->
862            pr "  /* caller will free this, but we need to add a NULL entry */\n";
863            pr "  ret.%s.%s_val =\n" n n;
864            pr "    safe_realloc (g, ret.%s.%s_val,\n" n n;
865            pr "                  sizeof (char *) * (ret.%s.%s_len + 1));\n"
866              n n;
867            pr "  ret.%s.%s_val[ret.%s.%s_len] = NULL;\n" n n n n;
868            pr "  return ret.%s.%s_val;\n" n n
869        | RStruct (n, _) ->
870            pr "  /* caller will free this */\n";
871            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
872        | RStructList (n, _) ->
873            pr "  /* caller will free this */\n";
874            pr "  return safe_memdup (g, &ret.%s, sizeof (ret.%s));\n" n n
875        | RBufferOut n ->
876            pr "  /* RBufferOut is tricky: If the buffer is zero-length, then\n";
877            pr "   * _val might be NULL here.  To make the API saner for\n";
878            pr "   * callers, we turn this case into a unique pointer (using\n";
879            pr "   * malloc(1)).\n";
880            pr "   */\n";
881            pr "  if (ret.%s.%s_len > 0) {\n" n n;
882            pr "    *size_r = ret.%s.%s_len;\n" n n;
883            pr "    return ret.%s.%s_val; /* caller will free */\n" n n;
884            pr "  } else {\n";
885            pr "    free (ret.%s.%s_val);\n" n n;
886            pr "    char *p = safe_malloc (g, 1);\n";
887            pr "    *size_r = ret.%s.%s_len;\n" n n;
888            pr "    return p;\n";
889            pr "  }\n";
890       );
891
892       pr "}\n\n"
893   ) daemon_functions;
894
895   (* Functions to free structures. *)
896   pr "/* Structure-freeing functions.  These rely on the fact that the\n";
897   pr " * structure format is identical to the XDR format.  See note in\n";
898   pr " * generator.ml.\n";
899   pr " */\n";
900   pr "\n";
901
902   List.iter (
903     fun (typ, _) ->
904       pr "void\n";
905       pr "guestfs_free_%s (struct guestfs_%s *x)\n" typ typ;
906       pr "{\n";
907       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s, (char *) x);\n" typ;
908       pr "  free (x);\n";
909       pr "}\n";
910       pr "\n";
911
912       pr "void\n";
913       pr "guestfs_free_%s_list (struct guestfs_%s_list *x)\n" typ typ;
914       pr "{\n";
915       pr "  xdr_free ((xdrproc_t) xdr_guestfs_int_%s_list, (char *) x);\n" typ;
916       pr "  free (x);\n";
917       pr "}\n";
918       pr "\n";
919
920   ) structs;
921
922   (* Functions which have optional arguments have two generated variants. *)
923   List.iter (
924     function
925     | shortname, (ret, args, (_::_ as optargs) as style), _, _, _, _, _ ->
926         let uc_shortname = String.uppercase shortname in
927
928         (* Get the name of the last regular argument. *)
929         let last_arg =
930           match args with
931           | [] -> "g"
932           | args -> name_of_argt (List.hd (List.rev args)) in
933
934         let rerrcode, rtype =
935           match ret with
936           | RErr | RInt _ | RBool _ -> "-1", "int "
937           | RInt64 _ -> "-1", "int64_t "
938           | RConstString _ | RConstOptString _ -> "NULL", "const char *"
939           | RString _ | RBufferOut _ -> "NULL", "char *"
940           | RStringList _ | RHashtable _ -> "NULL", "char **"
941           | RStruct (_, typ) -> "NULL", sprintf "struct guestfs_%s *" typ
942           | RStructList (_, typ) ->
943               "NULL", sprintf "struct guestfs_%s_list *" typ in
944
945         (* The regular variable args function, just calls the _va variant. *)
946         generate_prototype ~extern:false ~semicolon:false ~newline:true
947           ~handle:"g" ~prefix:"guestfs_" shortname style;
948         pr "{\n";
949         pr "  va_list optargs;\n";
950         pr "\n";
951         pr "  va_start (optargs, %s);\n" last_arg;
952         pr "  %sr = guestfs_%s_va " rtype shortname;
953         generate_c_call_args ~handle:"g" style;
954         pr ";\n";
955         pr "  va_end (optargs);\n";
956         pr "\n";
957         pr "  return r;\n";
958         pr "}\n\n";
959
960         generate_prototype ~extern:false ~semicolon:false ~newline:true
961           ~handle:"g" ~prefix:"guestfs_" ~suffix:"_va" ~optarg_proto:VA
962           shortname style;
963         pr "{\n";
964         pr "  struct guestfs_%s_argv optargs_s;\n" shortname;
965         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" shortname;
966         pr "  int i;\n";
967         pr "\n";
968         pr "  optargs_s.bitmask = 0;\n";
969         pr "\n";
970         pr "  while ((i = va_arg (args, int)) >= 0) {\n";
971         pr "    switch (i) {\n";
972
973         List.iter (
974           fun argt ->
975             let n = name_of_argt argt in
976             let uc_n = String.uppercase n in
977             pr "    case GUESTFS_%s_%s:\n" uc_shortname uc_n;
978             pr "      optargs_s.%s = va_arg (args, " n;
979             (match argt with
980              | Bool _ | Int _ -> pr "int"
981              | Int64 _ -> pr "int64_t"
982              | String _ -> pr "const char *"
983              | _ -> assert false
984             );
985             pr ");\n";
986             pr "      break;\n";
987         ) optargs;
988
989         pr "    default:\n";
990         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";
991         pr "             \"%s\", i);\n" shortname;
992         pr "      return %s;\n" rerrcode;
993         pr "    }\n";
994         pr "\n";
995         pr "    uint64_t i_mask = UINT64_C(1) << i;\n";
996         pr "    if (optargs_s.bitmask & i_mask) {\n";
997         pr "      error (g, \"%%s: same optional argument specified more than once\",\n";
998         pr "             \"%s\");\n" shortname;
999         pr "      return %s;\n" rerrcode;
1000         pr "    }\n";
1001         pr "    optargs_s.bitmask |= i_mask;\n";
1002         pr "  }\n";
1003         pr "\n";
1004         pr "  return guestfs_%s_argv " shortname;
1005         generate_c_call_args ~handle:"g" style;
1006         pr ";\n";
1007         pr "}\n\n"
1008     | _ -> ()
1009   ) all_functions_sorted
1010
1011 (* Generate the linker script which controls the visibility of
1012  * symbols in the public ABI and ensures no other symbols get
1013  * exported accidentally.
1014  *)
1015 and generate_linker_script () =
1016   generate_header HashStyle GPLv2plus;
1017
1018   let globals = [
1019     "guestfs_create";
1020     "guestfs_close";
1021     "guestfs_get_error_handler";
1022     "guestfs_get_out_of_memory_handler";
1023     "guestfs_get_private";
1024     "guestfs_last_errno";
1025     "guestfs_last_error";
1026     "guestfs_set_close_callback";
1027     "guestfs_set_error_handler";
1028     "guestfs_set_launch_done_callback";
1029     "guestfs_set_log_message_callback";
1030     "guestfs_set_out_of_memory_handler";
1031     "guestfs_set_private";
1032     "guestfs_set_progress_callback";
1033     "guestfs_set_subprocess_quit_callback";
1034
1035     (* Unofficial parts of the API: the bindings code use these
1036      * functions, so it is useful to export them.
1037      *)
1038     "guestfs_safe_calloc";
1039     "guestfs_safe_malloc";
1040     "guestfs_safe_strdup";
1041     "guestfs_safe_memdup";
1042     "guestfs_tmpdir";
1043   ] in
1044   let functions =
1045     List.flatten (
1046       List.map (
1047         function
1048         | name, (_, _, []), _, _, _, _, _ -> ["guestfs_" ^ name]
1049         | name, (_, _, _), _, _, _, _, _ ->
1050             ["guestfs_" ^ name;
1051              "guestfs_" ^ name ^ "_va";
1052              "guestfs_" ^ name ^ "_argv"]
1053       ) all_functions
1054     ) in
1055   let structs =
1056     List.concat (
1057       List.map (fun (typ, _) ->
1058                   ["guestfs_free_" ^ typ; "guestfs_free_" ^ typ ^ "_list"])
1059         structs
1060     ) in
1061   let globals = List.sort compare (globals @ functions @ structs) in
1062
1063   pr "{\n";
1064   pr "    global:\n";
1065   List.iter (pr "        %s;\n") globals;
1066   pr "\n";
1067
1068   pr "    local:\n";
1069   pr "        *;\n";
1070   pr "};\n"
1071
1072 and generate_max_proc_nr () =
1073   pr "%d\n" max_proc_nr