Stream: t-lang/wg-unsafe-code-guidelines

Topic: Transmuting `-1isize` to a `Option`.


Thom Chiovoloni (Apr 06 2020 at 01:49, on Zulip):

SQLite's API requires passing a -1isize as a Option<unsafe extern "C" fn(a: *mut c_void)>: https://www.sqlite.org/c3ref/c_static.html in some cases. Transmuting between these works, but it gives me the heebie jeebies and I suspect it's unsound...

I don't think rust code ever needs to call this, so I suspect we might be able to override bindgen and just use a repr(transparent) wrapper (I guess in theory a platform exists where isize and function pointers have a different ABI, but... realistically...)

comex (Apr 06 2020 at 03:18, on Zulip):

You shouldn't need to transmute; you should be able to convert to usize and then to a fn type like any other pointer.

comex (Apr 06 2020 at 03:18, on Zulip):

But see https://github.com/rust-lang/unsafe-code-guidelines/issues/72

comex (Apr 06 2020 at 03:19, on Zulip):

"With the proposed wording for a future RFC, the only value you can't assign to a function pointer is 0, all other values are ok." ... but this hasn't actually been accepted yet

Thom Chiovoloni (Apr 06 2020 at 05:44, on Zulip):

@comex hm? I'm not sure I follow what you mean by "and then to a fn type like any other pointer" -- I can't do some_usize as unsafe extern "C" fn(a: *mut c_void).

RalfJ (Apr 06 2020 at 07:08, on Zulip):

@comex fn ptrs in Rust are safe to call and thus not safe to cast from. there are no raw fn ptrs.

RalfJ (Apr 06 2020 at 07:08, on Zulip):

@Thom Chiovoloni ah, you basically want https://github.com/rust-lang/unsafe-code-guidelines/pull/197 I think

Thom Chiovoloni (Apr 06 2020 at 07:10, on Zulip):

Hmm, so AFAICT it's not strictly well defined, but there are no plans to make it UB (just the opposite) so I... probably am just not going to worry about it too much, since I don't have a lot of choice wrt using this API.

RalfJ (Apr 06 2020 at 07:19, on Zulip):

so right now it is well-defined if and only if fn ptrs have no alignment restrictions on your platform

RalfJ (Apr 06 2020 at 07:19, on Zulip):

see https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html

RalfJ (Apr 06 2020 at 07:19, on Zulip):

oh lol that actually doesnt even mention fn ptr alignment and just makes it well-defined

RalfJ (Apr 06 2020 at 07:20, on Zulip):

which I think is because all platforms we currently support do not make alignment requirements for fn ptrs

RalfJ (Apr 06 2020 at 07:20, on Zulip):

but we have no RFC that this cannot change in the future

comex (Apr 06 2020 at 08:53, on Zulip):

if function pointers have an alignment restriction, the original C API doesn't work either :)

comex (Apr 06 2020 at 08:54, on Zulip):

or rather, is undefined behavior in C

comex (Apr 06 2020 at 08:54, on Zulip):

(it might still work)

Last update: Jun 05 2020 at 22:55UTC