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