├── .github └── workflows │ ├── ci.yml │ └── issue_handler.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs └── src ├── lib.rs ├── riscv.rs └── xtensa.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | branches: 4 | - main 5 | push: 6 | workflow_dispatch: 7 | 8 | name: CI 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 13 | 14 | jobs: 15 | check-riscv: 16 | name: Check RISC-V 17 | runs-on: ubuntu-latest 18 | env: 19 | RUSTFLAGS: -Dwarnings 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | chip: [esp32c2, esp32c3, esp32c6, esp32h2, esp32p4] 24 | colors: ["colors"] 25 | method: ["println"] 26 | steps: 27 | - uses: actions/checkout@v3 28 | - uses: dtolnay/rust-toolchain@v1 29 | with: 30 | target: riscv32imc-unknown-none-elf 31 | toolchain: nightly 32 | components: rust-src 33 | - uses: Swatinem/rust-cache@v2 34 | - run: cargo check -Zbuild-std=core --target=riscv32imc-unknown-none-elf --no-default-features --features=esp-println/uart,${{ matrix.chip }},panic-handler,exception-handler,${{ matrix.method }},${{ matrix.colors }} 35 | 36 | check-xtensa: 37 | name: Check Xtensa 38 | runs-on: ubuntu-latest 39 | env: 40 | RUSTFLAGS: -Dwarnings 41 | strategy: 42 | fail-fast: false 43 | matrix: 44 | chip: [esp32, esp32s2, esp32s3] 45 | colors: ["colors"] 46 | method: ["println"] 47 | steps: 48 | - uses: actions/checkout@v3 49 | - uses: esp-rs/xtensa-toolchain@v1.5 50 | with: 51 | default: true 52 | ldproxy: false 53 | - uses: Swatinem/rust-cache@v2 54 | - run: cargo check -Zbuild-std=core --target=xtensa-${{ matrix.chip }}-none-elf --no-default-features --features=esp-println/uart,${{ matrix.chip }},panic-handler,exception-handler,${{ matrix.method }},${{ matrix.colors }} 55 | 56 | check-features: 57 | name: Check unusual feature combinations 58 | runs-on: ubuntu-latest 59 | env: 60 | RUSTFLAGS: -Dwarnings 61 | strategy: 62 | fail-fast: false 63 | matrix: 64 | chip: [esp32c3] 65 | colors: ["colors", ""] 66 | method: ["println","defmt"] 67 | steps: 68 | - uses: actions/checkout@v3 69 | - uses: dtolnay/rust-toolchain@v1 70 | with: 71 | target: riscv32imc-unknown-none-elf 72 | toolchain: nightly 73 | components: rust-src 74 | - uses: Swatinem/rust-cache@v2 75 | - run: cargo check -Zbuild-std=core --target=riscv32imc-unknown-none-elf --no-default-features --features=esp-println/uart,${{ matrix.chip }},panic-handler,exception-handler,${{ matrix.method }},${{ matrix.colors }} 76 | -------------------------------------------------------------------------------- /.github/workflows/issue_handler.yml: -------------------------------------------------------------------------------- 1 | name: Add new issues to project 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | add-to-project: 10 | name: Add issue to project 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/add-to-project@v0.5.0 14 | with: 15 | project-url: https://github.com/orgs/esp-rs/projects/2 16 | github-token: ${{ secrets.PAT }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "esp-backtrace" 3 | version = "0.11.1" 4 | edition = "2021" 5 | description = "Bare-metal backtrace support for ESP32" 6 | repository = "https://github.com/esp-rs/esp-backtrace" 7 | license = "MIT OR Apache-2.0" 8 | 9 | [package.metadata.docs.rs] 10 | default-target = "riscv32imc-unknown-none-elf" 11 | features = ["esp32c3", "panic-handler", "exception-handler", "println", "esp-println/uart"] 12 | 13 | [dependencies] 14 | esp-println = { version = "0.9.1", optional = true, default-features = false } 15 | defmt = { version = "0.3.6", optional = true } 16 | semihosting = { version = "0.1.7", optional = true } 17 | 18 | [features] 19 | default = [ "colors" ] 20 | 21 | # You must enable exactly one of the below features to support the correct chip: 22 | esp32 = ["esp-println?/esp32", "semihosting?/openocd-semihosting"] 23 | esp32c2 = ["esp-println?/esp32c2"] 24 | esp32c3 = ["esp-println?/esp32c3"] 25 | esp32c6 = ["esp-println?/esp32c6"] 26 | esp32h2 = ["esp-println?/esp32h2"] 27 | esp32p4 = ["esp-println?/esp32p4"] 28 | esp32s2 = ["esp-println?/esp32s2", "semihosting?/openocd-semihosting"] 29 | esp32s3 = ["esp-println?/esp32s3", "semihosting?/openocd-semihosting"] 30 | 31 | # Use esp-println 32 | println = [ "dep:esp-println" ] 33 | 34 | # Use defmt 35 | defmt = [ "dep:defmt" ] 36 | 37 | # You may optionally enable one or more of the below features to provide 38 | # additional functionality: 39 | exception-handler = [] 40 | panic-handler = [] 41 | halt-cores = [] 42 | colors = [] 43 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 esp-rs 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2022 esp-rs 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # esp-backtrace - backtrace for ESP32 bare-metal--- 2 | 3 | ## This project has moved! It can now be found in the [esp-rs/esp-hal](https://github.com/esp-rs/esp-hal/tree/main/esp-backtrace) repository. 4 | 5 | --- 6 | 7 | Supports the ESP32, ESP32-C2/C3/C6, ESP32-H2, ESP32-P4, and ESP32-S2/S3. Optional exception and panic handlers are included, both of which can be enabled via their respective features. 8 | 9 | Please note that when targeting a RISC-V device, you **need** to force frame pointers (i.e. `"-C", "force-frame-pointers",` in your `.cargo/config.toml`); this is **not** required for Xtensa. 10 | 11 | You can get an array of backtrace addresses (currently limited to 10) via `arch::backtrace()` if 12 | you want to create a backtrace yourself (i.e. not using the panic or exception handler). 13 | 14 | When using the panic and/or exception handler make sure to include `use esp_backtrace as _;`. 15 | 16 | ## Features 17 | 18 | | Feature | Description | 19 | | ----------------- | ------------------------------------------------------------------------------------------------------------------ | 20 | | esp32 | Target ESP32 | 21 | | esp32c2 | Target ESP32-C2 | 22 | | esp32c3 | Target ESP32-C3 | 23 | | esp32c6 | Target ESP32-C6 | 24 | | esp32h2 | Target ESP32-H2 | 25 | | esp32p4 | Target ESP32-P4 | 26 | | esp32s2 | Target ESP32-S2 | 27 | | esp32s3 | Target ESP32-S3 | 28 | | panic-handler | Include a panic handler, will add `esp-println` as a dependency | 29 | | exception-handler | Include an exception handler, will add `esp-println` as a dependency | 30 | | println | Use `esp-println` to print messages | 31 | | defmt | Use `defmt` logging to print messages\* (check [example](https://github.com/playfulFence/backtrace-defmt-example)) | 32 | | colors | Print messages in red\* | 33 | | halt-cores | Halt both CPUs on ESP32 / ESP32-S3 in case of a panic or exception | 34 | | semihosting | Call `semihosting::process::abort()` on panic. | 35 | 36 | \* _only used for panic and exception handlers_ 37 | 38 | ### `defmt` Feature 39 | 40 | Please note that `defmt` does _not_ provide MSRV guarantees with releases, and as such we are not able to make any MSRV guarantees when this feature is enabled. For more information refer to the MSRV section of `defmt`'s README: 41 | https://github.com/knurling-rs/defmt?tab=readme-ov-file#msrv 42 | 43 | ## License 44 | 45 | Licensed under either of: 46 | 47 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 48 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 49 | 50 | at your option. 51 | 52 | ### Contribution 53 | 54 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in 55 | the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without 56 | any additional terms or conditions. 57 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // Ensure that only a single chip is specified. 3 | let chip_features = [ 4 | cfg!(feature = "esp32"), 5 | cfg!(feature = "esp32c2"), 6 | cfg!(feature = "esp32c3"), 7 | cfg!(feature = "esp32c6"), 8 | cfg!(feature = "esp32h2"), 9 | cfg!(feature = "esp32p4"), 10 | cfg!(feature = "esp32s2"), 11 | cfg!(feature = "esp32s3"), 12 | ]; 13 | 14 | match chip_features.iter().filter(|&&f| f).count() { 15 | 1 => {} 16 | n => panic!("Exactly 1 chip must be enabled via its Cargo feature, {n} provided"), 17 | }; 18 | 19 | // Ensure that exactly a backend is selected 20 | let backend = [cfg!(feature = "println"), cfg!(feature = "defmt")]; 21 | 22 | if backend.iter().filter(|&&f| f).count() == 0 { 23 | panic!("A backend needs to be selected"); 24 | } 25 | 26 | if is_nightly() { 27 | println!("cargo:rustc-cfg=nightly"); 28 | } 29 | } 30 | 31 | fn is_nightly() -> bool { 32 | let version_output = std::process::Command::new( 33 | std::env::var_os("RUSTC").unwrap_or_else(|| std::ffi::OsString::from("rustc")), 34 | ) 35 | .arg("-V") 36 | .output() 37 | .unwrap() 38 | .stdout; 39 | let version_string = String::from_utf8_lossy(&version_output); 40 | 41 | version_string.contains("nightly") 42 | } 43 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![cfg_attr(target_arch = "xtensa", feature(asm_experimental_arch))] 3 | #![allow(rustdoc::bare_urls)] 4 | #![doc = include_str!("../README.md")] 5 | #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/46717278")] 6 | #![cfg_attr(nightly, feature(panic_info_message))] 7 | 8 | #[cfg(feature = "defmt")] 9 | use defmt as _; 10 | #[cfg(feature = "println")] 11 | use esp_println as _; 12 | 13 | const MAX_BACKTRACE_ADDRESSES: usize = 10; 14 | 15 | #[cfg(feature = "colors")] 16 | const RESET: &str = "\u{001B}[0m"; 17 | #[cfg(feature = "colors")] 18 | const RED: &str = "\u{001B}[31m"; 19 | 20 | #[cfg(feature = "defmt")] 21 | macro_rules! println { 22 | ("") => { 23 | // Do nothing if the string is just a space 24 | }; 25 | ($($arg:tt)*) => { 26 | defmt::error!($($arg)*); 27 | }; 28 | } 29 | 30 | #[cfg(all(feature = "println", not(feature = "defmt")))] 31 | macro_rules! println { 32 | ($($arg:tt)*) => { 33 | esp_println::println!($($arg)*); 34 | }; 35 | } 36 | 37 | #[allow(unused, unused_variables)] 38 | fn set_color_code(code: &str) { 39 | #[cfg(feature = "println")] 40 | { 41 | println!("{}", code); 42 | } 43 | } 44 | 45 | #[cfg_attr(target_arch = "riscv32", path = "riscv.rs")] 46 | #[cfg_attr(target_arch = "xtensa", path = "xtensa.rs")] 47 | pub mod arch; 48 | 49 | #[cfg(feature = "panic-handler")] 50 | #[panic_handler] 51 | fn panic_handler(info: &core::panic::PanicInfo) -> ! { 52 | #[cfg(feature = "colors")] 53 | set_color_code(RED); 54 | 55 | println!(""); 56 | println!(""); 57 | 58 | if let Some(location) = info.location() { 59 | let (file, line, column) = (location.file(), location.line(), location.column()); 60 | println!( 61 | "!! A panic occured in '{}', at line {}, column {}:", 62 | file, line, column 63 | ); 64 | } else { 65 | println!("!! A panic occured at an unknown location:"); 66 | } 67 | 68 | #[cfg(not(nightly))] 69 | { 70 | #[cfg(not(feature = "defmt"))] 71 | println!("{:#?}", info); 72 | 73 | #[cfg(feature = "defmt")] 74 | println!("{:#?}", defmt::Display2Format(info)); 75 | } 76 | 77 | #[cfg(nightly)] 78 | { 79 | if let Some(message) = info.message() { 80 | #[cfg(not(feature = "defmt"))] 81 | println!("{}", message); 82 | 83 | #[cfg(feature = "defmt")] 84 | println!("{}", defmt::Display2Format(message)); 85 | } 86 | } 87 | 88 | println!(""); 89 | println!("Backtrace:"); 90 | println!(""); 91 | 92 | let backtrace = crate::arch::backtrace(); 93 | #[cfg(target_arch = "riscv32")] 94 | if backtrace.iter().filter(|e| e.is_some()).count() == 0 { 95 | println!("No backtrace available - make sure to force frame-pointers. (see https://crates.io/crates/esp-backtrace)"); 96 | } 97 | for e in backtrace { 98 | if let Some(addr) = e { 99 | #[cfg(all(feature = "colors", feature = "println"))] 100 | println!("{}0x{:x}", RED, addr - crate::arch::RA_OFFSET); 101 | 102 | #[cfg(not(all(feature = "colors", feature = "println")))] 103 | println!("0x{:x}", addr - crate::arch::RA_OFFSET); 104 | } 105 | } 106 | 107 | #[cfg(feature = "colors")] 108 | set_color_code(RESET); 109 | 110 | #[cfg(feature = "semihosting")] 111 | semihosting::process::abort(); 112 | 113 | halt(); 114 | } 115 | 116 | #[cfg(all(feature = "exception-handler", target_arch = "xtensa"))] 117 | #[no_mangle] 118 | #[link_section = ".rwtext"] 119 | unsafe fn __user_exception(cause: arch::ExceptionCause, context: arch::Context) { 120 | #[cfg(feature = "colors")] 121 | set_color_code(RED); 122 | 123 | // Unfortunately, a different formatter string is used 124 | #[cfg(not(feature = "defmt"))] 125 | esp_println::println!("\n\nException occured '{:?}'", cause); 126 | 127 | #[cfg(feature = "defmt")] 128 | defmt::error!("\n\nException occured '{}'", cause); 129 | 130 | println!("{:?}", context); 131 | 132 | let backtrace = crate::arch::backtrace_internal(context.A1, 0); 133 | for e in backtrace { 134 | if let Some(addr) = e { 135 | println!("0x{:x}", addr); 136 | } 137 | } 138 | println!(""); 139 | println!(""); 140 | println!(""); 141 | 142 | #[cfg(feature = "colors")] 143 | set_color_code(RESET); 144 | 145 | #[cfg(feature = "semihosting")] 146 | semihosting::process::abort(); 147 | 148 | halt(); 149 | } 150 | 151 | #[cfg(all(feature = "exception-handler", target_arch = "riscv32"))] 152 | #[export_name = "ExceptionHandler"] 153 | fn exception_handler(context: &arch::TrapFrame) -> ! { 154 | let mepc = context.pc; 155 | let code = context.mcause & 0xff; 156 | let mtval = context.mtval; 157 | 158 | #[cfg(feature = "colors")] 159 | set_color_code(RED); 160 | 161 | if code == 14 { 162 | println!(""); 163 | println!( 164 | "Stack overflow detected at 0x{:x} called by 0x{:x}", 165 | mepc, context.ra 166 | ); 167 | println!(""); 168 | } else { 169 | let code = match code { 170 | 0 => "Instruction address misaligned", 171 | 1 => "Instruction access fault", 172 | 2 => "Illegal instruction", 173 | 3 => "Breakpoint", 174 | 4 => "Load address misaligned", 175 | 5 => "Load access fault", 176 | 6 => "Store/AMO address misaligned", 177 | 7 => "Store/AMO access fault", 178 | 8 => "Environment call from U-mode", 179 | 9 => "Environment call from S-mode", 180 | 10 => "Reserved", 181 | 11 => "Environment call from M-mode", 182 | 12 => "Instruction page fault", 183 | 13 => "Load page fault", 184 | 14 => "Reserved", 185 | 15 => "Store/AMO page fault", 186 | _ => "UNKNOWN", 187 | }; 188 | 189 | println!( 190 | "Exception '{}' mepc=0x{:08x}, mtval=0x{:08x}", 191 | code, mepc, mtval 192 | ); 193 | #[cfg(not(feature = "defmt"))] 194 | println!("{:x?}", context); 195 | 196 | #[cfg(feature = "defmt")] 197 | println!("{:?}", context); 198 | 199 | let backtrace = crate::arch::backtrace_internal(context.s0 as u32, 0); 200 | if backtrace.iter().filter(|e| e.is_some()).count() == 0 { 201 | println!("No backtrace available - make sure to force frame-pointers. (see https://crates.io/crates/esp-backtrace)"); 202 | } 203 | for e in backtrace { 204 | if let Some(addr) = e { 205 | #[cfg(all(feature = "colors", feature = "println"))] 206 | println!("{}0x{:x}", RED, addr - crate::arch::RA_OFFSET); 207 | 208 | #[cfg(not(all(feature = "colors", feature = "println")))] 209 | println!("0x{:x}", addr - crate::arch::RA_OFFSET); 210 | } 211 | } 212 | } 213 | 214 | println!(""); 215 | println!(""); 216 | println!(""); 217 | 218 | #[cfg(feature = "colors")] 219 | set_color_code(RESET); 220 | 221 | #[cfg(feature = "semihosting")] 222 | semihosting::process::abort(); 223 | 224 | halt(); 225 | } 226 | 227 | // Ensure that the address is in DRAM and that it is 16-byte aligned. 228 | // 229 | // Based loosely on the `esp_stack_ptr_in_dram` function from 230 | // `components/esp_hw_support/include/esp_memory_utils.h` in ESP-IDF. 231 | // 232 | // Address ranges can be found in `components/soc/$CHIP/include/soc/soc.h` as 233 | // `SOC_DRAM_LOW` and `SOC_DRAM_HIGH`. 234 | fn is_valid_ram_address(address: u32) -> bool { 235 | if (address & 0xF) != 0 { 236 | return false; 237 | } 238 | 239 | #[cfg(feature = "esp32")] 240 | if !(0x3FFA_E000..=0x4000_0000).contains(&address) { 241 | return false; 242 | } 243 | 244 | #[cfg(feature = "esp32c2")] 245 | if !(0x3FCA_0000..=0x3FCE_0000).contains(&address) { 246 | return false; 247 | } 248 | 249 | #[cfg(feature = "esp32c3")] 250 | if !(0x3FC8_0000..=0x3FCE_0000).contains(&address) { 251 | return false; 252 | } 253 | 254 | #[cfg(feature = "esp32c6")] 255 | if !(0x4080_0000..=0x4088_0000).contains(&address) { 256 | return false; 257 | } 258 | 259 | #[cfg(feature = "esp32h2")] 260 | if !(0x4080_0000..=0x4085_0000).contains(&address) { 261 | return false; 262 | } 263 | 264 | #[cfg(feature = "esp32p4")] 265 | if !(0x4FF0_0000..=0x4FFC_0000).contains(&address) { 266 | return false; 267 | } 268 | 269 | #[cfg(feature = "esp32s2")] 270 | if !(0x3FFB_0000..=0x4000_0000).contains(&address) { 271 | return false; 272 | } 273 | 274 | #[cfg(feature = "esp32s3")] 275 | if !(0x3FC8_8000..=0x3FD0_0000).contains(&address) { 276 | return false; 277 | } 278 | 279 | true 280 | } 281 | 282 | #[cfg(any( 283 | not(any(feature = "esp32", feature = "esp32p4", feature = "esp32s3")), 284 | not(feature = "halt-cores") 285 | ))] 286 | #[allow(unused)] 287 | fn halt() -> ! { 288 | loop {} 289 | } 290 | 291 | // TODO: Enable `halt` function for `esp32p4` feature once implemented 292 | #[cfg(all(any(feature = "esp32", feature = "esp32s3"), feature = "halt-cores"))] 293 | #[allow(unused)] 294 | fn halt() -> ! { 295 | #[cfg(feature = "esp32")] 296 | mod registers { 297 | pub(crate) const OPTIONS0: u32 = 0x3ff48000; 298 | pub(crate) const SW_CPU_STALL: u32 = 0x3ff480ac; 299 | } 300 | 301 | #[cfg(feature = "esp32p4")] 302 | mod registers { 303 | pub(crate) const SW_CPU_STALL: u32 = 0x50115200; 304 | } 305 | 306 | #[cfg(feature = "esp32s3")] 307 | mod registers { 308 | pub(crate) const OPTIONS0: u32 = 0x60008000; 309 | pub(crate) const SW_CPU_STALL: u32 = 0x600080bc; 310 | } 311 | 312 | let sw_cpu_stall = registers::SW_CPU_STALL as *mut u32; 313 | 314 | #[cfg(feature = "esp32p4")] 315 | unsafe {} 316 | 317 | #[cfg(not(feature = "esp32p4"))] 318 | unsafe { 319 | // We need to write the value "0x86" to stall a particular core. The write 320 | // location is split into two separate bit fields named "c0" and "c1", and the 321 | // two fields are located in different registers. Each core has its own pair of 322 | // "c0" and "c1" bit fields. 323 | 324 | let options0 = registers::OPTIONS0 as *mut u32; 325 | 326 | options0.write_volatile(options0.read_volatile() & !(0b1111) | 0b1010); 327 | 328 | sw_cpu_stall.write_volatile( 329 | sw_cpu_stall.read_volatile() & !(0b111111 << 20) & !(0b111111 << 26) 330 | | (0x21 << 20) 331 | | (0x21 << 26), 332 | ); 333 | } 334 | 335 | loop {} 336 | } 337 | -------------------------------------------------------------------------------- /src/riscv.rs: -------------------------------------------------------------------------------- 1 | use crate::MAX_BACKTRACE_ADDRESSES; 2 | use core::arch::asm; 3 | 4 | // subtract 4 from the return address 5 | // the return address is the address following the JALR 6 | // we get better results (especially if the caller was the last function in the calling function) 7 | // if we report the address of the JALR itself 8 | // even if it was a C.JALR we should get good results using RA - 4 9 | pub(super) const RA_OFFSET: usize = 4; 10 | 11 | /// Registers saved in trap handler 12 | #[doc(hidden)] 13 | #[allow(missing_docs)] 14 | #[derive(Default, Clone, Copy)] 15 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 16 | #[repr(C)] 17 | pub(crate) struct TrapFrame { 18 | pub ra: usize, 19 | pub t0: usize, 20 | pub t1: usize, 21 | pub t2: usize, 22 | pub t3: usize, 23 | pub t4: usize, 24 | pub t5: usize, 25 | pub t6: usize, 26 | pub a0: usize, 27 | pub a1: usize, 28 | pub a2: usize, 29 | pub a3: usize, 30 | pub a4: usize, 31 | pub a5: usize, 32 | pub a6: usize, 33 | pub a7: usize, 34 | pub s0: usize, 35 | pub s1: usize, 36 | pub s2: usize, 37 | pub s3: usize, 38 | pub s4: usize, 39 | pub s5: usize, 40 | pub s6: usize, 41 | pub s7: usize, 42 | pub s8: usize, 43 | pub s9: usize, 44 | pub s10: usize, 45 | pub s11: usize, 46 | pub gp: usize, 47 | pub tp: usize, 48 | pub sp: usize, 49 | pub pc: usize, 50 | pub mstatus: usize, 51 | pub mcause: usize, 52 | pub mtval: usize, 53 | } 54 | 55 | impl core::fmt::Debug for TrapFrame { 56 | fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { 57 | write!( 58 | fmt, 59 | "TrapFrame 60 | PC=0x{:08x} RA/x1=0x{:08x} SP/x2=0x{:08x} GP/x3=0x{:08x} TP/x4=0x{:08x} 61 | T0/x5=0x{:08x} T1/x6=0x{:08x} T2/x7=0x{:08x} S0/FP/x8=0x{:08x} S1/x9=0x{:08x} 62 | A0/x10=0x{:08x} A1/x11=0x{:08x} A2/x12=0x{:08x} A3/x13=0x{:08x} A4/x14=0x{:08x} 63 | A5/x15=0x{:08x} A6/x16=0x{:08x} A7/x17=0x{:08x} S2/x18=0x{:08x} S3/x19=0x{:08x} 64 | S4/x20=0x{:08x} S5/x21=0x{:08x} S6/x22=0x{:08x} S7/x23=0x{:08x} S8/x24=0x{:08x} 65 | S9/x25=0x{:08x} S10/x26=0x{:08x} S11/x27=0x{:08x} T3/x28=0x{:08x} T4/x29=0x{:08x} 66 | T5/x30=0x{:08x} T6/x31=0x{:08x} 67 | 68 | MSTATUS=0x{:08x} 69 | MCAUSE=0x{:08x} 70 | MTVAL=0x{:08x} 71 | ", 72 | self.pc, 73 | self.ra, 74 | self.gp, 75 | self.sp, 76 | self.tp, 77 | self.t0, 78 | self.t1, 79 | self.t2, 80 | self.s0, 81 | self.s1, 82 | self.a0, 83 | self.a1, 84 | self.a2, 85 | self.a3, 86 | self.a4, 87 | self.a5, 88 | self.a6, 89 | self.a7, 90 | self.s2, 91 | self.s3, 92 | self.s4, 93 | self.s5, 94 | self.s6, 95 | self.s7, 96 | self.s8, 97 | self.s9, 98 | self.s10, 99 | self.s11, 100 | self.t3, 101 | self.t4, 102 | self.t5, 103 | self.t6, 104 | self.mstatus, 105 | self.mcause, 106 | self.mtval, 107 | ) 108 | } 109 | } 110 | 111 | /// Get an array of backtrace addresses. 112 | /// 113 | /// This needs `force-frame-pointers` enabled. 114 | pub fn backtrace() -> [Option; MAX_BACKTRACE_ADDRESSES] { 115 | let fp = unsafe { 116 | let mut _tmp: u32; 117 | asm!("mv {0}, x8", out(reg) _tmp); 118 | _tmp 119 | }; 120 | 121 | backtrace_internal(fp, 2) 122 | } 123 | 124 | pub(crate) fn backtrace_internal( 125 | fp: u32, 126 | suppress: i32, 127 | ) -> [Option; MAX_BACKTRACE_ADDRESSES] { 128 | let mut result = [None; 10]; 129 | let mut index = 0; 130 | 131 | let mut fp = fp; 132 | let mut suppress = suppress; 133 | let mut old_address = 0; 134 | loop { 135 | unsafe { 136 | let address = (fp as *const u32).offset(-1).read_volatile(); // RA/PC 137 | fp = (fp as *const u32).offset(-2).read_volatile(); // next FP 138 | 139 | if old_address == address { 140 | break; 141 | } 142 | 143 | old_address = address; 144 | 145 | if address == 0 { 146 | break; 147 | } 148 | 149 | if !crate::is_valid_ram_address(fp) { 150 | break; 151 | } 152 | 153 | if suppress == 0 { 154 | result[index] = Some(address as usize); 155 | index += 1; 156 | 157 | if index >= MAX_BACKTRACE_ADDRESSES { 158 | break; 159 | } 160 | } else { 161 | suppress -= 1; 162 | } 163 | } 164 | } 165 | 166 | result 167 | } 168 | -------------------------------------------------------------------------------- /src/xtensa.rs: -------------------------------------------------------------------------------- 1 | use crate::MAX_BACKTRACE_ADDRESSES; 2 | use core::arch::asm; 3 | 4 | // subtract 3 from the return address 5 | // the return address is the address following the callxN 6 | // we get better results (especially if the caller was the last function in the calling function) 7 | // if we report the address of callxN itself 8 | pub(super) const RA_OFFSET: usize = 3; 9 | 10 | #[doc(hidden)] 11 | #[allow(missing_docs)] 12 | #[derive(Debug, Clone, Copy)] 13 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 14 | #[repr(C)] 15 | pub enum ExceptionCause { 16 | /// Illegal Instruction 17 | IllegalInstruction = 0, 18 | /// System Call (Syscall Instruction) 19 | Syscall = 1, 20 | /// Instruction Fetch Error 21 | InstrFetchError = 2, 22 | /// Load Store Error 23 | LoadStoreError = 3, 24 | /// Level 1 Interrupt 25 | LevelOneInterrupt = 4, 26 | /// Stack Extension Assist (movsp Instruction) For Alloca 27 | Alloca = 5, 28 | /// Integer Divide By Zero 29 | DivideByZero = 6, 30 | /// Use Of Failed Speculative Access (Not Implemented) 31 | NextPCValueIllegal = 7, 32 | /// Privileged Instruction 33 | PrivilegedInstruction = 8, 34 | /// Unaligned Load Or Store 35 | UnalignedLoadOrStore = 9, 36 | /// Reserved 37 | ExternalRegisterPrivilegeError = 10, 38 | /// Reserved 39 | ExclusiveError = 11, 40 | /// Pif Data Error On Instruction Fetch (Rb-200x And Later) 41 | InstrDataError = 12, 42 | /// Pif Data Error On Load Or Store (Rb-200x And Later) 43 | LoadStoreDataError = 13, 44 | /// Pif Address Error On Instruction Fetch (Rb-200x And Later) 45 | InstrAddrError = 14, 46 | /// Pif Address Error On Load Or Store (Rb-200x And Later) 47 | LoadStoreAddrError = 15, 48 | /// Itlb Miss (No Itlb Entry Matches, Hw Refill Also Missed) 49 | ItlbMiss = 16, 50 | /// Itlb Multihit (Multiple Itlb Entries Match) 51 | ItlbMultiHit = 17, 52 | /// Ring Privilege Violation On Instruction Fetch 53 | InstrRing = 18, 54 | /// Size Restriction On Ifetch (Not Implemented) 55 | Reserved19 = 19, 56 | /// Cache Attribute Does Not Allow Instruction Fetch 57 | InstrProhibited = 20, 58 | /// Reserved 59 | Reserved21 = 21, 60 | /// Reserved 61 | Reserved22 = 22, 62 | /// Reserved 63 | Reserved23 = 23, 64 | /// Dtlb Miss (No Dtlb Entry Matches, Hw Refill Also Missed) 65 | DtlbMiss = 24, 66 | /// Dtlb Multihit (Multiple Dtlb Entries Match) 67 | DtlbMultiHit = 25, 68 | /// Ring Privilege Violation On Load Or Store 69 | LoadStoreRing = 26, 70 | /// Size Restriction On Load/Store (Not Implemented) 71 | Reserved27 = 27, 72 | /// Cache Attribute Does Not Allow Load 73 | LoadProhibited = 28, 74 | /// Cache Attribute Does Not Allow Store 75 | StoreProhibited = 29, 76 | /// Reserved 77 | Reserved30 = 30, 78 | /// Reserved 79 | Reserved31 = 31, 80 | /// Access To Coprocessor 0 When Disabled 81 | Cp0Disabled = 32, 82 | /// Access To Coprocessor 1 When Disabled 83 | Cp1Disabled = 33, 84 | /// Access To Coprocessor 2 When Disabled 85 | Cp2Disabled = 34, 86 | /// Access To Coprocessor 3 When Disabled 87 | Cp3Disabled = 35, 88 | /// Access To Coprocessor 4 When Disabled 89 | Cp4Disabled = 36, 90 | /// Access To Coprocessor 5 When Disabled 91 | Cp5Disabled = 37, 92 | /// Access To Coprocessor 6 When Disabled 93 | Cp6Disabled = 38, 94 | /// Access To Coprocessor 7 When Disabled 95 | Cp7Disabled = 39, 96 | 97 | None = 255, 98 | } 99 | 100 | #[doc(hidden)] 101 | #[allow(missing_docs, non_snake_case)] 102 | #[derive(Clone, Copy)] 103 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 104 | #[repr(C)] 105 | pub struct Context { 106 | pub PC: u32, 107 | pub PS: u32, 108 | pub A0: u32, 109 | pub A1: u32, 110 | pub A2: u32, 111 | pub A3: u32, 112 | pub A4: u32, 113 | pub A5: u32, 114 | pub A6: u32, 115 | pub A7: u32, 116 | pub A8: u32, 117 | pub A9: u32, 118 | pub A10: u32, 119 | pub A11: u32, 120 | pub A12: u32, 121 | pub A13: u32, 122 | pub A14: u32, 123 | pub A15: u32, 124 | pub SAR: u32, 125 | pub EXCCAUSE: u32, 126 | pub EXCVADDR: u32, 127 | pub LBEG: u32, 128 | pub LEND: u32, 129 | pub LCOUNT: u32, 130 | pub THREADPTR: u32, 131 | pub SCOMPARE1: u32, 132 | pub BR: u32, 133 | pub ACCLO: u32, 134 | pub ACCHI: u32, 135 | pub M0: u32, 136 | pub M1: u32, 137 | pub M2: u32, 138 | pub M3: u32, 139 | pub F64R_LO: u32, 140 | pub F64R_HI: u32, 141 | pub F64S: u32, 142 | pub FCR: u32, 143 | pub FSR: u32, 144 | pub F0: u32, 145 | pub F1: u32, 146 | pub F2: u32, 147 | pub F3: u32, 148 | pub F4: u32, 149 | pub F5: u32, 150 | pub F6: u32, 151 | pub F7: u32, 152 | pub F8: u32, 153 | pub F9: u32, 154 | pub F10: u32, 155 | pub F11: u32, 156 | pub F12: u32, 157 | pub F13: u32, 158 | pub F14: u32, 159 | pub F15: u32, 160 | } 161 | 162 | impl core::fmt::Debug for Context { 163 | fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { 164 | write!( 165 | fmt, 166 | "Context 167 | PC=0x{:08x} PS=0x{:08x} 168 | A0=0x{:08x} A1=0x{:08x} A2=0x{:08x} A3=0x{:08x} A4=0x{:08x} 169 | A5=0x{:08x} A6=0x{:08x} A7=0x{:08x} A8=0x{:08x} A9=0x{:08x} 170 | A10=0x{:08x} A11=0x{:08x} A12=0x{:08x} A13=0x{:08x} A14=0x{:08x} 171 | A15=0x{:08x} 172 | SAR={:08x} 173 | EXCCAUSE=0x{:08x} EXCVADDR=0x{:08x} 174 | LBEG=0x{:08x} LEND=0x{:08x} LCOUNT=0x{:08x} 175 | THREADPTR=0x{:08x} 176 | SCOMPARE1=0x{:08x} 177 | BR=0x{:08x} 178 | ACCLO=0x{:08x} ACCHI=0x{:08x} 179 | M0=0x{:08x} M1=0x{:08x} M2=0x{:08x} M3=0x{:08x} 180 | F64R_LO=0x{:08x} F64R_HI=0x{:08x} F64S=0x{:08x} 181 | FCR=0x{:08x} FSR=0x{:08x} 182 | F0=0x{:08x} F1=0x{:08x} F2=0x{:08x} F3=0x{:08x} F4=0x{:08x} 183 | F5=0x{:08x} F6=0x{:08x} F7=0x{:08x} F8=0x{:08x} F9=0x{:08x} 184 | F10=0x{:08x} F11=0x{:08x} F12=0x{:08x} F13=0x{:08x} F14=0x{:08x} 185 | F15=0x{:08x} 186 | ", 187 | self.PC, 188 | self.PS, 189 | self.A0, 190 | self.A1, 191 | self.A2, 192 | self.A3, 193 | self.A4, 194 | self.A5, 195 | self.A6, 196 | self.A7, 197 | self.A8, 198 | self.A9, 199 | self.A10, 200 | self.A11, 201 | self.A12, 202 | self.A13, 203 | self.A14, 204 | self.A15, 205 | self.SAR, 206 | self.EXCCAUSE, 207 | self.EXCVADDR, 208 | self.LBEG, 209 | self.LEND, 210 | self.LCOUNT, 211 | self.THREADPTR, 212 | self.SCOMPARE1, 213 | self.BR, 214 | self.ACCLO, 215 | self.ACCHI, 216 | self.M0, 217 | self.M1, 218 | self.M2, 219 | self.M3, 220 | self.F64R_LO, 221 | self.F64R_HI, 222 | self.F64S, 223 | self.FCR, 224 | self.FSR, 225 | self.F0, 226 | self.F1, 227 | self.F2, 228 | self.F3, 229 | self.F4, 230 | self.F5, 231 | self.F6, 232 | self.F7, 233 | self.F8, 234 | self.F9, 235 | self.F10, 236 | self.F11, 237 | self.F12, 238 | self.F13, 239 | self.F14, 240 | self.F15, 241 | ) 242 | } 243 | } 244 | 245 | /// Get an array of backtrace addresses. 246 | /// 247 | pub fn backtrace() -> [Option; MAX_BACKTRACE_ADDRESSES] { 248 | let sp = unsafe { 249 | let mut _tmp: u32; 250 | asm!("mov {0}, a1", out(reg) _tmp); 251 | _tmp 252 | }; 253 | 254 | backtrace_internal(sp, 1) 255 | } 256 | 257 | pub(crate) fn sanitize_address(address: u32) -> u32 { 258 | (address & 0x3fff_ffff) | 0x4000_0000 259 | } 260 | 261 | pub(crate) fn backtrace_internal( 262 | sp: u32, 263 | suppress: i32, 264 | ) -> [Option; MAX_BACKTRACE_ADDRESSES] { 265 | let mut result = [None; 10]; 266 | let mut index = 0; 267 | 268 | let mut fp = sp; 269 | let mut suppress = suppress; 270 | let mut old_address = 0; 271 | 272 | loop { 273 | unsafe { 274 | let address = sanitize_address((fp as *const u32).offset(-4).read_volatile()); // RA/PC 275 | fp = (fp as *const u32).offset(-3).read_volatile(); // next FP 276 | 277 | if old_address == address { 278 | break; 279 | } 280 | 281 | old_address = address; 282 | 283 | if address == 0 { 284 | break; 285 | } 286 | 287 | if !crate::is_valid_ram_address(fp) { 288 | break; 289 | } 290 | 291 | if fp == 0 { 292 | break; 293 | } 294 | 295 | if suppress == 0 { 296 | result[index] = Some(address as usize); 297 | index += 1; 298 | 299 | if index >= MAX_BACKTRACE_ADDRESSES { 300 | break; 301 | } 302 | } else { 303 | suppress -= 1; 304 | } 305 | } 306 | } 307 | 308 | result 309 | } 310 | --------------------------------------------------------------------------------