-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Split large unsafe function slide #2406
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b1a3a3a
Split large unsafe function slide
mgeisler 893e2db
Update src/unsafe-rust/calling-unsafe-functions.md
mgeisler 16e6c2c
Updates per review
djmitche c3b2f86
Merge remote-tracking branch 'upstream/main' into split-unsafe-func-s…
djmitche 88d4398
formatting
djmitche ee50f6c
Talk about unsafe Rust functions before extern functions.
qwandor 86279d4
Use unsafe extern.
qwandor 3a529f2
Fix safety comments and explanation.
qwandor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,100 +1,19 @@ | ||
--- | ||
minutes: 5 | ||
minutes: 15 | ||
--- | ||
|
||
# Unsafe Functions | ||
|
||
## Calling Unsafe Functions | ||
|
||
A function or method can be marked `unsafe` if it has extra preconditions you | ||
must uphold to avoid undefined behaviour: | ||
|
||
```rust,editable | ||
extern "C" { | ||
fn abs(input: i32) -> i32; | ||
} | ||
|
||
fn main() { | ||
let emojis = "🗻∈🌏"; | ||
|
||
// SAFETY: The indices are in the correct order, within the bounds of the | ||
// string slice, and lie on UTF-8 sequence boundaries. | ||
unsafe { | ||
println!("emoji: {}", emojis.get_unchecked(0..4)); | ||
println!("emoji: {}", emojis.get_unchecked(4..7)); | ||
println!("emoji: {}", emojis.get_unchecked(7..11)); | ||
} | ||
|
||
println!("char count: {}", count_chars(unsafe { emojis.get_unchecked(0..7) })); | ||
|
||
// SAFETY: `abs` doesn't deal with pointers and doesn't have any safety | ||
// requirements. | ||
unsafe { | ||
println!("Absolute value of -3 according to C: {}", abs(-3)); | ||
} | ||
|
||
// Not upholding the UTF-8 encoding requirement breaks memory safety! | ||
// println!("emoji: {}", unsafe { emojis.get_unchecked(0..3) }); | ||
// println!("char count: {}", count_chars(unsafe { | ||
// emojis.get_unchecked(0..3) })); | ||
} | ||
|
||
fn count_chars(s: &str) -> usize { | ||
s.chars().count() | ||
} | ||
``` | ||
|
||
## Writing Unsafe Functions | ||
must uphold to avoid undefined behaviour. | ||
|
||
You can mark your own functions as `unsafe` if they require particular | ||
conditions to avoid undefined behaviour. | ||
There are two main categories: | ||
|
||
```rust,editable | ||
/// Swaps the values pointed to by the given pointers. | ||
/// | ||
/// # Safety | ||
/// | ||
/// The pointers must be valid and properly aligned. | ||
unsafe fn swap(a: *mut u8, b: *mut u8) { | ||
let temp = *a; | ||
*a = *b; | ||
*b = temp; | ||
} | ||
|
||
fn main() { | ||
let mut a = 42; | ||
let mut b = 66; | ||
|
||
// SAFETY: ... | ||
unsafe { | ||
swap(&mut a, &mut b); | ||
} | ||
|
||
println!("a = {}, b = {}", a, b); | ||
} | ||
``` | ||
- Foreign functions in `extern "C"` blocks. | ||
- Rust functions declared unsafe with `unsafe fn`. | ||
|
||
<details> | ||
|
||
## Calling Unsafe Functions | ||
|
||
`get_unchecked`, like most `_unchecked` functions, is unsafe, because it can | ||
create UB if the range is incorrect. `abs` is unsafe for a different reason: it | ||
is an external function (FFI). Calling external functions is usually only a | ||
problem when those functions do things with pointers which might violate Rust's | ||
memory model, but in general any C function might have undefined behaviour under | ||
any arbitrary circumstances. | ||
|
||
The `"C"` in this example is the ABI; | ||
[other ABIs are available too](https://doc.rust-lang.org/reference/items/external-blocks.html). | ||
|
||
## Writing Unsafe Functions | ||
|
||
We wouldn't actually use pointers for a `swap` function - it can be done safely | ||
with references. | ||
|
||
Note that unsafe code is allowed within an unsafe function without an `unsafe` | ||
block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. Try adding | ||
it and see what happens. This will likely change in a future Rust edition. | ||
We will look at the two kinds of unsafe functions next. | ||
|
||
</details> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Calling Unsafe Functions | ||
|
||
Failing to uphold the safety requirements breaks memory safety! | ||
|
||
```rust,editable | ||
#[derive(Debug)] | ||
#[repr(C)] | ||
struct KeyPair { | ||
pk: [u16; 4], // 8 bytes | ||
sk: [u16; 4], // 8 bytes | ||
} | ||
|
||
const PK_BYTE_LEN: usize = 8; | ||
|
||
fn log_public_key(pk_ptr: *const u16) { | ||
let pk: &[u16] = unsafe { std::slice::from_raw_parts(pk_ptr, PK_BYTE_LEN) }; | ||
println!("{pk:?}"); | ||
} | ||
|
||
fn main() { | ||
let key_pair = KeyPair { pk: [1, 2, 3, 4], sk: [0, 0, 42, 0] }; | ||
log_public_key(key_pair.pk.as_ptr()); | ||
} | ||
``` | ||
|
||
Always include a safety comment for each `unsafe` block. It must explain why the | ||
code is actually safe. This example is missing a safety comment and has UB. | ||
|
||
<details> | ||
|
||
Key points: | ||
|
||
- The second argument to `slice::from_raw_parts` is the number of _elements_, | ||
not bytes! This example demonstrate undefined behavior by reading past the end | ||
of one array and into another. | ||
|
||
- The standard library contains many low-level unsafe functions. Prefer the safe | ||
alternatives when possible! | ||
|
||
- If you use an unsafe function as an optimization, make sure to add a benchmark | ||
to demonstrate the gain. | ||
|
||
</details> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# Unsafe External Functions | ||
|
||
All functions implemented in a foreign language are considered unsafe in Rust: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is no longer true as of 1.82. We should talk about |
||
|
||
```rust,editable | ||
extern "C" { | ||
fn abs(input: i32) -> i32; | ||
} | ||
|
||
fn main() { | ||
// SAFETY: `abs` doesn't deal with pointers and doesn't have any safety | ||
// requirements. | ||
unsafe { | ||
println!("Absolute value of -3 according to C: {}", abs(-3)); | ||
} | ||
} | ||
``` | ||
|
||
<details> | ||
|
||
`abs` is unsafe because it is an external function (FFI). Calling external | ||
functions is usually only a problem when those functions do things with pointers | ||
which might violate Rust's memory model, but in general any C function might | ||
have undefined behaviour under any arbitrary circumstances. | ||
|
||
The `"C"` in this example is the ABI; | ||
[other ABIs are available too](https://doc.rust-lang.org/reference/items/external-blocks.html). | ||
|
||
Note that there is no verification that the Rust function signature matches that | ||
of the function definition -- that's up to you! | ||
|
||
</details> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# Unsafe Rust Functions | ||
|
||
You can mark your own functions as `unsafe` if they require particular | ||
conditions to avoid undefined behaviour. | ||
|
||
```rust,editable | ||
/// Swaps the values pointed to by the given pointers. | ||
/// | ||
/// # Safety | ||
/// | ||
/// The pointers must be valid and properly aligned. | ||
unsafe fn swap(a: *mut u8, b: *mut u8) { | ||
let temp = *a; | ||
*a = *b; | ||
*b = temp; | ||
} | ||
|
||
fn main() { | ||
let mut a = 42; | ||
let mut b = 66; | ||
|
||
// SAFETY: ... | ||
unsafe { | ||
swap(&mut a, &mut b); | ||
} | ||
|
||
println!("a = {}, b = {}", a, b); | ||
} | ||
``` | ||
|
||
<details> | ||
|
||
We wouldn't actually use pointers for a `swap` function --- it can be done | ||
safely with references. | ||
|
||
Note that unsafe code is allowed within an unsafe function without an `unsafe` | ||
block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. Try adding | ||
it and see what happens. This will | ||
[change in the 2024 Rust edition](https://github.com/rust-lang/rust/issues/120535). | ||
|
||
</details> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since Rust 1.82 (with
unsafe extern
) foreign functions aren't necessarily unsafe, so I don't think these are really separate categories. Either way, a function is unsafe if it has some safety prerequisites which must be met to avoid undefined behaviour (or IO safety issues).We should also update the example to use
unsafe extern
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This PR was from before Rust 1.82, so perhaps we can land it and update, unless you think that splitting the slides doesn't make sense anymore?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've pushed some commits to fix this and some other issues.