Skip to content

Auto-coercing from &T to *T is unsafe #7694

Closed
@erickt

Description

@erickt

I'm working on a *libc::c_char wrapper library, and I wanted to make sure that people didn't accidentally grab the inner pointer, deallocate the CStr, then pass the pointer to a function. I thought this would be a great place to use regions, so instead of returning *libc::c_char I returned &'self libc::c_char. This works in all cases except for when we auto-coerce from a &T to a *T.

You can find a demonstration of this problem in this gist. While CStr is full of unsafe code, I believe the interface is safe. The error is demonstrated in the bar/baz functions. bar properly reports that the lifetime of the &'self libc::c_char does not live long enough, but baz doesn't mention a problem at all.

I can think of a couple options to fixing this:

  • Force users to cast a &T to a *T. This at least adds a small roadblock force the end user to think about this cast, but it won't save you from shooting yourself in the foot if you so choose.
  • Allow raw pointers to live in a region. I don't really care about the coercion, it's just that I want to use rust's borrow checker to prevent me from holding a reference to a dead pointer. If I want to shoot myself in the foot, I can always use cast::transmute() to forget the region.
  • Change all the libc functions to take &libc::c_char instead of *libc::c_char. This is a nice short term bandaid for the stdlib, but doesn't really help out end users writing C bindings that don't know about this behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions