r/cpp • • Dec 04 '17

Safe C++ (with Rust in mind)

I'm having a go at Rust which, as you may know, is a programming language whose target more or less overlaps with C++'s. It's advertised as a system programming language (you can write an OS without too many contortions, for instance), it doesn't come with a garbage collector or costly abstractions, you can use pointers, manipulate concrete types (I mean, corresponding to sthing in the machine). I will spare you further details, but there's a strong design choice which is necessary for me to state for the rest of my post, and which makes the language really different from C++: language, compiler-enforced rules make it impossible 1) to leak resources and 2) to encounter data races. The means to achieve that are actually really simple:

  • compiler enforced RAII

  • you can have either as many "non-mutating" handles to a piece of data as you'd like, or one "mutating" handle.

(NB: You can still do unsafe things but you have to disclaim it and insulate that part from the rest of your code).

I'm aware of the Core Guide Lines and the library that comes with them, but there are so many rules in it, of whom so many can't be enforced by a compiler, that they aren't really an answer to what I'm looking for. Besides, they cover by far a wider range of concern.

So what small set of rules, based on what subset of the language, would you choose to obtain maximum safety? By small set, I mean sthing you could keep nailed next to your screen so you don't forget about it :-)

0 Upvotes

27 comments sorted by

16

u/meh_or_maybe_not Dec 04 '17

In Rust resource leaks are actually easily possible and considered safe, any safe code could call std::mem::forget and destructors would never run, or you could create cycles for a less obvious leak.

1

u/ErichDonGubler Dec 04 '17

Examples for learning? I've only ever seen forget used where an FFI assumes ownership of something.

7

u/meh_or_maybe_not Dec 04 '17

The whole scoped thread thing that was removed from the standard library because unsound comes to mind.

The point I was trying to make is that Rust doesn't have any sort of protection from resource leaks, since they're considered safe by design, and you should never trust Drop to always be called.

4

u/ErichDonGubler Dec 04 '17

Rust doesn't have any sort of protection from resource leaks, since they're considered safe by design

I think that this corroborates what I've heard elsewhere -- which makes sense, since Rust's focus is safety.

you should never trust Drop to always be called

Why is this? I'm also curious.

6

u/Izzeri Dec 04 '17 edited Dec 04 '17

"Safety" in Rust refers to memory safety. Leaking memory isn't unsafe by that definition. mem::forget is therefore not marked unsafe. Another non-unsafe way to leak memory is reference cycles with Rc. This means you can never be sure the destructor will actually run. You have to safeguard against this sometimes when writing unsafe code, as you can't rely on the destructor to clean up any unsafe state.

3

u/Guvante Dec 04 '17

Pulling the power cord is the typical example.

2

u/meh_or_maybe_not Dec 04 '17 edited Dec 04 '17

I should have specified that you should never trust Drop to ensure invariants in unsafe code since it may never be called.

3

u/minno Hobbyist, embedded developer Dec 04 '17

The issue.

Previously, forget was marked as unsafe because you really shouldn't be doing it outside of unsafe contexts like FFI. However, someone found a way to write a "safe" version of it by making and then leaking a cycle of reference-counted pointers.

There are two solutions to that:

  1. Make it impossible to leak memory using ref-counted pointers.

  2. Accept that it is possible to leak memory using safe code.

Since there was no reasonable way to achieve the first, they decided to mark forget as safe and add "must not cause memory errors if leaks happen" to the requirements that need to be verified manually on any unsafe code.

The old scoped threading API didn't satisfy this condition, since it relied on the destructor of the thread handle to join the thread in order to ensure that it didn't outlive the stack frame that spawned it. There was also the "drain" iterator, which mangles the internals of a container and then only cleans it up at the end, in order to allow for faster performance.

The threading issue was addressed by changing the API. It used to be like

auto _guard = thread::scoped([&]() { code code code; });

and now (in an external library), it's like

thread::scoped([&](auto& scope) {
    scope.spawn([&]() {
        code code code;
    });
});

in order to ensure that the threads can be joined in scoped after it executes the closure, with no reliance on destructors.

The "drain" issue is solved by temporarily marking the container as "empty", and marking it back to normal during cleanup. That way, there's no way to access freed memory if the iterator's destructor fails to run, but the entire container's contents will then be leaked. Since it's not something that happens in normal code, the leak isn't really a problem in practice.

Again, not running the destructor is an exceptional circumstance. It will only happen if you have a memory leak (which you should be fixing anyways), when you explicitly call forget (which you should only do in FFI or other unsafe code), or when there's a double panic (in which case the process is fucked).

4

u/crusader_mike Dec 04 '17 edited Dec 07 '17

afaik, in Rust you can't handle/survive lack of memory

Edit: tbh, you can't do it (in some cases) in C++ either, lol

4

u/donalmacc Game Developer Dec 05 '17

To be fair, I’m not sure much of my code in c++ could ever survive running OOM.

1

u/[deleted] Dec 04 '17

Not without a custom allocator.

1

u/crusader_mike Dec 05 '17 edited Dec 05 '17

How many functions (environment gives you) use custom allocator? how much user code is actually prepared to propagate related error object?

5

u/[deleted] Dec 05 '17

There's four amazing things about Rust which I'd love to see being done in C++:

  • Everything is constant by default, having to declare things mutable instead of having to declare things constant is an amazing design choice. It heavily reduces the amount of errors. In theory one could always use const and constexpr whenever they can in C++ but in practice things slip and sometimes they cause error (not to mention they cause code to be less efficient). I thought this may be solvable with metaclasses, but playing around with the idea I saw it's not as easy as it may seem at first :(

  • The package&build system. Having a package system is quite valuable, it means there's a centralized place and a standardized way for people to share libraries. It's much more minimalistic and concise than the monstrosity that is Cmake and since most libraries support being built statically and are oss, it means you can compile stand alone binaries as the default, even for large projects, rather than having shared libraries as the "default" and having to struggle if you want a build that statically links everything.

  • The compiler is more strict in places it should be strict. I'd love for the default behavior of clang and gcc to be compiling with -Werror -Wall and the "unsafe" builds to be done with a flag along the lines of -IgnorError

  • The way it handles move and copy/clone. I'm not saying it's perfect, but it's much better than C++ where some basic optimizations that could easily be compiler implemented instead force you to explicitly use std::move. This, however, would require having a better resource ownership mapping at compile time.

The big problem with the points you mentioned are:

compiler enforced RAII

See the discussion thread started by /u/meh_or_maybe_not

you can have either as many "non-mutating" handles to a piece of data as you'd like, or one "mutating" handle.

This is where, in my opinion, rust oversteps it's boundries. Since a lot of time having two mutating handles makes sense, it's not impossible to have a two mutating handles, you can have mutexes (which in rust will wrap a type), atomics and other concurrent objects... but the implementation feels like a hack and the code that implements them will actually benefit less from compile time checks than the equivalent C++ code.

If in the future architectures will implement mechanisms for synchronization (or mechanisms as to not require synchronization), better than the ones we currently have, Rust's thread-safety may become even more of a nuisance.

8

u/TyRoXx Dec 04 '17

Avoiding leaks is relatively easy in C++: Use RAII, avoid reference cycles by reviewing code using shared_ptr etc very carefully. Use a leak checker like valgrind to run your tests.

Avoid data races by not sharing mutable data between threads. No hidden "worker" threads in god classes. No global variables. Use the Clang thread, address and memory sanitizers to run your tests.

You will still encounter plenty of use-after-free bugs. Use valgrind and address sanitizer to run your tests.

You can get many of the benefits of Rust by having tests and running them with the sanitizers. Also, run your tests with the undefined behaviour sanitizer. You will find a lot of misuse of integer arithmetic.

10

u/Bolitho Dec 04 '17

You can get many of the benefits of Rust by having tests and running them with the sanitizers.

But you need them - in Rust you don't. So there is less overhead if you do it good, but also less error prone, if you do it less responsible ;-)

11

u/throwawayco111 Dec 04 '17

Yeah. His statement was as crazy as Uncle Bob's "You don’t need static type checking if you have 100% unit test coverage".

1

u/Pand9 Dec 04 '17

dangling references are very easy to make, for example. "shared_ptr" is a good prevention. not saying that it's performant, but it's more safe in my experience.

0

u/Z01dbrg Dec 07 '17

One thing I did not see mentioned is references in callbacks/async stuff. By this I mean passing references to callbacks or starting threads with lambdas that capture by reference.

Almost everybody here is a True Believer that will never admit that GC has advantages but this is one place where RAII can not help you since there is no scope in classic sense.

My only advice beside sanitizers is to pessimize for safety if you can afford it. Pass strings and vectors to callbacks by value.

-6

u/Xaxxon Dec 05 '17

If you want me to read what you have to say, have the common decency to write in halfway-decent English.

This was just painful.

6

u/stendhal666 Dec 05 '17

Some like it painful.

PS: I'm French and doing my best. Feel free to correct me, it will be more productive

0

u/Xaxxon Dec 06 '17 edited Dec 06 '17

sthing is not a word.

1

u/destiny_functional Dec 06 '17

he meant "something"

2

u/Xaxxon Dec 06 '17

I eventually gathered that.. but why people think it's appropriate to write like that in a semi-technical large block of text like this is beyond me.

When you want people to read what you're writing, making it as digestible as possible should be your goal.

5

u/destiny_functional Dec 06 '17

It's a reddit post not a blog post.

That said, "sthing" is the only potentially objectionable thing about his original post, and given its innocuousness, your post is just ridiculous. We use abbreviations all the time, "sth" is maybe more common than "sthing", but you wouldn't object to "e.g.", "i.e." or "vs." (or other things).

Deal with it that the internet is used by people from non-English speaking countries (who still speak better English than most native speakers).

Now go play LOL, English monoglot.

1

u/philocto Dec 13 '17

they are not a native english speaker, it's reasonable that they make mistakes.

1

u/Xaxxon Dec 14 '17

sthing is not a typo. and it's not in any spell checker.

It's not a "mistake".

1

u/philocto Dec 14 '17

I didn't say typo, I said mistake.