Niko Matsakis
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Niches and `UnsafeCell<T>` summary ## Background: UnsafeCell and niches Presently, `UnsafeCell<T>` is considered to expose "niches" found in `T` that can be used for layout optimization. This implies that `Option<UnsafeCell<bool>>`, for example, has the same size as a bool, since the invalid bit patterns of `bool` can be used to represent `None`. ## Potential for data races However, as reported in [#68206], because the memory inside an `UnsafeCell` may be accessed from other threads, this introduces the potential for a data race: * A `&Option<Mutex<bool>>`, for example, might be shared between two threads. * One thread could be matching on the `&Option<_>` to determine if it is `Some` or `None`. This would require reading the `bool` value that is protected by the mutex (but this would happen without acquiring the mutex). * Another thread could acquire the mutex and do writes to that same memory, introducing a data race. * The same pattern can happen with a `&Option<RefCell<bool>>`, as one might use `borrow_mut()` to get an `&mut bool` that is then sent to another thread using rayon or some such library. * Naturally the same pattern could apply to numerous types in third-party libraries (e.g., parking-lot) that are based on `UnsafeCell`. ## A deeper conflict Even beyond data races, there is a deeper conflict at play here. The first observation is that the design of `UnsafeCell<T>` generally defines "some portion" of a type which may be mutated even when shared. Things that are logically outside of the `UnsafeCell` are not affected by it. Further, with enums, if you ignore niche optimizations, then there is conceptually a discriminant field and a payload field. **Niches allow these two conceptually distinct fields to overlap in memory.** If you combine these two things, you start to see the problem with `Option<UnsafeCell<bool>>` -- the discriminant for the option is conceptually outside of the `UnsafeCell`, and hence unaffected by it. The `bool` meanwhile is inside the `UnsafeCell`. However, because of the niche, the discriminant is actually stored **in the same memory as the bool**. This is particularly problematic for our attempts to formalize the unsafety rules in an operational and machine checkable way. Stacked borrows has the goal of defining the rules in terms of "which memory can be mutated and when" and not introducing very specific bits of "ghost state", such as tracking the "current variant" of an enum. But this implies that if you can mutate the payload of an `UnsafeCell`, you are also able to mutate the discriminant of the enum, unless those permission rules start to be expressed in a much more subtle and complex way that accounts somehow for niches. This has manifested in two surprising examples thus far: [#68303] and [unsafe-code-guidelines#204]. ### Issue 68303 -- reading discriminant invalidates reference to payload Issue [#68303] is as follows: ```rust use std::cell::RefCell; fn main() { let optional=Some(RefCell::new(false)); // handle acquires a **mutable lock** on the payload let mut handle=optional.as_ref().unwrap().borrow_mut(); // accessing the discriminant **releases that lock**, because // discriminant is in the same memory as the payload optional.is_some(); // lock has expired here, error: *handle=true; } ``` This results (presently) in a miri error. Why is that? The comments above try to give an intution for it. The basic idea of stacked borrows is that creating a `&` or `&mut` reference to some memory effectively "locks it" so that it can only be accessed in a way compatible with the reference. So a `&` reference acquires a "read lock", making the memory immutable, and a `&mut` acquires a "write lock", making the memory inaccessible. These locks are automatically released when the memory is accessed in a way that is incompatible with the reference. Trying to use the reference after its lock has been released is an error. In this case, the `handle` acquires a "write lock" on the payload of the option (the `bool` inside the `RefCell`, specifically). But then `optional.is_some()` accesses the discriminant of the `Option`. Remember that this **logically distinct** but (thanks to niches) **physically overlapping** memory. Since the actual memory is the same, the lock from `handle` is released. In that case, it becomes an error to do `*handle = true` later on, as the lock hasbeen released. This explanation is very specific to stacked borrows, but the conflict is more fundamental. ### Unsafe code guidelines #204 -- mutating payload invalidates discriminant In [unsafe-code-guidelines#204], the problem is reversed. It contains a function `evil` that takes a `&Option<Cell<&T>>`. `evil` then mutates the payload of that `Cell`. This has the side-effect of also mutating the discriminant, effectively converting the `Option` (outside the `Cell`!) from a `Some` into a `None`: ```rust /// Sets `x` to `None`. fn evil<T>(x: &Option<Cell<&T>>) { assert_eq!( mem::size_of_val(x), mem::size_of_val(x.as_ref().unwrap()), "layout optimization did not kick in?", ); unsafe { *(x as *const _ as *mut usize) = 0; } } ``` This could be quite surprising to innocent callers of `evil`: ```rust fn main() { let my = Some(Cell::new(&0)); evil(&my); dbg!(my); // surprise! `my` is now `None`! } ``` This would also imply that the compiler must be much more conservative around code that manipulates a `&Option<T>`, as the discriminant could now suddenly change from `Some` to `None` (and vice versa). ## What about Cell? `Cell` is different from `RefCell` and `Mutex`, since it does not permit references to its interior. This means that many of the examples and potential problems do not apply to it, as they often rely on creating a reference to the interior and then accessing an enum discriminant that is logically outside that reference but physically overlapping. One might be tempted to think that it should still permit niches. However, the [unsafe-code-guidelines#204] example shows why this is probably a bad idea. In particular, while mutating the interior of a `Cell` cannot still alter the contents of enum discriminants outside the cell, and thus have surprising side-effects that will inhibit optimization and reasoning. [RalfJung expands](https://github.com/rust-lang/rust/issues/68206#issuecomment-575274715): *I see an inherent conflict here between niches, that basically "overlay" multiple pieces of information on the same location, and trying to define interior mutability operationally (in terms of which memory can and cannot be mutated when) in a way that it only applies to "parts of" the information stored in that location.* ## Resolved In the lang-team meeting on [2020-01-16], we discussed this and came to the conclusion that **we ought to inhibit niches in `UnsafeCell<T>` in order to resolve these various issues.** (This was a preliminary in-meeting consensus, not a formal decision.) ## Implications This will cause potential regressions. These regressions are considered justified as this is a soundness fix, and that scenario is not very likely. * Specifically, the type `Option<UnsafeCell<&i32>>` [is currently considered FFI-safe](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7027b7e22dab5bedeeb9c54679dd4ea7) (and same for `Cell`), as it would be represented as a `Option<&i32>` which in turn is a nullable pointer. After this change, that will no longer be the case. ## Possible future directions It is possible that we could re-enable niches on `Cell`, although it is not clear that we want this (c.f. [unsafe-code-guidelines#204]). If we were to do so, we would either want to introduce some way for `Cell` to "opt back in" to niches or perhaps introduce a variant of `UnsafeCell` that *also* implies that its contents are guaranteed to be thread-local. [#68206]: https://github.com/rust-lang/rust/issues/68206 [unsafe-code-guidelines#204]: https://github.com/rust-lang/unsafe-code-guidelines/issues/204 [2020-01-16]: https://github.com/rust-lang/lang-team/blob/master/minutes/2020-01-16.md [#68303]: https://github.com/rust-lang/rust/issues/68303

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully