-
Notifications
You must be signed in to change notification settings - Fork 50
Raw pointer #51
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
Open
ricked-twice
wants to merge
12
commits into
ANSSI-FR:master
Choose a base branch
from
ricked-twice:raw-pointer
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Raw pointer #51
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8c2a693
Add rule concerning raw pointers and usage of std::ptr::read
fa895f2
Add rule concerning raw pointers and usage of std::ptr::read - FR
ddf9ac4
Fixing typos and phrasing
3529cab
Apply suggestions from code review - EN
ricked-twice b5c8d80
Fixing URL
ba1bc8a
Fixing typos - (FR)
4716c7f
Add examples output
3d4ca30
Merge branch 'ANSSI-FR:master' into raw-pointer
ricked-twice 4fcfeb4
(Finally) Taking last reviews into accounts
ricked-twice ab8a1b7
Merge branch 'raw-pointer' of github.com:ricked-twice/rust-guide into…
ricked-twice 2d9b485
Update src/fr/04_language.md
ricked-twice 97781d7
Update src/fr/04_language.md
ricked-twice 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -223,3 +223,74 @@ d'autres raisons. | |
| <mark>TODO</mark> : complexité cyclomatique du code macro-expansé, limites de | ||
| récursion, ... | ||
| --> | ||
|
|
||
| ## Déplacement de valeurs | ||
|
|
||
| Rust propose trois différents modes de déplacement de valeur: | ||
|
|
||
| - Soit par *déplacement*, qui est le comportement par défaut. | ||
| - Ou par *déplacement* plus un *drop* de la valeur si le type implément le trait `Drop`. | ||
ricked-twice marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - Ou par *copie*, si son type implémente le trait `Copy` | ||
|
|
||
| Cependant, des problèmes peuvent être constater lors de l'utilisation de la fonction `std::ptr::read`. | ||
ricked-twice marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Selon la [documentation](https://doc.rust-lang.org/std/ptr/fn.read.html), cette fonction: | ||
| > Lis la valeur pointée par src sans la déplacer. Ce qui laisse la mémoire pointée intact. | ||
|
|
||
| Cette fonction est donc responsable d'effectuer une copie de la valeur pointée, indépemment du mode de déplacement du type en question. | ||
| Ce comportement peut être dangeureux car il peut mener à des *double-free* et/ou des *double-drop*. | ||
|
|
||
| Pour illustrer ce comportement, considérons le code suivant : | ||
|
|
||
| ```rust | ||
| # use std::ops::Drop; | ||
| # | ||
| #[derive(Debug)] | ||
| struct MyStruct(u8); | ||
|
|
||
| impl Drop for MyStruct { | ||
| fn drop(&mut self) { | ||
| # println!("---Dropping an object---\nBefore zeroing: {} @ {:p}", self.0, &self.0 as *const u8); | ||
| self.0 = 0; | ||
| # println!("After zeroing: {} @ {:p}", self.0, &self.0 as *const u8); | ||
| } | ||
| } | ||
ricked-twice marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| fn main(){ | ||
| let obj: MyStruct = MyStruct(100); | ||
| let ptr: *const MyStruct = &test as *const MyStruct; | ||
| println!("{:?} @ {:p}", unsafe { std::ptr::read(ptr) }, ptr); | ||
| } | ||
|
Comment on lines
+256
to
+260
Contributor
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. Donner le résultat obtenu après exécution du programme |
||
| ``` | ||
|
|
||
| On peut observer qu'un deuxième objet a implicitement été créé lors de l'appel à `std::ptr::read`, i.e. une copie d'un objet *non copiable* est effectuée. | ||
| Ici, le problème n'est pas réellement dangeureux, sauf si du nettoyage de mémoire en dehors de l'implémentation de `drop` est réalisée (tel que recommandé): des données sensibles peuvent donc persister en mémoire. | ||
|
|
||
| Mais ce comportement peut causer des problèmes de résilience lors de l'utilisation de cette fonction avec un *raw pointer* pointant vers des données allouées sur le tas avec un mode de déplacement par déplacement, tel qu'illustré ici : | ||
|
|
||
| ```rust | ||
| # use std::boxed::Box; | ||
| # use std::ops::Drop; | ||
| # | ||
| #[derive(Debug)] | ||
| struct MyStructBoxed(Box<u8>); | ||
|
|
||
| impl Drop for MyStructBoxed { | ||
| fn drop(&mut self) { | ||
| # println!("---Dropping an object---\nBefore zeroing: {} @ {:p}", self.0, self.0); | ||
| let value: &mut u8 = self.0.as_mut(); | ||
| *value = 0; | ||
| # println!("After zeroing: {} @ {:p}", self.0, self.0); | ||
| } | ||
| } | ||
|
|
||
| fn main(){ | ||
| let test: MyStructBoxed = MyStructBoxed(Box::new(100)); | ||
| let ptr: *const MyStructBoxed = &test as *const MyStructBoxed; | ||
| println!("{:?} @ {:p}", unsafe { std::ptr::read(ptr) }, unsafe { &*ptr }.0 ); | ||
| } | ||
| ``` | ||
|
|
||
| > ### Règle {{#check LANG-RAW-PTR | Éviter d'utiliser `std::ptr::read`}} | ||
| > | ||
| > `std::ptr::read` peut avoir des effets de bords indésirables en fonction du mode déplacement du type pointé par le *raw pointer* source. | ||
| > Il est donc préférable d'utiliser l'opération de référencement/déréférencement (`&*`) pour les éviter. | ||
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.
Uh oh!
There was an error while loading. Please reload this page.