« call to unsafe function is unsafe and requires unsafe block » : unsafe et FFI en Rust "call to unsafe function is unsafe and requires unsafe block": unsafe and FFI in Rust

En Rust, unsafe ne désactive pas le compilateur. Il débloque cinq opérations que rustc ne sait pas vérifier, comme suivre un pointeur brut ou appeler une fonction C, et transfère leur preuve à l'auteur du code. Le borrow checker reste actif dans le bloc. Ce que ça implique : l'erreur E0133, le commentaire SAFETY, un cœur unsafe derrière une API sûre, ce qui arrive quand on retire la ligne qui porte la preuve, et les blocs unsafe extern de l'édition 2024.In Rust, unsafe does not turn the compiler off. It unlocks five operations rustc cannot check, such as following a raw pointer or calling a C function, and transfers their proof to the author of the code. The borrow checker stays on inside the block. What follows from it: error E0133, the SAFETY comment, an unsafe core behind a safe API, what happens when you remove the line that carries the proof, and the unsafe extern blocks of the 2024 edition.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PerformancePerformance
PubliéPublished

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

unsafe ne 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

unsafe turns 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;
Qui prouve quoiWho proves whatunsafe ne désactive aucune règleunsafe turns off no rulele compilateur vérifiethe compiler checksvous garantissezyou guaranteeempruntsborrowsdurées de vielifetimestypestypesrien pour l’instantnothing for nowpreuves à votre charge : 0proofs on you: 0vérifié par rustcchecked by rustcgaranti par vousguaranteed by yourefusérejectedsortie du programmeprogram outputrien n’est encore affichénothing printed yetsorties : rustc 1.100output: rustc 1.100le danger n’est pas dans le pointeur, il est dans son usagethe danger is not in the pointer, it is in its usecréer un pointeur brut est sûrcreating a raw pointer is safe
  1. p est un pointeur brut vers x. 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.p is a raw pointer to x. 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.
  2. Écrire à travers p est 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 through p is 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.
  3. Le bloc unsafe ne dit pas « laisse-moi faire ». Il dit « cette opération, je la garantis moi-même ». La preuve que p est valide passe du compilateur à vous, et le commentaire // SAFETY: l'écrit noir sur blanc. Le reste du programme est vérifié comme avant.The unsafe block does not say "let me do it". It says "this operation, I guarantee myself". The proof that p is valid moves from the compiler to you, and the // SAFETY: comment writes it down. The rest of the program is checked as before.
  4. Prendre deux &mut sur le même Vec est refusé dans un bloc unsafe exactement comme dehors : E0499. Emprunter ne fait pas partie des opérations qu'unsafe débloque. Le compilateur signale même que ce bloc ne sert à rien.Taking two &mut on the same Vec is rejected inside an unsafe block exactly as outside: E0499. Borrowing is not one of the operations unsafe unlocks. The compiler even reports that this block is useless.
unsafe en Rust ne désactive pas le compilateur. Suivre un pointeur brut hors d’un bloc unsafe donne E0133 ; dans le bloc, la preuve de validité passe à l’auteur du code. Deux &mut sur la même donnée restent refusés (E0499), dans unsafe comme dehors.unsafe in Rust does not turn the compiler off. Following a raw pointer outside an unsafe block gives E0133; inside the block, the proof of validity moves to the author of the code. Two &mut on the same data stay rejected (E0499), inside unsafe as outside.

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 behavior

get_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 behavior

Deux 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}");
}
11

Les cinq opérations

unsafe débloque cinq opérations, et la liste est fermée :

OpérationExempleCe que vous garantissez
Suivre un pointeur brut*pp est non nul, aligné, pointe sur une valeur vivante
Appeler une fonction ou une méthode unsafev.get_unchecked(i)les préconditions de sa documentation
Lire ou modifier une static mutCOMPTEUR += 1aucun autre thread n’y touche en même temps
Implémenter un trait unsafeunsafe impl Send for T {}le contrat du trait
Lire un champ d’unionu.entierc’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-slices

L’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-slices

Les 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() = 2

Avec 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 backtrace

La 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 backtrace

Avec rustc -O, cette vérification n’existe plus :

a = [10, 20, 30, 40, 1801035952, 1]
b.len() = 18446744073709551614

Le 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éelecture hors du tableau, code 0
La fonction est…sûrefausse, 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  = 7

Trois choses se passent ici.

  • Le bloc est unsafe extern. En édition 2024, c’est obligatoire. Écrire extern "C" { … } seul donne error: extern blocks must be unsafe. Le bloc est une promesse : « ces signatures sont exactes ». Si abs prenait en réalité un i64, chaque appel serait faux, et aucun outil ne le verrait.
  • abs est déclarée safe fn. L’appeler n’a aucune précondition, donc elle s’appelle sans bloc unsafe. strlen, elle, exige un pointeur vers une chaîne terminée par un octet nul : elle reste unsafe à l’appel.
  • longueur_c est la frontière. Elle prend un &str, fabrique un CString (qui ajoute l’octet nul), le garde vivant pendant l’appel, et rend un usize. Le reste du programme ne manipule ni pointeur ni unsafe.

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 behavior

Le 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 lives

La 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));
}
1

Ce que l’image cache

  • unsafe fn et bloc unsafe ne disent pas la même chose. unsafe fn signifie « m’appeler a des préconditions » : c’est une contrainte pour l’appelant, à documenter dans une section # Safety. Le bloc unsafe { } signifie « je garantis que les préconditions sont remplies ». En édition 2024, le corps d’une unsafe fn n’est plus un bloc unsafe implicite : suivre un pointeur dedans sans bloc donne l’avertissement unsafe_op_in_unsafe_fn.
  • unsafe n’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 couper repose sur une ligne placée hors du bloc unsafe. Dans un type comme Vec, elle repose sur des champs privés : du code sûr qui modifierait la longueur à tort casserait le code unsafe voisin. 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. Et unsafe se cherche par une simple recherche de texte : c’est la liste des endroits à relire en priorité.

Pour aller plus loin

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 behavior

get_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 behavior

Two 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:

OperationExampleWhat you guarantee
Following a raw pointer*pp is non-null, aligned, points to a live value
Calling an unsafe function or methodv.get_unchecked(i)the preconditions in its documentation
Reading or modifying a static mutCOMPTEUR += 1no other thread touches it at the same time
Implementing an unsafe traitunsafe impl Send for T {}the trait’s contract
Reading a union fieldu.entierthat 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-slices

Error 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-slices

The 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() = 2

With 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 backtrace

The 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 backtrace

With rustc -O, that check no longer exists:

a = [10, 20, 30, 40, 1801035952, 1]
b.len() = 18446744073709551614

The 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 namedread past the array, code 0
The function is…safewrong, 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  = 7

Three things happen here.

  • The block is unsafe extern. In the 2024 edition, this is mandatory. Writing extern "C" { … } alone gives error: extern blocks must be unsafe. The block is a promise: “these signatures are exact”. If abs actually took an i64, every call would be wrong, and no tool would see it.
  • abs is declared safe fn. Calling it has no precondition, so it is called without an unsafe block. strlen requires a pointer to a string ending with a nul byte: it stays unsafe to call.
  • longueur_c is the boundary. It takes a &str, builds a CString (which adds the nul byte), keeps it alive during the call, and returns a usize. The rest of the program handles neither pointers nor unsafe.

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 behavior

The 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 lives

The 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));
}
1

What the picture hides

  • unsafe fn and an unsafe block do not say the same thing. unsafe fn means “calling me has preconditions”: it is a constraint on the caller, to be documented in a # Safety section. The unsafe { } block means “I guarantee the preconditions hold”. In the 2024 edition, the body of an unsafe fn is no longer an implicit unsafe block: following a pointer in it without a block gives the unsafe_op_in_unsafe_fn warning.
  • unsafe is 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 couper rests on a line placed outside the unsafe block. In a type like Vec, it rests on private fields: safe code that wrongly changed the length would break the neighbouring unsafe code. 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. And unsafe can be found with a plain text search: that is the list of places to review first.

Going further

Questions fréquentesFrequently asked questions

Que signifie « call to unsafe function is unsafe and requires unsafe block » (E0133) ?What does "call to unsafe function is unsafe and requires unsafe block" (E0133) mean?

Que vous appelez une fonction déclarée unsafe fn hors d'un bloc unsafe. Une telle fonction a des préconditions que le compilateur ne peut pas vérifier : par exemple, get_unchecked exige que l'indice soit dans les bornes. L'erreur demande d'écrire l'appel dans unsafe { ... }, ce qui revient à affirmer que ces préconditions sont remplies. La même erreur E0133 existe pour suivre un pointeur brut : « dereference of raw pointer is unsafe and requires unsafe block ». Avant d'ajouter le bloc, lisez la section Safety de la documentation de la fonction, et vérifiez s'il n'existe pas une version sûre, comme get, qui rend une Option.That you are calling a function declared unsafe fn outside an unsafe block. Such a function has preconditions the compiler cannot check: for example, get_unchecked requires the index to be in bounds. The error asks you to write the call inside unsafe { ... }, which amounts to asserting that those preconditions hold. The same error E0133 exists for following a raw pointer: "dereference of raw pointer is unsafe and requires unsafe block". Before adding the block, read the Safety section of the function's documentation, and check whether a safe version exists, such as get, which returns an Option.

Est-ce que unsafe désactive le borrow checker ?Does unsafe turn off the borrow checker?

Non. Dans un bloc unsafe, les emprunts, les durées de vie et les types sont vérifiés exactement comme ailleurs. Prendre deux &mut sur le même Vec dans un bloc unsafe donne toujours l'erreur E0499, et rustc ajoute l'avertissement « unnecessary unsafe block ». unsafe débloque seulement cinq opérations : suivre un pointeur brut, appeler une fonction ou une méthode unsafe, lire ou modifier une static mut, implémenter un trait unsafe, et lire un champ d'union. Tout le reste du langage garde ses règles.No. Inside an unsafe block, borrows, lifetimes and types are checked exactly as elsewhere. Taking two &mut on the same Vec inside an unsafe block still gives error E0499, and rustc adds the warning "unnecessary unsafe block". unsafe only unlocks five operations: following a raw pointer, calling an unsafe function or method, reading or modifying a static mut, implementing an unsafe trait, and reading a union field. The rest of the language keeps its rules.

À quoi sert le commentaire // SAFETY: ?What is the // SAFETY: comment for?

À écrire la preuve que le compilateur ne fait plus. Dans un bloc unsafe, c'est l'auteur qui garantit que l'opération est correcte. Le commentaire // SAFETY: énonce le fait qui la rend correcte, par exemple « i <= len, donc les deux moitiés sont disjointes ». Ce n'est pas une formalité : le commentaire doit renvoyer à quelque chose que le code établit vraiment, comme un assert placé juste au-dessus. Un relecteur peut alors vérifier la preuve sans la reconstruire. Clippy propose le lint undocumented_unsafe_blocks pour exiger ce commentaire sur chaque bloc.To write down the proof the compiler no longer makes. Inside an unsafe block, the author guarantees that the operation is correct. The // SAFETY: comment states the fact that makes it correct, for example "i <= len, so the two halves are disjoint". It is not a formality: the comment has to point at something the code really establishes, such as an assert placed just above. A reviewer can then check the proof without rebuilding it. Clippy offers the undocumented_unsafe_blocks lint to require this comment on every block.

Pourquoi « extern blocks must be unsafe » en édition 2024 ?Why "extern blocks must be unsafe" in the 2024 edition?

Parce qu'un bloc extern est une promesse que le compilateur ne peut pas vérifier : il déclare la signature d'une fonction écrite dans un autre langage, sans voir son corps. Si la signature déclarée est fausse, chaque appel est un comportement indéfini. L'édition 2024 exige donc d'écrire unsafe extern "C" { ... }, pour que cette promesse soit visible. En échange, chaque fonction du bloc peut être marquée safe fn quand l'appeler n'a aucune précondition, comme abs : elle s'appelle alors sans bloc unsafe. Les autres restent unsafe à l'appel.Because an extern block is a promise the compiler cannot check: it declares the signature of a function written in another language, without seeing its body. If the declared signature is wrong, every call is undefined behaviour. So the 2024 edition requires writing unsafe extern "C" { ... }, to make that promise visible. In exchange, each function in the block can be marked safe fn when calling it has no precondition, like abs: it is then called without an unsafe block. The others stay unsafe to call.

Qu'est-ce qu'un comportement indéfini (undefined behavior) en Rust ?What is undefined behavior in Rust?

C'est ce qui se passe quand un programme viole une règle que le compilateur suppose toujours respectée : lire hors d'un tableau, suivre un pointeur pendant, avoir deux &mut sur la même donnée, créer une course de données. Le compilateur optimise en supposant que ces cas n'arrivent jamais, donc le résultat n'est pas défini : le programme peut planter, afficher des valeurs fausses ou sembler fonctionner. Dans l'exemple de l'article, une fonction sans son assert lit deux cases hors du tableau et se termine avec le code 0. En Rust sûr, le compilateur garantit l'absence de comportement indéfini ; dans un bloc unsafe, c'est à vous de la garantir.It is what happens when a program breaks a rule the compiler assumes is always respected: reading past an array, following a dangling pointer, having two &mut on the same data, creating a data race. The compiler optimises assuming these cases never happen, so the result is not defined: the program may crash, print wrong values or appear to work. In the article's example, a function without its assert reads two slots past the array and exits with code 0. In safe Rust, the compiler guarantees the absence of undefined behavior; inside an unsafe block, guaranteeing it is on you.

RustunsafeFFIE0133Modèle mental

← Tous les articlesAll articles