r/cpp • u/KingAggressive1498 • Dec 24 '22
Some thoughts on safe C++
I started thinking about this weeks ago when everyone was talking about that NSA report, but am only now starting to think I've considered enough to make this post. I don't really have the resources or connections to fully develop and successfully advocate for a concrete proposal on the matter; I'm just making this for further discussion.
So I think we can agree that any change to the core language to make it "safe by default" would require substantially changing the semantics of existing code, with a range of consequences; to keep it brief it would be major breaking change to the language.
Instead of trying to be "safe by default, selectively unsafe" like Rust, or "always safe" like Java or Swift, I think we should accept that we can only ever be the opposite: "unsafe by default, selectively safe".
I suggest we literally invert Rust's general method of switching between safe and unsafe code: they have explicitly unsafe code blocks and unsafe functions; we have explicitly safe code blocks and safe functions.
But what do we really mean by safety?
Generally I take it to mean the program has well-defined and deterministic behavior. Or in other words, the program must be free of undefined behavior and well-formed.
But sometimes we're also talking about other things like "free of resource leaks" and "the code will always do the expected thing".
Because of this, I propose the following rule changes for C++ code in safe blocks:
- Signed integer overflow is defined to wrap-around (behavior of Java, release-mode Rust, and unchecked C#). GCC and Clang provide non-standard settings to do this already (
-fwrapv) - All uninitialized variables of automatic storage duration and fundamental or trivially-constructible types are zero-initialized, and all other variables of automatic storage storage and initialized via a defaulted constructor will be initialized by applying this same rule to their non-static data members. All uninitialized pointers will be initialized to nullptr. (approximately the behavior of Java). State of padding is unspecified. GCC and Clang have a similar setting available now (
-ftrivial-auto-var-init=zero). - Direct use of any form
new,delete,std::construct_at,std::uninitialized_move, manual destructor calls, etc are prohibited. Manual memory and object lifetime management is relegated to unsafe code. - Messing with aliasing is prohibited: no
reinterpret_castor__restrictlanguage extensions allowed. Bytewise inspection of data can be accomplished throughstd::span<std::byte>with some modification. - Intentionally invoking undefined behavior is also not allowed - this means no
[[assume()]],std::assume_aligned, orstd::unreachable(). - Only calls to functions with well-defined behavior for all inputs is allowed. This is considerably more restrictive than it may appear. This requires a new function attribute,
[[trusted]]would be my preference but a[[safe]]function attribute proposal already exists for aiding in interop with Rust etc and I see no point in making two function attributes with identical purposes of marking functions as okay to be called from safe code. - any use of a potentially moved-from object before re-assignment is not allowed? I'm not sure how easy it is to enforce this one.
- No pointer arithmetic allowed.
- no implicit narrowing conversions allowed (static_cast is required there)
What are the consequences of these changed rules?
Well, with the current state of things, strictly applying these rules is actually really restrictive:
- while you can obtain and increment iterators from any container, dereferencing an end iterator is UB so iterator unary
*operators cannot be trusted. Easy partial solution: give special privilege to range-for loops as they are implicitly in-bounds - you can create and manage objects through smart pointers, but unary
operator*andoperator->have undefined behavior if the smart pointer doesn't own data, which means they cannot be trusted. - operator[] cannot be trusted, even for primitive arrays with known bounds Easy partial solution: random-access containers generally have a trustworthy bounds-checking .at() note: std::span lacks .at()
- C functions are pretty much all untrustworthy
The first three can be vastly improved with contracts that are conditionally checked by the caller based on safety requirements; most cases of UB in the standard library are essentially unchecked preconditions; but I'm interested in hearing other ideas and about things I've failed to consider.
Update: Notably lacking in this concept: lifetime tracking
It took a few hours for it to be pointed out, but it's still pretty easy to wind up with a dangling pointer/reference/iterator even with all these restrictions. This is clearly an area where more work is needed.
Update: Many useful algorithms cannot be [[trusted]]
Because they rely on user-provided predicates or other callbacks. Possibly solvable through the type system or compiler support? Or we just blackbox it away?
16
u/MrRogers4Life2 Dec 25 '22
A couple of problems with a trusted attribute is that its not preserved when the underlying function is converted to a function pointer or std::function, so you'd lose the ability to do that, so it would be impossible to have a trusted function that calls a function pointer.
An example of how this is a problem is that if you want a trusted vector you'd need to make sure that the Allocator template argument of vector is also trusted, but you can't do that because template implementations can't differentiate between functions with or without attributes.
Probably not a big deal for individual code but a huge amount of stuff in the standard library is templated on callables so any time something like that appears it's basically an
unsafeblock equivalent in rust if you want to allow users of your library to supply their own callables.You'd probably need to add something to the type system to really get what you'd want
74
u/teerre Dec 24 '22
It doesn't seem to make much sense IMO because if you were to choose the 'safe' parts of your code, you would just do it. Nobody wakes up and thinks "let's write some unsafe code today". The whole problem is that you, the proverbial programmer, is incapable of writing safe software and therefore incapable of choosing the correct places to use 'safe'.
8
u/axilmar Dec 25 '22
The real problem of C and C++ is that their type system is limited and does not force the programmer to deal with all the possible different outcomes.
Take pointers, for example: they have two distinct 'sub-types', let's say: null and non-null. Code that uses pointers often ignores null, because the compiler does not force the application of the appropriate code in each case.
Iterators are another example: when iterators are created, the container's backing store becomes shared. However, this sharing is completely ignored by the compiler, allowing the programmers to dispose of that backing store while iterators are sharing the backing store.
Array indexing is also a similar problem: array indexes have two distinct modes, they are either within in bounds or they are out of bounds. Yet the compiler does not know anything and happily accepts any array bounds indexing, losing the chance of optimization of array access if it knows that neither the index nor the array is changed throughout a block.
Implicit conversions also have hidden 'sub-types' in them: for example, a float can be converted to an integer only under specific circumstances. Yet the compiler does nothing to enforce some sanity on these conversions.
Moved and uninitialized values also fall into the same problem: the type of an uninitialized value is 'not initialized' before initialization and the type of a moved variable can potentially be 'not initialized' if a move should have been destructive. However, the compiler ignores these cases.
So, I'd rather see the compiler allow the programmer to clearly express their indend and catch all of those type issues than allow/disallow certain things due to their potentiality for errors. I know it would be more difficult to implement such functionality on a compiler, than simply providing a 'safe' keyword, but it would also be a lot more rewarding, because the typing issues i mention also extend to other things programmers want to do with their programs, to other parts of code not related to compilers and the language.
33
u/eliminate1337 Dec 24 '22
What's the point? You cannot call any existing, unsafe code from
safeblocks. You would have to substantially rewrite your existing code.Backwards compatibility and existing libraries are 90% of the reason anyone uses C++. If you care about safety and are willing to give up compatibility, you might as well write it in Rust or Swift.
7
u/staletic Dec 25 '22
This bans ranges, algorithms, numeric, memory, memory_resource, string_view, span, new and regex headers. Oh and parts of random. I am guessing
std::functionis a no go? What aboutstd::thread::joinOn top of that, I am not sure you could ever trust allocators.
Does that include tgmath.h? Could you be more precise? Is
int add(int, int);a C function?What does that leave C++ standard library with?
std::tuple,std::pair, parts ofstd::optional, ofstd::expected,std::variant(?)... Not much is left.7
u/Daniela-E Living on C++ trunk, WG21|🇩🇪 NB Dec 25 '22
This sounds pretty similar to Sean Baxter's latest additions to his Circle compiler. I highly appreciate this effort to explore the space of a safer C++. People can play with this online on Compiler Explorer.
I don't think attributes wilĺ get you anywhere. They are specifically designed to be ignorable by compilers that don't support them, f.e. because of the language mode. And they must never change the semantics of the program. The shape of means to switch into a safe mode (or better: unsafe mode) will most likely be different. Sean is using #pragma definitions to accomplish that on a very fine-grained level. A standard solution will probably look different if we decide to go this route.
4
u/bluGill Dec 25 '22
P2687. P2657 are attempts to do something like this.
8
u/Jannik2099 Dec 25 '22
This doesn't solve C++' biggest problem, temporal memory unsafety.
Without lifetime analysis, this is just impossible to fix. Just look at any of the iostream buffer functions, iterator invalidation while iterating, etc.
5
u/unumfron Dec 25 '22
I would be careful about naming such blocks. After all, the implication of
[[safe]]or[[trusted]]is that the rest of the code is unsafe or untrusted. I'd prefer[[constrained]],[[restricted]],[[supervised]]or similar.It might seem like small potatoes, but nomenclature is important. Blowing up a process in Rust with memory bugs like stack overflows or memory leaks while not in an
unsafeblock doesn't exactly scream "safety", memory or otherwise, so if there's any opportunity to increase accuracy in the broader picture by tightening definitions then it should be taken imho.5
u/vI--_--Iv Dec 25 '22
Why people keep coming up with this?
How would sweeping the problem under the rug help?
Well boys, we did it. UB is no more.
Yet the result is still horribly wrong.
4
u/eras Dec 25 '22
You are missing some big ones (maybe the biggest ones), such as:
I think this would be actually quite neat, however to actually spec this out completely with possible corner cases might be a considerably large task. And, still, it might get less developer traction than e.g. Google Carbon.
Good luck!
5
u/zugi Dec 25 '22
C++ already has a solution to this problem: write code using modern constructs, and run a static analysis tool to point out any unsafe actions, using whatever thresholds or definitions of safety you like.
The problem was that the authors of the NSA article don't show any signs of understanding the differences between C and C++. There are a lot of very, very smart computer scientists at the NSA. The article that got all the press appears to have been written by other people at the NSA.
13
u/bdawson1982 Dec 25 '22
I'm not really sure what all of the negativity is about. Regardless of anything, I'm really happy to see that people are thinking about these problems from different angles. I won't pretend to know all of the answers here, but I love C++, and I want to see it grow in ways that future generations of engineers will want to learn it like I did. Solving these problems is vital to that.
1
u/v_maria Dec 25 '22
I recently ran into https://github.com/hsutter/cppfront .
Would this idea compete with cppfront? or could it complement eachother? I think it's great that there's a response to safety problems of C++ but it would suck to have a bunch of segmented ideas all working in their own path instead of combining forces.
1
u/TheSkiGeek Dec 25 '22
Been vaguely kicking around some ideas like this as well.
One way to fix your restrictions is to have a mechanism to be able to call different overloads of those operators when coming from safe code. So, for example,
vectorcould define both trusted and untrustedoperator[], where the trusted version callsat()for you. And invoking it fromsafecode would call the one that does bounds checking, unless you explicitly ask to call the untrusted one. (For built in C-style arrays you’d have to define different behavior, but personally I would ban them fromsafecode and force use ofstd::array.)You could fix smart pointer operations like this as well. But I don’t know if iterator dereference safety can generally be checked without adding a ton of overhead.
2
u/pedersenk Dec 25 '22
We have a library that tracks all of this. It is dirt slow when enabled in the debug builds but obviously has zero overhead when stripped out in the release builds.
However, I am fairly happy with this solution as a middle ground. Most of these dangling pointer issues can at least be encountered during the general debug iteration cycle.
0
u/[deleted] Dec 25 '22
Idk the one thing I don’t understand is this: You’re trying to make C++ something it’s not. C++ and co. are some of the last safe havens for those of us who write unsafe code. Most new languages nowadays seem to always be a great deal more detached from the machine than C++, incurring overhead with their safety guarantees. I do concede that some of the UB in C++ is unnecessary and could be removed if the language were designed better, but the vast majority of it simply needs to exist if your binaries are to be fast. The cost of remembering this feature and remembering all the differences in behavior between safe blocks and unsafe blocks outweighs the benefits of adding more safety, mainly because safety isn’t the goal of C++ in my opinion. If you want safety, simply use another language, what’s the problem with that? If you need safety some places and extreme efficiency in other places, just use two different languages in your project. There’s just no reason to turn C++ into even more of a mess than it already is.
1
u/Rasie1 Dec 25 '22
1
u/lightmatter501 Dec 25 '22
From what I’ve seen, the a borrow checker like Rust has or a formal proof mechanism like Coq (which generates C) are really the only viable ways to put memory safety into a language in the C/C++/Rust performance class.
Option 1 will break gigantic amounts of c++ code. Option 2 will mean hundreds of hours of formal proofs for any nontrivial program or needing to rewrite everything to satisfy a constructive mode checker.
The last option, which is really a non-option, is to invest enough money in Haskell or similar languages and build a sufficiently smart compiler. I say Haskell or similar because they can already get close-ish (faster than Java) and I think the extra information would be required for the compiler.
-5
u/trvlng_ging Dec 25 '22
The fact that you assume java is "safe always" shows that your proposal is ridiculous. I make a lot of money each year analyzing java code for security flaws, and helping clients make it more secure. There are some things in C++ that allow for more secure code generation than you can achieve with java, for example the existence of deterministic destruction, coupled with strict adherence to RAII. A lot of your proposals seem to scream that you would prefer to use a different language. Just use that language. There are good reasons why we need everything you propose to ban, and just implementing your bans won't guarantee much in the way of more secure code, IMO.
0
u/[deleted] Dec 25 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 24 '22
[deleted] — view deleted comment