daemon: debug segv correct use of dereferencing NULL.
[libguestfs.git] / generator / generator_ruby.ml
1 (* libguestfs
2  * Copyright (C) 2009-2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 (* Please read generator/README first. *)
20
21 open Printf
22
23 open Generator_types
24 open Generator_utils
25 open Generator_pr
26 open Generator_docstrings
27 open Generator_optgroups
28 open Generator_actions
29 open Generator_structs
30 open Generator_c
31 open Generator_events
32
33 (* Generate ruby bindings. *)
34 let rec generate_ruby_c () =
35   generate_header CStyle LGPLv2plus;
36
37   pr "\
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdint.h>
41
42 #include <ruby.h>
43
44 #include \"guestfs.h\"
45
46 #include \"extconf.h\"
47
48 /* For Ruby < 1.9 */
49 #ifndef RARRAY_LEN
50 #define RARRAY_LEN(r) (RARRAY((r))->len)
51 #endif
52
53 /* For Ruby < 1.8 */
54 #ifndef RSTRING_LEN
55 #define RSTRING_LEN(r) (RSTRING((r))->len)
56 #endif
57
58 #ifndef RSTRING_PTR
59 #define RSTRING_PTR(r) (RSTRING((r))->ptr)
60 #endif
61
62 static VALUE m_guestfs;                 /* guestfs module */
63 static VALUE c_guestfs;                 /* guestfs_h handle */
64 static VALUE e_Error;                   /* used for all errors */
65
66 static void ruby_event_callback_wrapper (guestfs_h *g, void *data, uint64_t event, int event_handle, int flags, const char *buf, size_t buf_len, const uint64_t *array, size_t array_len);
67 static VALUE ruby_event_callback_wrapper_wrapper (VALUE argv);
68 static VALUE ruby_event_callback_handle_exception (VALUE not_used, VALUE exn);
69 static VALUE **get_all_event_callbacks (guestfs_h *g, size_t *len_rtn);
70
71 static void
72 ruby_guestfs_free (void *gvp)
73 {
74   guestfs_h *g = gvp;
75
76   if (g) {
77     /* As in the OCaml binding, there is a nasty, difficult to
78      * solve case here where the user deletes events in one of
79      * the callbacks that we are about to invoke, resulting in
80      * a double-free.  XXX
81      */
82     size_t len, i;
83     VALUE **roots = get_all_event_callbacks (g, &len);
84
85     /* Close the handle: this could invoke callbacks from the list
86      * above, which is why we don't want to delete them before
87      * closing the handle.
88      */
89     guestfs_close (g);
90
91     /* Now unregister the global roots. */
92     for (i = 0; i < len; ++i) {
93       rb_gc_unregister_address (roots[i]);
94       free (roots[i]);
95     }
96     free (roots);
97   }
98 }
99
100 /*
101  * call-seq:
102  *   Guestfs::Guestfs.new() -> Guestfs::Guestfs
103  *
104  * Call
105  * +guestfs_create+[http://libguestfs.org/guestfs.3.html#guestfs_create]
106  * to create a new libguestfs handle.  The handle is represented in
107  * Ruby as an instance of the Guestfs::Guestfs class.
108  */
109 static VALUE
110 ruby_guestfs_create (VALUE m)
111 {
112   guestfs_h *g;
113
114   g = guestfs_create ();
115   if (!g)
116     rb_raise (e_Error, \"failed to create guestfs handle\");
117
118   /* Don't print error messages to stderr by default. */
119   guestfs_set_error_handler (g, NULL, NULL);
120
121   /* Wrap it, and make sure the close function is called when the
122    * handle goes away.
123    */
124   return Data_Wrap_Struct (c_guestfs, NULL, ruby_guestfs_free, g);
125 }
126
127 /*
128  * call-seq:
129  *   g.close() -> nil
130  *
131  * Call
132  * +guestfs_close+[http://libguestfs.org/guestfs.3.html#guestfs_close]
133  * to close the libguestfs handle.
134  */
135 static VALUE
136 ruby_guestfs_close (VALUE gv)
137 {
138   guestfs_h *g;
139   Data_Get_Struct (gv, guestfs_h, g);
140
141   ruby_guestfs_free (g);
142   DATA_PTR (gv) = NULL;
143
144   return Qnil;
145 }
146
147 /*
148  * call-seq:
149  *   g.set_event_callback(cb, event_bitmask) -> event_handle
150  *
151  * Call
152  * +guestfs_set_event_callback+[http://libguestfs.org/guestfs.3.html#guestfs_set_event_callback]
153  * to register an event callback.  This returns an event handle.
154  */
155 static VALUE
156 ruby_set_event_callback (VALUE gv, VALUE cbv, VALUE event_bitmaskv)
157 {
158   guestfs_h *g;
159   uint64_t event_bitmask;
160   int eh;
161   VALUE *root;
162   char key[64];
163
164   Data_Get_Struct (gv, guestfs_h, g);
165
166   event_bitmask = NUM2ULL (event_bitmaskv);
167
168   root = guestfs_safe_malloc (g, sizeof *root);
169   *root = cbv;
170
171   eh = guestfs_set_event_callback (g, ruby_event_callback_wrapper,
172                                    event_bitmask, 0, root);
173   if (eh == -1) {
174     free (root);
175     rb_raise (e_Error, \"%%s\", guestfs_last_error (g));
176   }
177
178   rb_gc_register_address (root);
179
180   snprintf (key, sizeof key, \"_ruby_event_%%d\", eh);
181   guestfs_set_private (g, key, root);
182
183   return INT2NUM (eh);
184 }
185
186 /*
187  * call-seq:
188  *   g.delete_event_callback(event_handle) -> nil
189  *
190  * Call
191  * +guestfs_delete_event_callback+[http://libguestfs.org/guestfs.3.html#guestfs_delete_event_callback]
192  * to delete an event callback.
193  */
194 static VALUE
195 ruby_delete_event_callback (VALUE gv, VALUE event_handlev)
196 {
197   guestfs_h *g;
198   char key[64];
199   int eh = NUM2INT (event_handlev);
200   VALUE *root;
201
202   Data_Get_Struct (gv, guestfs_h, g);
203
204   snprintf (key, sizeof key, \"_ruby_event_%%d\", eh);
205
206   root = guestfs_get_private (g, key);
207   if (root) {
208     rb_gc_unregister_address (root);
209     free (root);
210     guestfs_set_private (g, key, NULL);
211     guestfs_delete_event_callback (g, eh);
212   }
213
214   return Qnil;
215 }
216
217 static void
218 ruby_event_callback_wrapper (guestfs_h *g,
219                              void *data,
220                              uint64_t event,
221                              int event_handle,
222                              int flags,
223                              const char *buf, size_t buf_len,
224                              const uint64_t *array, size_t array_len)
225 {
226   size_t i;
227   VALUE eventv, event_handlev, bufv, arrayv;
228   VALUE argv[5];
229
230   eventv = ULL2NUM (event);
231   event_handlev = INT2NUM (event_handle);
232
233   bufv = rb_str_new (buf, buf_len);
234
235   arrayv = rb_ary_new2 (array_len);
236   for (i = 0; i < array_len; ++i)
237     rb_ary_push (arrayv, ULL2NUM (array[i]));
238
239   /* This is a crap limitation of rb_rescue.
240    * http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/~poffice/mail/ruby-talk/65698
241    */
242   argv[0] = * (VALUE *) data; /* function */
243   argv[1] = eventv;
244   argv[2] = event_handlev;
245   argv[3] = bufv;
246   argv[4] = arrayv;
247
248   rb_rescue (ruby_event_callback_wrapper_wrapper, (VALUE) argv,
249              ruby_event_callback_handle_exception, Qnil);
250 }
251
252 static VALUE
253 ruby_event_callback_wrapper_wrapper (VALUE argvv)
254 {
255   VALUE *argv = (VALUE *) argvv;
256   VALUE fn, eventv, event_handlev, bufv, arrayv;
257
258   fn = argv[0];
259
260   /* Check the Ruby callback still exists.  For reasons which are not
261    * fully understood, even though we registered this as a global root,
262    * it is still possible for the callback to go away (fn value remains
263    * but its type changes from T_DATA to T_NONE).  (RHBZ#733297)
264    */
265   if (rb_type (fn) != T_NONE) {
266     eventv = argv[1];
267     event_handlev = argv[2];
268     bufv = argv[3];
269     arrayv = argv[4];
270
271     rb_funcall (fn, rb_intern (\"call\"), 4,
272                 eventv, event_handlev, bufv, arrayv);
273   }
274
275   return Qnil;
276 }
277
278 static VALUE
279 ruby_event_callback_handle_exception (VALUE not_used, VALUE exn)
280 {
281   /* Callbacks aren't supposed to throw exceptions.  The best we
282    * can do is to print the error.
283    */
284   fprintf (stderr, \"libguestfs: exception in callback: %%s\\n\",
285            StringValueCStr (exn));
286
287   return Qnil;
288 }
289
290 static VALUE **
291 get_all_event_callbacks (guestfs_h *g, size_t *len_rtn)
292 {
293   VALUE **r;
294   size_t i;
295   const char *key;
296   VALUE *root;
297
298   /* Count the length of the array that will be needed. */
299   *len_rtn = 0;
300   root = guestfs_first_private (g, &key);
301   while (root != NULL) {
302     if (strncmp (key, \"_ruby_event_\", strlen (\"_ruby_event_\")) == 0)
303       (*len_rtn)++;
304     root = guestfs_next_private (g, &key);
305   }
306
307   /* Copy them into the return array. */
308   r = guestfs_safe_malloc (g, sizeof (VALUE *) * (*len_rtn));
309
310   i = 0;
311   root = guestfs_first_private (g, &key);
312   while (root != NULL) {
313     if (strncmp (key, \"_ruby_event_\", strlen (\"_ruby_event_\")) == 0) {
314       r[i] = root;
315       i++;
316     }
317     root = guestfs_next_private (g, &key);
318   }
319
320   return r;
321 }
322
323 /*
324  * call-seq:
325  *   g.user_cancel() -> nil
326  *
327  * Call
328  * +guestfs_user_cancel+[http://libguestfs.org/guestfs.3.html#guestfs_user_cancel]
329  * to cancel the current transfer.  This is safe to call from Ruby
330  * signal handlers and threads.
331  */
332 static VALUE
333 ruby_user_cancel (VALUE gv)
334 {
335   guestfs_h *g;
336
337   Data_Get_Struct (gv, guestfs_h, g);
338   if (g)
339     guestfs_user_cancel (g);
340   return Qnil;
341 }
342
343 ";
344
345   List.iter (
346     fun (name, (ret, args, optargs as style), _, flags, _, shortdesc, longdesc) ->
347       (* Generate rdoc. *)
348       if not (List.mem NotInDocs flags); then (
349         let doc = replace_str longdesc "C<guestfs_" "C<g." in
350         let doc =
351           if optargs <> [] then
352             doc ^ "\n\nOptional arguments are supplied in the final hash parameter, which is a hash of the argument name to its value.  Pass an empty {} for no optional arguments."
353           else doc in
354         let doc =
355           if List.mem ProtocolLimitWarning flags then
356             doc ^ "\n\n" ^ protocol_limit_warning
357           else doc in
358         let doc =
359           match deprecation_notice flags with
360           | None -> doc
361           | Some txt -> doc ^ "\n\n" ^ txt in
362         let doc = pod2text ~width:60 name doc in
363         let doc = String.concat "\n * " doc in
364         let doc = trim doc in
365
366         let args = List.map name_of_argt args in
367         let args = if optargs <> [] then args @ ["{optargs...}"] else args in
368         let args = String.concat ", " args in
369
370         let ret =
371           match ret with
372           | RErr -> "nil"
373           | RBool _ -> "[True|False]"
374           | RInt _ -> "fixnum"
375           | RInt64 _ -> "fixnum"
376           | RConstString _ -> "string"
377           | RConstOptString _ -> "string"
378           | RString _ -> "string"
379           | RBufferOut _ -> "string"
380           | RStruct _
381           | RHashtable _ -> "hash"
382           | RStringList _
383           | RStructList _ -> "list" in
384
385         pr "\
386 /*
387  * call-seq:
388  *   g.%s(%s) -> %s
389  *
390  * %s
391  *
392  * %s
393  *
394  * (For the C API documentation for this function, see
395  * +guestfs_%s+[http://libguestfs.org/guestfs.3.html#guestfs_%s]).
396  */
397 " name args ret shortdesc doc name name
398       );
399
400       (* Generate the function. *)
401       pr "static VALUE\n";
402       pr "ruby_guestfs_%s (VALUE gv" name;
403       List.iter (fun arg -> pr ", VALUE %sv" (name_of_argt arg)) args;
404       (* XXX This makes the hash mandatory, meaning that you have
405        * to specify {} for no arguments.  We could make it so this
406        * can be omitted.  However that is a load of hassle because
407        * you have to completely change the way that arguments are
408        * passed in.  See:
409        * http://www.redhat.com/archives/libvir-list/2008-April/msg00004.html
410        *)
411       if optargs <> [] then
412         pr ", VALUE optargsv";
413       pr ")\n";
414       pr "{\n";
415       pr "  guestfs_h *g;\n";
416       pr "  Data_Get_Struct (gv, guestfs_h, g);\n";
417       pr "  if (!g)\n";
418       pr "    rb_raise (rb_eArgError, \"%%s: used handle after closing it\", \"%s\");\n"
419         name;
420       pr "\n";
421
422       List.iter (
423         function
424         | Pathname n | Device n | Dev_or_Path n | String n | Key n
425         | FileIn n | FileOut n ->
426             pr "  const char *%s = StringValueCStr (%sv);\n" n n;
427         | BufferIn n ->
428             pr "  Check_Type (%sv, T_STRING);\n" n;
429             pr "  const char *%s = RSTRING_PTR (%sv);\n" n n;
430             pr "  if (!%s)\n" n;
431             pr "    rb_raise (rb_eTypeError, \"expected string for parameter %%s of %%s\",\n";
432             pr "              \"%s\", \"%s\");\n" n name;
433             pr "  size_t %s_size = RSTRING_LEN (%sv);\n" n n
434         | OptString n ->
435             pr "  const char *%s = !NIL_P (%sv) ? StringValueCStr (%sv) : NULL;\n" n n n
436         | StringList n | DeviceList n ->
437             pr "  char **%s;\n" n;
438             pr "  Check_Type (%sv, T_ARRAY);\n" n;
439             pr "  {\n";
440             pr "    size_t i, len;\n";
441             pr "    len = RARRAY_LEN (%sv);\n" n;
442             pr "    %s = ALLOC_N (char *, len+1);\n"
443               n;
444             pr "    for (i = 0; i < len; ++i) {\n";
445             pr "      VALUE v = rb_ary_entry (%sv, i);\n" n;
446             pr "      %s[i] = StringValueCStr (v);\n" n;
447             pr "    }\n";
448             pr "    %s[len] = NULL;\n" n;
449             pr "  }\n";
450         | Bool n ->
451             pr "  int %s = RTEST (%sv);\n" n n
452         | Int n ->
453             pr "  int %s = NUM2INT (%sv);\n" n n
454         | Int64 n ->
455             pr "  long long %s = NUM2LL (%sv);\n" n n
456         | Pointer (t, n) ->
457             pr "  %s %s = (%s) (intptr_t) NUM2LL (%sv);\n" t n t n
458       ) args;
459       pr "\n";
460
461       (* Optional arguments are passed in a final hash parameter. *)
462       if optargs <> [] then (
463         let uc_name = String.uppercase name in
464         pr "  Check_Type (optargsv, T_HASH);\n";
465         pr "  struct guestfs_%s_argv optargs_s = { .bitmask = 0 };\n" name;
466         pr "  struct guestfs_%s_argv *optargs = &optargs_s;\n" name;
467         pr "  VALUE v;\n";
468         List.iter (
469           fun argt ->
470             let n = name_of_optargt argt in
471             let uc_n = String.uppercase n in
472             pr "  v = rb_hash_lookup (optargsv, ID2SYM (rb_intern (\"%s\")));\n" n;
473             pr "  if (v != Qnil) {\n";
474             (match argt with
475              | OBool n ->
476                  pr "    optargs_s.%s = RTEST (v);\n" n;
477              | OInt n ->
478                  pr "    optargs_s.%s = NUM2INT (v);\n" n;
479              | OInt64 n ->
480                  pr "    optargs_s.%s = NUM2LL (v);\n" n;
481              | OString _ ->
482                  pr "    optargs_s.%s = StringValueCStr (v);\n" n
483             );
484             pr "    optargs_s.bitmask |= GUESTFS_%s_%s_BITMASK;\n" uc_name uc_n;
485             pr "  }\n";
486         ) optargs;
487         pr "\n";
488       );
489
490       (match ret with
491        | RErr | RInt _ | RBool _ -> pr "  int r;\n"
492        | RInt64 _ -> pr "  int64_t r;\n"
493        | RConstString _ | RConstOptString _ ->
494            pr "  const char *r;\n"
495        | RString _ -> pr "  char *r;\n"
496        | RStringList _ | RHashtable _ -> pr "  char **r;\n"
497        | RStruct (_, typ) -> pr "  struct guestfs_%s *r;\n" typ
498        | RStructList (_, typ) ->
499            pr "  struct guestfs_%s_list *r;\n" typ
500        | RBufferOut _ ->
501            pr "  char *r;\n";
502            pr "  size_t size;\n"
503       );
504       pr "\n";
505
506       if optargs = [] then
507         pr "  r = guestfs_%s " name
508       else
509         pr "  r = guestfs_%s_argv " name;
510       generate_c_call_args ~handle:"g" style;
511       pr ";\n";
512
513       List.iter (
514         function
515         | Pathname _ | Device _ | Dev_or_Path _ | String _ | Key _
516         | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _
517         | BufferIn _ | Pointer _ -> ()
518         | StringList n | DeviceList n ->
519             pr "  free (%s);\n" n
520       ) args;
521
522       (match errcode_of_ret ret with
523        | `CannotReturnError -> ()
524        | `ErrorIsMinusOne ->
525            pr "  if (r == -1)\n";
526            pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n"
527        | `ErrorIsNULL ->
528            pr "  if (r == NULL)\n";
529            pr "    rb_raise (e_Error, \"%%s\", guestfs_last_error (g));\n"
530       );
531       pr "\n";
532
533       (match ret with
534        | RErr ->
535            pr "  return Qnil;\n"
536        | RInt _ | RBool _ ->
537            pr "  return INT2NUM (r);\n"
538        | RInt64 _ ->
539            pr "  return ULL2NUM (r);\n"
540        | RConstString _ ->
541            pr "  return rb_str_new2 (r);\n";
542        | RConstOptString _ ->
543            pr "  if (r)\n";
544            pr "    return rb_str_new2 (r);\n";
545            pr "  else\n";
546            pr "    return Qnil;\n";
547        | RString _ ->
548            pr "  VALUE rv = rb_str_new2 (r);\n";
549            pr "  free (r);\n";
550            pr "  return rv;\n";
551        | RStringList _ ->
552            pr "  size_t i, len = 0;\n";
553            pr "  for (i = 0; r[i] != NULL; ++i) len++;\n";
554            pr "  VALUE rv = rb_ary_new2 (len);\n";
555            pr "  for (i = 0; r[i] != NULL; ++i) {\n";
556            pr "    rb_ary_push (rv, rb_str_new2 (r[i]));\n";
557            pr "    free (r[i]);\n";
558            pr "  }\n";
559            pr "  free (r);\n";
560            pr "  return rv;\n"
561        | RStruct (_, typ) ->
562            let cols = cols_of_struct typ in
563            generate_ruby_struct_code typ cols
564        | RStructList (_, typ) ->
565            let cols = cols_of_struct typ in
566            generate_ruby_struct_list_code typ cols
567        | RHashtable _ ->
568            pr "  VALUE rv = rb_hash_new ();\n";
569            pr "  size_t i;\n";
570            pr "  for (i = 0; r[i] != NULL; i+=2) {\n";
571            pr "    rb_hash_aset (rv, rb_str_new2 (r[i]), rb_str_new2 (r[i+1]));\n";
572            pr "    free (r[i]);\n";
573            pr "    free (r[i+1]);\n";
574            pr "  }\n";
575            pr "  free (r);\n";
576            pr "  return rv;\n"
577        | RBufferOut _ ->
578            pr "  VALUE rv = rb_str_new (r, size);\n";
579            pr "  free (r);\n";
580            pr "  return rv;\n";
581       );
582
583       pr "}\n";
584       pr "\n"
585   ) all_functions;
586
587   pr "\
588 /* Initialize the module. */
589 void Init__guestfs ()
590 {
591   m_guestfs = rb_define_module (\"Guestfs\");
592   c_guestfs = rb_define_class_under (m_guestfs, \"Guestfs\", rb_cObject);
593   e_Error = rb_define_class_under (m_guestfs, \"Error\", rb_eStandardError);
594
595 #ifdef HAVE_RB_DEFINE_ALLOC_FUNC
596   rb_define_alloc_func (c_guestfs, ruby_guestfs_create);
597 #endif
598
599   rb_define_module_function (m_guestfs, \"create\", ruby_guestfs_create, 0);
600   rb_define_method (c_guestfs, \"close\", ruby_guestfs_close, 0);
601   rb_define_method (c_guestfs, \"set_event_callback\",
602                     ruby_set_event_callback, 2);
603   rb_define_method (c_guestfs, \"delete_event_callback\",
604                     ruby_delete_event_callback, 1);
605   rb_define_method (c_guestfs, \"user_cancel\",
606                     ruby_user_cancel, 0);
607
608 ";
609
610   (* Constants. *)
611   List.iter (
612     fun (name, bitmask) ->
613       pr "  rb_define_const (m_guestfs, \"EVENT_%s\",\n"
614         (String.uppercase name);
615       pr "                   ULL2NUM (UINT64_C (0x%x)));\n" bitmask;
616   ) events;
617   pr "\n";
618
619   (* Methods. *)
620   List.iter (
621     fun (name, (_, args, optargs), _, _, _, _, _) ->
622       let nr_args = List.length args + if optargs <> [] then 1 else 0 in
623       pr "  rb_define_method (c_guestfs, \"%s\",\n" name;
624       pr "        ruby_guestfs_%s, %d);\n" name nr_args
625   ) all_functions;
626
627   pr "}\n"
628
629 (* Ruby code to return a struct. *)
630 and generate_ruby_struct_code typ cols =
631   pr "  VALUE rv = rb_hash_new ();\n";
632   List.iter (
633     function
634     | name, FString ->
635         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new2 (r->%s));\n" name name
636     | name, FBuffer ->
637         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, r->%s_len));\n" name name name
638     | name, FUUID ->
639         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_str_new (r->%s, 32));\n" name name
640     | name, (FBytes|FUInt64) ->
641         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
642     | name, FInt64 ->
643         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), LL2NUM (r->%s));\n" name name
644     | name, FUInt32 ->
645         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), UINT2NUM (r->%s));\n" name name
646     | name, FInt32 ->
647         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), INT2NUM (r->%s));\n" name name
648     | name, FOptPercent ->
649         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), rb_dbl2big (r->%s));\n" name name
650     | name, FChar -> (* XXX wrong? *)
651         pr "  rb_hash_aset (rv, rb_str_new2 (\"%s\"), ULL2NUM (r->%s));\n" name name
652   ) cols;
653   pr "  guestfs_free_%s (r);\n" typ;
654   pr "  return rv;\n"
655
656 (* Ruby code to return a struct list. *)
657 and generate_ruby_struct_list_code typ cols =
658   pr "  VALUE rv = rb_ary_new2 (r->len);\n";
659   pr "  size_t i;\n";
660   pr "  for (i = 0; i < r->len; ++i) {\n";
661   pr "    VALUE hv = rb_hash_new ();\n";
662   List.iter (
663     function
664     | name, FString ->
665         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new2 (r->val[i].%s));\n" name name
666     | name, FBuffer ->
667         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, r->val[i].%s_len));\n" name name name
668     | name, FUUID ->
669         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_str_new (r->val[i].%s, 32));\n" name name
670     | name, (FBytes|FUInt64) ->
671         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
672     | name, FInt64 ->
673         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), LL2NUM (r->val[i].%s));\n" name name
674     | name, FUInt32 ->
675         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), UINT2NUM (r->val[i].%s));\n" name name
676     | name, FInt32 ->
677         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), INT2NUM (r->val[i].%s));\n" name name
678     | name, FOptPercent ->
679         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), rb_dbl2big (r->val[i].%s));\n" name name
680     | name, FChar -> (* XXX wrong? *)
681         pr "    rb_hash_aset (hv, rb_str_new2 (\"%s\"), ULL2NUM (r->val[i].%s));\n" name name
682   ) cols;
683   pr "    rb_ary_push (rv, hv);\n";
684   pr "  }\n";
685   pr "  guestfs_free_%s_list (r);\n" typ;
686   pr "  return rv;\n"