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