En bref. unsafe a la réputation d’être le mode « tout est permis ». C’est faux. Le mot-clé débloque cinq opérations précises que le compilateur ne sait pas vérifier, et rien d’autre : les emprunts, les durées de vie et les types restent contrôlés. Ce qui change, c’est qui porte la preuve. Bien utilisé, unsafe tient en quelques lignes, derrière une fonction que tout le monde appelle sans le voir.
Le modèle en une phrase
unsafene désactive aucune règle : il déplace la preuve. Pour quelques opérations que le compilateur ne sait pas vérifier, c’est vous qui garantissez qu’elles sont correctes. Tout le reste est vérifié comme avant.
L’animation montre d’abord ce qui change de main quand on écrit unsafe, puis une fonction sûre construite autour d’une ligne unsafe, avec et sans sa preuve.
In short. unsafe has a reputation as the “anything goes” mode. That is wrong. The keyword unlocks five precise operations the compiler cannot check, and nothing else: borrows, lifetimes and types stay under control. What changes is who carries the proof. Used well, unsafe is a few lines long, behind a function everyone calls without seeing it.
The model in one sentence
unsafeturns off no rule: it moves the proof. For a few operations the compiler cannot check, you are the one who guarantees they are correct. Everything else is checked as before.
The animation first shows what changes hands when you write unsafe, then a safe function built around one unsafe line, with and without its proof.
let mut x = 10;let p = &raw mut x;
pest un pointeur brut versx. Le créer est du Rust sûr : un pointeur brut qu'on ne suit pas ne peut rien casser. À ce stade, le compilateur vérifie tout ce qu'il vérifie d'habitude, et vous n'avez rien à garantir.pis a raw pointer tox. Creating it is safe Rust: a raw pointer nobody follows cannot break anything. At this point the compiler checks everything it usually checks, and you have nothing to guarantee.- Écrire à travers
pest une autre affaire. Un pointeur brut peut être nul, pendant ou mal aligné, et le compilateur n'a aucun moyen de savoir si celui-ci est valide. Il refuse donc l'opération : E0133, dereference of raw pointer is unsafe and requires unsafe block.Writing throughpis another matter. A raw pointer may be null, dangling or misaligned, and the compiler has no way to know whether this one is valid. So it rejects the operation: E0133, dereference of raw pointer is unsafe and requires unsafe block. - Le bloc
unsafene dit pas « laisse-moi faire ». Il dit « cette opération, je la garantis moi-même ». La preuve quepest valide passe du compilateur à vous, et le commentaire// SAFETY:l'écrit noir sur blanc. Le reste du programme est vérifié comme avant.Theunsafeblock does not say "let me do it". It says "this operation, I guarantee myself". The proof thatpis valid moves from the compiler to you, and the// SAFETY:comment writes it down. The rest of the program is checked as before. - Prendre deux
&mutsur le mêmeVecest refusé dans un blocunsafeexactement comme dehors : E0499. Emprunter ne fait pas partie des opérations qu'unsafedébloque. Le compilateur signale même que ce bloc ne sert à rien.Taking two&muton the sameVecis rejected inside anunsafeblock exactly as outside: E0499. Borrowing is not one of the operationsunsafeunlocks. The compiler even reports that this block is useless.
Ce que dit E0133
L’erreur apparaît dès qu’on appelle une fonction marquée unsafe comme une fonction ordinaire :
fn main() {
let v = [10, 20, 30, 40];
let x = v.get_unchecked(7);
println!("{x}");
}error[E0133]: call to unsafe function `core::slice::<impl [T]>::get_unchecked` is unsafe and requires unsafe block
--> appel.rs:3:13
|
3 | let x = v.get_unchecked(7);
| ^^^^^^^^^^^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behaviorget_unchecked lit une case sans vérifier l’indice. Sa documentation pose une condition : l’indice doit être dans les bornes. Le compilateur ne peut pas la vérifier, donc il exige que l’appelant s’engage. Ici l’indice vaut 7 pour un tableau de 4 : ajouter unsafe { } ferait compiler le programme, et le rendrait faux.
La même erreur existe pour les pointeurs bruts :
fn main() {
let mut x = 10;
let p = &raw mut x;
*p = 11;
println!("{x}");
}error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
--> brut.rs:4:5
|
4 | *p = 11;
| ^^ dereference of raw pointer
|
= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behaviorDeux choses à remarquer. La ligne 3 compile : créer un pointeur brut est sûr, seul le fait de le suivre ne l’est pas. Et la note liste exactement ce que le compilateur ne peut pas savoir sur p.
Avec le bloc, et la raison écrite :
fn main() {
let mut x = 10;
let p = &raw mut x;
// SAFETY: p vient de x, qui est vivant et que personne d'autre n'emprunte
unsafe { *p = 11 };
println!("{x}");
}11Les cinq opérations
unsafe débloque cinq opérations, et la liste est fermée :
| Opération | Exemple | Ce que vous garantissez |
|---|---|---|
| Suivre un pointeur brut | *p | p est non nul, aligné, pointe sur une valeur vivante |
Appeler une fonction ou une méthode unsafe | v.get_unchecked(i) | les préconditions de sa documentation |
Lire ou modifier une static mut | COMPTEUR += 1 | aucun autre thread n’y touche en même temps |
Implémenter un trait unsafe | unsafe impl Send for T {} | le contrat du trait |
Lire un champ d’union | u.entier | c’est bien ce champ qui a été écrit |
Elles ont un point commun : leur correction dépend d’un fait que le compilateur ne voit pas. Le mot-clé ne lui demande pas de fermer les yeux. Il lui dit que ce fait-là, quelqu’un d’autre s’en porte garant.
Rust sûr bloc unsafe
le compilateur prouve le compilateur prouve
┌───────────────────┐ ┌───────────────────┐
│ emprunts │ │ emprunts │
│ durées de vie │ │ durées de vie │
│ types │ │ types │
└───────────────────┘ └───────────────────┘
vous prouvez
┌───────────────────┐
│ les 5 opérations │
└───────────────────┘Ce qu’unsafe ne débloque pas
L’idée reçue veut qu’un bloc unsafe suspende le borrow checker. Essayons :
fn main() {
let mut v = vec![10, 20, 30, 40];
unsafe {
let a = &mut v[0];
let b = &mut v[1];
*a += 1;
*b += 1;
}
println!("{v:?}");
}warning: unnecessary `unsafe` block
--> deux.rs:3:5
|
3 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` (part of `#[warn(unused)]`) on by default
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> deux.rs:5:22
|
4 | let a = &mut v[0];
| - first mutable borrow occurs here
5 | let b = &mut v[1];
| ^ second mutable borrow occurs here
6 | *a += 1;
| ------- first borrow later used here
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slicesL’erreur E0499 est la même que hors du bloc. Et le compilateur ajoute un avertissement : ce bloc unsafe ne contient aucune des cinq opérations, il ne sert à rien.
L’aide en bas du message donne la bonne sortie : split_at_mut. C’est une fonction sûre de la bibliothèque standard, et elle est justement écrite avec unsafe. Voyons comment.
Un cœur unsafe derrière une API sûre
On veut une fonction qui coupe un tableau en deux moitiés modifiables. En Rust sûr, elle est refusée :
fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
(&mut v[..i], &mut v[i..])
}error[E0499]: cannot borrow `*v` as mutable more than once at a time
--> couper_safe.rs:2:24
|
1 | fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
2 | (&mut v[..i], &mut v[i..])
| -------------------^------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*v` is borrowed for `'1`
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slicesLes deux moitiés ne se recouvrent jamais : la propriété est vraie. Mais le compilateur raisonne sur v entier, pas sur des plages d’indices, et il ne sait pas la démontrer. C’est le cas d’école d’un unsafe légitime : une opération correcte que l’outil ne sait pas vérifier.
use std::slice;
fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
let len = v.len();
assert!(i <= len);
let p = v.as_mut_ptr();
// SAFETY: i <= len, donc [0, i) et [i, len) sont disjoints
unsafe { (slice::from_raw_parts_mut(p, i), slice::from_raw_parts_mut(p.add(i), len - i)) }
}
fn main() {
let i: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let mut v = [10, 20, 30, 40];
let (a, b) = couper(&mut v, i);
println!("a = {a:?}");
println!("b.len() = {}", b.len());
}Avec l’indice 2 :
a = [10, 20]
b.len() = 2Avec l’indice 6, pour un tableau de 4 :
thread 'main' (323680) panicked at couper.rs:5:5:
assertion failed: i <= len
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceLa structure se lit en trois couches :
┌─ l'appelant ───────────────────────────────────────────┐
│ couper(&mut v, 2) jamais de mot unsafe │
│ ┌─ la fonction sûre ─────────────────────────────────┐ │
│ │ assert!(i <= len); établit le fait │ │
│ │ ┌─ le cœur unsafe ───────────────────────────────┐ │ │
│ │ │ // SAFETY: i <= len, donc … disjoints │ │ │
│ │ │ unsafe { from_raw_parts_mut(…) } s'y appuie │ │ │
│ │ └────────────────────────────────────────────────┘ │ │
│ └────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────┘Aucune valeur de i ne permet à un appelant de provoquer un comportement indéfini : soit les moitiés sont disjointes, soit la fonction panique. C’est ce qui fait qu’elle est sûre, alors qu’elle contient unsafe.
Retirer la ligne qui porte la preuve
Le commentaire // SAFETY: n’établit rien par lui-même. Il renvoie à l’assert. Retirons l’assert, gardons le commentaire, et rappelons avec l’indice 6.
En compilation ordinaire, une vérification de débordement nous rattrape par chance :
thread 'main' (323682) panicked at couper_sans.rs:8:84:
attempt to subtract with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceAvec rustc -O, cette vérification n’existe plus :
a = [10, 20, 30, 40, 1801035952, 1]
b.len() = 18446744073709551614Le programme se termine avec le code 0. a contient six éléments, dont deux lus dans la mémoire qui suit le tableau. b annonce plus de dix-huit milliards de milliards d’éléments. Relancé, le programme affiche une autre cinquième valeur.
C’est ce qu’on appelle un comportement indéfini. Ce n’est pas un plantage : c’est un programme qui continue avec un état faux, sans aucun signal. Et ici a est un &mut : écrire dedans écraserait la mémoire voisine.
Avec assert!(i <= len) | Sans | |
|---|---|---|
couper(&mut v, 2) | a = [10, 20] | a = [10, 20] |
couper(&mut v, 6) | panique, condition nommée | lecture hors du tableau, code 0 |
| La fonction est… | sûre | fausse, bien que sa signature dise le contraire |
FFI : appeler du C
Appeler une fonction écrite dans un autre langage est le cas le plus courant d’unsafe. Le compilateur ne voit que la signature qu’on lui déclare, pas le corps de la fonction.
use std::ffi::{CString, c_char};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
safe fn abs(x: i32) -> i32;
}
fn longueur_c(texte: &str) -> usize {
let c = CString::new(texte).expect("pas d'octet nul au milieu");
// SAFETY: c est vivant jusqu'à la fin de la fonction et se termine par un octet nul
unsafe { strlen(c.as_ptr()) }
}
fn main() {
println!("abs(-7) = {}", abs(-7));
println!("strlen = {}", longueur_c("bonjour"));
}abs(-7) = 7
strlen = 7Trois choses se passent ici.
- Le bloc est
unsafe extern. En édition 2024, c’est obligatoire. Écrireextern "C" { … }seul donneerror: extern blocks must be unsafe. Le bloc est une promesse : « ces signatures sont exactes ». Siabsprenait en réalité uni64, chaque appel serait faux, et aucun outil ne le verrait. absest déclaréesafe fn. L’appeler n’a aucune précondition, donc elle s’appelle sans blocunsafe.strlen, elle, exige un pointeur vers une chaîne terminée par un octet nul : elle resteunsafeà l’appel.longueur_cest la frontière. Elle prend un&str, fabrique unCString(qui ajoute l’octet nul), le garde vivant pendant l’appel, et rend unusize. Le reste du programme ne manipule ni pointeur niunsafe.
Deux pièges de terrain
Le CString temporaire. as_ptr() ne transfère rien : il prête l’adresse d’un tampon qui appartient au CString.
let p = CString::new("bonjour").unwrap().as_ptr();
let n = unsafe { strlen(p) };
println!("strlen = {n}");warning: this creates a dangling pointer because temporary `CString` is dropped at end of statement
--> cstr.rs:8:46
|
8 | let p = CString::new("bonjour").unwrap().as_ptr();
| -------------------------------- ^^^^^^ pointer created here
| |
| this `CString` is dropped at end of statement
|
= help: bind the `CString` to a variable such that it outlives the pointer returned by `as_ptr`
= note: a dangling pointer is safe, but dereferencing one is undefined behaviorLe programme compile, avec cet avertissement. À l’exécution, sur ma machine :
strlen = 1« bonjour » fait sept caractères. Le CString a été libéré au point-virgule, et strlen a lu de la mémoire rendue à l’allocateur. La correction est celle de longueur_c plus haut : donner un nom au CString, pour qu’il vive plus longtemps que le pointeur.
Le compteur static mut. Une variable globale modifiable n’est protégée par rien. L’édition 2024 refuse d’en prendre une référence :
static mut COMPTEUR: u32 = 0;
fn main() {
unsafe { COMPTEUR += 1 };
println!("{}", unsafe { COMPTEUR });
let r = unsafe { &mut COMPTEUR };
*r += 1;
}error: creating a mutable reference to mutable static
--> smut.rs:6:22
|
6 | let r = unsafe { &mut COMPTEUR };
| ^^^^^^^^^^^^^ mutable reference to mutable static
|
= note: mutable references to mutable statics are dangerous; it's undefined behavior if any other pointer to the static is used or if any other reference is created for the static while the mutable reference livesLa bonne réponse n’est presque jamais de contourner cette erreur. Un compteur global s’écrit avec un atomique, sans mut et sans unsafe :
use std::sync::atomic::{AtomicU32, Ordering};
static COMPTEUR: AtomicU32 = AtomicU32::new(0);
fn main() {
COMPTEUR.fetch_add(1, Ordering::Relaxed);
println!("{}", COMPTEUR.load(Ordering::Relaxed));
}1Ce que l’image cache
unsafe fnet blocunsafene disent pas la même chose.unsafe fnsignifie « m’appeler a des préconditions » : c’est une contrainte pour l’appelant, à documenter dans une section# Safety. Le blocunsafe { }signifie « je garantis que les préconditions sont remplies ». En édition 2024, le corps d’uneunsafe fnn’est plus un blocunsafeimplicite : suivre un pointeur dedans sans bloc donne l’avertissementunsafe_op_in_unsafe_fn.unsafen’est pas un remède au borrow checker. Quand le compilateur refuse deux&mut, la réponse est presque toujours dans le code sûr :split_at_mut, des indices, une autre répartition de la possession. Forcer l’emprunt avec des pointeurs bruts ramène le bug que le compilateur venait de signaler, sans le message d’erreur.- Un bloc faux contamine tout le programme. Un comportement indéfini peut corrompre n’importe quelle donnée, y compris dans du code sûr très éloigné. La garantie « pas de comportement indéfini » vaut pour le programme entier ou ne vaut pas.
- La frontière est le module, pas le bloc. La preuve de
couperrepose sur une ligne placée hors du blocunsafe. Dans un type commeVec, elle repose sur des champs privés : du code sûr qui modifierait la longueur à tort casserait le codeunsafevoisin. C’est la visibilité qui protège l’invariant. - Le bon usage est rare. Trois raisons tiennent la route : parler à du code étranger (FFI), construire une primitive que le langage ne sait pas exprimer (une structure de données, un allocateur), ou une optimisation mesurée. La plupart des programmes n’en ont besoin d’aucune.
- Il existe des outils. Miri interprète le programme et détecte beaucoup de comportements indéfinis à l’exécution des tests, dont les lectures hors limites. Clippy peut exiger un commentaire
// SAFETY:sur chaque bloc. Etunsafese cherche par une simple recherche de texte : c’est la liste des endroits à relire en priorité.
Pour aller plus loin
- Volume 9, numéro 03 de The Rust Loop, unsafe & FFI, ou le dernier recours encapsulé, qui démonte la fonction
coupercas par cas et détaille les pièges de terrain. C’est le dernier numéro de la série (lien en bas de page). - Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119), panic et invariants, traits et generics (E0369), dyn et vtable (E0038), règle de l’orphelin (E0117), Box et types récursifs (E0072), Rc et Arc (E0277), Cell et RefCell, threads et move (E0373), Send, Sync etArc<Mutex<T>>(E0277), les canaux mpsc (E0382), Future et .await (E0728), les fonctions colorées et Send, annuler et sélectionner, les itérateurs, clone, emprunt et Cow. - Le Rust Book, chapitre 20.1 : Unsafe Rust, pour les cinq opérations et
split_at_mut - Le Rustonomicon, le guide de référence pour écrire du code
unsafecorrect - La Reference : les comportements considérés comme indéfinis, la liste exacte
- Le guide de l’édition 2024 : les blocs
unsafe externet les références auxstatic mut - La documentation de
CString, qui décrit le piège du pointeur temporaire - Miri, l’interpréteur qui détecte les comportements indéfinis
What E0133 says
The error shows up as soon as you call a function marked unsafe like an ordinary one:
fn main() {
let v = [10, 20, 30, 40];
let x = v.get_unchecked(7);
println!("{x}");
}error[E0133]: call to unsafe function `core::slice::<impl [T]>::get_unchecked` is unsafe and requires unsafe block
--> appel.rs:3:13
|
3 | let x = v.get_unchecked(7);
| ^^^^^^^^^^^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behaviorget_unchecked reads a slot without checking the index. Its documentation sets a condition: the index must be in bounds. The compiler cannot check it, so it requires the caller to commit. Here the index is 7 for an array of 4: adding unsafe { } would make the program compile, and make it wrong.
The same error exists for raw pointers:
fn main() {
let mut x = 10;
let p = &raw mut x;
*p = 11;
println!("{x}");
}error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
--> brut.rs:4:5
|
4 | *p = 11;
| ^^ dereference of raw pointer
|
= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behaviorTwo things to notice. Line 3 compiles: creating a raw pointer is safe, only following it is not. And the note lists exactly what the compiler cannot know about p.
With the block, and the reason written down:
fn main() {
let mut x = 10;
let p = &raw mut x;
// SAFETY: p vient de x, qui est vivant et que personne d'autre n'emprunte
unsafe { *p = 11 };
println!("{x}");
}11(The comment reads: p comes from x, which is alive and borrowed by no one else.)
The five operations
unsafe unlocks five operations, and the list is closed:
| Operation | Example | What you guarantee |
|---|---|---|
| Following a raw pointer | *p | p is non-null, aligned, points to a live value |
Calling an unsafe function or method | v.get_unchecked(i) | the preconditions in its documentation |
Reading or modifying a static mut | COMPTEUR += 1 | no other thread touches it at the same time |
Implementing an unsafe trait | unsafe impl Send for T {} | the trait’s contract |
Reading a union field | u.entier | that field is the one that was written |
They have one thing in common: their correctness depends on a fact the compiler cannot see. The keyword does not ask it to look away. It tells it that someone else vouches for that fact.
safe Rust unsafe block
the compiler proves the compiler proves
┌───────────────────┐ ┌───────────────────┐
│ borrows │ │ borrows │
│ lifetimes │ │ lifetimes │
│ types │ │ types │
└───────────────────┘ └───────────────────┘
you prove
┌───────────────────┐
│ the 5 operations │
└───────────────────┘What unsafe does not unlock
The common belief is that an unsafe block suspends the borrow checker. Let us try:
fn main() {
let mut v = vec![10, 20, 30, 40];
unsafe {
let a = &mut v[0];
let b = &mut v[1];
*a += 1;
*b += 1;
}
println!("{v:?}");
}warning: unnecessary `unsafe` block
--> deux.rs:3:5
|
3 | unsafe {
| ^^^^^^ unnecessary `unsafe` block
|
= note: `#[warn(unused_unsafe)]` (part of `#[warn(unused)]`) on by default
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> deux.rs:5:22
|
4 | let a = &mut v[0];
| - first mutable borrow occurs here
5 | let b = &mut v[1];
| ^ second mutable borrow occurs here
6 | *a += 1;
| ------- first borrow later used here
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slicesError E0499 is the same as outside the block. And the compiler adds a warning: this unsafe block contains none of the five operations, it serves no purpose.
The help at the bottom of the message gives the right way out: split_at_mut. It is a safe function of the standard library, and it happens to be written with unsafe. Let us see how.
An unsafe core behind a safe API
We want a function that splits an array into two mutable halves. In safe Rust, it is rejected:
fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
(&mut v[..i], &mut v[i..])
}error[E0499]: cannot borrow `*v` as mutable more than once at a time
--> couper_safe.rs:2:24
|
1 | fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
2 | (&mut v[..i], &mut v[i..])
| -------------------^------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*v` is borrowed for `'1`
|
= help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slicesThe two halves never overlap: the property is true. But the compiler reasons about v as a whole, not about index ranges, and it cannot demonstrate it. This is the textbook case of a legitimate unsafe: a correct operation the tool cannot check.
use std::slice;
fn couper(v: &mut [i32], i: usize) -> (&mut [i32], &mut [i32]) {
let len = v.len();
assert!(i <= len);
let p = v.as_mut_ptr();
// SAFETY: i <= len, donc [0, i) et [i, len) sont disjoints
unsafe { (slice::from_raw_parts_mut(p, i), slice::from_raw_parts_mut(p.add(i), len - i)) }
}
fn main() {
let i: usize = std::env::args().nth(1).unwrap().parse().unwrap();
let mut v = [10, 20, 30, 40];
let (a, b) = couper(&mut v, i);
println!("a = {a:?}");
println!("b.len() = {}", b.len());
}(couper means “to split”; the comment reads: i <= len, so [0, i) and [i, len) are disjoint.) With index 2:
a = [10, 20]
b.len() = 2With index 6, for an array of 4:
thread 'main' (323680) panicked at couper.rs:5:5:
assertion failed: i <= len
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceThe structure reads as three layers:
┌─ the caller ───────────────────────────────────────────┐
│ couper(&mut v, 2) never the word unsafe │
│ ┌─ the safe function ────────────────────────────────┐ │
│ │ assert!(i <= len); establishes the fact │ │
│ │ ┌─ the unsafe core ──────────────────────────────┐ │ │
│ │ │ // SAFETY: i <= len, so … disjoint │ │ │
│ │ │ unsafe { from_raw_parts_mut(…) } relies on it│ │ │
│ │ └────────────────────────────────────────────────┘ │ │
│ └────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────┘No value of i lets a caller trigger undefined behaviour: either the halves are disjoint, or the function panics. That is what makes it safe, even though it contains unsafe.
Removing the line that carries the proof
The // SAFETY: comment establishes nothing by itself. It points at the assert. Let us remove the assert, keep the comment, and call again with index 6.
In an ordinary build, an overflow check happens to catch us:
thread 'main' (323682) panicked at couper_sans.rs:8:84:
attempt to subtract with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceWith rustc -O, that check no longer exists:
a = [10, 20, 30, 40, 1801035952, 1]
b.len() = 18446744073709551614The program exits with code 0. a holds six elements, two of them read from the memory that follows the array. b reports more than eighteen quintillion elements. Run again, the program prints a different fifth value.
This is what is called undefined behaviour. It is not a crash: it is a program that carries on with a wrong state, with no signal at all. And here a is a &mut: writing into it would overwrite the neighbouring memory.
With assert!(i <= len) | Without | |
|---|---|---|
couper(&mut v, 2) | a = [10, 20] | a = [10, 20] |
couper(&mut v, 6) | panic, condition named | read past the array, code 0 |
| The function is… | safe | wrong, although its signature says otherwise |
FFI: calling C
Calling a function written in another language is the most common case of unsafe. The compiler only sees the signature you declare, not the body of the function.
use std::ffi::{CString, c_char};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
safe fn abs(x: i32) -> i32;
}
fn longueur_c(texte: &str) -> usize {
let c = CString::new(texte).expect("pas d'octet nul au milieu");
// SAFETY: c est vivant jusqu'à la fin de la fonction et se termine par un octet nul
unsafe { strlen(c.as_ptr()) }
}
fn main() {
println!("abs(-7) = {}", abs(-7));
println!("strlen = {}", longueur_c("bonjour"));
}abs(-7) = 7
strlen = 7Three things happen here.
- The block is
unsafe extern. In the 2024 edition, this is mandatory. Writingextern "C" { … }alone giveserror: extern blocks must be unsafe. The block is a promise: “these signatures are exact”. Ifabsactually took ani64, every call would be wrong, and no tool would see it. absis declaredsafe fn. Calling it has no precondition, so it is called without anunsafeblock.strlenrequires a pointer to a string ending with a nul byte: it staysunsafeto call.longueur_cis the boundary. It takes a&str, builds aCString(which adds the nul byte), keeps it alive during the call, and returns ausize. The rest of the program handles neither pointers norunsafe.
Two traps from the field
The temporary CString. as_ptr() transfers nothing: it lends the address of a buffer that belongs to the CString.
let p = CString::new("bonjour").unwrap().as_ptr();
let n = unsafe { strlen(p) };
println!("strlen = {n}");warning: this creates a dangling pointer because temporary `CString` is dropped at end of statement
--> cstr.rs:8:46
|
8 | let p = CString::new("bonjour").unwrap().as_ptr();
| -------------------------------- ^^^^^^ pointer created here
| |
| this `CString` is dropped at end of statement
|
= help: bind the `CString` to a variable such that it outlives the pointer returned by `as_ptr`
= note: a dangling pointer is safe, but dereferencing one is undefined behaviorThe program compiles, with this warning. At run time, on my machine:
strlen = 1“bonjour” is seven characters long. The CString was freed at the semicolon, and strlen read memory handed back to the allocator. The fix is the one in longueur_c above: give the CString a name, so that it outlives the pointer.
The static mut counter. A mutable global variable is protected by nothing. The 2024 edition refuses to take a reference to one:
static mut COMPTEUR: u32 = 0;
fn main() {
unsafe { COMPTEUR += 1 };
println!("{}", unsafe { COMPTEUR });
let r = unsafe { &mut COMPTEUR };
*r += 1;
}error: creating a mutable reference to mutable static
--> smut.rs:6:22
|
6 | let r = unsafe { &mut COMPTEUR };
| ^^^^^^^^^^^^^ mutable reference to mutable static
|
= note: mutable references to mutable statics are dangerous; it's undefined behavior if any other pointer to the static is used or if any other reference is created for the static while the mutable reference livesThe right answer is almost never to work around this error. A global counter is written with an atomic, with no mut and no unsafe:
use std::sync::atomic::{AtomicU32, Ordering};
static COMPTEUR: AtomicU32 = AtomicU32::new(0);
fn main() {
COMPTEUR.fetch_add(1, Ordering::Relaxed);
println!("{}", COMPTEUR.load(Ordering::Relaxed));
}1What the picture hides
unsafe fnand anunsafeblock do not say the same thing.unsafe fnmeans “calling me has preconditions”: it is a constraint on the caller, to be documented in a# Safetysection. Theunsafe { }block means “I guarantee the preconditions hold”. In the 2024 edition, the body of anunsafe fnis no longer an implicitunsafeblock: following a pointer in it without a block gives theunsafe_op_in_unsafe_fnwarning.unsafeis not a cure for the borrow checker. When the compiler rejects two&mut, the answer is almost always in safe code:split_at_mut, indices, a different split of ownership. Forcing the borrow with raw pointers brings back the bug the compiler had just reported, without the error message.- One wrong block contaminates the whole program. Undefined behaviour can corrupt any data, including in safe code far away. The “no undefined behaviour” guarantee holds for the whole program or does not hold.
- The boundary is the module, not the block. The proof of
couperrests on a line placed outside theunsafeblock. In a type likeVec, it rests on private fields: safe code that wrongly changed the length would break the neighbouringunsafecode. Visibility is what protects the invariant. - Good use is rare. Three reasons hold up: talking to foreign code (FFI), building a primitive the language cannot express (a data structure, an allocator), or a measured optimisation. Most programs need none of them.
- There are tools. Miri interprets the program and detects many kinds of undefined behaviour while running the tests, including out-of-bounds reads. Clippy can require a
// SAFETY:comment on every block. Andunsafecan be found with a plain text search: that is the list of places to review first.
Going further
- Volume 9, issue 03 of The Rust Loop, unsafe & FFI, or the encapsulated last resort, which takes the
couperfunction apart case by case and details the traps from the field. It is the last issue of the series (link at the bottom of the page). - Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119), panic and invariants, traits and generics (E0369), dyn and the vtable (E0038), the orphan rule (E0117), Box and recursive types (E0072), Rc and Arc (E0277), Cell and RefCell, threads and move (E0373), Send, Sync andArc<Mutex<T>>(E0277), mpsc channels (E0382), Future and .await (E0728), colored functions and Send, cancel and select, iterators, clone, borrowing and Cow. - The Rust Book, chapter 20.1: Unsafe Rust, for the five operations and
split_at_mut - The Rustonomicon, the reference guide to writing correct
unsafecode - The Reference: behavior considered undefined, the exact list
- The 2024 edition guide:
unsafe externblocks and references tostatic mut - The
CStringdocumentation, which describes the temporary pointer trap - Miri, the interpreter that detects undefined behaviour