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