Skip to content

Commit ead205c

Browse files
cuvipertraviscross
andauthored
Add a section for unsafe extern
Co-authored-by: Travis Cross <[email protected]>
1 parent d735b97 commit ead205c

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

posts/2024-10-17-Rust-1.82.0.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,27 @@ Relaxing this may cause problems where some unsafe blocks are now reported as un
156156

157157
A future version of Rust is expected to generalize this to other expressions which would be safe in this position, not just statics.
158158

159+
### Unsafe extern
160+
161+
Rust code can use functions and statics from foreign code. The type signatures of these foreign items are provided in `extern` blocks. Historically, all items within `extern` blocks have been unsafe to call, but we didn't have to write `unsafe` anywhere on the `extern` block itself.
162+
163+
However, if a signature within the `extern` block is incorrect, then using that item will result in undefined behavior. Would that be the fault of the person who wrote the `extern` block, or the person who used that item?
164+
165+
We've decided that it's the responsibility of the person writing the `extern` block to ensure that all signatures contained within it are correct, and so we now allow writing `unsafe extern`:
166+
167+
```rust
168+
unsafe extern {
169+
pub safe fn sqrt(x: f64) -> f64;
170+
pub unsafe fn strlen(p: *const u8) -> usize;
171+
}
172+
```
173+
174+
One benefit of this is that items within an `unsafe extern` block can be marked as safe to call. In the above example, we can call `sqrt` without using `unsafe`. Items that aren't marked with either `safe` or `unsafe` are conservatively assumed to be `unsafe`.
175+
176+
In future releases, we'll be encouraging the use of `unsafe extern` with lints. Starting in Rust 2024, using `unsafe extern` will be required.
177+
178+
For further details, see [RFC 3484](https://github.com/rust-lang/rfcs/blob/master/text/3484-unsafe-extern-blocks.md) and the ["Unsafe extern blocks"](https://doc.rust-lang.org/nightly/edition-guide/rust-2024/unsafe-extern.html) chapter of the edition guide.
179+
159180
### Unsafe attributes
160181

161182
Some Rust attributes, such as [`no_mangle`](https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute), can be used to [cause Undefined Behavior without any `unsafe` block](https://github.com/rust-lang/rust/issues/28179). If this was regular code we would require them to be placed in an `unsafe {}` block, but so far attributes have not had comparable syntax. To reflect the fact that these attributes can undermine Rust's safety guarantees, they are now considered "unsafe" and should be written as follows:

0 commit comments

Comments
 (0)