4 ms·
I am trying to understand how these two statements work together. 1) > unsafe code is infectious like Java's exceptions. If you call an unsafe function, you ne
by rdtsc 12y ago
I am trying to understand how these two statements work together.
1) > unsafe code is infectious like Java's exceptions. If you call an unsafe function, you need to mark yourself as unsafe, or explicitly state the boundaries where the unsafety is handled.
2) > Unsafe is for the lowest levels of abstraction to deal with
So according to 1) unsafe code is infectious but according to 2) you should only use it at the lowest level in your code. By this I understand things like mmap-ing a file, get a value out of shared memory, interacting with C code and so on. Presumably if your high level code depends on low level code, wouldn't the lower level "usafety" bubble all the way to the top. And next thing your main do_top_level_business_logic() function has to be wrapped in an unsafe block?
Now while typing this I am thinking of maybe one way to handle is and that is to create a separate task and shuffle data via messages between another unsafe task. If task crashes just restart it...
- Hemospectrum 12y agoIt bubbles up as far as an `unsafe { ... }` block, but no higher.
- vutekst 12y agoYes, presuming that the author of the unsafe code in question has manually verified the effective safety in all relevant scenarios. `unsafe` is an assertion to the Rust compiler that you know what you're doing, and you will preserve its guarantees as far as external observers are concerned. I might point out to the grandparent post that even the basic vector collection in Rust is full of unsafe {} blocks.
- rdtsc 12y agoI understand now, thanks for explaining. It was implied in the article too, by analogy with java's exceptions, I just forgot how that works too.
- kibwen 12y agoTo clarify, there are two places that you can use the `unsafe` keyword: unsafe { /* arbitrary code in here */ } // applied to a block unsafe fn foo() { /* function body */ } // applied to a function It's the second form that is infectious. When applied to a function, that function can only be called from an unsafe block or another unsafe function. The use of this form is to say, "hey, as the author of this function, I have no ability to determine whether or not this function is safe to use; let the caller beware." However if, as the author of a function, you can take steps to ensure that the function is used safely, then you can stop the infection with an unsafe block. For illustration, let's do one of the things mentioned in the post. Here's a function that prints every element in a vector: fn foo1(v: Vec<int>) { let length = v.len(); let mut i = 0; while i < length { println!("{}", v[i]); i += 1; } } That `v[i]` in there is potentially doing bounds checking (in practice a simple case like this would get optimized away by LLVM, but let's ignore that), but note that this is superfluous because we've written this code such that `i` will always be a valid index. So let's turn off bounds checking by using the `unsafe_get` method mentioned in the OP: fn foo2(v: Vec<int>) { let length = v.len(); let mut i = 0; while i < length { println!("{}", unsafe { v.unsafe_get(i) }); i += 1; } } Like I was saying above, `unsafe_get` is a function that is itself marked unsafe, because the author of `unsafe_get` knows that you can cause memory unsafety by passing in an invalid index. But because we've written this program carefully, we know that both foo1 and foo2 are exactly as safe, so we've fenced off the unsafety here with the `unsafe` block. Both foo1 and foo2 can be called from safe Rust code with no special consideration. Now, what happens when, years down the road, someone who isn't paying attention accidentally modifies this function? fn foo3(v: Vec<int>) { let length = v.len(); let mut i = 0; while i <= length { // look carefully println!("{}", unsafe { v.unsafe_get(i) }); i += 1; } } This version of the function contains an off-by-one error. Anyone calling foo3 will try to index beyond the end of the array, and all hell will break loose. What do you do then? Well, you grep for the word "unsafe" and you start auditing unsafe blocks, looking at all the inputs that you send into them. This is generally the same approach you'd take in any other systems language, except that by limiting where unsafe code can appear you reduce the code that can potentially go wrong by 10-100 times, and speed up your auditing commeasurably. And the promise made in the OP stands: if you don't yourself use `unsafe` code and memory safety happens, it's someone else's fault, not yours. :) And how often do you need to resort to unsafe code in Rust? It depends on your domain. Efficient data structures often require all sorts of custom pointer tricks, so maybe a tenth to a third of their code is unsafe in Rust. For application-level programming, I'd expect no more than 1-3% unsafe code (maybe up to 5-10% if you're trying to push performance to the absolute limit, like Servo is doing).
- Animats 12y agoAnyone calling foo3 will try to index beyond the end of the array, and all hell will break loose. What do you do then? Well, you grep for the word "unsafe" and you start auditing unsafe blocks, looking at all the inputs that you send into them. That's not a very good solution. "Kill problems, don't just wound then" - Kelly Johnson, Lockheed Skunk Works, designer of the U-2 and SR-71. I used to work on this problem, about a decade ago. I was trying to figure out how to make C++ safe. I finally gave up, since memory safety wasn't a priority with the C++ committee. I'd proposed scope-based "borrowing" (I used the term "keeping", as the inverse of borrowing) and reference counts. Complex data structures remained a problem. The best idea I could come up with was to use weak pointers heavily. When you have something like a GUI widget library, with pointers going upwards, downwards, and sideways, who owns what is a big issue. One solution is that all the graphics widgets are owned by some top level object, like the "window" object, all the inter-widget links are weak, and all the weak pointers are in objects that can't outlive the top level object. This creates a sort of allocation pool. Objects pointed to by weak pointers can't fully go away until the parent object of all the weak pointers goes away. They only get marked as invalid for weak pointer referencing. This is memory-safe, but you don't get the space used by widgets back until the top-level page object is deleted. That can be a problem for long-lived graph structures with a lot of churn, like the scene graph in a game or the active collision structures of a collision detection system. For most applications, though, it's not a big deal; browsers build a DOM, use a DOM, and discard a DOM when the page closes. Might be a problem if you left Facebook open for a month. Go for safety. We do not need yet another unsafe language. We have plenty of those. The day there's a CERT advisory for a buffer overflow in a Rust program, Rust has failed.
- kibwen 12y agoFortunately for your use case, Rust provides a reference-counted type in the standard library that does indeed feature weak pointers to break cycles. It's like C++'s `shared_ptr`, except safer and faster (since Rust's safety rules mean that we can prove that the refcounted data isn't shared between threads, and hence we don't need to resort to atomic operations). All of these are possible because of a thin layer of `unsafe` code on the ground, which we then wrap in a safe interface. > We do not need yet another unsafe language. We have plenty of those. I sadly must disagree. If safety were truly paramount, people would have dropped C++ entirely in favor of Java in the 90s. The people still using C++ aren't idiots, they just have requirements with respect to efficiency, control, determinism, and expressiveness that other languages don't match. Rust exists to provide an alternative to these people, so that we can at last bring some semblance of safety to domains with the requirements intimated above. > The day there's a CERT advisory for a buffer overflow in a Rust program, > Rust has failed. I dread that day, and yet I know that it's inevitable. In the meantime, that same buffer-overflowing Rust program may well have produced ten times the CERT advisories had it been written in C. I'm not an absolutist; I'll take that improvement as a win. > I used to work on this problem, about a decade ago. > I was trying to figure out how to make C++ safe. Honestly, the Rust developers would love your perspective if you'd like to take a harder look at Rust.