Better HN
topnewbestaskshowjobs
Log inSign up

duneroadrunner

157 karma · joined Sep 26, 2016 (10y ago) · 164 submissions

Submissions

comment 9y ago · link · parent

SaferCPlusPlus does not recommend relying directly on mutexes at all. For most straightforward cases, you can use the "access requesters" to safely manage asynchronous access automatically.

Recursive mutexes are analogous to having multiple pointers (or iterators), some of which are "non-const", to an object in the same thread at the same time. Some suggest that this too is a bad idea. For example, the Rust language does not allow a "mutable" (i.e. "non-const") reference to an object to co-exist with any other reference to that object, even in the same thread.

SaferCPlusPlus does not necessarily disagree with this position, but it also does not require adherence to it, like Rust does. So if SaferCPlusPlus is going to allow multiple pointers (or iterators) to a shared object in the same thread, then it's going to need to lock the mutex protecting the object multiple times from the same thread. Giving each pointer/iterator its own separate lock, as opposed to having one lock encompass the all the pointer/iterators, allows the locks to be managed automatically, which ensures against data races, and that resource locks will be released as soon as it is safe to do so.

Again, there's rarely any reason you'd need to interact with the mutex directly. It's primarily there to support "access requester" functionality.

Also, note that this is a recursive shared mutex, not just a recursive mutex, which means that, for example, it provides a kind of "upgrade mutex" functionality. So if a thread has a "read" lock, it can obtain a "write" lock (blocking if necessary), without having to give up its read lock. Then when it's done with the write lock, it can release it without fear of losing its read lock (or blocking).

comment 9y ago · link · parent

Yeah, I think it might be a familiarity bias.

Anyway, the point of access requesters are that they are much safer than manually protecting resources with mutexes. That is, using access requesters eliminates the possibility of data races[1]. Which is important because data races can be particularly insidious bugs.

Just like how smart pointers can improve safety by automatically managing object lifetimes, access requesters can improve safety by automatically managing object lifetimes and asynchronous access.

[1] As long as you adhere to the rule that shared objects not have "unprotected" mutable or indirect (i.e. pointers/references) members.

comment 9y ago · link · parent

While "just enforcing `make_shared`" wouldn't solve all the memory safety issues, it actually can be somewhat practical to "just avoid using any (or most) C++ elements that can access invalid (or uninitialized) memory", instead using the safe, compatible substitutes in the SaferCPlusPlus[1] library.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

> "- Span For when you want to take an array or a vector."

> How's this different from taking a pair of iterators?

Safety and (a little) convenience. If your function takes a pair of iterators, there's no way to ensure (at compile-time anyway) that both iterators are even pointing into the same array/vector. Also, spans can ensure, with bounds-checking, that only elements within a specified sub-range can be accessed.

Such bounds-enforcement is particularly important in cases like, for example, SaferCPlusPlus' "TRASectionSplitter", which is a data type that allows you to partition an array/vector/whatever into subsections that can each be safely accessed/modified concurrently from different threads. ("TRASectionSplitter" is not yet documented, but for those interested, example code can be found here[1].)

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus/blob/master...

comment 9y ago · link · parent

> - Mutex

From their "Devguide":

Clients of Mutex must obey these rules:

1. Each time a thread acquires a Mutex it must later release it.

2. A thread may not attempt to release a Mutex unless it holds it.

3. A thread may not attempt to acquire an exclusive lock on a Mutex it already holds.

For basic sharing of resources between threads, using "access requesters"[1] can be safer and more convenient as they automatically take care of these rules for you.

And if you need to use the mutex directly, the SaferCPlusPlus library provides a "recursive_shared_timed_mutex"[2] (the one missing from the standard library), which allows a thread to hold multiple ("read" and/or "write") locks at the same time (relieving the "self-deadlock" issue). The mutex isn't documented, but it functions just as its name suggests.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus#asynchronou...

[2] https://github.com/duneroadrunner/SaferCPlusPlus/blob/master...

comment 9y ago · link · parent

SaferCPlusPlus[1] is the library that's probably closer to Rust "in spirit and intent". And more importantly, safety effectiveness. And it does address the data race issue.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

You can use the SaferCPlusPlus library[1] to get closer to "java safety".

C++ compile times are a problem. Apparently there is a C++ interpreter[2]. Anyone have any experience with it?

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

[2] https://root.cern.ch/cling

comment 9y ago · link · parent

One case the author left out was translation to "idiomatic" higher level language, which involves identifying abstractions that are intrinsically present, but where never explicitly expressed, in the original code. For example I've been working on a translator/converter from C to a memory-safe subset of C++[1]. The output is intended to be readable and maintainable as source code in its own right.

So when for example, encountering a pointer in the original C source, you have to determine from context whether the author is using it as an iterator to a fixed-sized array, an iterator to a dynamically-sized array, an "owning" reference to a dynamically allocated object, or just a weak/observer reference to an object, and translate to the appropriate "higher-level" element.

So in a sense it's a "decompiler" to a (higher-level) language the code was never compiled from. As a source-to-source transformer, presumably it would qualify as a "transpiler". But does that term have an connotation that the output is just an intermediate translation not intended to be maintained or used directly?

[1] https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...

comment 9y ago · link · parent

Yeah, I don't know if there's ever going to be a portable way to enforceably "disallow" the sharing of state between threads in C++. For straightforward cases, the SaferCPlusPlus library provides an easy way to "wrap" any object so that access from different threads is safely controlled[1].

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus#asynchronou...

comment 9y ago · link · parent

Sorry, I don't think I was thinking very clearly for the last part. I think you're right, the missing Send/Sync functionality is one of the areas where SaferCPlusPlus is still lacking.

comment 9y ago · link · parent

Well, the "scope" pointers, which roughly correspond to Rust's "non-mut" (i.e. non-retargetable) references and are generally the most commonly used pointer/reference type, don't have any run-time overhead. By their nature, as long as they exist, so does their target. You don't need a sophisticated borrow checker to ensure it.

"Mut" (i.e. retargetable) references, on the other hand, do require a borrow checker to ensure, at compile-time, that their target will outlive them. Since SaferCPlusPlus does not have a borrow checker (yet), you'd have to use "registered" pointers, which do have run-time overhead. But in practice, retargetable references are generally much less common than non-retargetable ones (particularly in inner loops), so there tends not to be much effect on performance.

SaferCPlusPlus does not yet have an exact analogy to Send/Sync. But as I understand it, those are basically just indicators that say "Trust me, this object is safe to send to / share with other threads." without any verification of the proclaimed safety. At the moment, SaferCPlusPlus does something functionally similar by providing the "TAsyncSharedObjectThatYouAreSureHasNoUnprotectedMutablesReadWriteAccessRequester" which basically allows you to make the same claim about the safe shareability of the object. (And has an unwieldy name to remind you of the seriousness of the claim.) Basically the rule of thumb is "Don't share any object that contains pointers/references/iterators (or is declared "mutable" in C++) or has any (non-static) member functions that return pointers/references/iterators."

Rust and SaferCPlusPlus maybe take different positions on whether sharing objects between threads should be encouraged with abandon, or done prudently and only as necessary.

comment 9y ago · link · parent

Technically, you would need to unambiguously define what you mean by "safe" and "Rust", but in the way that I think you mean it, the answer is essentially yes. "SaferCPlusPlus" does not refer to "modern" C++ programming practices that can help avoid many traditional classes of bugs. It, in theory, refers to the avoidance/prohibition of any C++ element that can access unallocated/deallocated or uninitialized memory. That means for example, no native pointers (including the implicit "this" pointer in member functions), references, arrays, unions, etc.. It also means no unsafe standard library elements like std::vector, std::array, std::shared_ptr, std::unique_ptr, etc.. In order to make this practical, there is a SaferCPlusPlus library that provides largely compatible (memory) safe substitutes for the most commonly used of these elements.

The implementation of SaferCPlusPlus as a language/dialect is not yet complete. For example, there is not yet a proper compile-time "enforcement" tool to verify that your code is actually free from unsafe elements. But as a programmer, you basically know what those potentially unsafe elements are, and the SaferCPlusPlus library already makes it practical to write C++ code that avoids the vast majority of them.

That said, I would say that, at the moment, SaferCPlusPlus is not a direct alternative to Rust. If you have the resources to do a rewrite of your project in Rust and memory safety is paramount, then that's probably the way to go. On the other hand, if you need a more expedient way to address code safety or have some other issue with using Rust, SaferCPlusPlus may be a more attractive choice.

https://github.com/duneroadrunner/SaferCPlusPlus#safercplusp...

comment 9y ago · link · parent

Have to mention SaferCPlusPlus[1] here - basically a memory-safe subset of C++ with (fairly) low migration cost. For example, here[2] is an open source png encoder/decoder that was ensured to be free from buffer overflow vulnerabilities via automated (partial) translation to SaferCPlusPlus.

[1] Shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

[2] https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...

comment 9y ago · link · parent

> I think there really needs to be a "Safe STL" in addition to "Performant STL" that performs range checks.

SaferCPlusPlus[1] provides compatible, memory-safe versions of the most commonly used STL containers. (The compiler switches mentioned by others add range checking, but do not, for example, catch use-after-free bugs.)

> > It's not simple to write memory safe code in C++, otherwise we would have a lot fewer vulnerabilities in C++ codebases.

Using SaferCPlusPlus, it now is simple to write memory-safe code in C++. And it's not much different from writing traditional (unsafe) C++ code.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

I think all your points are probably right (and insightful). But I think in this case the (immediate) goal isn't really popular adoption of this solution by existing C (or maybe even C++) programmers.

In part, it is simply a practical, relatively low cost solution to address the problem of invalid memory access in existing C/C++ code (and thus, for example, remote code execution vulnerabilities in internet facing code). Clearly we've still not reached the point where critical internet infrastructure vulnerabilities are perceived as costly enough to justify actually solving the problem (as you say in point 5). And collectively, we've not yet concluded that cheaper mitigation techniques aren't a "good enough" solution. At least for now.

But the costs (of critical vulnerabilities) are still going up, and there may come a time when some conclude that they have no choice but to properly address the issue. And some may opt for the least expensive option (i.e. something like SaferCPlusPlus rather than a full rewrite in another memory-safe language).

Of course, more appealing solutions might emerge before that time comes.

But there is also a longer term goal. I see a safe dialect of C++ (like SaferCPlusPlus) perhaps relevant in a future where code is liberated from the "language silo" it's trapped in, via auto-translators. For example, I don't expect C programmers to switch to SaferCPlusPlus en masse (although I'll probably continue to encourage it :). The idea is that legacy C code would be auto-translated to SaferCPlusPlus (with or without the support/consent of the original author). Kind of like how the tor guys used to build their ("safer") version of firefox with the sanitizers enabled[1], and didn't need the permission of the firefox developers to do it.

But it doesn't have to be restricted to just legacy C/C++ code. Modern C++ is so powerful that lots of languages could be translated to (a safe dialect of) it. I think. Presumably C++ would be a more appealing language if it had easy access to, say, all the existing Java code via auto-translation. This of course would apply to any language, but I think its power and performance makes C++ a good target for auto-translation. I'm sure other languages would make good targets too.

Basically, in the future I expect auto-translation quality to be a bigger factor wrt language relevance than marketing or mind-share.

[1] https://blog.torproject.org/blog/tor-browser-55a4-hardened-r...

comment 9y ago · link · parent

I can't say for certain why none of the "safer C"s have caught on, but I can say that they all have significant compromises and/or impracticalities. Often, performance cost is one of them. Today though, you can use the safe numerics[1] library along with SaferCPlusPlus[2] (shameless plug) as a high performance solution to address undefined behavior in your C code. This solution preserves most of your C code intact, and there is an auto-translation assistance tool[3] in development to further reduce the effort required. (SaferCPlusPlus currently has a dependency on the standard library, so may not be usable on the most restricted embedded platforms[4].)

If performance is not a concern, just compiling with the appropriate sanitizers[5] is an easy option (though not a complete solution).

But note that all of these solutions take the position that not only is the undefined behavior itself a problem, but also the operation which instigated the undefined behavior. And there is good reason for that. If you just want the undefined behavior to be defined, then the question is, what exactly are you trying to achieve by doing so? Are you hoping to guarantee deterministic behavior while maintaining portability?

[1] https://github.com/robertramey/safe_numerics

[2] https://github.com/duneroadrunner/SaferCPlusPlus#safercplusp...

[3] https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...

[4] https://github.com/duneroadrunner/SaferCPlusPlus/issues/3

[5] http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html

comment 9y ago · link · parent

Obligatory shameless SaferCPlusPlus[1] plug: It is now practical to eliminate the use of unsafe C/C++ elements (like pointers and iterators) by replacing them with safe, compatible substitutes. Using the SaferCPlusPlus library, your example code could become:

    #include "msemstdvector.h"
    // ...
    auto v = mse::mstd::vector<int> { 1, 2, 3 };
    auto e = v.begin() + 0; // 'e' is a safe iterator here
    // ...
    v.push_back(v.size());
    // ...
    cout << *e << "\n"; // no problem
Not much different from your original code.

Rust's policy of static enforcement of "exclusive mutable references" still might be preferable in many cases, but there is a practical option of using C++ in a safe(r) way.

[1] https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

It's still in early development, but there is a tool[1] that automatically converts potentially unsafe C/C++ code to be memory-safe. If the problem is C/C++ programmers that write unsafe code, rather than trying to change their practices (or even change the language they program in) maybe it's more practical to just have a robot "fix" the code.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus-AutoTransla...

comment 9y ago · link · parent

> Switching languages requires a full rewrite ...

It's not ready for use in the wild, but I'll just mention that some good progress is being made on a "C to SaferCPlusPlus[1]" auto-translation assistant. (SaferCPlusPlus is essentially a memory-safe subset of C++.) At this point it can recognize arrays and "pointers used as array iterators" in C code and replace them with memory-safe substitutes. Hopefully an (incomplete but) usable version will be available before long and we can gauge the interest of developers/maintainers.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

> That said, the expected win for Rust over C(++) in practice is that you can be more "reckless", ...

I'm glad to see somebody articulate this observation. SaferCPlusPlus[1] is meant to, in part, bring this benefit to existing C++ code bases. The question is, would a borrow checker for C++ make sense?

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

And don't forget the llvm (and gcc) sanitizers[1] and SaferCPlusPlus[2] (essentially a memory safe subset of C++), which are more modern and have arguably better overall combinations of performance/safety/compatibility/practicality.

Automatic translation (assistance) from native C to SaferCPlusPlus is being worked on. And if you'll permit me to gripe a little here - you might think it's a reasonable undertaking, until you start contemplating code like this:

  int **var1 = (int **)malloc(20);
  var1[2] = (int *)malloc(10);
  int *var2 = var1[2] + 4;
  var2--;
  free(var2 - 3);
  free(var1);
:)

[1] https://github.com/google/sanitizers

[2] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

Thanks. I'll take all the git/github advice I can get. :)

comment 9y ago · link · parent

If any of the developers are reading this, converting the existing C code to SaferCPlusPlus[1] (a memory safe subset of C++) is probably a more expedient solution (if that's what they're looking for). (And speaking of contributing, an automatic translation (assistance) tool is in early development, and could maybe be functional in short order with a little extra motivated talent... :)

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

> when you have a lock held but then attempt to take a lock again in some control path (perhaps through a recursive or deep call stack, or, in your case, calling another member function

The standard library provides std::recursive_mutex which supports being locked multiple times by the same thread. Unfortunately, it doesn't provide an std::recursive_shared_timed_mutex for the general case where you might want to support multiple simultaneous read operations. The SaferCPlusPlus library does implement such a mutex, and, like I mentioned in another comment, provides data types that automatically control access to shared objects. I think for most cases, it's the safest and easiest way to share objects asynchronously (in C++). (The data types are kind of analogous to Arc<> and Arc< Mutex<> > for those familiar with Rust.)

Btw, the implementation is self-contained, so you can use the safe sharing data types without having to include the rest of the library. Or you can just copy the source code and make your own safe sharing data types.

comment 9y ago · link · parent

When data races are the concern, SaferCPlusPlus provides nice data types for safely sharing objects asynchronously[1]. Basically, glorified shared_ptrs that automatically handle all the necessary locking (and blocking).

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus#asynchronou...

comment 9y ago · link · parent

> I just don't think there's a viable alternative

Fyi, when safety is important and C++ is the only viable alternative, there's SaferCPlusPlus[1].

And wrt new C++17 features, I'll just point out that the SaferCPlusPlus library provides a version of std::any (and std::variant) geared specifically for pointer/iterators. That is, you can, for example, dereference the contained pointer/iterator without needing to know its actual type. And for those that need it, it also provides the "recursive_shared_timed_mutex" that's notably missing from the standard library.

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

I haven't read the book. What's the gist of the recommendations for addressing those issues? SaferCPlusPlus addresses the signed/unsigned issue by providing compatible substitutes[1] for "int" and "size_t" that automatically handle it. And it addresses the integer underflow/overflow issue by recommending another compatible "int" substitute[2] and introducing the concept (but not yet the implementation) of "quarantined" types for untrusted input values.

[1] https://github.com/duneroadrunner/SaferCPlusPlus#cint-csize_...

[2] https://github.com/robertramey/safe_numerics

comment 9y ago · link · parent

> This one is totally obvious but has a stunning number of ways you can fail to adhere to it, some of which look reasonable at first blush

If memory safety is actually important to you, there's now an actual practical solution: SaferCPlusPlus[1].

A tool to automatically retrofit memory safety to existing C/C++ code is in early development (but resources are limited so it might be a while).

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

That's one of the arguments for SaferCPlusPlus[1]. It's a (high performance) option for retrofitting memory safety to existing C/C++ codebases. It requires (straightforward) modifications to the existing code, but involves much less effort than a complete rewrite. A tool to (mostly) automate the required modifications is being worked on. (But more resources might hasten its progress, if any of those well-resourced entities wanted to redirect some of their efforts from vulnerability detection and mitigation to prevention :)

Just out of curiosity, what kind of performance penalty are people be willing to accept in exchange for memory safety?

[1] shameless plug: https://github.com/duneroadrunner/SaferCPlusPlus

comment 9y ago · link · parent

Not technically a separate language, SaferCPlusPlus[1] is a memory safe dialect/subset of C++. As far as I know, it is by far the highest performance[2] solution currently available for addressing memory safety in C/C++ code (aside from full static verification when that is feasible, of course). The idea is basically just to replace the potentially unsafe elements of C/C++ (like pointers and arrays/vectors) with compatible (memory) safe substitutes. A nice thing about this approach is that converting existing (unsafe) C/C++ code is a simple, straightforward process (that should hopefully be (mostly) automated before long), and it doesn't require learning/adopting any new paradigms. If you want maximal performance though, you'll need to understand the technique of using "scope lifetimes" to achieve memory safety with no run-time overhead.

It's been perfectly usable for a while now, but it's not yet complete. Static tools for automatically identifying uses of potentially unsafe C/C++ elements in existing code, and (at least mostly) automated translation are still being worked on. And there are still elements that are missing safe substitutes (like std::string). So, if anyone's looking to kill some free time... :)

[1] https://github.com/duneroadrunner/SaferCPlusPlus

[2] https://github.com/duneroadrunner/SaferCPlusPlus-BenchmarksG...

123456