Does Rust code, statically linked to a C program, gain any beneficial safety properties as a result?

125 views Asked by At

Inspired by Carol Goulding's talk on "Rust Out Your C" and an article I read on porting C to Rust function by function.

If I have a program consisting of 3 functions called one after another:

1 (C) --> 2 (C) --> 3 (C)

And replace the second function as a statically linked, Rust function so the flow becomes:

1 (C) --> 2 (R) --> 3 (C)

Is the code in function 2, now memory and / or type safe? Does it gain any additional, beneficial properties in terms of safety?

2

There are 2 answers

8
mcarton On

Yes. And no. It depends.

  1. First of, the C code in functions 1 and 3 will not be affected in any way, and will be just as unsafe (per Rust's definition as unsafe) as any C.

  2. The code in function 2 will however benefit from Rust safety. Its implementation can be considered safer.

    However, you'll need some glue between your C and Rust. Rust safety mostly come from its type system, and C type system is quite poor in comparison. You'll need to properly call your Rust function from your C function and C function from your Rust function. C is mostly unaware of Rust, so this needs to be done on the Rust side. While there are tools and crates to help with FFI, you always have to assume at some point that the C is correct, as a bug in the C could manifest even in (safe) Rust. Moreover calling a C function from Rust always requires unsafe, and a Rust function called from C will often have some unsafe too. FFI is easy to get wrong: Wrong size of parameters, bad alignments, bad ABI, use of freed memory are all more likely at a language barrier and are all very unsafe.

0
Yann Vernier On

No, being embedded in C code doesn't make your code safe. You may gain lifetime checking in the Rust section, but only if the entry and exits are correctly annotated; e.g. if your code returns an owned reference, but C code expected it to be borrowed, you still have a memory leak. Rust code itself may also be unsafe; the Rust compiler has tools to help you track memory and types more strictly than a C compiler, but it doesn't force you to use those tools. It just makes it more awkward to write risky code to encourage safe code.