]> xenbits.xensource.com Git - xen.git/commitdiff
tools/ocaml/libs: Fix memory/resource leaks with caml_alloc_custom()
authorAndrew Cooper <andrew.cooper3@citrix.com>
Wed, 1 Feb 2023 11:27:42 +0000 (11:27 +0000)
committerAndrew Cooper <andrew.cooper3@citrix.com>
Mon, 6 Feb 2023 10:22:12 +0000 (10:22 +0000)
All caml_alloc_*() functions can throw exceptions, and longjump out of
context.  If this happens, we leak the xch/xce handle.

Reorder the logic to allocate the the Ocaml object first.

Fixes: 8b3c06a3e545 ("tools/ocaml/xenctrl: OCaml 5 support, fix use-after-free")
Fixes: 22d5affdf0ce ("tools/ocaml/evtchn: OCaml 5 support, fix potential resource leak")
Signed-off-by: Andrew Cooper <andrew.cooper3@citrix.com>
Acked-by: Christian Lindig <christian.lindig@citrix.com>
tools/ocaml/libs/eventchn/xeneventchn_stubs.c
tools/ocaml/libs/xc/xenctrl_stubs.c

index 34dcfed30275f66e9e143eac6560b3e471c325a4..1980acf405a5cb84aca0b407fc6bb0fcb13c523a 100644 (file)
@@ -63,6 +63,8 @@ CAMLprim value stub_eventchn_init(value cloexec)
        if ( !Bool_val(cloexec) )
                flags |= XENEVTCHN_NO_CLOEXEC;
 
+       result = caml_alloc_custom(&xenevtchn_ops, sizeof(xce), 0, 1);
+
        caml_enter_blocking_section();
        xce = xenevtchn_open(NULL, flags);
        caml_leave_blocking_section();
@@ -70,7 +72,6 @@ CAMLprim value stub_eventchn_init(value cloexec)
        if (xce == NULL)
                caml_failwith("open failed");
 
-       result = caml_alloc_custom(&xenevtchn_ops, sizeof(xce), 0, 1);
        *(xenevtchn_handle **)Data_custom_val(result) = xce;
 
        CAMLreturn(result);
@@ -82,6 +83,8 @@ CAMLprim value stub_eventchn_fdopen(value fdval)
        CAMLlocal1(result);
        xenevtchn_handle *xce;
 
+       result = caml_alloc_custom(&xenevtchn_ops, sizeof(xce), 0, 1);
+
        caml_enter_blocking_section();
        xce = xenevtchn_fdopen(NULL, Int_val(fdval), 0);
        caml_leave_blocking_section();
@@ -89,7 +92,6 @@ CAMLprim value stub_eventchn_fdopen(value fdval)
        if (xce == NULL)
                caml_failwith("evtchn fdopen failed");
 
-       result = caml_alloc_custom(&xenevtchn_ops, sizeof(xce), 0, 1);
        *(xenevtchn_handle **)Data_custom_val(result) = xce;
 
        CAMLreturn(result);
index f9006c662382a650db6a6719e846aa9b32ea6211..ed1cbafdb488820fb45447ad2c7afb685cc8efd8 100644 (file)
@@ -98,6 +98,8 @@ CAMLprim value stub_xc_interface_open(value unit)
        CAMLlocal1(result);
        xc_interface *xch;
 
+       result = caml_alloc_custom(&xenctrl_ops, sizeof(xch), 0, 1);
+
        caml_enter_blocking_section();
        xch = xc_interface_open(NULL, NULL, 0);
        caml_leave_blocking_section();
@@ -105,7 +107,6 @@ CAMLprim value stub_xc_interface_open(value unit)
        if ( !xch )
                failwith_xc(xch);
 
-       result = caml_alloc_custom(&xenctrl_ops, sizeof(xch), 0, 1);
        *(xc_interface **)Data_custom_val(result) = xch;
 
        CAMLreturn(result);