|
|
Log in / Subscribe / Register

Memory-safe C code

Memory-safe C code

Posted Nov 16, 2025 13:28 UTC (Sun) by tialaramex (subscriber, #21167)
In reply to: Memory-safe C code by alx.manpages
Parent article: Rust in Android: move fast and fix things (Google Security Blog)

So, the trouble is that Rust actually goes a little beyond memory safe - though that's the headline feature. All the stuff that's Undefined Behaviour in C or C++ is either well defined in safe Rust or does not exist. This rules out things that aren't typically associated with remote code execution or even segfaults but have Undefined Behaviour because we can't actually say they're safe, even though we might suspect in practice they are.

I *think* if you're restricted to only the unsigned integer types and only a few arithmetic operators (not including division) you can make a "safe C" but I could be wrong, and anyway it's too restricted to be of any practical use.

In particular I'm pretty sure a "safe C" cannot have pointers at all. Safe Rust is allowed to make pointers, because it isn't allowed to dereference them and in Rust all the pointers are allowed to exist, even if they're nonsense, so long as we do not dereference them - in contrast my understanding is that in C nonsense pointers are prohibited because historically they might be impossible at runtime on some hardware.


to post comments

Memory-safe C code

Posted Nov 16, 2025 15:13 UTC (Sun) by alx.manpages (subscriber, #145117) [Link] (4 responses)

About UB, in C we're now gaining an attribute that makes the behavior well-defined for signed overflow, but keeps diagnostics. Kees talked about it in the Linux Security Summit. I think that's a good approach.

Another thing is that C is removing many of the Undefined Behaviors. In the last year, the C Committee has transformed many UBs into constraint violations (mandatory diagnostic) or well-defined behavior, depending on the case. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3529.pdf

About safety and pointers, I think it's not only possible, but easy. - Make sure all pointers have a provenance. This disallows things like (int *)42. (int*) 42; // diagnostic - Make sure all pointers are paired with a variable holding the number of elements in the array (with the only exception being functions that *read* null-terminated strings).
void f(int p[]);  // diagnostic
void g(size_t n, int p[n]);  // ok
- Assume that pointers with no specified length only have one element.
void h(int *p)  // p is a pointer to a single integer.  Pointer arithmetic not allowed.
{
    *p = 42;  // ok
    p++;  // diagnostic
}
- Make sure pointers are non-null before dereferencing.
void i(_Optional int *p)
{
    *p;  // diagnostic
    if (p != NULL)
        *p;  // ok
}
- Make sure pointer arithmetic is within the bounds specified by the number of elements.
void j(size_t n, int a[n])
{
    a[countof(a) - 1] = 42;  // ok
    a[countof(a)] = 7;  // diagnostic

    for (int i = 0; i < countof(a); i++)  // ok
        a[i] = 0;
    for (int i = 0; i < countof(a) + 1; i++)  // diagnostic
        a[i] = 0;

    a[42] = 0;  // diagnostic (42 not proved within [0,countof(a)).
}
--- These restrictions can't be used by every program, so some code might need to turn some of these off, but most programs could enforce all of this via a set of -Werror=... flags.

Memory-safe C code

Posted Nov 17, 2025 13:16 UTC (Mon) by plugwash (subscriber, #29694) [Link] (1 responses)

> About safety and pointers, I think it's not only possible, but easy. - Make sure all pointers have a provenance.

Provenance alone is insufficient, that a pointer was valid at some time in the past does not mean it is still valid now.

Memory-safe C code

Posted Nov 17, 2025 13:22 UTC (Mon) by alx.manpages (subscriber, #145117) [Link]

I'm aware of that. I said previously that I intend to resolve buffer-overflows, not use-after-free.

While both are connected, they're different, and the solutions need to be different. It's quite easy to remove buffer overflows in C, but it's more complex to resolve use-after-free bugs.

Memory-safe C code

Posted Dec 13, 2025 23:48 UTC (Sat) by sammythesnake (guest, #17693) [Link] (1 responses)

I'm not a C programmer* but I have aa feeling that you still have problems with the following:

int a[] = []; /* or however you spell this in C */

j(0, a)

because

a[countof{a} - 1]
is out of bounds, right?

* By firm choice - every time I even think about C, I'm bemused that anyone would choose a language apparently composed entirely of foot guns. If I ever need anything closer to the iron then higher level languages, I'll go for rust, but I've never had enough reason to actually learn it properly so far. YMMV, of course!

Memory-safe C code

Posted Dec 14, 2025 0:16 UTC (Sun) by alx.manpages (subscriber, #145117) [Link]

Yup, I got a mistake in the example. It should have been:
void j(size_t n, int a[n])
{
    a[countof(a) - 1] = 42;  // diagnostic
    if (countof(a) >= 1)
        a[countof(a) - 1] = 42;  // ok
    a[countof(a)] = 7;  // diagnostic

    for (int i = 0; i < countof(a); i++)  // ok
        a[i] = 0;
    for (int i = 0; i < countof(a) + 1; i++)  // diagnostic
        a[i] = 0;

    a[42] = 0;  // diagnostic (42 not proved within [0,countof(a)).
}

MISRA C might be provably safe.

Posted Nov 19, 2025 12:57 UTC (Wed) by gmatht (guest, #58961) [Link] (6 responses)

Much of the difficulty of proving the safety of C is use-after free and double-frees. MISRA-C solves this by completely banning the use of dynamically allocated memory (even in memory-safe languages; you don't want your brakes to fail when malloc does). In MISRA-C:2012 there is also the advisory rule 17.5 which requires that array parameters to functions should have bounds specified.

For all I know MISRA-C is provably safe. I have seen many claims that MISRA is safe, but the context implies that they mean safe in an informal English sense of the word.

I wouldn't want to write a word processor in MISRA-C, but I understand there is a lot of safety-critical code written in MISRA-C. If there isn't a memory-safe compiler for MISRA-C there should be.

MISRA C is not provably safe.

Posted Nov 19, 2025 14:22 UTC (Wed) by tialaramex (subscriber, #21167) [Link] (5 responses)

MISRA-C is basically a glorified style guide so, no, it's definitely not "provably safe" in a useful sense.

MISRA-C;2012 R17.5 describes an ambition C cannot fulfil. It might almost as well say "Programs shall not have bugs". For rule 17.5 it wants to specify that the array size is part of the parameter type, but in C that is nonsense, the array types always decay to pointers here. You can write this out in C but C compilers will ignore your intent.

You can actually do what MISRA-C calls for here in Rust, and I have, exactly once, because it's very rarely actually useful. The case where I did took memory pages, they're always exactly 4096 bytes long (no, I don't handle huge pages), and I specified that the function takes only (references to) arrays of precisely 4096 bytes, so for Rust passing some other size won't compile for the same reason you can't pass a boolean to a function which takes a string - they're different types. C doesn't provide any such thing and MISRA can't imagine it into existence.

Obeying MISRA's style is a sign of compliance, which is a useful trait for safety systems, but to a considerable extent it's functioning as a Brown M&M check, it's not a proof of anything.

MISRA C is not provably safe.

Posted Nov 20, 2025 12:10 UTC (Thu) by khim (subscriber, #9252) [Link] (2 responses)

> You can write this out in C but C compilers will ignore your intent.

C compiler would, but there are other programs that wouldn't. It's the same story as Ada and SPARK, Rust and mrustc, etc.

The big question is whether full-blown checker for MISRA C exists or may even theoretically exist. PVS-Studio claims 80% coverage.

> they're always exactly 4096 bytes long (no, I don't handle huge pages)

What about 16KiB pages? MacOS uses them and Android moves there, too.

> but to a considerable extent it's functioning as a Brown M&M check, it's not a proof of anything

You can as well only use Rust with mrustc and claim that all these lifetime markups are just a wishful thinking. The big question about MISRA C is how much enforcement can be done automatically with existing tools, not whether C decays pointers. Sure, it decays them but for the MISRA C it's not a problem if you have an external checker.

MISRA C is not provably safe.

Posted Nov 21, 2025 10:10 UTC (Fri) by taladar (subscriber, #68407) [Link] (1 responses)

Are you seriously comparing the situation in C where everyone is using compilers that do not do these checks along with rumored full blown checkers that basically no C programmer ever tried with people on Rust using the standard compiler that everyone uses and a strawman user who uses mrustc, a compiler only used for bootstrapping?

MISRA C is not provably safe.

Posted Nov 21, 2025 11:52 UTC (Fri) by khim (subscriber, #9252) [Link]

We are talking about MISRA C here, isn't it?

All companies that I knew about with MISRA C aspirations have verifiers that they use to ensure [partial] compliance. Yes, these checkers do have bugs and don't catch 100% of violations, but so does Rust.

Thus I have no idea what are you talking about here, sorry: MISRA C and Rust approaches are very comparable.

Why not?

Posted Nov 21, 2025 14:17 UTC (Fri) by gmatht (guest, #58961) [Link] (1 responses)

The major innovation in Rust is the borrow checker. This does not accept all valid programs but (should) only accept valid programs.

Writing a general borrow checker for C is hard because C lacks the lifetime annotations and valid standards compliant C code may not conform to the borrow checkers expectations.

However MISRA-C is much more pedantic than the Rust borrow-checker. Since dynamic allocations are banned, unless all lifetimes are static, the program is not valid MISRA-C. And if all lifetimes are static, lifetime annotations are redundant, and lifetime checks are redundant.

There are lots of edge cases to consider, for example, if race conditions could result in memory unsafety. However, it seems that if a compiler is allowed to reject non-MISRA-C this would make it vastly easier to only accept provably safe programs.

Why not?

Posted Nov 21, 2025 15:21 UTC (Fri) by excors (subscriber, #95769) [Link]

> However MISRA-C is much more pedantic than the Rust borrow-checker. Since dynamic allocations are banned, unless all lifetimes are static, the program is not valid MISRA-C. And if all lifetimes are static, lifetime annotations are redundant, and lifetime checks are redundant.

MISRA C still allows automatic storage duration (i.e. stack variables), so not all lifetimes are static, and you can get bugs when a stack pointer escapes the function's scope.

MISRA C has the rule "The address of an object with automatic or thread-local storage shall not be copied to another object that persists after the first object has ceased to exist", but that's an explicitly undecidable rule, so it's basically saying "your program must not be buggy".

Some static checkers apparently detect simple violations of that rule (e.g. assigning the address to a global variable or returning it from the function that allocated it: https://www.mathworks.com/help/bugfinder/ref/misrac2023ru...), but I don't believe it's possible to detect all violations in otherwise-compliant code without rejecting plenty of reasonable and fully-compliant code.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds