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
      • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
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
# Unwinding by default on C FFI? ## Premise We have been acting under the assumption that calls to `extern "C"` functions should not permit unwinding. But this is not entirely clear. Presuming that we do the work to define how unwinding and foreign exceptions interact, we can then choose for one of two paths: * with `extern "C"`, unwinding is UB; with `extern "C unwind"`, it is permitted * with `extern "C"`, unwinding is permitted; with `extern "C noexcept"`, it is UB (There are other variations, such as a `#[noexcept]` attribute to be placed on function items. However, in prior discussion we opted that ABIs were the preferred way to communicate unwinding information, so I've stuck to that convention. I think the arguments here apply in either case.) ## Some unknowns that might be important * Should `catch_unwind` allow one to intercept foreign exceptions? * How does `-Zpanic=abort` interact with FFI calls that may unwind? * In particular, is it UB if unwinding occurs with -Zpanic=abort? * What about if that unwinding occurs as a result of longjmp? * Or do we guarantee an abort? ## Assumptions ### We can define unwinding semantics in some reasonable and consistent way across virtually all platforms For example, there seem to be some unknowns about how longjmp and dtors interact with LLVM. I'm presuming they can be resolved in a satisfactory way. If this is not the case, then we may want to have people "opt-in" to unwinding because it would allow us to error out on platforms that can't handle exceptions properly. ## Arguments for making the default (`"C"`) forbid unwinding, and requiring opt-in ### Most FFI calls, in practice, will never unwind, but will still use extern "C" It is believed to be true that the vast majority of FFI calls are to functions (typically implemented in C) that are never expected to unwind. Thus this default aligns better with the reality. If we did introduce a "C noexcept" ABI, then there are two possibilities: * Nobody will use it, meaning that we have no reliable signal whether unwinding is to be expected at a particular call site (which has implications outlined below) * People will use it all the time, but it seems verbose and unfortunate ### Smaller code size if the default is that unwinding is UB Most FFI calls will be `extern "C"` and most FFI calls will never unwind. Aligning those defaults allows the compiler to remove more dead code. In the case of `-Zpanic=abort`, if we define that we will give a hard abort on unwinding, then each call site to a FFI function (at least an `extern "C"` function) will require some amount of "shim code" to catch and give a hard error. On the other hand, if we say that unwinding through an extern "C" function with `-Zpanic=abort` is UB, the code size is not a problem, but there are interactions with unsafe code (see next section). ### Potential for unwinding interacts strongly with unsafe code Let us first assume that `-Zpanic=abort` means that unwinding is *UB*. In that case, if you have Rust code which invokes a foreign function that does indeed unwind, that Rust code becomes UB just by changing to `-Zpanic=abort` (whereas it was well-defined before). To sidestep that, you can assume that `-Zpanic=abort` will insert an abort shim, but now we are paying a higher price. (We could also make it configurable whether or not a shim is created, perhaps even tied to debug/release builds like overflow, but this is making the feature more complex and less ergonomic.) On the other hand, if unwinding must be explicitly declared (via a "C unwind" ABI), we could make it an error to invoke a "C unwind" function with `-Zpanic=abort`, or we could choose to add an abort shim -- but this is expect to occur much less frequently, since most functions do not unwind. ### People will overlook unwinding, better for it to be made explicit Because most FFI calls do not unwind, people who make FFI calls are likely not to consider that unwinding is a possible outcome. Thus they are unlikely to help ensure that their code is unwind safe. Using the "C unwind" ABI helps draw attention to the unusual case, making it easier to do code audits. The danger with a misaligned default, like "C can unwind but usually doesn't", is that it will be hard to tell if someone is using `extern "C"` because their function *can* unwind or simply because it was the obvious thing to do. ### People may adopt the folk wisdom of 'just use "C noexcept"' everywhere e.g., cramertj mentioned that Fuschia would likely prefer to just use "C noexcept" everywhere rather than use "C", given that it would save them on codesize. However, this is not really "doable" via just a local change: for example, libc exports using the "C" ABI could cause trouble if fuschia is using them. ## Arguments for making the default (`"C"`) permit unwinding ### Rust's C ABI would match the system definition Most system ABIs specify an unwinding standard. This would make Rust's "C" ABI match the underlying system ABI more completely ### The default ABI ("C") permits invoking a wider set of functions without UB This could be seen as leading to less UB overall, although it must be balanced against the interactions with `-Zpanic=abort`. ### The precedent in C/C++ is to permit unwinding by default When compiling with `-fexceptions`, at least, the assumption is that most functions can unwind. To rule out unwinding, one must tag a function with a `noexcept` attribute (it is UB if a `noexcept` function unwinds, though in many cases C++ will also catch the exception and abort). Therefore, users might expect this default. (N.B. "C/C++" is not one language and the C standard has no such thing as `-fexceptions` afaik. // Centril) ### Existing libc bindings use "C" but sometimes unwind Because of the potential for pthread-cancelation, a large set of libc bindings would more accurately be "C unwind". The [pthreads man page] lists them out (search for "cancelation points") but they include many common functions. [pthreads man page]: http://man7.org/linux/man-pages/man7/pthreads.7.html This implies a few things: * to be correct, libc would either have to rule out cancelation (it's UB to use cancelation) * or change the types, inducing a 2.0 * and more generally, (dangling sentence... // Centril) (Seems like a great service to users to clarify unwinding/not in the `libc` crate by using `extern "C nounwind"`! // Centril) ### ABI boundaries should not change semantic behavior This is from an email from Nick Lewycky, a Wasmer dev who worked on LLVM for ~5 years: > If the callee can unwind, then it can unwind. FFI isn't a sandbox, it's not supposed to change behaviour or protect the caller. At the extreme I can recognize that some mapping of types is done in some systems (strings are a common one). On Linux, exceptions are primitive and well-defined much like 32-bit integers, despite the lack of support in C[1]. > > [1] - You can both throw and capture exceptions in C. The language doesn't define a syntax, but it doesn't need to. It doesn't define a syntax for networking or for threading either. Just include the header file and use the appropriate API. ("Supposed to" isn't justified here and we are allowed to, and do add shims on e.g. coercing things, including function pointers, afaik. // Centril) ### You might like to avoid unwinding of Rust functions, too We discussed how unsafe code in particular must be careful to be "unwind safe", but this applies not just to "C" functions but really to any Rust function. Therefore, we might like to have a feature that guarantees that some callee cannot unwind. But do we really want to use the ABI string to contrl this in the more general case? # Addendums ### Expressive power of a `extern "C"` feature that is guaranteed not to unwind > Note: this section assumes that `extern "C"` functions do not unwind. The C++ language has a `noexcept` keyword that implements a couple of features, one of which is to be able to make whether a function unwinds or not part of a functions' type (e.g. similar to `#[unwind(aborts)]`, but being part of the type system). Adding the guarantee to the language that `extern "C"` do not unwind has the same expressive power as C++ `noexcept` keyword, but it ties that guarantee to foreign functions, whereas it might be something you want more generally (see prior point). Proof: first, by using `extern "C"` on a function declaration, we state that it does not unwind, just like `noexcept`. We can also use `extern "C"` in type declarations, to constrain the types that generic code accepts. For example, `extern "C"` allows implementing a `NeverUnwind` trait that can be used to bound function types that never unwind: ```rust trait NeverUnwinds {} // manually expand this to multiple impls for different argument numbers: impl<Ret, Args...> NeverUnwinds for extern "C" fn(Args...) -> Ret {} ``` This trait can be used to implement APIs that rely on a function never unwinding for correctness, like the ones in the [take_mut] crate, without using `DropGuard`s to restore invariants that `unsafe` code temporarily violates in case of a panic: ```rust // notice that this is a Rust function, so it can unwind: /* safe */ extern "Rust" fn duplicate_map_nounwind<F>(x: &mut Vec<i32>, map: F) where F: Fn(i32)->i32 + NeverUnwinds { unsafe { // safe because `map`is safe and it never unwinds // no dropgurad, no catch_unwind let old_len = x.len(); let new_len = old_len * 2; // this can panic, and that's ok // since the vector invariants have not been broken yet x.reserve(new_len); x.set_len(new_len); // this will never panic, so we don't need to use a DropGuard to // restore the vector invariants for i in 0..old_len { x.as_ptr().add(i + old_len).write(map(x.as_ptr().add(i).read()) } }} ``` With `specialization`, code that uses `DropGuards` can be provided in the generic case, and code that does not in the case of `+ NeverUnwinds` is satisfied. [take_mut]: https://github.com/Sgeo/take_mut [no_panic]: https://github.com/dtolnay/no-panic It also allows implementing a trait that makes sure that calling a function never unwinds, subsuming the use cases of the [no_panic] crate: ```rust trait NoUnwindCall { type Args; type Ret; extern "C" fn nounwind_call(&self, arg: Self::Args) -> Self::Ret; } impl<Ret, Args...> NoUnwindCall for fn(Args...) -> Ret { type Args = (Args...); type Ret = Ret; extern "C" fn nounwind_call(&self, arg: Self::Args) -> Self::Ret { self(arg...) } } ``` which can be used to make sure that function calls do not unwind: ```rust let foo: extern "Rust" fn(...) -> ...; // Instead of calling foo directly, one can // use `NoUnwindCall::nounwind_call` to perform the call. let x = foo.nounwind_call((args...)); ``` All `.nounwind_call`s are guaranteed not to unwind. They will be `nounwind` in LLVM-IR, eliminating panic handling code in the caller. The `-C panic=abort` feature is very effective at applying these optimizations to the whole binary. However, it might be tempting for users using `-C panic=uninwd`, or for library writers, to start using `extern "C"` instead of the Rust ABI as an optimization hammer similar to, e.g., `#[inline]`, to work around the cases for which LLVM does not deduce the `nounwind` attribute appropiately. By adding a `extern "C"` feature to the language that's guaranteed not to unwind we are actually adding a feature to Rust that's very similar in power to `noexcept`, but with worse ergonomics. It might make more sense to allow `extern "C"` and all ABIs to unwind by default, and provide a better language feature for specifying that a function never unwinds (e.g. `nounwind fn foo(...) { ... }`). Having some ABIs that unwind by default and some that do not might complicate adding such a feature. (Why would it complicate things? At most it seems like `extern "C" fn` would be subsumed by `nopanic extern "C" fn` but the former is still shorter (see arguments above for nounwind as common default). // Centril)

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