diff options
45 files changed, 1954 insertions, 0 deletions
diff --git a/cortex-m-semihosting/.github/CODEOWNERS b/cortex-m-semihosting/.github/CODEOWNERS new file mode 100644 index 0000000..d810925 --- /dev/null +++ b/cortex-m-semihosting/.github/CODEOWNERS @@ -0,0 +1 @@ +* @rust-embedded/cortex-m
\ No newline at end of file diff --git a/cortex-m-semihosting/.github/bors.toml b/cortex-m-semihosting/.github/bors.toml new file mode 100644 index 0000000..ca42be0 --- /dev/null +++ b/cortex-m-semihosting/.github/bors.toml @@ -0,0 +1,4 @@ +block_labels = ["needs-decision"] +delete_merged_branches = true +required_approvals = 1 +status = ["continuous-integration/travis-ci/push"] diff --git a/cortex-m-semihosting/.gitignore b/cortex-m-semihosting/.gitignore new file mode 100644 index 0000000..c857ba8 --- /dev/null +++ b/cortex-m-semihosting/.gitignore @@ -0,0 +1,6 @@ +.#* +Cargo.lock +bin/*.after +bin/*.before +bin/*.o +target diff --git a/cortex-m-semihosting/.travis.yml b/cortex-m-semihosting/.travis.yml new file mode 100644 index 0000000..4ca6a3a --- /dev/null +++ b/cortex-m-semihosting/.travis.yml @@ -0,0 +1,107 @@ +language: rust + +env: + global: + - RUSTFLAGS="-D warnings" + +matrix: + include: + - env: TARGET=x86_64-unknown-linux-gnu + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv6m-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv8m.main-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=x86_64-unknown-linux-gnu + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv6m-none-eabi + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv8m.main-none-eabi + rust: nightly + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + # MSRV + - env: TARGET=x86_64-unknown-linux-gnu + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv6m-none-eabi + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv8m.main-none-eabi + rust: 1.33.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + +before_install: set -e + +install: + - bash ci/install.sh + - export PATH="$PATH:$PWD/gcc/bin" + +script: + - bash ci/script.sh + +after_script: set +e + +cache: cargo +before_cache: + # Travis can't cache files that are not readable by "others" + - chmod -R a+r $HOME/.cargo + +branches: + only: + - master + - staging + - trying + +notifications: + email: + on_success: never diff --git a/cortex-m-semihosting/CHANGELOG.md b/cortex-m-semihosting/CHANGELOG.md new file mode 100644 index 0000000..f813f8b --- /dev/null +++ b/cortex-m-semihosting/CHANGELOG.md @@ -0,0 +1,123 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.3.5] - 2019-08-29 + +### Added + +- Adds a feature to work around JLink quirks +- Adds a dbg! macro using heprintln +- Added thumbv8m.main support on stable + +### Fixed + +- Now Rust 2018 edition + +## [v0.3.4] - 2019-08-13 + +### Fixed + +- Support for thumbv8 mainline hf target + +## [v0.3.3] - 2019-04-22 + +### Added + +- Adds support for thumbv8 and cortex-m v0.6.0 + +## [v0.3.2] - 2018-11-04 + +### Added + +- Added a family of `hprint` macros for printing to the host standard output / + error via globally shared `HStdout` / `HStderr` handles . + +## [v0.3.1] - 2018-08-27 + +### Changed + +- This crate no longer depends on `arm-none-eabi-gcc`. + +## [v0.3.0] - 2018-05-10 + +### Changed + +- [breaking-change] `inline-asm` is no longer a default feature (i.e. a feature that's enabled by + default). The consequence is that this crate now compiles on 1.27 (beta) by default, and opting + into `inline-asm` requires nightly. + +## [v0.2.1] - 2018-04-25 + +### Added + +- An opt-out "inline-asm" Cargo feature. When this feature is disabled semihosting is implemented + using an external assembly file instead of using the unstable inline assembly (`asm!`) feature + meaning that this crate can be compiled on stable. + +## [v0.2.0] - 2017-07-07 + +### Added + +- `exit` and `report_exception` syscalls + +- `HStdout` and `HStderr` structs that represent handles to the host stdout and + stderr stream respectively. + +### Changed + +- [breaking-change] The `io` module has been renamed to `hio` to reflect that + this is I/O *on the host*. + +### Removed + +- [breaking-change] the family of `write` functions in the `io` module. Instead + use `HStdout` / `HStderr` and its `write_all` method and `fmt::Write` + implementation. + +- [breaking-change] the `hprint!` family of macros. Instead use `HStdout` and + the standard `write!` macro. + +## [v0.1.3] - 2017-02-27 + +### Added + +- A family of `ewrite` functions and `ehprint!` macros to write to the host's + stderr. + +### Fixed + +- `write_all` logic when a single write doesn't write all the buffer bytes + +## [v0.1.2] - 2017-02-15 + +### Fixed + +- the `hprintln!` macro when called without arguments. + +## [v0.1.1] - 2017-01-22 + +### Added + +- Expose a family of `write` functions to write to the host's stdout without + going through the `hprint!` macros. + +## v0.1.0 - 2017-01-22 + +- Initial release + +[Unreleased]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.5...HEAD +[v0.3.5]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.4...v0.3.5 +[v0.3.4]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.3...v0.3.4 +[v0.3.3]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.2...v0.3.3 +[v0.3.2]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.1...v0.3.2 +[v0.3.1]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.3.0...v0.3.1 +[v0.3.0]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.2.1...v0.3.0 +[v0.2.1]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.2.0...v0.2.1 +[v0.2.0]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.1.3...v0.2.0 +[v0.1.3]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.1.2...v0.1.3 +[v0.1.2]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.1.1...v0.1.2 +[v0.1.1]: https://github.com/rust-embedded/cortex-m-semihosting/compare/v0.1.0...v0.1.1 diff --git a/cortex-m-semihosting/CODE_OF_CONDUCT.md b/cortex-m-semihosting/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3ab76c6 --- /dev/null +++ b/cortex-m-semihosting/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [Cortex-M team](https://github.com/rust-embedded/wg#the-cortex-m-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 [Cortex-M 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-cortex-m-team diff --git a/cortex-m-semihosting/Cargo.toml b/cortex-m-semihosting/Cargo.toml new file mode 100644 index 0000000..2885d3f --- /dev/null +++ b/cortex-m-semihosting/Cargo.toml @@ -0,0 +1,22 @@ +[package] +authors = [ + "The Cortex-M Team <cortex-m@teams.rust-embedded.org>", + "Jorge Aparicio <japaricious@gmail.com>", +] +description = "Semihosting for ARM Cortex-M processors" +documentation = "https://docs.rs/cortex-m-semihosting" +keywords = ["semihosting", "arm", "cortex-m"] +license = "MIT OR Apache-2.0" +name = "cortex-m-semihosting" +readme = "README.md" +repository = "https://github.com/rust-embedded/cortex-m-semihosting" +version = "0.3.5" +edition = "2018" + +[features] +inline-asm = [] +jlink-quirks = [] +no-semihosting = [] + +[dependencies] +cortex-m = ">= 0.5.8, < 0.7" diff --git a/cortex-m-semihosting/LICENSE-APACHE b/cortex-m-semihosting/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/cortex-m-semihosting/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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. diff --git a/cortex-m-semihosting/LICENSE-MIT b/cortex-m-semihosting/LICENSE-MIT new file mode 100644 index 0000000..52cb453 --- /dev/null +++ b/cortex-m-semihosting/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017-2018 Jorge Aparicio + +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. diff --git a/cortex-m-semihosting/README.md b/cortex-m-semihosting/README.md new file mode 100644 index 0000000..e5f35b0 --- /dev/null +++ b/cortex-m-semihosting/README.md @@ -0,0 +1,40 @@ +[](https://crates.io/crates/cortex-m-semihosting) +[](https://crates.io/crates/cortex-m-semihosting) + +# `cortex-m-semihosting` + +> Semihosting for ARM Cortex-M processors + +This project is developed and maintained by the [Cortex-M team][team]. + +## [Documentation](https://docs.rs/cortex-m-semihosting) + +# Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on stable Rust 1.33.0 and up. It *might* +compile with older versions but that may change in any new patch release. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +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 [Cortex-M team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-cortex-m-team diff --git a/cortex-m-semihosting/asm.s b/cortex-m-semihosting/asm.s new file mode 100644 index 0000000..26a13fc --- /dev/null +++ b/cortex-m-semihosting/asm.s @@ -0,0 +1,6 @@ + .section .text.__syscall + .global __syscall + .thumb_func +__syscall: + bkpt 0xAB + bx lr diff --git a/cortex-m-semihosting/assemble.sh b/cortex-m-semihosting/assemble.sh new file mode 100755 index 0000000..f77acf6 --- /dev/null +++ b/cortex-m-semihosting/assemble.sh @@ -0,0 +1,29 @@ +#!/bin/bash + +set -euxo pipefail + +# cflags taken from cc 1.0.22 + +crate=cortex-m-semihosting + +# remove existing blobs because otherwise this will append object files to the old blobs +rm -f bin/*.a + +arm-none-eabi-as -march=armv6s-m asm.s -o bin/$crate.o +ar crs bin/thumbv6m-none-eabi.a bin/$crate.o + +arm-none-eabi-as -march=armv7-m asm.s -o bin/$crate.o +ar crs bin/thumbv7m-none-eabi.a bin/$crate.o + +arm-none-eabi-as -march=armv7e-m asm.s -o bin/$crate.o +ar crs bin/thumbv7em-none-eabi.a bin/$crate.o +ar crs bin/thumbv7em-none-eabihf.a bin/$crate.o + +arm-none-eabi-as -march=armv8-m.base asm.s -o bin/$crate.o +ar crs bin/thumbv8m.base-none-eabi.a bin/$crate.o + +arm-none-eabi-as -march=armv8-m.main asm.s -o bin/$crate.o +ar crs bin/thumbv8m.main-none-eabi.a bin/$crate.o +ar crs bin/thumbv8m.main-none-eabihf.a bin/$crate.o + +rm bin/$crate.o diff --git a/cortex-m-semihosting/bin/thumbv6m-none-eabi.a b/cortex-m-semihosting/bin/thumbv6m-none-eabi.a Binary files differnew file mode 100644 index 0000000..d01b38c --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv6m-none-eabi.a diff --git a/cortex-m-semihosting/bin/thumbv7em-none-eabi.a b/cortex-m-semihosting/bin/thumbv7em-none-eabi.a Binary files differnew file mode 100644 index 0000000..254b42f --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv7em-none-eabi.a diff --git a/cortex-m-semihosting/bin/thumbv7em-none-eabihf.a b/cortex-m-semihosting/bin/thumbv7em-none-eabihf.a Binary files differnew file mode 100644 index 0000000..254b42f --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv7em-none-eabihf.a diff --git a/cortex-m-semihosting/bin/thumbv7m-none-eabi.a b/cortex-m-semihosting/bin/thumbv7m-none-eabi.a Binary files differnew file mode 100644 index 0000000..5b7f5cc --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv7m-none-eabi.a diff --git a/cortex-m-semihosting/bin/thumbv8m.base-none-eabi.a b/cortex-m-semihosting/bin/thumbv8m.base-none-eabi.a Binary files differnew file mode 100644 index 0000000..496a9c8 --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv8m.base-none-eabi.a diff --git a/cortex-m-semihosting/bin/thumbv8m.main-none-eabi.a b/cortex-m-semihosting/bin/thumbv8m.main-none-eabi.a Binary files differnew file mode 100644 index 0000000..1d2a03a --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv8m.main-none-eabi.a diff --git a/cortex-m-semihosting/bin/thumbv8m.main-none-eabihf.a b/cortex-m-semihosting/bin/thumbv8m.main-none-eabihf.a Binary files differnew file mode 100644 index 0000000..1d2a03a --- /dev/null +++ b/cortex-m-semihosting/bin/thumbv8m.main-none-eabihf.a diff --git a/cortex-m-semihosting/build.rs b/cortex-m-semihosting/build.rs new file mode 100644 index 0000000..4f4a6d6 --- /dev/null +++ b/cortex-m-semihosting/build.rs @@ -0,0 +1,22 @@ +use std::path::PathBuf; +use std::{env, fs}; + +fn main() { + let target = env::var("TARGET").unwrap(); + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + let name = env::var("CARGO_PKG_NAME").unwrap(); + + if target.starts_with("thumbv") { + if env::var_os("CARGO_FEATURE_INLINE_ASM").is_none() { + fs::copy( + format!("bin/{}.a", target), + out_dir.join(format!("lib{}.a", name)), + ).unwrap(); + + println!("cargo:rustc-link-lib=static={}", name); + println!("cargo:rustc-link-search={}", out_dir.display()); + } + + println!("cargo:rustc-cfg=thumb"); + } +} diff --git a/cortex-m-semihosting/check-blobs.sh b/cortex-m-semihosting/check-blobs.sh new file mode 100755 index 0000000..94fde42 --- /dev/null +++ b/cortex-m-semihosting/check-blobs.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# Checks that the blobs are up to date with the committed assembly files + +set -euxo pipefail + +for lib in $(ls bin/*.a); do + filename=$(basename $lib) + arm-none-eabi-objdump -Cd $lib > bin/${filename%.a}.before +done + +./assemble.sh + +for lib in $(ls bin/*.a); do + filename=$(basename $lib) + arm-none-eabi-objdump -Cd $lib > bin/${filename%.a}.after +done + +for cksum in $(ls bin/*.after); do + diff -u $cksum ${cksum%.after}.before +done diff --git a/cortex-m-semihosting/ci/install.sh b/cortex-m-semihosting/ci/install.sh new file mode 100644 index 0000000..e63e805 --- /dev/null +++ b/cortex-m-semihosting/ci/install.sh @@ -0,0 +1,13 @@ +set -euxo pipefail + +main() { + if [ $TARGET != x86_64-unknown-linux-gnu ]; then + rustup target add $TARGET + fi + + mkdir gcc + + curl -L https://developer.arm.com/-/media/Files/downloads/gnu-rm/7-2018q2/gcc-arm-none-eabi-7-2018-q2-update-linux.tar.bz2?revision=bc2c96c0-14b5-4bb4-9f18-bceb4050fee7?product=GNU%20Arm%20Embedded%20Toolchain,64-bit,,Linux,7-2018-q2-update | tar --strip-components=1 -C gcc -xj +} + +main diff --git a/cortex-m-semihosting/ci/script.sh b/cortex-m-semihosting/ci/script.sh new file mode 100644 index 0000000..dc0be46 --- /dev/null +++ b/cortex-m-semihosting/ci/script.sh @@ -0,0 +1,15 @@ +set -euxo pipefail + +main() { + cargo check --target $TARGET + + if [ $TRAVIS_RUST_VERSION = nightly ]; then + cargo check --target $TARGET --features inline-asm + fi + + if [ $TARGET = x86_64-unknown-linux-gnu ]; then + ./check-blobs.sh + fi +} + +main diff --git a/cortex-m-semihosting/src/debug.rs b/cortex-m-semihosting/src/debug.rs new file mode 100644 index 0000000..a4fa6d8 --- /dev/null +++ b/cortex-m-semihosting/src/debug.rs @@ -0,0 +1,96 @@ +//! Interacting with debugging agent +//! +//! # Example +//! +//! This example will show how to terminate the QEMU session. The program +//! should be running under QEMU with semihosting enabled +//! (use `-semihosting` flag). +//! +//! Target program: +//! +//! ```no_run +//! use cortex_m_semihosting::debug::{self, EXIT_SUCCESS, EXIT_FAILURE}; +//! +//! fn main() { +//! if 2 == 2 { +//! // report success +//! debug::exit(EXIT_SUCCESS); +//! } else { +//! // report failure +//! debug::exit(EXIT_FAILURE); +//! } +//! } +//! + +/// This values are taken from section 5.5.2 of +/// ADS Debug Target Guide (DUI0058). +// TODO document +#[allow(missing_docs)] +pub enum Exception { + // Hardware reason codes + BranchThroughZero = 0x20000, + UndefinedInstr = 0x20001, + SoftwareInterrupt = 0x20002, + PrefetchAbort = 0x20003, + DataAbort = 0x20004, + AddressException = 0x20005, + IRQ = 0x20006, + FIQ = 0x20007, + // Software reason codes + BreakPoint = 0x20020, + WatchPoint = 0x20021, + StepComplete = 0x20022, + RunTimeErrorUnknown = 0x20023, + InternalError = 0x20024, + UserInterruption = 0x20025, + ApplicationExit = 0x20026, + StackOverflow = 0x20027, + DivisionByZero = 0x20028, + OSSpecific = 0x20029, +} + +/// Status enum for `exit` syscall. +pub type ExitStatus = Result<(), ()>; + +/// Successful execution of a program. +pub const EXIT_SUCCESS: ExitStatus = Ok(()); + +/// Unsuccessful execution of a program. +pub const EXIT_FAILURE: ExitStatus = Err(()); + +/// Reports to the debugger that the execution has completed. +/// +/// This call can be used to terminate QEMU session and report back success +/// or failure. If you need to pass more than one type of error, consider +/// using `report_exception` syscall instead. +/// +/// This call should not return. However, it is possible for the debugger +/// to request that the application continue. In that case this call +/// returns normally. +/// +pub fn exit(status: ExitStatus) { + match status { + EXIT_SUCCESS => report_exception(Exception::ApplicationExit), + EXIT_FAILURE => report_exception(Exception::RunTimeErrorUnknown), + } +} + +/// Report an exception to the debugger directly. +/// +/// Exception handlers can use this SWI at the end of handler chains +/// as the default action, to indicate that the exception has not been handled. +/// +/// This call should not return. However, it is possible for the debugger +/// to request that the application continue. In that case this call +/// returns normally. +/// +/// # Arguments +/// +/// * `reason` - A reason code reported back to the debugger. +/// +pub fn report_exception(reason: Exception) { + let code = reason as usize; + unsafe { + syscall1!(REPORT_EXCEPTION, code); + } +} diff --git a/cortex-m-semihosting/src/export.rs b/cortex-m-semihosting/src/export.rs new file mode 100644 index 0000000..c188ab0 --- /dev/null +++ b/cortex-m-semihosting/src/export.rs @@ -0,0 +1,51 @@ +//! IMPLEMENTATION DETAILS USED BY MACROS + +use core::fmt::{self, Write}; + +use cortex_m::interrupt; + +use crate::hio::{self, HStderr, HStdout}; + +static mut HSTDOUT: Option<HStdout> = None; + +pub fn hstdout_str(s: &str) { + let _result = interrupt::free(|_| unsafe { + if HSTDOUT.is_none() { + HSTDOUT = Some(hio::hstdout()?); + } + + HSTDOUT.as_mut().unwrap().write_str(s).map_err(drop) + }); +} + +pub fn hstdout_fmt(args: fmt::Arguments) { + let _result = interrupt::free(|_| unsafe { + if HSTDOUT.is_none() { + HSTDOUT = Some(hio::hstdout()?); + } + + HSTDOUT.as_mut().unwrap().write_fmt(args).map_err(drop) + }); +} + +static mut HSTDERR: Option<HStderr> = None; + +pub fn hstderr_str(s: &str) { + let _result = interrupt::free(|_| unsafe { + if HSTDERR.is_none() { + HSTDERR = Some(hio::hstderr()?); + } + + HSTDERR.as_mut().unwrap().write_str(s).map_err(drop) + }); +} + +pub fn hstderr_fmt(args: fmt::Arguments) { + let _result = interrupt::free(|_| unsafe { + if HSTDERR.is_none() { + HSTDERR = Some(hio::hstderr()?); + } + + HSTDERR.as_mut().unwrap().write_fmt(args).map_err(drop) + }); +} diff --git a/cortex-m-semihosting/src/hio.rs b/cortex-m-semihosting/src/hio.rs new file mode 100644 index 0000000..61ac749 --- /dev/null +++ b/cortex-m-semihosting/src/hio.rs @@ -0,0 +1,88 @@ +//! Host I/O + +use core::{fmt, slice}; +use crate::nr; + +/// Host's standard error +#[derive(Clone, Copy)] +pub struct HStderr { + fd: usize, +} + +impl HStderr { + /// Attempts to write an entire `buffer` into this sink + pub fn write_all(&mut self, buffer: &[u8]) -> Result<(), ()> { + write_all(self.fd, buffer) + } +} + +impl fmt::Write for HStderr { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.write_all(s.as_bytes()).map_err(|_| fmt::Error) + } +} + +/// Host's standard output +#[derive(Clone, Copy)] +pub struct HStdout { + fd: usize, +} + +impl HStdout { + /// Attempts to write an entire `buffer` into this sink + pub fn write_all(&mut self, buffer: &[u8]) -> Result<(), ()> { + write_all(self.fd, buffer) + } +} + +impl fmt::Write for HStdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.write_all(s.as_bytes()).map_err(|_| fmt::Error) + } +} + +/// Construct a new handle to the host's standard error. +pub fn hstderr() -> Result<HStderr, ()> { + // There is actually no stderr access in ARM Semihosting documentation. Use + // convention used in libgloss. + // See: libgloss/arm/syscalls.c, line 139. + // https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=libgloss/arm/syscalls.c#l139 + open(":tt\0", nr::open::W_APPEND).map(|fd| HStderr { fd }) +} + +/// Construct a new handle to the host's standard output. +pub fn hstdout() -> Result<HStdout, ()> { + open(":tt\0", nr::open::W_TRUNC).map(|fd| HStdout { fd }) +} + +fn open(name: &str, mode: usize) -> Result<usize, ()> { + let name = name.as_bytes(); + match unsafe { syscall!(OPEN, name.as_ptr(), mode, name.len() - 1) } as + isize { + -1 => Err(()), + fd => Ok(fd as usize), + } +} + +fn write_all(fd: usize, mut buffer: &[u8]) -> Result<(), ()> { + while !buffer.is_empty() { + match unsafe { syscall!(WRITE, fd, buffer.as_ptr(), buffer.len()) } { + // Done + 0 => return Ok(()), + // `n` bytes were not written + n if n <= buffer.len() => { + let offset = (buffer.len() - n) as isize; + buffer = unsafe { + slice::from_raw_parts(buffer.as_ptr().offset(offset), n) + } + } + #[cfg(feature = "jlink-quirks")] + // Error (-1) - should be an error but JLink can return -1, -2, -3,... + // For good measure, we allow up to negative 15. + n if n > 0xfffffff0 => return Ok(()), + // Error + _ => return Err(()), + } + } + Ok(()) +} diff --git a/cortex-m-semihosting/src/lib.rs b/cortex-m-semihosting/src/lib.rs new file mode 100644 index 0000000..b70dea0 --- /dev/null +++ b/cortex-m-semihosting/src/lib.rs @@ -0,0 +1,232 @@ +//! Semihosting for ARM Cortex-M processors +//! +//! # What is semihosting? +//! +//! "Semihosting is a mechanism that enables code running on an ARM target to communicate and use +//! the Input/Output facilities on a host computer that is running a debugger." - ARM +//! +//! # Interface +//! +//! This crate provides implementations of +//! [`core::fmt::Write`](https://doc.rust-lang.org/core/fmt/trait.Write.html), so you can use it, +//! in conjunction with +//! [`core::format_args!`](https://doc.rust-lang.org/core/macro.format_args.html) or the [`write!` macro](https://doc.rust-lang.org/core/macro.write.html), for user-friendly construction and printing of formatted strings. +//! +//! Since semihosting operations are modeled as [system calls][sc], this crate exposes an untyped +//! `syscall!` interface just like the [`sc`] crate does. +//! +//! [sc]: https://en.wikipedia.org/wiki/System_call +//! [`sc`]: https://crates.io/crates/sc +//! +//! # Forewarning +//! +//! Semihosting operations are *very* slow. Like, each WRITE operation can take hundreds of +//! milliseconds. +//! +//! # Example +//! +//! ## Using `hio::HStdout` +//! +//! This example will demonstrate how to print formatted strings. +//! +//! ```no_run +//! use cortex_m_semihosting::hio; +//! use core::fmt::Write; +//! +//! // This function will be called by the application +//! fn print() -> Result<(), core::fmt::Error> { +//! let mut stdout = match hio::hstdout() { +//! Ok(fd) => fd, +//! Err(()) => return Err(core::fmt::Error), +//! }; +//! +//! let language = "Rust"; +//! let ranking = 1; +//! +//! write!(stdout, "{} on embedded is #{}!", language, ranking)?; +//! +//! Ok(()) +//! } +//! ``` +//! +//! On the host side: +//! +//! ``` text +//! $ openocd -f $INTERFACE -f $TARGET -l /tmp/openocd.log +//! Open On-Chip Debugger 0.9.0 (2016-04-27-23:18) +//! Licensed under GNU GPL v2 +//! For bug reports, read +//! http://openocd.org/doc/doxygen/bugs.html +//! # the command will block at this point +//! ``` +//! +//! The OpenOCD logs will be redirected to `/tmp/openocd.log`. You can view those logs in "real +//! time" using `tail` +//! +//! ``` text +//! $ tail -f /tmp/openocd.log +//! Info : Unable to match requested speed 1000 kHz, using 950 kHz +//! Info : Unable to match requested speed 1000 kHz, using 950 kHz +//! Info : clock speed 950 kHz +//! Info : STLINK v1 JTAG v11 API v2 SWIM v0 VID 0x0483 PID 0x3744 +//! Info : using stlink api v2 +//! Info : nrf51.cpu: hardware has 4 breakpoints, 2 watchpoints +//! ``` +//! +//! Alternatively you could omit the `-l` flag from the `openocd` call, and the `tail -f` command +//! but the OpenOCD output will have intermingled in it logs from its normal operation. +//! +//! Then, we run the program: +//! +//! ``` text +//! $ arm-none-eabi-gdb hello-world +//! (gdb) # Connect to OpenOCD +//! (gdb) target remote :3333 +//! +//! (gdb) # Enable OpenOCD's semihosting support +//! (gdb) monitor arm semihosting enable +//! +//! (gdb) # Flash the program +//! (gdb) load +//! +//! (gdb) # Run the program +//! (gdb) continue +//! ``` +//! +//! And you'll see the output under OpenOCD's terminal +//! +//! ``` text +//! # openocd -f $INTERFACE -f $TARGET -l /tmp/openocd.log +//! (..) +//! Rust on embedded is #1! +//! ``` +//! ## Using the syscall interface +//! +//! This example will show how to print "Hello, world!" on the host. +//! +//! Target program: +//! +//! ```no_run +//! use cortex_m_semihosting::syscall; +//! +//! // This function will be called by the application +//! fn print() { +//! // File descriptor (on the host) +//! const STDOUT: usize = 1; // NOTE the host stdout may not always be fd 1 +//! static MSG: &'static [u8] = b"Hello, world!\n"; +//! +//! // Signature: fn write(fd: usize, ptr: *const u8, len: usize) -> usize +//! let r = unsafe { syscall!(WRITE, STDOUT, MSG.as_ptr(), MSG.len()) }; +//! } +//! ``` +//! Output and monitoring proceed as in the above example. +//! +//! ## The `dbg!` macro +//! +//! Analogous to [`std::dbg`](https://doc.rust-lang.org/std/macro.dbg.html) the macro +//! `dbg!` returns a given expression and prints it using `heprintln!` including context +//! for quick and dirty debugging. +//! +//! Panics if `heprintln!` returns an error. +//! +//! Example: +//! +//! ```no_run +//! const UUID: *mut u32 = 0x0009_FC70 as *mut u32; +//! dbg!(UUID); +//! let mut uuid: [u32; 4] = [0; 4]; +//! for i in 0..4 { +//! dbg!(i); +//! uuid[i] = unsafe { dbg!(UUID.offset(i as isize).read_volatile()) }; +//! } +//! ``` +//! outputs +//! ```text +//! [examples/semihosting.rs:37] UUID = 0x0009fc70 +//! [examples/semihosting.rs:40] i = 0 +//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 3370045464 +//! [examples/semihosting.rs:40] i = 1 +//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 1426218275 +//! [examples/semihosting.rs:40] i = 2 +//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 2422621116 +//! [examples/semihosting.rs:40] i = 3 +//! [examples/semihosting.rs:41] UUID.offset(i as isize).read_volatile() = 1044138593 +//! ``` +//! +//! # Optional features +//! +//! ## `inline-asm` +//! +//! When this feature is enabled semihosting is implemented using inline assembly (`llvm_asm!`) and +//! compiling this crate requires nightly. +//! +//! When this feature is disabled semihosting is implemented using FFI calls into an external +//! assembly file and compiling this crate works on stable and beta. +//! +//! ## `jlink-quirks` +//! +//! When this feature is enabled, return values above `0xfffffff0` from semihosting operation +//! `SYS_WRITE` (0x05) are interpreted as if the entire buffer had been written. The current +//! latest version 6.48b of J-Link exhibits such behaviour, causing a panic if this feature +//! is not enabled. +//! +//! ## `no-semihosting` +//! +//! When this feature is enabled, the underlying system calls to `bkpt` are patched out. +//! +//! # Reference +//! +//! For documentation about the semihosting operations, check: +//! +//! 'Chapter 8 - Semihosting' of the ['ARM Compiler toolchain Version 5.0'][pdf] +//! manual. +//! +//! [pdf]: http://infocenter.arm.com/help/topic/com.arm.doc.dui0471e/DUI0471E_developing_for_arm_processors.pdf + +#![cfg_attr(feature = "inline-asm", feature(llvm_asm))] +#![deny(missing_docs)] +#![no_std] + +#[macro_use] +mod macros; + +pub mod debug; +#[doc(hidden)] +pub mod export; +pub mod hio; +pub mod nr; + +#[cfg(all(thumb, not(feature = "inline-asm")))] +extern "C" { + fn __syscall(nr: usize, arg: usize) -> usize; +} + +/// Performs a semihosting operation, takes a pointer to an argument block +#[inline(always)] +pub unsafe fn syscall<T>(nr: usize, arg: &T) -> usize { + syscall1(nr, arg as *const T as usize) +} + +/// Performs a semihosting operation, takes one integer as an argument +#[inline(always)] +pub unsafe fn syscall1(_nr: usize, _arg: usize) -> usize { + match () { + #[cfg(all(thumb, not(feature = "inline-asm"), not(feature = "no-semihosting")))] + () => __syscall(_nr, _arg), + + #[cfg(all(thumb, feature = "inline-asm", not(feature = "no-semihosting")))] + () => { + let mut nr = _nr; + llvm_asm!("bkpt 0xAB" : "+{r0}"(nr) : "{r1}"(_arg) :: "volatile"); + nr + } + + #[cfg(all(thumb, feature = "no-semihosting"))] + () => { + 0 + } + + #[cfg(not(thumb))] + () => unimplemented!(), + } +} diff --git a/cortex-m-semihosting/src/macros.rs b/cortex-m-semihosting/src/macros.rs new file mode 100644 index 0000000..d10cd3f --- /dev/null +++ b/cortex-m-semihosting/src/macros.rs @@ -0,0 +1,119 @@ +/// Variable argument version of `syscall` +#[macro_export] +macro_rules! syscall { + ($nr:ident) => { + $crate::syscall1($crate::nr::$nr, 0) + }; + ($nr:ident, $a1:expr) => { + $crate::syscall($crate::nr::$nr, &[$a1 as usize]) + }; + ($nr:ident, $a1:expr, $a2:expr) => { + $crate::syscall($crate::nr::$nr, &[$a1 as usize, $a2 as usize]) + }; + ($nr:ident, $a1:expr, $a2:expr, $a3:expr) => { + $crate::syscall($crate::nr::$nr, &[$a1 as usize, $a2 as usize, + $a3 as usize]) + }; + ($nr:ident, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => { + $crate::syscall($crate::nr::$nr, &[$a1 as usize, $a2 as usize, + $a3 as usize, $a4 as usize]) + }; +} + +/// Macro version of `syscall1`. +#[macro_export] +macro_rules! syscall1 { + ($nr:ident, $a1:expr) => { + $crate::syscall1($crate::nr::$nr, $a1 as usize) + }; +} + +/// Macro for printing to the HOST standard output. +/// +/// This is similar to the `print!` macro in the standard library. Both will panic on any failure to +/// print. +#[macro_export] +macro_rules! hprint { + ($s:expr) => { + $crate::export::hstdout_str($s) + }; + ($($tt:tt)*) => { + $crate::export::hstdout_fmt(format_args!($($tt)*)) + }; +} + +/// Macro for printing to the HOST standard output, with a newline. +/// +/// This is similar to the `println!` macro in the standard library. Both will panic on any failure to +/// print. +#[macro_export] +macro_rules! hprintln { + () => { + $crate::export::hstdout_str("\n") + }; + ($s:expr) => { + $crate::export::hstdout_str(concat!($s, "\n")) + }; + ($s:expr, $($tt:tt)*) => { + $crate::export::hstdout_fmt(format_args!(concat!($s, "\n"), $($tt)*)) + }; +} + +/// Macro for printing to the HOST standard error. +/// +/// This is similar to the `eprint!` macro in the standard library. Both will panic on any failure +/// to print. +#[macro_export] +macro_rules! heprint { + ($s:expr) => { + $crate::export::hstderr_str($s) + }; + ($($tt:tt)*) => { + $crate::export::hstderr_fmt(format_args!($($tt)*)) + }; +} + +/// Macro for printing to the HOST standard error, with a newline. +/// +/// This is similar to the `eprintln!` macro in the standard library. Both will panic on any failure +/// to print. +#[macro_export] +macro_rules! heprintln { + () => { + $crate::export::hstderr_str("\n") + }; + ($s:expr) => { + $crate::export::hstderr_str(concat!($s, "\n")) + }; + ($s:expr, $($tt:tt)*) => { + $crate::export::hstderr_fmt(format_args!(concat!($s, "\n"), $($tt)*)) + }; +} + +/// Macro that prints and returns the value of a given expression for quick and +/// dirty debugging. +/// +/// Works exactly like `dbg!` in the standard library, replacing `eprintln!` +/// with `heprintln!`. +#[macro_export] +macro_rules! dbg { + () => { + $crate::heprintln!("[{}:{}]", file!(), line!()); + }; + ($val:expr) => { + // Use of `match` here is intentional because it affects the lifetimes + // of temporaries - https://stackoverflow.com/a/48732525/1063961 + match $val { + tmp => { + $crate::heprintln!("[{}:{}] {} = {:#?}", + file!(), line!(), stringify!($val), &tmp); + tmp + } + } + }; + // Trailing comma with single argument is ignored + ($val:expr,) => { $crate::dbg!($val) }; + ($($val:expr),+ $(,)?) => { + ($($crate::dbg!($val)),+,) + }; +} diff --git a/cortex-m-semihosting/src/nr.rs b/cortex-m-semihosting/src/nr.rs new file mode 100644 index 0000000..5d206de --- /dev/null +++ b/cortex-m-semihosting/src/nr.rs @@ -0,0 +1,57 @@ +//! Semihosting operations + +// TODO document +#![allow(missing_docs)] + +pub const CLOCK: usize = 0x10; +pub const CLOSE: usize = 0x02; +pub const ELAPSED: usize = 0x30; +pub const ERRNO: usize = 0x13; +pub const FLEN: usize = 0x0c; +pub const GET_CMDLINE: usize = 0x15; +pub const HEAPINFO: usize = 0x16; +pub const ISERROR: usize = 0x08; +pub const ISTTY: usize = 0x09; +pub const OPEN: usize = 0x01; +pub const READ: usize = 0x06; +pub const READC: usize = 0x07; +pub const REMOVE: usize = 0x0e; +pub const RENAME: usize = 0x0f; +pub const SEEK: usize = 0x0a; +pub const SYSTEM: usize = 0x12; +pub const TICKFREQ: usize = 0x31; +pub const TIME: usize = 0x11; +pub const TMPNAM: usize = 0x0d; +pub const WRITE0: usize = 0x04; +pub const WRITE: usize = 0x05; +pub const WRITEC: usize = 0x03; +pub const ENTER_SVC: usize = 0x17; +pub const REPORT_EXCEPTION: usize = 0x18; + +/// Values for the mode parameter of the OPEN syscall. +pub mod open { + /// Mode corresponding to fopen "r" mode. + pub const R: usize = 0; + /// Mode corresponding to fopen "rb" mode. + pub const R_BINARY: usize = 1; + /// Mode corresponding to fopen "r+" mode. + pub const RW: usize = 2; + /// Mode corresponding to fopen "r+b" mode. + pub const RW_BINARY: usize = 3; + /// Mode corresponding to fopen "w" mode. + pub const W_TRUNC: usize = 4; + /// Mode corresponding to fopen "wb" mode. + pub const W_TRUNC_BINARY: usize = 5; + /// Mode corresponding to fopen "w+" mode. + pub const RW_TRUNC: usize = 6; + /// Mode corresponding to fopen "w+b" mode. + pub const RW_TRUNC_BINARY: usize = 7; + /// Mode corresponding to fopen "a" mode. + pub const W_APPEND: usize = 8; + /// Mode corresponding to fopen "ab" mode. + pub const W_APPEND_BINARY: usize = 9; + /// Mode corresponding to fopen "a+" mode. + pub const RW_APPEND: usize = 10; + /// Mode corresponding to fopen "a+b" mode. + pub const RW_APPEND_BINARY: usize = 11; +} diff --git a/cortex-m-semihosting/triagebot.toml b/cortex-m-semihosting/triagebot.toml new file mode 100644 index 0000000..fa0824a --- /dev/null +++ b/cortex-m-semihosting/triagebot.toml @@ -0,0 +1 @@ +[assign] diff --git a/panic-semihosting/.github/CODEOWNERS b/panic-semihosting/.github/CODEOWNERS new file mode 100644 index 0000000..d810925 --- /dev/null +++ b/panic-semihosting/.github/CODEOWNERS @@ -0,0 +1 @@ +* @rust-embedded/cortex-m
\ No newline at end of file diff --git a/panic-semihosting/.github/bors.toml b/panic-semihosting/.github/bors.toml new file mode 100644 index 0000000..ca42be0 --- /dev/null +++ b/panic-semihosting/.github/bors.toml @@ -0,0 +1,4 @@ +block_labels = ["needs-decision"] +delete_merged_branches = true +required_approvals = 1 +status = ["continuous-integration/travis-ci/push"] diff --git a/panic-semihosting/.gitignore b/panic-semihosting/.gitignore new file mode 100644 index 0000000..2691a8f --- /dev/null +++ b/panic-semihosting/.gitignore @@ -0,0 +1,4 @@ +**/*.rs.bk +.#* +/target +Cargo.lock diff --git a/panic-semihosting/.travis.yml b/panic-semihosting/.travis.yml new file mode 100644 index 0000000..9121565 --- /dev/null +++ b/panic-semihosting/.travis.yml @@ -0,0 +1,105 @@ +language: rust + +matrix: + include: + - env: TARGET=x86_64-unknown-linux-gnu + rust: stable + + - env: TARGET=thumbv6m-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: stable + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=x86_64-unknown-linux-gnu + rust: nightly + + - env: TARGET=thumbv6m-none-eabi + rust: nightly + addons: + apt: + packages: + - gcc-arm-none-eabi + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: nightly + addons: + apt: + packages: + - gcc-arm-none-eabi + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: nightly + addons: + apt: + packages: + - gcc-arm-none-eabi + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: nightly + addons: + apt: + packages: + - gcc-arm-none-eabi + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + # MSRV + - env: TARGET=x86_64-unknown-linux-gnu + rust: 1.32.0 + + - env: TARGET=thumbv6m-none-eabi + rust: 1.32.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7m-none-eabi + rust: 1.32.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabi + rust: 1.32.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + + - env: TARGET=thumbv7em-none-eabihf + rust: 1.32.0 + if: (branch = staging OR branch = trying) OR (type = pull_request AND branch = master) + +before_install: set -e + +install: + - bash ci/install.sh + +script: + - bash ci/script.sh + +after_success: + - bash ci/after-success.sh + +after_script: set +e + +cache: cargo + +before_cache: + - chmod -R a+r $HOME/.cargo; + +branches: + only: + - master + - staging + - trying + +notifications: + email: + on_success: never diff --git a/panic-semihosting/CHANGELOG.md b/panic-semihosting/CHANGELOG.md new file mode 100644 index 0000000..0036754 --- /dev/null +++ b/panic-semihosting/CHANGELOG.md @@ -0,0 +1,66 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## [v0.5.3] - 2019-09-01 + +- Added feature `jlink-quirks` to work with JLink + +## [v0.5.2] - 2019-04-28 + +- Updated `cortex-m` version to not have the issue when linking multiple + versions of it. + +## [v0.5.1] - 2018-10-27 + +### Added + +- An opt-in "exit" Cargo feature to have the panic handler perform an exit + semihosting call after logging the panic message. + +## [v0.5.0] - 2018-09-10 + +- [breaking-change] The `panic_handler` feature gate has been removed. This + crate will compile on 1.30-beta and on stable 1.30 when they are released. + +## [v0.4.0] - 2018-09-03 + +### Changed + +- This crate no longer depends on `arm-none-eabi-gcc`. + +- [breaking-change] Move from the `panic_implementation` attribute to the + `panic_handler` attribute, which will be stabilized. + +## [v0.3.0] - 2018-06-04 + +### Changed + +- [breaking-change] moved from the, now removed, `panic_fmt` lang item to the + `#[panic_implementation]` attribute. + +## [v0.2.0] - 2018-05-11 + +### Changed + +- [breaking-change] made inline assembly (`asm!`) opt-in via the `"inline-asm"` feature. This is a + breaking change because this crate now requires `arm-none-eabi-gcc` to be installed to build + without the `"inline-asm"` feature, which is the default. + +## v0.1.0 - 2018-04-09 + +Initial release + +[Unreleased]: https://github.com/rust-embedded/panic-semihosting/compare/v0.5.3...HEAD +[v0.5.3]: https://github.com/rust-embedded/panic-semihosting/compare/v0.5.2...v0.5.3 +[v0.5.2]: https://github.com/rust-embedded/panic-semihosting/compare/v0.5.1...v0.5.2 +[v0.5.1]: https://github.com/rust-embedded/panic-semihosting/compare/v0.5.0...v0.5.1 +[v0.5.0]: https://github.com/rust-embedded/panic-semihosting/compare/v0.4.0...v0.5.0 +[v0.4.0]: https://github.com/rust-embedded/panic-semihosting/compare/v0.3.0...v0.4.0 +[v0.3.0]: https://github.com/rust-embedded/panic-semihosting/compare/v0.2.0...v0.3.0 +[v0.2.0]: https://github.com/rust-embedded/panic-semihosting/compare/v0.1.0...v0.2.0 diff --git a/panic-semihosting/CODE_OF_CONDUCT.md b/panic-semihosting/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..9bd9aab --- /dev/null +++ b/panic-semihosting/CODE_OF_CONDUCT.md @@ -0,0 +1,37 @@ +# The Rust Code of Conduct + +## Conduct + +**Contact**: [Cortex-M team](https://github.com/rust-embedded/wg#the-cortex-m-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 Matrix and 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 [Cortex-M 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 the official Matrix room (#rust-embedded:matrix.org) and linked IRC channels (#rust-embedded on Freenode); 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-cortex-m-team diff --git a/panic-semihosting/Cargo.toml b/panic-semihosting/Cargo.toml new file mode 100644 index 0000000..708c029 --- /dev/null +++ b/panic-semihosting/Cargo.toml @@ -0,0 +1,22 @@ +[package] +authors = [ + "The Cortex-M Team <cortex-m@teams.rust-embedded.org>", + "Jorge Aparicio <jorge@japaric.io>", +] +categories = ["no-std"] +description = "Report panic messages to the host stderr using semihosting" +documentation = "https://docs.rs/panic-semihosting" +keywords = ["panic-handler", "panic-impl", "panic", "semihosting"] +license = "MIT OR Apache-2.0" +name = "panic-semihosting" +repository = "https://github.com/rust-embedded/panic-semihosting" +version = "0.5.3" + +[dependencies] +cortex-m = ">= 0.5.6, < 0.7" +cortex-m-semihosting = "0.3" + +[features] +exit = [] +inline-asm = ["cortex-m-semihosting/inline-asm", "cortex-m/inline-asm"] +jlink-quirks = ["cortex-m-semihosting/jlink-quirks"] diff --git a/panic-semihosting/LICENSE-APACHE b/panic-semihosting/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/panic-semihosting/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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. diff --git a/panic-semihosting/LICENSE-MIT b/panic-semihosting/LICENSE-MIT new file mode 100644 index 0000000..432fbea --- /dev/null +++ b/panic-semihosting/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Jorge Aparicio + +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. diff --git a/panic-semihosting/README.md b/panic-semihosting/README.md new file mode 100644 index 0000000..c6865ef --- /dev/null +++ b/panic-semihosting/README.md @@ -0,0 +1,37 @@ +# `panic-semihosting` + +> Report panic messages to the host stderr using semihosting + +This project is developed and maintained by the [Cortex-M team][team]. + +## [Documentation](https://docs.rs/panic-semihosting) + +## Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on stable Rust 1.32.0 and up. It *might* +compile with older versions but that may change in any new patch release. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +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 [Cortex-M team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-cortex-m-team diff --git a/panic-semihosting/ci/after-success.sh b/panic-semihosting/ci/after-success.sh new file mode 100644 index 0000000..4377267 --- /dev/null +++ b/panic-semihosting/ci/after-success.sh @@ -0,0 +1,20 @@ +set -euxo pipefail + +main() { + cargo doc + + mkdir ghp-import + + curl -Ls https://github.com/davisp/ghp-import/archive/master.tar.gz | + tar --strip-components 1 -C ghp-import -xz + + ./ghp-import/ghp_import.py target/doc + + set +x + git push -fq https://$GH_TOKEN@github.com/$TRAVIS_REPO_SLUG.git gh-pages && echo OK +} + +# only publish on successful merges to master +if [ $TRAVIS_BRANCH = master ] && [ $TRAVIS_PULL_REQUEST = false ] && [ $TARGET = x86_64-unknown-linux-gnu ]; then + main +fi diff --git a/panic-semihosting/ci/install.sh b/panic-semihosting/ci/install.sh new file mode 100644 index 0000000..3c41921 --- /dev/null +++ b/panic-semihosting/ci/install.sh @@ -0,0 +1,9 @@ +set -euxo pipefail + +main() { + if [ $TARGET != x86_64-unknown-linux-gnu ]; then + rustup target add $TARGET + fi +} + +main diff --git a/panic-semihosting/ci/script.sh b/panic-semihosting/ci/script.sh new file mode 100644 index 0000000..eb1a313 --- /dev/null +++ b/panic-semihosting/ci/script.sh @@ -0,0 +1,11 @@ +set -euxo pipefail + +main() { + cargo check --target $TARGET + + if [ $TRAVIS_RUST_VERSION = nightly ]; then + cargo check --target $TARGET --features inline-asm + fi +} + +main diff --git a/panic-semihosting/src/lib.rs b/panic-semihosting/src/lib.rs new file mode 100644 index 0000000..71d2774 --- /dev/null +++ b/panic-semihosting/src/lib.rs @@ -0,0 +1,95 @@ +//! Report panic messages to the host stderr using semihosting +//! +//! This crate contains an implementation of `panic_fmt` that logs panic messages to the host stderr +//! using [`cortex-m-semihosting`]. Before logging the message the panic handler disables (masks) +//! the device specific interrupts. After logging the message the panic handler trigger a breakpoint +//! and then goes into an infinite loop. +//! +//! Currently, this crate only supports the ARM Cortex-M architecture. +//! +//! [`cortex-m-semihosting`]: https://crates.io/crates/cortex-m-semihosting +//! +//! # Usage +//! +//! ``` ignore +//! #![no_std] +//! +//! extern crate panic_semihosting; +//! +//! fn main() { +//! panic!("FOO") +//! } +//! ``` +//! +//! ``` text +//! (gdb) monitor arm semihosting enable +//! (gdb) continue +//! Program received signal SIGTRAP, Trace/breakpoint trap. +//! rust_begin_unwind (args=..., file=..., line=8, col=5) +//! at $CRATE/src/lib.rs:69 +//! 69 asm::bkpt(); +//! ``` +//! +//! ``` text +//! $ openocd -f (..) +//! (..) +//! panicked at 'FOO', src/main.rs:6:5 +//! ``` +//! +//! # Optional features +//! +//! ## `exit` +//! +//! When this feature is enabled the panic handler performs an exit semihosting call after logging +//! the panic message. This is useful when emulating the program on QEMU as it causes the QEMU +//! process to exit with a non-zero exit code; thus it can be used to implement Cortex-M tests that +//! run on the host. +//! +//! We discourage using this feature when the program will run on hardware as the exit call can +//! leave the hardware debugger in an inconsistent state. +//! +//! ## `inline-asm` +//! +//! When this feature is enabled semihosting is implemented using inline assembly (`asm!`) and +//! compiling this crate requires nightly. +//! +//! When this feature is disabled semihosting is implemented using FFI calls into an external +//! assembly file and compiling this crate works on stable and beta. + +#![deny(missing_docs)] +#![deny(warnings)] +#![no_std] + +extern crate cortex_m; +extern crate cortex_m_semihosting as sh; + +use core::fmt::Write; +use core::panic::PanicInfo; + +#[cfg(not(feature = "exit"))] +use cortex_m::asm; +use cortex_m::interrupt; +#[cfg(feature = "exit")] +use sh::debug::{self, EXIT_FAILURE}; +use sh::hio; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + interrupt::disable(); + + if let Ok(mut hstdout) = hio::hstdout() { + writeln!(hstdout, "{}", info).ok(); + } + + match () { + // Exit the QEMU process + #[cfg(feature = "exit")] + () => debug::exit(EXIT_FAILURE), + // OK to fire a breakpoint here because we know the microcontroller is connected to a + // debugger + #[cfg(not(feature = "exit"))] + () => asm::bkpt(), + } + + loop {} +} diff --git a/panic-semihosting/triagebot.toml b/panic-semihosting/triagebot.toml new file mode 100644 index 0000000..fa0824a --- /dev/null +++ b/panic-semihosting/triagebot.toml @@ -0,0 +1 @@ +[assign] |