urschrei
urschrei

Reputation: 26859

Memory leak when trying to free array of CString

The following (MCVE if compiled as a cdylib called libffitest, requires libc as a dependency) demonstrates the problem:

use libc::{c_char, c_void, size_t};
use std::ffi::CString;
use std::mem;
use std::slice;

#[repr(C)]
#[derive(Clone)]
pub struct Array {
    pub data: *const c_void,
    pub len: size_t,
}

#[no_mangle]
pub unsafe extern "C" fn bar() -> Array {
    let v = vec![
        CString::new("Hi There").unwrap().into_raw(),
        CString::new("Hi There").unwrap().into_raw(),
    ];
    v.into()
}

#[no_mangle]
pub extern "C" fn drop_word_array(arr: Array) {
    if arr.data.is_null() {
        return;
    }
    // Convert incoming data to Vec so we own it
    let mut f: Vec<c_char> = arr.into();
    // Deallocate the underlying c_char data by reconstituting it as a CString
    let _: Vec<CString> = unsafe { f.iter_mut().map(|slice| CString::from_raw(slice)).collect() };
}

// Transmute to array for FFI
impl From<Vec<*mut c_char>> for Array {
    fn from(sl: Vec<*mut c_char>) -> Self {
        let array = Array {
            data: sl.as_ptr() as *const c_void,
            len: sl.len() as size_t,
        };
        mem::forget(sl);
        array
    }
}

// Reconstitute from FFI
impl From<Array> for Vec<c_char> {
    fn from(arr: Array) -> Self {
        unsafe { slice::from_raw_parts_mut(arr.data as *mut c_char, arr.len).to_vec() }
    }
}

I thought that by reconstituting the incoming Array as a slice, taking ownership of it as a Vec, then reconstituting the elements as CString, I was freeing any allocated memory, but I'm clearly doing something wrong. Executing this Python script tells me that it's trying to free a pointer that was not allocated: python(85068,0x10ea015c0) malloc: *** error for object 0x7ffdaa512ca1: pointer being freed was not allocated

import sys
import ctypes
from ctypes import c_void_p, Structure, c_size_t, cast, POINTER, c_char_p

class _FFIArray(Structure):
    """
    Convert sequence of structs to C-compatible void array

    """
    _fields_ = [("data", c_void_p),
                ("len", c_size_t)]


def _arr_to_wordlist(res, _func, _args):
    ls = cast(res.data, POINTER(c_char_p * res.len))[0][:]
    print(ls)
    _drop_wordarray(res)


prefix = {"win32": ""}.get(sys.platform, "lib")
extension = {"darwin": ".dylib", "win32": ".dll"}.get(sys.platform, ".so")
lib = ctypes.cdll.LoadLibrary(prefix + "ffitest" + extension)

lib.bar.argtypes = ()
lib.bar.restype = _FFIArray
lib.bar.errcheck = _arr_to_wordlist
_drop_wordarray = lib.drop_word_array

if __name__ == "__main__":
    lib.bar()

Upvotes: 0

Views: 248

Answers (1)

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19662

Well, that was a fun one to go through.

Your biggest problem is the following conversion:

impl From<Array> for Vec<c_char> {
    fn from(arr: Array) -> Self {
        unsafe { slice::from_raw_parts_mut(arr.data as *mut c_char, arr.len).to_vec() }
    }
}

You start with what comes out of the FFI boundary as an array of strings (i.e. *mut *mut c_char). For some reason, you decide that all of a sudden, it is a Vec<c_char> and not a Vec<*const c_char> as you would expect for the CString conversion. That's UB #1 - and the cause of your use-after-free.

The unnecessarily convoluted conversions made things even muddier due to the constant juggling between types. If your FFI boundary is Vec<CString>, why do you split the return into two separate calls? That's literally calling for disaster, as it happened.

Consider the following:

impl From<Array> for Vec<CString> {
    fn from(arr: Array) -> Self {
        unsafe {
          slice::from_raw_parts(
            arr.data as *mut *mut c_char,
            arr.len
          )
            .into_iter().map(|r| CString::from_raw(*r))
            .collect()
        }
    }
}

This gives you a one-step FFI boundary conversion (without the necessity for the second unsafe block in your method), clean types and no leaks.

Upvotes: 2

Related Questions