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