critical-section-1.2.0/.cargo_vcs_info.json0000644000000001360000000000100142700ustar { "git": { "sha1": "ed0f84c5ca3697a2166ed76e656c958cd3915b00" }, "path_in_vcs": "" }critical-section-1.2.0/.github/CODEOWNERS000064400000000000000000000000251046102023000160100ustar 00000000000000* @rust-embedded/hal critical-section-1.2.0/.github/bors.toml000064400000000000000000000003461046102023000162650ustar 00000000000000block_labels = ["needs-decision"] delete_merged_branches = true required_approvals = 1 status = [ "clippy (1.54)", "clippy (1.63)", "clippy (1.63, std)", "rustfmt", "test (1.54)", "test (1.63)", "test (1.63, std)", ]critical-section-1.2.0/.github/workflows/clippy.yml000064400000000000000000000011671046102023000205050ustar 00000000000000name: Clippy check on: push: branches: [ main ] pull_request: merge_group: jobs: clippy: runs-on: ubuntu-latest strategy: matrix: include: - rust: 1.54 features: '' - rust: 1.63 features: '' - rust: 1.63 features: 'std' steps: - uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: ${{matrix.rust}} components: clippy override: true - name: Clippy check run: cargo clippy --features "${{matrix.features}}" critical-section-1.2.0/.github/workflows/rustfmt.yml000064400000000000000000000003631046102023000207060ustar 00000000000000name: Code formatting check on: push: branches: [ main ] pull_request: merge_group: jobs: rustfmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Check fmt run: cargo fmt -- --check critical-section-1.2.0/.github/workflows/test.yml000064400000000000000000000011431046102023000201560ustar 00000000000000name: Test on: push: branches: [ main ] pull_request: merge_group: jobs: test: runs-on: ubuntu-latest strategy: matrix: include: - rust: 1.54 features: '' - rust: 1.63 features: '' - rust: 1.63 features: 'std' steps: - uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: toolchain: ${{matrix.rust}} components: clippy override: true - name: Test run: cargo test --features "${{matrix.features}}" critical-section-1.2.0/.gitignore000064400000000000000000000000231046102023000150430ustar 00000000000000/target Cargo.lock critical-section-1.2.0/CHANGELOG.md000064400000000000000000000133201046102023000146700ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] No unreleased changes yet ## [v1.2.0] - 2024-10-16 - Soundness fix: ensure the `CriticalSection` token is not `Send` or `Sync`, so that it can only be used in the thread that acquired it. [#55](https://github.com/rust-embedded/critical-section/issues/55) - Soundness fix: Fix aliasing `&mut` in the `std` implementation. [#46](https://github.com/rust-embedded/critical-section/pull/46) - Fix build with `restore-state-usize`. [#50](https://github.com/rust-embedded/critical-section/pull/50) ## [v1.1.3] - 2024-08-22 - Added option to use a `usize` sized restore state ## [v1.1.2] - 2023-08-09 - Clarified that `acquire()` must provide ordering guarantees - Updated atomic-polyfill reference to point to portable-atomic instead - Improved documentation for `Mutex` example - Added list of some known implementations ## [v1.1.1] - 2022-09-13 - On the `std` implementation, panicking inside the `critical_section::with()` closure no longer accidentally leaves the critical section locked (#26). ## [v1.1.0] - 2022-08-17 - Added built-in critical section implementation using `std::sync::Mutex`, enabled by the `std` Cargo feature. - MSRV changed to `1.54` when `std` feature is disabled, `1.63` when enabled. ## [v1.0.0] - 2022-08-10 - Improved docs. ## [v1.0.0-alpha.2] - 2022-07-28 - Change name of the `extern fn`s to avoid clash with critical-section 0.2. ## [v1.0.0-alpha.1] - 2022-07-28 Breaking changes: - Removed all builtin impls. These are going to be provided by platform-support crates now. - Renamed `custom_impl!` to `set_impl!`. - RestoreState is now an opaque struct for the user, and a transparent `RawRestoreState` type alias for impl writers. - RestoreState type is now configurable with Cargo features. Default is `()`. (previously it was fixed to `u8`.) - Added own `CriticalSection` and `Mutex` types, instead of reexporting them from `bare_metal`. ## [v0.2.8] - 2022-11-29 - Implemented critical-section by forwarding to version 1.1.1 Breaking changes: - `acquire` and `release` are only implemented if the restore-state used by version 1.1.1 is an u8 or smaller. - No default critical-section implementation is provided. Those breaking changes are necessary because versions <= 0.2.7 were unsound, and that was impossible to fix without a breaking change. This version is meant to minimize that breaking change. However, all users are encouraged to upgrade to critical-section 1.1. If you're seeing a linker error like `undefined symbol: _critical_section_1_0_acquire`, you're affected. To fix it: - If your target supports `std`: Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. ```toml [dependencies] critical-section = { version = "1.1", features = ["std"]} ``` - For single-core Cortex-M targets in privileged mode: ```toml [dependencies] cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} ``` - For single-hart RISC-V targets in privileged mode: ```toml [dependencies] riscv = { version = "0.10", features = ["critical-section-single-hart"]} ``` - For other targets: check if your HAL or architecture-support crate has a `critical-section 1.0` implementation available. Otherwise, [provide your own](https://github.com/rust-embedded/critical-section#providing-an-implementation). ## [v0.2.7] - 2022-04-08 - Add support for AVR targets. ## [v0.2.6] - 2022-04-02 - Improved docs. ## [v0.2.5] - 2021-11-02 - Fix `std` implementation to allow reentrant (nested) critical sections. This would previously deadlock. ## [v0.2.4] - 2021-09-24 - Add support for 32bit RISC-V targets. ## [v0.2.3] - 2021-09-13 - Use correct `#[vcfg]` for `wasm` targets. ## [v0.2.2] - 2021-09-13 - Added support for `wasm` targets. ## [v0.2.1] - 2021-05-11 - Added critical section implementation for `std`, based on a global Mutex. ## [v0.2.0] - 2021-05-10 - Breaking change: use `CriticalSection<'_>` instead of `&CriticalSection<'_>` ## v0.1.0 - 2021-05-10 - First release [Unreleased]: https://github.com/rust-embedded/critical-section/compare/v1.2.0...HEAD [v1.2.0]: https://github.com/rust-embedded/critical-section/compare/v1.1.3...v1.2.0 [v1.1.3]: https://github.com/rust-embedded/critical-section/compare/v1.1.2...v1.1.3 [v1.1.2]: https://github.com/rust-embedded/critical-section/compare/v1.1.1...v1.1.2 [v1.1.1]: https://github.com/rust-embedded/critical-section/compare/v1.1.0...v1.1.1 [v1.1.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0...v1.1.0 [v1.0.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.2...v1.0.0 [v1.0.0-alpha.2]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.1...v1.0.0-alpha.2 [v1.0.0-alpha.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v1.0.0-alpha.1 [v0.2.8]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v0.2.8 [v0.2.7]: https://github.com/rust-embedded/critical-section/compare/v0.2.6...v0.2.7 [v0.2.6]: https://github.com/rust-embedded/critical-section/compare/v0.2.5...v0.2.6 [v0.2.5]: https://github.com/rust-embedded/critical-section/compare/v0.2.4...v0.2.5 [v0.2.4]: https://github.com/rust-embedded/critical-section/compare/v0.2.3...v0.2.4 [v0.2.3]: https://github.com/rust-embedded/critical-section/compare/v0.2.2...v0.2.3 [v0.2.2]: https://github.com/rust-embedded/critical-section/compare/v0.2.1...v0.2.2 [v0.2.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.0...v0.2.1 [v0.2.0]: https://github.com/rust-embedded/critical-section/compare/v0.1.0...v0.2.0 critical-section-1.2.0/CODE_OF_CONDUCT.md000064400000000000000000000106761046102023000156710ustar 00000000000000# The Rust Code of Conduct ## Conduct **Contact**: [HAL team][team] * We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. * On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. * Please be kind and courteous. There's no need to be mean or rude. * Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. ## Moderation These are the policies for upholding our community's standards of conduct. 1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) 2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. 3. Moderators will first respond to such remarks with a warning. 4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. 5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. 6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. 7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. 8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). *Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* [team]: https://github.com/rust-embedded/wg#the-hal-team critical-section-1.2.0/Cargo.toml0000644000000021540000000000100122700ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "critical-section" version = "1.2.0" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Cross-platform critical section" readme = "README.md" categories = [ "embedded", "no-std", "concurrency", ] license = "MIT OR Apache-2.0" repository = "https://github.com/rust-embedded/critical-section" [lib] name = "critical_section" path = "src/lib.rs" [features] restore-state-bool = [] restore-state-none = [] restore-state-u16 = [] restore-state-u32 = [] restore-state-u64 = [] restore-state-u8 = [] restore-state-usize = [] std = ["restore-state-bool"] critical-section-1.2.0/Cargo.toml.orig000064400000000000000000000016171046102023000157540ustar 00000000000000[package] name = "critical-section" version = "1.2.0" edition = "2018" description = "Cross-platform critical section" repository = "https://github.com/rust-embedded/critical-section" readme = "README.md" license = "MIT OR Apache-2.0" categories = [ "embedded", "no-std", "concurrency", ] [features] # Enable a critical-section implementation for platforms supporting `std`, based on `std::sync::Mutex`. # If you enable this, the `critical-section` crate itself provides the implementation, # you don't have to get another crate to to do it. std = ["restore-state-bool"] # Set the RestoreState size. # The crate supplying the critical section implementation can set ONE of them. # Other crates MUST NOT set any of these. restore-state-none = [] # Default restore-state-bool = [] restore-state-u8 = [] restore-state-u16 = [] restore-state-u32 = [] restore-state-u64 = [] restore-state-usize = [] critical-section-1.2.0/LICENSE-APACHE000064400000000000000000000251371046102023000150140ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. critical-section-1.2.0/LICENSE-MIT000064400000000000000000000020601046102023000145120ustar 00000000000000Copyright (c) 2022 The critical-section authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. critical-section-1.2.0/README.md000064400000000000000000000247151046102023000143500ustar 00000000000000# critical-section [![crates.io](https://img.shields.io/crates/d/critical-section.svg)](https://crates.io/crates/critical-section) [![crates.io](https://img.shields.io/crates/v/critical-section.svg)](https://crates.io/crates/critical-section) [![Documentation](https://docs.rs/critical-section/badge.svg)](https://docs.rs/critical-section) This project is developed and maintained by the [HAL team][team]. A critical section that works everywhere! When writing software for embedded systems, it's common to use a "critical section" as a basic primitive to control concurrency. A critical section is essentially a mutex global to the whole process, that can be acquired by only one thread at a time. This can be used to protect data behind mutexes, to [emulate atomics](https://crates.io/crates/portable-atomic) in targets that don't support them, etc. There's a wide range of possible implementations depending on the execution environment: - For bare-metal single core, disabling interrupts in the current (only) core. - For bare-metal multicore, disabling interrupts in the current core and acquiring a hardware spinlock to prevent other cores from entering a critical section concurrently. - For bare-metal using a RTOS, using library functions for acquiring a critical section, often named "scheduler lock" or "kernel lock". - For bare-metal running in non-privileged mode, calling some system call is usually needed. - For `std` targets, acquiring a global `std::sync::Mutex`. Libraries often need to use critical sections, but there's no universal API for this in `core`. This leads library authors to hard-code them for their target, or at best add some `cfg`s to support a few targets. This doesn't scale since there are many targets out there, and in the general case it's impossible to know which critical section implementation is needed from the Rust target alone. For example, the `thumbv7em-none-eabi` target could be cases 1-4 from the above list. This crate solves the problem by providing this missing universal API. - It provides functions `acquire`, `release` and `with` that libraries can directly use. - It provides a way for any crate to supply an implementation. This allows "target support" crates such as architecture crates (`cortex-m`, `riscv`), RTOS bindings, or HALs for multicore chips to supply the correct implementation so that all the crates in the dependency tree automatically use it. ## Usage in `no-std` binaries. First, add a dependency on a crate providing a critical section implementation. Enable the `critical-section-*` Cargo feature if required by the crate. Implementations are typically provided by either architecture-support crates, HAL crates, and OS/RTOS bindings, including: * The [`cortex-m`] crate provides an implementation for all single-core Cortex-M microcontrollers via its `critical-section-single-core` feature * The [`riscv`] crate provides an implementation for all single-hart RISC-V microcontrollers via its `critical-section-single-hart` feature * The [`msp430`] crate provides an implementation for all MSP430 microcontrollers via its `critical-section-single-core` feature * The [`rp2040-hal`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature * The [`avr-device`] crate provides an implementation for all AVR microcontrollers via its `critical-section-impl` feature * The [`esp-hal-common`] crate provides an implementation for ESP32 microcontrollers which is used by the ESP HALs * The [`embassy-rp`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature * The [`nrf-softdevice`] crate provides a critical section that's compatible with the nRF soft-device firmware via its `critical-section-impl` feature [`cortex-m`]: https://crates.io/crates/cortex-m [`riscv`]: https://crates.io/crates/riscv [`msp430`]: https://crates.io/crates/msp430 [`rp2040-hal`]: https://crates.io/crates/rp2040-hal [`avr-device`]: https://crates.io/crates/avr-device [`esp-hal-common`]: https://crates.io/crates/esp-hal-common [`embassy-rp`]: https://docs.embassy.dev/embassy-rp [`nrf-softdevice`]: https://docs.embassy.dev/nrf-softdevice For example, for single-core Cortex-M targets, you can use: ```toml [dependencies] cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} ``` Then you can use `critical_section::with()`. ```rust use core::cell::Cell; use critical_section::Mutex; static MY_VALUE: Mutex> = Mutex::new(Cell::new(0)); critical_section::with(|cs| { // This code runs within a critical section. // `cs` is a token that you can use to "prove" that to some API, // for example to a `Mutex`: MY_VALUE.borrow(cs).set(42); }); # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` # mod no_std { # struct MyCriticalSection; # critical_section::set_impl!(MyCriticalSection); # unsafe impl critical_section::Impl for MyCriticalSection { # unsafe fn acquire() -> () {} # unsafe fn release(token: ()) {} # } # } ``` ## Usage in `std` binaries. Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. This makes the `critical-section` crate itself provide an implementation based on `std::sync::Mutex`, so you don't have to add any other dependency. ```toml [dependencies] critical-section = { version = "1.1", features = ["std"]} ``` ## Usage in libraries If you're writing a library intended to be portable across many targets, simply add a dependency on `critical-section` and use `critical_section::free` and/or `Mutex` as usual. **Do not** add any dependency supplying a critical section implementation. Do not enable any `critical-section-*` Cargo feature. This has to be done by the end user, enabling the correct implementation for their target. **Do not** enable any Cargo feature in `critical-section`. ## Usage in `std` tests for `no-std` libraries. If you want to run `std`-using tests in otherwise `no-std` libraries, enable the `std` feature in `dev-dependencies` only. This way the main target will use the `no-std` implementation chosen by the end-user's binary, and only the test targets will use the `std` implementation. ```toml [dependencies] critical-section = "1.1" [dev-dependencies] critical-section = { version = "1.1", features = ["std"]} ``` ## Providing an implementation Crates adding support for a particular architecture, chip or operating system should provide a critical section implementation. It is **strongly recommended** to gate the implementation behind a feature, so the user can still use another implementation if needed (having two implementations in the same binary will cause linking to fail). Add the dependency, and a `critical-section-*` feature to your `Cargo.toml`: ```toml [features] # Enable critical section implementation that does "foo" critical-section-foo = ["critical-section/restore-state-bool"] [dependencies] critical-section = { version = "1.0", optional = true } ``` Then, provide the critical implementation like this: ```rust # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` # mod no_std { // This is a type alias for the enabled `restore-state-*` feature. // For example, it is `bool` if you enable `restore-state-bool`. use critical_section::RawRestoreState; struct MyCriticalSection; critical_section::set_impl!(MyCriticalSection); unsafe impl critical_section::Impl for MyCriticalSection { unsafe fn acquire() -> RawRestoreState { // TODO } unsafe fn release(token: RawRestoreState) { // TODO } } # } ``` ## Troubleshooting ### Undefined reference errors If you get an error like these: ```not_rust undefined reference to `_critical_section_1_0_acquire' undefined reference to `_critical_section_1_0_release' ``` it is because you (or a library) are using `critical_section::with` without providing a critical section implementation. Make sure you're depending on a crate providing the implementation, and have enabled the `critical-section-*` feature in it if required. See the `Usage` section above. The error can also be caused by having the dependency but never `use`ing it. This can be fixed by adding a dummy `use`: ```rust,ignore use the_cs_impl_crate as _; ``` ### Duplicate symbol errors If you get errors like these: ```not_rust error: symbol `_critical_section_1_0_acquire` is already defined ``` it is because you have two crates trying to provide a critical section implementation. You can only have one implementation in a program. You can use `cargo tree --format '{p} {f}'` to view all dependencies and their enabled features. Make sure that in the whole dependency tree, exactly one implementation is provided. Check for multiple versions of the same crate as well. For example, check the `critical-section-single-core` feature is not enabled for both `cortex-m` 0.7 and 0.8. ## Why not generics? An alternative solution would be to use a `CriticalSection` trait, and make all code that needs acquiring the critical section generic over it. This has a few problems: - It would require passing it as a generic param to a very big amount of code, which would be quite unergonomic. - It's common to put `Mutex`es in `static` variables, and `static`s can't be generic. - It would allow mixing different critical section implementations in the same program, which would be unsound. ## Minimum Supported Rust Version (MSRV) This crate is guaranteed to compile on the following Rust versions: - If the `std` feature is not enabled: stable Rust 1.54 and up. - If the `std` feature is enabled: stable Rust 1.63 and up. It might compile with older versions but that may change in any new patch release. See [here](docs/msrv.md) for details on how the MSRV may be upgraded. ## License This work is licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ## Code of Conduct Contribution to this crate is organized under the terms of the [Rust Code of Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises to intervene to uphold that code of conduct. [CoC]: CODE_OF_CONDUCT.md [team]: https://github.com/rust-embedded/wg#the-hal-team critical-section-1.2.0/docs/msrv.md000064400000000000000000000024171046102023000153250ustar 00000000000000# Minimum Supported Rust Version (MSRV) This crate is guaranteed to compile on all stable Rust versions going back to the version stated as MSRV in the README. It *might* compile with even older versions but that may change in any new patch release. ## How the MSRV will be upgraded For `critical-section`, we do not consider upgrading the MSRV a strictly breaking change as defined by [SemVer](https://semver.org). We follow these rules when upgrading it: - We will not update the MSRV on any patch release: \_.\_.*Z*. - We may upgrade the MSRV on any *major* or *minor* release: *X*.*Y*.\_. - We may upgrade the MSRV in any preliminary version release (e.g. an `-alpha` release) as these serve as preparation for the final release. - MSRV upgrades will be clearly stated in the changelog. This applies both to `0._._` releases as well as `>=1._._` releases. For example: For a given `x.y.z` release, we may upgrade the MSRV on `x` and `y` releases but not on `z` releases. If your MSRV upgrade policy differs from this, you are advised to specify the `critical-section` dependency in your `Cargo.toml` accordingly. See the [Rust Embedded Working Group MSRV RFC](https://github.com/rust-embedded/wg/blob/master/rfcs/0523-msrv-2020.md) for more background information and reasoning. critical-section-1.2.0/src/lib.rs000064400000000000000000000255031046102023000147700ustar 00000000000000#![cfg_attr(not(feature = "std"), no_std)] #![doc = include_str!("../README.md")] mod mutex; #[cfg(feature = "std")] mod std; use core::marker::PhantomData; pub use self::mutex::Mutex; /// Critical section token. /// /// An instance of this type indicates that the current thread is executing code within a critical /// section. #[derive(Clone, Copy, Debug)] pub struct CriticalSection<'cs> { _private: PhantomData<&'cs ()>, // Prevent CriticalSection from being Send or Sync // https://github.com/rust-embedded/critical-section/issues/55 _not_send_sync: PhantomData<*mut ()>, } impl<'cs> CriticalSection<'cs> { /// Creates a critical section token. /// /// This method is meant to be used to create safe abstractions rather than being directly used /// in applications. /// /// # Safety /// /// This must only be called when the current thread is in a critical section. The caller must /// ensure that the returned instance will not live beyond the end of the critical section. /// /// The caller must use adequate fences to prevent the compiler from moving the /// instructions inside the critical section to the outside of it. Sequentially consistent fences are /// suggested immediately after entry and immediately before exit from the critical section. /// /// Note that the lifetime `'cs` of the returned instance is unconstrained. User code must not /// be able to influence the lifetime picked for this type, since that might cause it to be /// inferred to `'static`. #[inline(always)] pub unsafe fn new() -> Self { CriticalSection { _private: PhantomData, _not_send_sync: PhantomData, } } } #[cfg(any( all(feature = "restore-state-none", feature = "restore-state-bool"), all(feature = "restore-state-none", feature = "restore-state-u8"), all(feature = "restore-state-none", feature = "restore-state-u16"), all(feature = "restore-state-none", feature = "restore-state-u32"), all(feature = "restore-state-none", feature = "restore-state-u64"), all(feature = "restore-state-bool", feature = "restore-state-u8"), all(feature = "restore-state-bool", feature = "restore-state-u16"), all(feature = "restore-state-bool", feature = "restore-state-u32"), all(feature = "restore-state-bool", feature = "restore-state-u64"), all(feature = "restore-state-bool", feature = "restore-state-usize"), all(feature = "restore-state-u8", feature = "restore-state-u16"), all(feature = "restore-state-u8", feature = "restore-state-u32"), all(feature = "restore-state-u8", feature = "restore-state-u64"), all(feature = "restore-state-u8", feature = "restore-state-usize"), all(feature = "restore-state-u16", feature = "restore-state-u32"), all(feature = "restore-state-u16", feature = "restore-state-u64"), all(feature = "restore-state-u16", feature = "restore-state-usize"), all(feature = "restore-state-u32", feature = "restore-state-u64"), all(feature = "restore-state-u32", feature = "restore-state-usize"), all(feature = "restore-state-u64", feature = "restore-state-usize"), ))] compile_error!("You must set at most one of these Cargo features: restore-state-none, restore-state-bool, restore-state-u8, restore-state-u16, restore-state-u32, restore-state-u64, restore-state-usize"); #[cfg(not(any( feature = "restore-state-bool", feature = "restore-state-u8", feature = "restore-state-u16", feature = "restore-state-u32", feature = "restore-state-u64", feature = "restore-state-usize" )))] type RawRestoreStateInner = (); #[cfg(feature = "restore-state-bool")] type RawRestoreStateInner = bool; #[cfg(feature = "restore-state-u8")] type RawRestoreStateInner = u8; #[cfg(feature = "restore-state-u16")] type RawRestoreStateInner = u16; #[cfg(feature = "restore-state-u32")] type RawRestoreStateInner = u32; #[cfg(feature = "restore-state-u64")] type RawRestoreStateInner = u64; #[cfg(feature = "restore-state-usize")] type RawRestoreStateInner = usize; // We have RawRestoreStateInner and RawRestoreState so that we don't have to copypaste the docs 5 times. // In the docs this shows as `pub type RawRestoreState = u8` or whatever the selected type is, because // the "inner" type alias is private. /// Raw, transparent "restore state". /// /// This type changes based on which Cargo feature is selected, out of /// - `restore-state-none` (default, makes the type be `()`) /// - `restore-state-bool` /// - `restore-state-u8` /// - `restore-state-u16` /// - `restore-state-u32` /// - `restore-state-u64` /// - `restore-state-usize` /// /// See [`RestoreState`]. /// /// User code uses [`RestoreState`] opaquely, critical section implementations /// use [`RawRestoreState`] so that they can use the inner value. pub type RawRestoreState = RawRestoreStateInner; /// Opaque "restore state". /// /// Implementations use this to "carry over" information between acquiring and releasing /// a critical section. For example, when nesting two critical sections of an /// implementation that disables interrupts globally, acquiring the inner one won't disable /// the interrupts since they're already disabled. The impl would use the restore state to "tell" /// the corresponding release that it does *not* have to reenable interrupts yet, only the /// outer release should do so. /// /// User code uses [`RestoreState`] opaquely, critical section implementations /// use [`RawRestoreState`] so that they can use the inner value. #[derive(Clone, Copy, Debug)] pub struct RestoreState(RawRestoreState); impl RestoreState { /// Create an invalid, dummy `RestoreState`. /// /// This can be useful to avoid `Option` when storing a `RestoreState` in a /// struct field, or a `static`. /// /// Note that due to the safety contract of [`acquire`]/[`release`], you must not pass /// a `RestoreState` obtained from this method to [`release`]. pub const fn invalid() -> Self { #[cfg(not(any( feature = "restore-state-bool", feature = "restore-state-u8", feature = "restore-state-u16", feature = "restore-state-u32", feature = "restore-state-u64", feature = "restore-state-usize" )))] return Self(()); #[cfg(feature = "restore-state-bool")] return Self(false); #[cfg(feature = "restore-state-u8")] return Self(0); #[cfg(feature = "restore-state-u16")] return Self(0); #[cfg(feature = "restore-state-u32")] return Self(0); #[cfg(feature = "restore-state-u64")] return Self(0); #[cfg(feature = "restore-state-usize")] return Self(0); } } /// Acquire a critical section in the current thread. /// /// This function is extremely low level. Strongly prefer using [`with`] instead. /// /// Nesting critical sections is allowed. The inner critical sections /// are mostly no-ops since they're already protected by the outer one. /// /// # Safety /// /// - Each `acquire` call must be paired with exactly one `release` call in the same thread. /// - `acquire` returns a "restore state" that you must pass to the corresponding `release` call. /// - `acquire`/`release` pairs must be "properly nested", ie it's not OK to do `a=acquire(); b=acquire(); release(a); release(b);`. /// - It is UB to call `release` if the critical section is not acquired in the current thread. /// - It is UB to call `release` with a "restore state" that does not come from the corresponding `acquire` call. /// - It must provide ordering guarantees at least equivalent to a [`core::sync::atomic::Ordering::Acquire`] /// on a memory location shared by all critical sections, on which the `release` call will do a /// [`core::sync::atomic::Ordering::Release`] operation. #[inline(always)] pub unsafe fn acquire() -> RestoreState { extern "Rust" { fn _critical_section_1_0_acquire() -> RawRestoreState; } #[allow(clippy::unit_arg)] RestoreState(_critical_section_1_0_acquire()) } /// Release the critical section. /// /// This function is extremely low level. Strongly prefer using [`with`] instead. /// /// # Safety /// /// See [`acquire`] for the safety contract description. #[inline(always)] pub unsafe fn release(restore_state: RestoreState) { extern "Rust" { fn _critical_section_1_0_release(restore_state: RawRestoreState); } #[allow(clippy::unit_arg)] _critical_section_1_0_release(restore_state.0) } /// Execute closure `f` in a critical section. /// /// Nesting critical sections is allowed. The inner critical sections /// are mostly no-ops since they're already protected by the outer one. /// /// # Panics /// /// This function panics if the given closure `f` panics. In this case /// the critical section is released before unwinding. #[inline] pub fn with(f: impl FnOnce(CriticalSection) -> R) -> R { // Helper for making sure `release` is called even if `f` panics. struct Guard { state: RestoreState, } impl Drop for Guard { #[inline(always)] fn drop(&mut self) { unsafe { release(self.state) } } } let state = unsafe { acquire() }; let _guard = Guard { state }; unsafe { f(CriticalSection::new()) } } /// Methods required for a critical section implementation. /// /// This trait is not intended to be used except when implementing a critical section. /// /// # Safety /// /// Implementations must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. pub unsafe trait Impl { /// Acquire the critical section. /// /// # Safety /// /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. unsafe fn acquire() -> RawRestoreState; /// Release the critical section. /// /// # Safety /// /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. unsafe fn release(restore_state: RawRestoreState); } /// Set the critical section implementation. /// /// # Example /// /// ``` /// # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` /// # mod no_std { /// use critical_section::RawRestoreState; /// /// struct MyCriticalSection; /// critical_section::set_impl!(MyCriticalSection); /// /// unsafe impl critical_section::Impl for MyCriticalSection { /// unsafe fn acquire() -> RawRestoreState { /// // ... /// } /// /// unsafe fn release(restore_state: RawRestoreState) { /// // ... /// } /// } /// # } #[macro_export] macro_rules! set_impl { ($t: ty) => { #[no_mangle] unsafe fn _critical_section_1_0_acquire() -> $crate::RawRestoreState { <$t as $crate::Impl>::acquire() } #[no_mangle] unsafe fn _critical_section_1_0_release(restore_state: $crate::RawRestoreState) { <$t as $crate::Impl>::release(restore_state) } }; } critical-section-1.2.0/src/mutex.rs000064400000000000000000000155101046102023000153610ustar 00000000000000use super::CriticalSection; use core::cell::{Ref, RefCell, RefMut, UnsafeCell}; /// A mutex based on critical sections. /// /// # Example /// /// ```no_run /// # use critical_section::Mutex; /// # use std::cell::Cell; /// /// static FOO: Mutex> = Mutex::new(Cell::new(42)); /// /// fn main() { /// critical_section::with(|cs| { /// FOO.borrow(cs).set(43); /// }); /// } /// /// fn interrupt_handler() { /// let _x = critical_section::with(|cs| FOO.borrow(cs).get()); /// } /// ``` /// /// /// # Design /// /// [`std::sync::Mutex`] has two purposes. It converts types that are [`Send`] /// but not [`Sync`] into types that are both; and it provides /// [interior mutability]. `critical_section::Mutex`, on the other hand, only adds /// `Sync`. It does *not* provide interior mutability. /// /// This was a conscious design choice. It is possible to create multiple /// [`CriticalSection`] tokens, either by nesting critical sections or `Copy`ing /// an existing token. As a result, it would not be sound for [`Mutex::borrow`] /// to return `&mut T`, because there would be nothing to prevent calling /// `borrow` multiple times to create aliased `&mut T` references. /// /// The solution is to include a runtime check to ensure that each resource is /// borrowed only once. This is what `std::sync::Mutex` does. However, this is /// a runtime cost that may not be required in all circumstances. For instance, /// `Mutex>` never needs to create `&mut T` or equivalent. /// /// If `&mut T` is needed, the simplest solution is to use `Mutex>`, /// which is the closest analogy to `std::sync::Mutex`. [`RefCell`] inserts the /// exact runtime check necessary to guarantee that the `&mut T` reference is /// unique. /// /// To reduce verbosity when using `Mutex>`, we reimplement some of /// `RefCell`'s methods on it directly. /// /// ```no_run /// # use critical_section::Mutex; /// # use std::cell::RefCell; /// /// static FOO: Mutex> = Mutex::new(RefCell::new(42)); /// /// fn main() { /// critical_section::with(|cs| { /// // Instead of calling this /// let _ = FOO.borrow(cs).take(); /// // Call this /// let _ = FOO.take(cs); /// // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to /// // `borrow_ref` and `borrow_ref_mut` to avoid name collisions /// let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs); /// }) /// } /// ``` /// /// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html /// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html #[derive(Debug)] pub struct Mutex { // The `UnsafeCell` is not strictly necessary here: In theory, just using `T` should // be fine. // However, without `UnsafeCell`, the compiler may use niches inside `T`, and may // read the niche value _without locking the mutex_. As we don't provide interior // mutability, this is still not violating any aliasing rules and should be perfectly // fine. But as the cost of adding `UnsafeCell` is very small, we add it out of // cautiousness, just in case the reason `T` is not `Sync` in the first place is // something very obscure we didn't consider. inner: UnsafeCell, } impl Mutex { /// Creates a new mutex. #[inline] pub const fn new(value: T) -> Self { Mutex { inner: UnsafeCell::new(value), } } /// Gets a mutable reference to the contained value when the mutex is already uniquely borrowed. /// /// This does not require locking or a critical section since it takes `&mut self`, which /// guarantees unique ownership already. Care must be taken when using this method to /// **unsafely** access `static mut` variables, appropriate fences must be used to prevent /// unwanted optimizations. #[inline] pub fn get_mut(&mut self) -> &mut T { unsafe { &mut *self.inner.get() } } /// Unwraps the contained value, consuming the mutex. #[inline] pub fn into_inner(self) -> T { self.inner.into_inner() } /// Borrows the data for the duration of the critical section. #[inline] pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T { unsafe { &*self.inner.get() } } } impl Mutex> { /// Borrow the data and call [`RefCell::replace`] /// /// This is equivalent to `self.borrow(cs).replace(t)` /// /// # Panics /// /// This call could panic. See the documentation for [`RefCell::replace`] /// for more details. #[inline] #[track_caller] pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T { self.borrow(cs).replace(t) } /// Borrow the data and call [`RefCell::replace_with`] /// /// This is equivalent to `self.borrow(cs).replace_with(f)` /// /// # Panics /// /// This call could panic. See the documentation for /// [`RefCell::replace_with`] for more details. #[inline] #[track_caller] pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> T where F: FnOnce(&mut T) -> T, { self.borrow(cs).replace_with(f) } /// Borrow the data and call [`RefCell::borrow`] /// /// This is equivalent to `self.borrow(cs).borrow()` /// /// # Panics /// /// This call could panic. See the documentation for [`RefCell::borrow`] /// for more details. #[inline] #[track_caller] pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T> { self.borrow(cs).borrow() } /// Borrow the data and call [`RefCell::borrow_mut`] /// /// This is equivalent to `self.borrow(cs).borrow_mut()` /// /// # Panics /// /// This call could panic. See the documentation for [`RefCell::borrow_mut`] /// for more details. #[inline] #[track_caller] pub fn borrow_ref_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, T> { self.borrow(cs).borrow_mut() } } impl Mutex> { /// Borrow the data and call [`RefCell::take`] /// /// This is equivalent to `self.borrow(cs).take()` /// /// # Panics /// /// This call could panic. See the documentation for [`RefCell::take`] /// for more details. #[inline] #[track_caller] pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T { self.borrow(cs).take() } } // NOTE A `Mutex` can be used as a channel so the protected data must be `Send` // to prevent sending non-Sendable stuff (e.g. access tokens) across different // threads. unsafe impl Sync for Mutex where T: Send {} /// ``` compile_fail /// fn bad(cs: critical_section::CriticalSection) -> &u32 { /// let x = critical_section::Mutex::new(42u32); /// x.borrow(cs) /// } /// ``` #[cfg(doctest)] const BorrowMustNotOutliveMutexTest: () = (); critical-section-1.2.0/src/std.rs000064400000000000000000000061041046102023000150100ustar 00000000000000use std::cell::Cell; use std::mem::MaybeUninit; use std::sync::{Mutex, MutexGuard}; static GLOBAL_MUTEX: Mutex<()> = Mutex::new(()); // This is initialized if a thread has acquired the CS, uninitialized otherwise. static mut GLOBAL_GUARD: MaybeUninit> = MaybeUninit::uninit(); std::thread_local!(static IS_LOCKED: Cell = Cell::new(false)); struct StdCriticalSection; crate::set_impl!(StdCriticalSection); unsafe impl crate::Impl for StdCriticalSection { unsafe fn acquire() -> bool { // Allow reentrancy by checking thread local state IS_LOCKED.with(|l| { if l.get() { // CS already acquired in the current thread. return true; } // Note: it is fine to set this flag *before* acquiring the mutex because it's thread local. // No other thread can see its value, there's no potential for races. // This way, we hold the mutex for slightly less time. l.set(true); // Not acquired in the current thread, acquire it. let guard = match GLOBAL_MUTEX.lock() { Ok(guard) => guard, Err(err) => { // Ignore poison on the global mutex in case a panic occurred // while the mutex was held. err.into_inner() } }; GLOBAL_GUARD.write(guard); false }) } unsafe fn release(nested_cs: bool) { if !nested_cs { // SAFETY: As per the acquire/release safety contract, release can only be called // if the critical section is acquired in the current thread, // in which case we know the GLOBAL_GUARD is initialized. // // We have to `assume_init_read` then drop instead of `assume_init_drop` because: // - drop requires exclusive access (&mut) to the contents // - mutex guard drop first unlocks the mutex, then returns. In between those, there's a brief // moment where the mutex is unlocked but a `&mut` to the contents exists. // - During this moment, another thread can go and use GLOBAL_GUARD, causing `&mut` aliasing. #[allow(let_underscore_lock)] let _ = GLOBAL_GUARD.assume_init_read(); // Note: it is fine to clear this flag *after* releasing the mutex because it's thread local. // No other thread can see its value, there's no potential for races. // This way, we hold the mutex for slightly less time. IS_LOCKED.with(|l| l.set(false)); } } } #[cfg(test)] mod tests { use std::thread; use crate as critical_section; #[cfg(feature = "std")] #[test] #[should_panic(expected = "Not a PoisonError!")] fn reusable_after_panic() { let _ = thread::spawn(|| { critical_section::with(|_| { panic!("Boom!"); }) }) .join(); critical_section::with(|_| { panic!("Not a PoisonError!"); }) } }