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