Repository: oli-obk/priroda Branch: main Commit: 0cc9d44c3726 Files: 21 Total size: 129.3 KB Directory structure: gitextract_34yhs5wo/ ├── .github/ │ └── workflows/ │ └── build.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── Rocket.toml ├── example.rs ├── resources/ │ ├── positioning.css │ ├── style-default.css │ ├── svg-pan-zoom.js │ └── zoom_mir.js ├── rust-toolchain └── src/ ├── main.rs ├── render/ │ ├── graphviz.rs │ ├── locals.rs │ ├── mod.rs │ └── source.rs ├── step.rs └── watch/ ├── mod.rs └── stack_trace.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/build.yml ================================================ name: Continuous Integration on: [push, pull_request] jobs: check: name: Check runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 # Toolchain installation should appear as a seperate step for timing purposes - run: rustup show - name: Setup Graphviz uses: ts-graphviz/setup-graphviz@v1 - uses: actions-rs/cargo@v1 with: command: check fmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: rustup component add rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check ================================================ FILE: .gitignore ================================================ /target flame_graph* config.json ================================================ FILE: Cargo.toml ================================================ [package] authors = ["Oliver Schneider "] description = "A graphical debugger for Rust MIR." license = "MIT/Apache-2.0" name = "priroda" repository = "https://github.com/oli-obk/priroda" version = "0.1.0" edition = "2018" [dependencies] regex = "1.3" lazy_static = "1.4.0" rocket = "0.4.7" # This needs to be the version of miri for the nightly in the `rust-toolchain` file miri = { git = "https://github.com/rust-lang/miri.git", rev = "ae964207bb17911cf96d9744d9469fa2734093a8" } log = "0.4" env_logger = "0.7" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" open = "1.4.0" syntect = "4.2" horrorshow = "0.8" cgraph = { git = "https://github.com/oli-obk/cgraph.git", rev = "5e6a6d4527522609772a9a9a1565b74c9bfe1560" } # Uncomment to use local checkout of miri # [patch."https://github.com/rust-lang/miri.git"] # miri = { path = "../miri" } [features] static_resources = [] [package.metadata.rust-analyzer] rustc_private = true [profile.dev] debug = 1 ================================================ FILE: LICENSE-APACHE ================================================ 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 2016 The Miri Developers 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. ================================================ FILE: LICENSE-MIT ================================================ Copyright (c) 2016 The Miri Developers 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. ================================================ FILE: README.md ================================================ # Priroda Priroda is a graphical (UI in browser) debugger for Rust programs ## Setup You need a few things before you can get started. At the very minimum you need to have the graphviz libraries present. * debian/ubuntu: `apt install libgraphviz-dev` Next, you're going to want a libstd with full MIR. The easiest way to obtain this is via `cargo miri`: ```bash # Install cargo miri: rustup component add miri # Compile libstd: cargo miri setup # Set the MIRI_SYSROOT environment variable to the path printed by the setup command: export MIRI_SYSROOT=... ``` ## Features * Supports commands known from gdb * next, step, continue * Inspect memory of all stack frames visually * Follow pointers by clicking hyperlinks * Track your progress through a function in a graph of the MIR * Style your debugging experience with CSS ## Usage `cargo run some_rust_file.rs` will automatically start a http server and open a browser. UI is changing rapidly right now, so you need to figure out how to use it by yourself (or by asking on irc) for now. ## Contributing and getting help Check out the issues on this GitHub repository for some ideas. There's lots that needs to be done that I haven't documented in the issues yet, however. For more ideas or help with running or hacking on Priroda, you can ask at [`#miri`] on the rust-lang zulip. [`#miri`]: https://rust-lang.zulipchat.com/#narrow/stream/269128-miri ### Miri This project depends entirely on [Miri](https://github.com/rust-lang/miri). So if you want to improve something that we fail to interpret, add a unit test to Miri and fix it there. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) * MIT license ([LICENSE-MIT](LICENSE-MIT)) ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. ================================================ FILE: Rocket.toml ================================================ [development] address = "localhost" port = 54321 #spawn_browser = true [production] address = "0.0.0.0" port = 8080 spawn_browser = false ================================================ FILE: example.rs ================================================ #![allow(dead_code)] fn some_fn() { let mut val = 2; let mut my_wrapper = MyWrapper(&mut val); let wrapper_ref = &mut my_wrapper; for i in 0..16 { *wrapper_ref.0 = i; } } struct MyWrapper<'a>(&'a mut u8); struct SomeRandomStruct<'a, A> { ernrer: u8, feijoc: i64, ioieoe: bool, fewije: char, chr_ref: &'a char, efoiri: A, irrfio: SomeOtherStruct, } struct SomeOtherStruct { efufrr: u8, frireg: u16, } union SomeUnion { a: bool, b: u64, } fn main() { let chr = '4'; let _rer = SomeRandomStruct { ernrer: 24, feijoc: -34438, ioieoe: true, fewije: '@', chr_ref: &chr, efoiri: Some(2u16), irrfio: SomeOtherStruct { efufrr: 34, frireg: 45804, }, }; let u = SomeUnion { a: true }; let abc = Box::new(42); some_fn(); let f = 1.4f64; let _sum = 1f64 + f; let _s = "ieeoe"; let _bcd: Box<[u8]> = Box::new([0, 1]); let _d = true; format!("ewioio: {}", abc); } ================================================ FILE: resources/positioning.css ================================================ * { box-sizing: border-box; } body { margin: 0px; height: 100vh; overflow-y: hidden; } #left, #right { display: inline-block; width: calc(50vw - 4px); height: 100vh; margin: 2px; vertical-align: top; overflow: auto; } #mir { width: 100%; height: calc(100% - 150px); } #mir > svg { display: block; max-width: 100%; max-height: 100%; width: auto; height: auto; } #mir > svg:first-child { width: 100%; height: 100%; } #stack, #locals { overflow: auto; } .vertical { writing-mode: tb-rl; } @media only screen and (max-width: 600px) { body { height: unset; overflow-y: scroll; } #left, #right { display: block; width: 100vw; height: unset; margin: 2px 0; padding: 0 5px; } #mir { width: calc(100vw - 100px) !important; height: unset; } #mir:first-child { height: 50vh !important; } } ================================================ FILE: resources/style-default.css ================================================ #mir { border: 2px grey solid; } #stack { border: grey 2px solid; margin: 2px 0; padding: 2px; } #stack table tr td:nth-child(1) { color: red; } #locals { border: grey 2px solid; margin: 2px 0; } #locals table { border-collapse:collapse; border: none; font-family: monospace; } /* left top corner */ #locals table tbody :first-child td { border: none; } #locals table tr th { background-color: lightgrey; } #locals table tr th { min-width: 14px; font-size: 12px } #return_ptr { display: inline-block; border: 1px solid black; } #commands { display: flex; width: 100%; flex-wrap: wrap; padding: 2px; } #commands > a { text-decoration: none; padding-right: 2px; margin: 3px; } #commands > a > div { padding: 5px 7px; background: #4479BA; color: #FFF; border-radius: 4px; border: solid 1px #20538D; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2); transition-duration: 0.2s; user-select:none; } #commands > a > div:hover { background: #356094; border: solid 1px #2A4E77; text-decoration: none; } #commands > a > div:active { box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); background: #2E5481; border: solid 1px #203E5F; } #stack table { border: none; border-collapse: collapse; } #stack table tr :first-child { border: none; } td { padding: 0px; } ================================================ FILE: resources/svg-pan-zoom.js ================================================ // svg-pan-zoom v3.5.2 // https://github.com/ariutta/svg-pan-zoom !function t(e,o,n){function i(r,a){if(!o[r]){if(!e[r]){var l="function"==typeof require&&require;if(!a&&l)return l(r,!0);if(s)return s(r,!0);var u=new Error("Cannot find module '"+r+"'");throw u.code="MODULE_NOT_FOUND",u}var h=o[r]={exports:{}};e[r][0].call(h.exports,function(t){var o=e[r][1][t];return i(o?o:t)},h,h.exports,t,e,o,n)}return o[r].exports}for(var s="function"==typeof require&&require,r=0;r=0;n--)this.eventListeners.hasOwnProperty(o[n])&&delete this.eventListeners[o[n]]}for(var i in this.eventListeners)(this.options.eventsListenerElement||this.svg).addEventListener(i,this.eventListeners[i],!1);this.options.mouseWheelZoomEnabled&&(this.options.mouseWheelZoomEnabled=!1,this.enableMouseWheelZoom())},l.prototype.enableMouseWheelZoom=function(){if(!this.options.mouseWheelZoomEnabled){var t=this;this.wheelListener=function(e){return t.handleMouseWheel(e)},n.on(this.options.eventsListenerElement||this.svg,this.wheelListener,!1),this.options.mouseWheelZoomEnabled=!0}},l.prototype.disableMouseWheelZoom=function(){this.options.mouseWheelZoomEnabled&&(n.off(this.options.eventsListenerElement||this.svg,this.wheelListener,!1),this.options.mouseWheelZoomEnabled=!1)},l.prototype.handleMouseWheel=function(t){if(this.options.zoomEnabled&&"none"===this.state){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1);var e=t.deltaY||1,o=Date.now()-this.lastMouseWheelEventTime,n=3+Math.max(0,30-o);this.lastMouseWheelEventTime=Date.now(),"deltaMode"in t&&0===t.deltaMode&&t.wheelDelta&&(e=0===t.deltaY?0:Math.abs(t.wheelDelta)/t.deltaY),e=-.30?1:-1)*Math.log(Math.abs(e)+10)/n;var i=this.svg.getScreenCTM().inverse(),s=r.getEventPoint(t,this.svg).matrixTransform(i),a=Math.pow(1+this.options.zoomScaleSensitivity,-1*e);this.zoomAtPoint(a,s)}},l.prototype.zoomAtPoint=function(t,e,o){var n=this.viewport.getOriginalState();o?(t=Math.max(this.options.minZoom*n.zoom,Math.min(this.options.maxZoom*n.zoom,t)),t/=this.getZoom()):this.getZoom()*tthis.options.maxZoom*n.zoom&&(t=this.options.maxZoom*n.zoom/this.getZoom());var i=this.viewport.getCTM(),s=e.matrixTransform(i.inverse()),r=this.svg.createSVGMatrix().translate(s.x,s.y).scale(t).translate(-s.x,-s.y),a=i.multiply(r);a.a!==i.a&&this.viewport.setCTM(a)},l.prototype.zoom=function(t,e){this.zoomAtPoint(t,r.getSvgCenterPoint(this.svg,this.width,this.height),e)},l.prototype.publicZoom=function(t,e){e&&(t=this.computeFromRelativeZoom(t)),this.zoom(t,e)},l.prototype.publicZoomAtPoint=function(t,e,o){if(o&&(t=this.computeFromRelativeZoom(t)),"SVGPoint"!==s.getType(e)){if(!("x"in e&&"y"in e))throw new Error("Given point is invalid");e=r.createSVGPoint(this.svg,e.x,e.y)}this.zoomAtPoint(t,e,o)},l.prototype.getZoom=function(){return this.viewport.getZoom()},l.prototype.getRelativeZoom=function(){return this.viewport.getRelativeZoom()},l.prototype.computeFromRelativeZoom=function(t){return t*this.viewport.getOriginalState().zoom},l.prototype.resetZoom=function(){var t=this.viewport.getOriginalState();this.zoom(t.zoom,!0)},l.prototype.resetPan=function(){this.pan(this.viewport.getOriginalState())},l.prototype.reset=function(){this.resetZoom(),this.resetPan()},l.prototype.handleDblClick=function(t){if(this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),this.options.controlIconsEnabled){var e=t.target.getAttribute("class")||"";if(e.indexOf("svg-pan-zoom-control")>-1)return!1}var o;o=t.shiftKey?1/(2*(1+this.options.zoomScaleSensitivity)):2*(1+this.options.zoomScaleSensitivity);var n=r.getEventPoint(t,this.svg).matrixTransform(this.svg.getScreenCTM().inverse());this.zoomAtPoint(o,n)},l.prototype.handleMouseDown=function(t,e){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),s.mouseAndTouchNormalize(t,this.svg),this.options.dblClickZoomEnabled&&s.isDblClick(t,e)?this.handleDblClick(t):(this.state="pan",this.firstEventCTM=this.viewport.getCTM(),this.stateOrigin=r.getEventPoint(t,this.svg).matrixTransform(this.firstEventCTM.inverse()))},l.prototype.handleMouseMove=function(t){if(this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),"pan"===this.state&&this.options.panEnabled){var e=r.getEventPoint(t,this.svg).matrixTransform(this.firstEventCTM.inverse()),o=this.firstEventCTM.translate(e.x-this.stateOrigin.x,e.y-this.stateOrigin.y);this.viewport.setCTM(o)}},l.prototype.handleMouseUp=function(t){this.options.preventMouseEventsDefault&&(t.preventDefault?t.preventDefault():t.returnValue=!1),"pan"===this.state&&(this.state="none")},l.prototype.fit=function(){var t=this.viewport.getViewBox(),e=Math.min(this.width/t.width,this.height/t.height);this.zoom(e,!0)},l.prototype.contain=function(){var t=this.viewport.getViewBox(),e=Math.max(this.width/t.width,this.height/t.height);this.zoom(e,!0)},l.prototype.center=function(){var t=this.viewport.getViewBox(),e=.5*(this.width-(t.width+2*t.x)*this.getZoom()),o=.5*(this.height-(t.height+2*t.y)*this.getZoom());this.getPublicInstance().pan({x:e,y:o})},l.prototype.updateBBox=function(){this.viewport.simpleViewBoxCache()},l.prototype.pan=function(t){var e=this.viewport.getCTM();e.e=t.x,e.f=t.y,this.viewport.setCTM(e)},l.prototype.panBy=function(t){var e=this.viewport.getCTM();e.e+=t.x,e.f+=t.y,this.viewport.setCTM(e)},l.prototype.getPan=function(){var t=this.viewport.getState();return{x:t.x,y:t.y}},l.prototype.resize=function(){var t=r.getBoundingClientRectNormalized(this.svg);this.width=t.width,this.height=t.height;var e=this.viewport;e.options.width=this.width,e.options.height=this.height,e.processCTM(),this.options.controlIconsEnabled&&(this.getPublicInstance().disableControlIcons(),this.getPublicInstance().enableControlIcons())},l.prototype.destroy=function(){var t=this;this.beforeZoom=null,this.onZoom=null,this.beforePan=null,this.onPan=null,this.onUpdatedCTM=null,null!=this.options.customEventsHandler&&this.options.customEventsHandler.destroy({svgElement:this.svg,eventsListenerElement:this.options.eventsListenerElement,instance:this.getPublicInstance()});for(var e in this.eventListeners)(this.options.eventsListenerElement||this.svg).removeEventListener(e,this.eventListeners[e],!1);this.disableMouseWheelZoom(),this.getPublicInstance().disableControlIcons(),this.reset(),h=h.filter(function(e){return e.svg!==t.svg}),delete this.options,delete this.viewport,delete this.publicInstance,delete this.pi,this.getPublicInstance=function(){return null}},l.prototype.getPublicInstance=function(){var t=this;return this.publicInstance||(this.publicInstance=this.pi={enablePan:function(){return t.options.panEnabled=!0,t.pi},disablePan:function(){return t.options.panEnabled=!1,t.pi},isPanEnabled:function(){return!!t.options.panEnabled},pan:function(e){return t.pan(e),t.pi},panBy:function(e){return t.panBy(e),t.pi},getPan:function(){return t.getPan()},setBeforePan:function(e){return t.options.beforePan=null===e?null:s.proxy(e,t.publicInstance),t.pi},setOnPan:function(e){return t.options.onPan=null===e?null:s.proxy(e,t.publicInstance),t.pi},enableZoom:function(){return t.options.zoomEnabled=!0,t.pi},disableZoom:function(){return t.options.zoomEnabled=!1,t.pi},isZoomEnabled:function(){return!!t.options.zoomEnabled},enableControlIcons:function(){return t.options.controlIconsEnabled||(t.options.controlIconsEnabled=!0,i.enable(t)),t.pi},disableControlIcons:function(){return t.options.controlIconsEnabled&&(t.options.controlIconsEnabled=!1,i.disable(t)),t.pi},isControlIconsEnabled:function(){return!!t.options.controlIconsEnabled},enableDblClickZoom:function(){return t.options.dblClickZoomEnabled=!0,t.pi},disableDblClickZoom:function(){return t.options.dblClickZoomEnabled=!1,t.pi},isDblClickZoomEnabled:function(){return!!t.options.dblClickZoomEnabled},enableMouseWheelZoom:function(){return t.enableMouseWheelZoom(),t.pi},disableMouseWheelZoom:function(){return t.disableMouseWheelZoom(),t.pi},isMouseWheelZoomEnabled:function(){return!!t.options.mouseWheelZoomEnabled},setZoomScaleSensitivity:function(e){return t.options.zoomScaleSensitivity=e,t.pi},setMinZoom:function(e){return t.options.minZoom=e,t.pi},setMaxZoom:function(e){return t.options.maxZoom=e,t.pi},setBeforeZoom:function(e){return t.options.beforeZoom=null===e?null:s.proxy(e,t.publicInstance),t.pi},setOnZoom:function(e){return t.options.onZoom=null===e?null:s.proxy(e,t.publicInstance),t.pi},zoom:function(e){return t.publicZoom(e,!0),t.pi},zoomBy:function(e){return t.publicZoom(e,!1),t.pi},zoomAtPoint:function(e,o){return t.publicZoomAtPoint(e,o,!0),t.pi},zoomAtPointBy:function(e,o){return t.publicZoomAtPoint(e,o,!1),t.pi},zoomIn:function(){return this.zoomBy(1+t.options.zoomScaleSensitivity),t.pi},zoomOut:function(){return this.zoomBy(1/(1+t.options.zoomScaleSensitivity)),t.pi},getZoom:function(){return t.getRelativeZoom()},setOnUpdatedCTM:function(e){return t.options.onUpdatedCTM=null===e?null:s.proxy(e,t.publicInstance),t.pi},resetZoom:function(){return t.resetZoom(),t.pi},resetPan:function(){return t.resetPan(),t.pi},reset:function(){return t.reset(),t.pi},fit:function(){return t.fit(),t.pi},contain:function(){return t.contain(),t.pi},center:function(){return t.center(),t.pi},updateBBox:function(){return t.updateBBox(),t.pi},resize:function(){return t.resize(),t.pi},getSizes:function(){return{width:t.width,height:t.height,realZoom:t.getZoom(),viewBox:t.viewport.getViewBox()}},destroy:function(){return t.destroy(),t.pi}}),this.publicInstance};var h=[],c=function(t,e){var o=s.getSvg(t);if(null===o)return null;for(var n=h.length-1;n>=0;n--)if(h[n].svg===o)return h[n].instance.getPublicInstance();return h.push({svg:o,instance:new l(o,e)}),h[h.length-1].instance.getPublicInstance()};e.exports=c},{"./control-icons":2,"./shadow-viewport":3,"./svg-utilities":5,"./uniwheel":6,"./utilities":7}],5:[function(t,e,o){var n=t("./utilities"),i="unknown";document.documentMode&&(i="ie"),e.exports={svgNS:"http://www.w3.org/2000/svg",xmlNS:"http://www.w3.org/XML/1998/namespace",xmlnsNS:"http://www.w3.org/2000/xmlns/",xlinkNS:"http://www.w3.org/1999/xlink",evNS:"http://www.w3.org/2001/xml-events",getBoundingClientRectNormalized:function(t){if(t.clientWidth&&t.clientHeight)return{width:t.clientWidth,height:t.clientHeight};if(t.getBoundingClientRect())return t.getBoundingClientRect();throw new Error("Cannot get BoundingClientRect for SVG.")},getOrCreateViewport:function(t,e){var o=null;if(o=n.isElement(e)?e:t.querySelector(e),!o){var i=Array.prototype.slice.call(t.childNodes||t.children).filter(function(t){return"defs"!==t.nodeName&&"#text"!==t.nodeName});1===i.length&&"g"===i[0].nodeName&&null===i[0].getAttribute("transform")&&(o=i[0])}if(!o){var s="viewport-"+(new Date).toISOString().replace(/\D/g,"");o=document.createElementNS(this.svgNS,"g"),o.setAttribute("id",s);var r=t.childNodes||t.children;if(r&&r.length>0)for(var a=r.length;a>0;a--)"defs"!==r[r.length-a].nodeName&&o.appendChild(r[r.length-a]);t.appendChild(o)}var l=[];return o.getAttribute("class")&&(l=o.getAttribute("class").split(" ")),~l.indexOf("svg-pan-zoom_viewport")||(l.push("svg-pan-zoom_viewport"),o.setAttribute("class",l.join(" "))),o},setupSvgAttributes:function(t){if(t.setAttribute("xmlns",this.svgNS),t.setAttributeNS(this.xmlnsNS,"xmlns:xlink",this.xlinkNS),t.setAttributeNS(this.xmlnsNS,"xmlns:ev",this.evNS),null!==t.parentNode){var e=t.getAttribute("style")||"";e.toLowerCase().indexOf("overflow")===-1&&t.setAttribute("style","overflow: hidden; "+e)}},internetExplorerRedisplayInterval:300,refreshDefsGlobal:n.throttle(function(){for(var t=document.querySelectorAll("defs"),e=t.length,o=0;oe?(clearTimeout(a),a=null,l=h,s=t.apply(n,i),a||(n=i=null)):a||o.trailing===!1||(a=setTimeout(u,c)),s}},createRequestAnimationFrame:function(t){var e=null;return"auto"!==t&&t<60&&t>1&&(e=Math.floor(1e3/t)),null===e?window.requestAnimationFrame||n(33):n(e)}}},{}]},{},[1]); ================================================ FILE: resources/zoom_mir.js ================================================ function enable_mir_mousewheel() { var svg = svgPanZoom("#mir > svg", { controlIconsEnabled: true, zoomScaleSensitivity: 0.5, maxZoom: 50.0, minZoom: 1.0, fit: true, }); } ================================================ FILE: rust-toolchain ================================================ [toolchain] channel = "nightly-2021-03-13" components = ["miri", "rustc-dev", "llvm-tools-preview"] ================================================ FILE: src/main.rs ================================================ #![feature(rustc_private, decl_macro, plugin, try_blocks, proc_macro_hygiene)] #![feature(never_type)] #![allow(unused_attributes)] #![recursion_limit = "5000"] #![warn(rust_2018_idioms)] extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_index; extern crate rustc_interface; extern crate rustc_middle; extern crate rustc_mir; extern crate rustc_span; extern crate rustc_target; extern crate rustc_type_ir; #[macro_use] extern crate rocket; mod render; mod step; mod watch; use std::ops::FnOnce; use std::path::PathBuf; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use miri::Evaluator; use rustc_driver::Compilation; use rustc_hir::def_id::LOCAL_CRATE; use rustc_interface::interface; use rustc_middle::mir; use rustc_middle::ty::TyCtxt; use rocket::response::content::*; use rocket::response::status::BadRequest; use rocket::response::NamedFile; use rocket::State; use serde::Deserialize; use step::{step, ShouldContinue}; use crate::step::BreakpointTree; fn should_hide_stmt(stmt: &mir::Statement<'_>) -> bool { use rustc_middle::mir::StatementKind::*; match stmt.kind { StorageLive(_) | StorageDead(_) | Nop => true, _ => false, } } type InterpCx<'tcx> = rustc_mir::interpret::InterpCx<'tcx, 'tcx, Evaluator<'tcx, 'tcx>>; pub struct PrirodaContext<'a, 'tcx: 'a> { ecx: InterpCx<'tcx>, step_count: &'a mut u128, traces: watch::Traces<'tcx>, config: &'a mut Config, skip_to_main: bool, } impl<'a, 'tcx: 'a> PrirodaContext<'a, 'tcx> { fn restart(&mut self) { self.ecx = create_ecx(self.ecx.tcx.tcx); *self.step_count = 0; self.traces.clear(); // Cleanup all traces self.to_main(); } // Step to main fn to_main(&mut self) { if self.skip_to_main { let main_id = self .ecx .tcx .tcx .entry_fn(LOCAL_CRATE) .expect("no main or start function found") .0 .to_def_id(); let _ = step(self, |ecx| { let frame = ecx.frame(); if main_id == frame.instance.def_id() { ShouldContinue::Stop } else { ShouldContinue::Continue } }); } } } #[derive(Deserialize)] pub struct Config { #[serde(default = "true_bool")] auto_refresh: bool, #[serde(default = "default_theme")] theme: String, #[serde(default)] bptree: BreakpointTree, } fn true_bool() -> bool { true } fn default_theme() -> String { "default".to_string() } impl Default for Config { fn default() -> Self { ::std::fs::File::open("config.json") .map(|f| serde_json::from_reader(f).unwrap()) .unwrap_or(Config { auto_refresh: true, theme: "default".to_string(), bptree: step::BreakpointTree::default(), }) } } type RResult = Result>; fn create_ecx<'mir, 'tcx>(tcx: TyCtxt<'tcx>) -> InterpCx<'tcx> { let (main_id, _) = tcx .entry_fn(LOCAL_CRATE) .expect("no main or start function found"); miri::create_ecx( tcx, main_id.to_def_id(), miri::MiriConfig { args: vec![], communicate: true, excluded_env_vars: vec![], ignore_leaks: true, seed: None, tracked_pointer_tag: None, tracked_alloc_id: None, tracked_call_id: None, validate: true, stacked_borrows: false, check_alignment: miri::AlignmentCheck::None, track_raw: false, data_race_detector: false, cmpxchg_weak_failure_rate: 0.8, }, ) .unwrap() .0 } pub struct PrirodaSender( Mutex<::std::sync::mpsc::Sender) + Send>>>, ); impl PrirodaSender { fn do_work<'r, T, F>(&self, f: F) -> Result> where T: rocket::response::Responder<'r> + Send + 'static, F: FnOnce(&mut PrirodaContext<'_, '_>) -> T + Send + 'static, { let (tx, rx) = mpsc::sync_channel(0); let sender = self.0.lock().unwrap_or_else(|err| err.into_inner()); match sender.send(Box::new(move |pcx: &mut PrirodaContext<'_, '_>| { tx.send(f(pcx)).unwrap(); })) { Ok(()) => match rx.recv() { Ok(val) => Ok(val), Err(mpsc::RecvError) => Err(Html( "

Miri crashed please go to index

" .to_string(), )), }, Err(_) => Err(Html( "

Miri crashed too often. Please restart priroda.

" .to_string(), )), } } } #[get("/please_panic")] fn please_panic(sender: State<'_, PrirodaSender>) -> RResult<()> { sender.do_work(|_pcx| panic!("You requested a panic")) } #[cfg(not(feature = "static_resources"))] #[get("/resources/")] fn resources(path: PathBuf) -> Result { let mut res_path = PathBuf::from("./resources/"); res_path.push(path); NamedFile::open(res_path) } #[cfg(feature = "static_resources")] #[get("/resources/")] fn resources(path: PathBuf) -> Result, std::io::Error> { use rocket::http::ContentType; use std::io::{Error, ErrorKind}; match path.as_os_str().to_str() { Some("svg-pan-zoom.js") => Ok(Content( ContentType::JavaScript, include_str!("../resources/svg-pan-zoom.js"), )), Some("zoom_mir.js") => Ok(Content( ContentType::JavaScript, include_str!("../resources/zoom_mir.js"), )), Some("style-default.css") => Ok(Content( ContentType::CSS, include_str!("../resources/style-default.css"), )), Some("positioning.css") => Ok(Content( ContentType::CSS, include_str!("../resources/positioning.css"), )), _ => Err(Error::new(ErrorKind::InvalidInput, "Unknown resource")), } } #[get("/step_count")] fn step_count(sender: State<'_, PrirodaSender>) -> RResult { sender.do_work(|pcx| format!("{}", pcx.step_count)) } fn server(sender: PrirodaSender) { use rocket::config::Value; rocket::ignite() .manage(sender) .mount("/", routes![please_panic, resources, step_count]) .mount("/", render::routes::routes()) .mount("/breakpoints", step::bp_routes::routes()) .mount("/step", step::step_routes::routes()) .mount("/watch", watch::routes()) .attach(rocket::fairing::AdHoc::on_launch( "Priroda, because code has no privacy rights", |rocket| { let config = rocket.config(); if config.extras.get("spawn_browser") == Some(&Value::Boolean(true)) { let addr = format!("http://{}:{}", config.address, config.port); if open::that(&addr).is_err() { println!("open {} in your browser", addr); } } }, )) .launch(); } // Copied from miri/bin/miri.rs fn find_sysroot() -> String { if let Ok(sysroot) = std::env::var("MIRI_SYSROOT") { return sysroot; } // Taken from https://github.com/rust-lang/rust-clippy/pull/911 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME")); let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN")); match (home, toolchain) { (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain), _ => option_env!("RUST_SYSROOT") .expect("need to specify RUST_SYSROOT env var or use rustup or multirust") .to_owned(), } } struct PrirodaCompilerCalls { step_count: Arc>, config: Arc>, receiver: Arc) + Send>>>>, skip_to_main: bool, } impl rustc_driver::Callbacks for PrirodaCompilerCalls { fn after_analysis<'tcx>( &mut self, compiler: &interface::Compiler, queries: &'tcx rustc_interface::Queries<'tcx>, ) -> Compilation { compiler.session().abort_if_errors(); queries.global_ctxt().unwrap().peek_mut().enter(|tcx| { let mut step_count = self .step_count .lock() .unwrap_or_else(|err| err.into_inner()); let mut config = self.config.lock().unwrap_or_else(|err| err.into_inner()); let mut pcx = PrirodaContext { ecx: create_ecx(tcx), step_count: &mut *step_count, traces: watch::Traces::new(), config: &mut *config, skip_to_main: self.skip_to_main, }; // Whether we reset to the same place where miri crashed let mut reset = false; // Step to the position where miri crashed if it crashed for _ in 0..*pcx.step_count { reset = true; match pcx.ecx.step() { Ok(true) => {} res => panic!("Miri is not deterministic causing error {:?}", res), } } // Just ignore poisoning by panicking let receiver = self.receiver.lock().unwrap_or_else(|err| err.into_inner()); // At the very beginning, go to the start of main unless we have already crashed and are trying to reset if !reset { pcx.to_main(); } // process commands for command in receiver.iter() { command(&mut pcx); } }); compiler.session().abort_if_errors(); Compilation::Stop } } fn main() { rustc_driver::init_rustc_env_logger(); let mut args: Vec = std::env::args().collect(); // TODO: Move to a 'proper' argument parser // Maybe use xflags? let sysroot_flag = String::from("--sysroot"); if !args.contains(&sysroot_flag) { args.push(sysroot_flag); args.push(find_sysroot()); } // Use the --no-main flag to stop let stops_at_start = args .iter() .enumerate() .find(|(_, v)| v.as_str() == "--no-main") .map(|(i, _)| i); if let Some(index) = stops_at_start { // We pass these arguments to miri. // This is the lowest-effort way to not pass our custom argument to miri args.remove(index); } // Eagerly initialise syntect static // Makes highlighting performance profiles clearer render::initialise_statics(); // setup http server and similar let (sender, receiver) = mpsc::channel(); let sender = PrirodaSender(Mutex::new(sender)); let step_count = Arc::new(Mutex::new(0)); let config = Arc::new(Mutex::new(Config::default())); let handle = std::thread::spawn(move || { let args = Arc::new(args); let receiver = Arc::new(Mutex::new(receiver)); for i in 0..5 { if i != 0 { println!( "\n============== Miri crashed - restart try {} ==============\n", i ); } let step_count = step_count.clone(); let config = config.clone(); let receiver = receiver.clone(); let args = args.clone(); // Ignore result to restart in case of a crash let _ = std::thread::spawn(move || { let _ = rustc_driver::catch_fatal_errors(move || { rustc_driver::RunCompiler::new( &*args, &mut PrirodaCompilerCalls { step_count, config, receiver, skip_to_main: stops_at_start.is_none(), }, ) .run() }); }) .join(); std::thread::sleep(std::time::Duration::from_millis(200)); } println!("\n============== Miri crashed too often. Aborting ==============\n"); }); server(sender); handle.join().unwrap(); } ================================================ FILE: src/render/graphviz.rs ================================================ // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use crate::step::LocalBreakpoints; use miri::{FrameData, Tag}; use rustc_middle::mir::*; use rustc_mir::interpret::Frame; use std::fmt::{self, Debug, Write}; pub fn render_html<'tcx>( frame: &Frame<'_, '_, Tag, FrameData<'_>>, breakpoints: LocalBreakpoints<'_>, ) -> String { let mut rendered = String::new(); render_mir_svg(&frame.body, breakpoints, &mut rendered, None).unwrap(); let (block, statement_index) = if let Some(location) = frame.current_loc().ok() { (location.block, location.statement_index) } else { rendered.push_str("
Unwinding
"); return rendered; }; let (bb, stmt) = { let blck = &frame.body.basic_blocks()[block]; ( block.index() + 1, if statement_index == blck.statements.len() { if blck.statements.is_empty() { 6 } else { blck.statements.len() + 7 } } else { assert!(statement_index < blck.statements.len()); statement_index + 6 }, ) }; let edge_colors = { let blck = &frame.body.basic_blocks()[block]; let (targets, unwind) = if statement_index == blck.statements.len() { use rustc_middle::mir::TerminatorKind::*; match blck.terminator().kind { Goto { target } => (vec![target], None), SwitchInt { ref targets, .. } => (targets.all_targets().to_owned(), None), Drop { target, unwind, .. } | DropAndReplace { target, unwind, .. } => { (vec![target], unwind) } Call { ref destination, cleanup, .. } => { if let Some((_, target)) = *destination { (vec![target], cleanup) } else { (vec![], cleanup) } } _ => (vec![], None), } } else { (vec![], None) }; format!( "let edge_colors = {{{}}};", targets .into_iter() .map(|target| (block, target, "green")) .chain(unwind.into_iter().map(|target| (block, target, "red"))) .map(|(from, to, color)| format!( "'bb{}->bb{}':'{}'", from.index(), to.index(), color )) .collect::>() .join(",") ) }; rendered .write_fmt(format_args!( r##" "##, bb, stmt, edge_colors = edge_colors )) .unwrap(); rendered } /// Write a graphviz DOT graph of a list of MIRs. pub fn render_mir_svg( mir: &Body<'_>, breakpoints: LocalBreakpoints<'_>, w: &mut W, promoted: Option, ) -> fmt::Result { let mut dot = String::new(); if let Some(promoted) = promoted { writeln!(dot, "digraph promoted{} {{", promoted)?; } else { writeln!(dot, "digraph Body {{")?; } // Global graph properties writeln!(dot, r#" graph [fontname="monospace"];"#)?; writeln!(dot, r#" node [fontname="monospace"];"#)?; writeln!(dot, r#" edge [fontname="monospace"];"#)?; // Nodes for (block, _) in mir.basic_blocks().iter_enumerated() { write_node(block, mir, breakpoints, promoted, &mut dot)?; } // Edges for (source, _) in mir.basic_blocks().iter_enumerated() { write_edges(source, mir, &mut dot)?; } writeln!(dot, "}}")?; w.write_str( ::std::str::from_utf8(&::cgraph::Graph::parse(dot).unwrap().render_dot().unwrap()).unwrap(), ) } /// Write a graphviz HTML-styled label for the given basic block, with /// all necessary escaping already performed. (This is suitable for /// emitting directly, as is done in this module, or for use with the /// `LabelText::HtmlStr` from libgraphviz.) fn write_node_label( block: BasicBlock, mir: &Body<'_>, breakpoints: LocalBreakpoints<'_>, promoted: Option, w: &mut W, ) -> fmt::Result { let data = &mir[block]; write!(w, r#""#)?; // Basic block number at the top. write!( w, r#""#, blk = node(promoted, block) )?; // List of statements in the middle. if !data.statements.is_empty() { write!(w, r#"")?; } // Terminator head at the bottom, not including the list of successor blocks. Those will be // displayed as labels on the edges between blocks. let mut terminator_head = String::new(); data.terminator() .kind .fmt_head(&mut terminator_head) .unwrap(); write!( w, r#""#, escape_html(&terminator_head) )?; // Close the table writeln!(w, "
{blk}
"#)?; for (statement_index, statement) in data.statements.iter().enumerate() { if breakpoints.breakpoint_exists(Some(Location { block, statement_index, })) { write!(w, "+ ")?; } else { write!(w, "  ")?; } if crate::should_hide_stmt(statement) { write!(w, "<+>
")?; } else { write!(w, "{}
", escape(statement))?; } } write!(w, "
{}
") } /// Write a graphviz DOT node for the given basic block. fn write_node( block: BasicBlock, mir: &Body<'_>, breakpoints: LocalBreakpoints<'_>, promoted: Option, w: &mut W, ) -> fmt::Result { // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables. write!( w, r#" "{}" [shape="none", label=<"#, node(promoted, block) )?; write_node_label(block, mir, breakpoints, promoted, w)?; // Close the node label and the node itself. writeln!(w, ">];") } /// Write graphviz DOT edges with labels between the given basic block and all of its successors. fn write_edges(source: BasicBlock, mir: &Body<'_>, w: &mut W) -> fmt::Result { let terminator = mir[source].terminator(); let labels = terminator.kind.fmt_successor_labels(); for (&target, label) in terminator.successors().zip(labels) { writeln!( w, r#" {} -> {} [label="{}"];"#, node(None, source), node(None, target), label )?; } Ok(()) } fn node(promoted: Option, block: BasicBlock) -> String { if let Some(promoted) = promoted { format!("promoted{}.{}", promoted, block.index()) } else { format!("bb{}", block.index()) } } fn escape(t: &T) -> String { escape_html(&format!("{:?}", t)).into_owned() } fn escape_html(s: &str) -> ::std::borrow::Cow<'_, str> { ::rocket::http::RawStr::from_str(s).html_escape() } ================================================ FILE: src/render/locals.rs ================================================ use rustc_middle::mir::{ self, interpret::{InterpError, UndefinedBehaviorInfo}, }; use rustc_middle::ty::{subst::Subst, ParamEnv, TyKind, TypeAndMut}; use rustc_mir::interpret::{ Allocation, Frame, Immediate, InterpResult, MemPlaceMeta, OpTy, Operand, Pointer, Scalar, ScalarMaybeUninit, }; use rustc_target::abi::{Abi, Size}; use miri::{AllocExtra, Tag}; use horrorshow::prelude::*; use horrorshow::Template; use crate::InterpCx; pub fn render_locals<'tcx>( ecx: &InterpCx<'tcx>, frame: &Frame<'tcx, 'tcx, Tag, miri::FrameData<'tcx>>, ) -> String { let &Frame { ref body, ref return_place, ref instance, .. } = frame; // name ty alloc val style let locals: Vec<(String, String, Option, String, &str)> = body .local_decls .iter_enumerated() .map(|(id, local_decl)| { let name = body .var_debug_info .iter() .find(|var_debug_info| match var_debug_info.value { mir::VarDebugInfoContents::Place(place) => { place.projection.is_empty() && place.local == id } _ => false, }) .map(|var_debug_info| var_debug_info.name.as_str().to_string()) .unwrap_or_else(String::new); // FIXME Don't panic when trying to read from uninit variable. // Panic message: // > error: internal compiler error: src/librustc_mir/interpret/eval_context.rs:142: // > The type checker should prevent reading from a never-written local let op_ty = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { if id == mir::RETURN_PLACE { return_place .map(|p| ecx.place_to_op(&p).unwrap()) .ok_or(false) } else { ecx.access_local(frame, id, None).map_err(|_| false) } })) { Ok(op_ty) => op_ty, Err(_) => Err(true), }; let (alloc, val, style) = match op_ty { Err(false) => (None, "<dead>".to_owned(), "font-size: 0;"), Err(true) => (None, "<uninit>".to_owned(), "color: darkmagenta;"), Ok(op_ty) => match print_operand(ecx, op_ty) { Ok((alloc, text)) => (alloc, text, ""), Err(()) => (None, "<error>".to_owned(), "color: red;"), }, }; let ty = ecx.tcx.normalize_erasing_regions( ParamEnv::reveal_all(), local_decl.ty.subst(ecx.tcx.tcx, instance.substs), ); (name, ty.to_string(), alloc, val, style) }) .collect(); let (arg_count, var_count, tmp_count) = ( body.args_iter().count(), body.vars_iter().count(), body.temps_iter().count(), ); (horrorshow::html! { table(border="1") { tr { td(width="20px"); th { : "id" } th { : "name" } th { : "alloc" } th { : "memory" } th { : "type" } } @ for (i, &(ref name, ref ty, alloc, ref text, ref style)) in locals.iter().enumerate() { tr(style=style) { @if i == 0 { th(rowspan=1) { span(class="vertical") { : "Return" } } } else if i == 1 && arg_count != 0 { th(rowspan=arg_count) { span(class="vertical") { : "Arguments" } } } else if i == arg_count + 1 && var_count != 0 { th(rowspan=var_count) { span(class="vertical") { : "Variables" } } } else if i == var_count + arg_count + 1 && tmp_count != 0 { th(rowspan=tmp_count) { span(class="vertical") { : "Temporaries" } } } td { : format!("_{}", i) } td { : name } @if let Some(alloc) = alloc { td { : alloc.to_string() } } else { td; } td { : Raw(text) } td { : ty } } } } }).into_string() .unwrap() } fn print_scalar_maybe_undef(val: ScalarMaybeUninit) -> String { match val { ScalarMaybeUninit::Uninit => "<undef >".to_string(), ScalarMaybeUninit::Scalar(val) => print_scalar(val), } } fn print_scalar(val: Scalar) -> String { match val { Scalar::Ptr(ptr) => format!( "Pointer({alloc})[{offset}]", alloc = ptr.alloc_id.0, offset = ptr.offset.bytes() ), Scalar::Int(int) => { if int.size().bytes() == 0 { // Can't use `Debug` impl directly because it would be unescaped "<zst>".to_string() } else { format!("0x{:X}", int) } } } } fn pp_operand<'tcx>( ecx: &InterpCx<'tcx>, op_ty: OpTy<'tcx, miri::Tag>, ) -> InterpResult<'tcx, String> { let err = || InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(String::new())); match op_ty.layout.ty.kind() { TyKind::RawPtr(TypeAndMut { ty, .. }) | TyKind::Ref(_, ty, _) if matches!(ty.kind(), TyKind::Str) => { if let Operand::Immediate(val) = *op_ty { if let Immediate::ScalarPair( ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)), ScalarMaybeUninit::Scalar(Scalar::Int(int)), ) = val { if let Ok(allocation) = ecx.memory.get_raw(ptr.alloc_id) { let offset = ptr.offset.bytes(); if (offset as u128) < allocation.len() as u128 { let start = offset as usize; let len = int.assert_bits(int.size()); let end = start.checked_add(len as usize).ok_or(err())?; let alloc_bytes = &allocation .inspect_with_uninit_and_ptr_outside_interpreter(start..end); let s = String::from_utf8_lossy(alloc_bytes); return Ok(format!("\"{}\"", s)); } } } } } TyKind::Adt(adt_def, _substs) => { if let Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Uninit)) = *op_ty { Err(err())?; } let variant = ecx.read_discriminant(&op_ty)?.1; let adt_fields = &adt_def.variants[variant].fields; let should_collapse = adt_fields.len() > 1; //println!("{:?} {:?} {:?}", val, ty, adt_def.variants); let mut pretty = ecx .tcx .def_path_str(adt_def.did) .replace("<", "<") .replace(">", ">") .to_string(); if adt_def.is_enum() { pretty.push_str("::"); pretty.push_str(&*adt_def.variants[variant].ident.as_str()); } pretty.push_str(" { "); if should_collapse { pretty.push_str("
"); } for (i, adt_field) in adt_fields.iter().enumerate() { let field_pretty: InterpResult<'_, String> = try { let field_op_ty = ecx.operand_field(&op_ty, i as usize)?; pp_operand(ecx, field_op_ty)? }; pretty.push_str(&format!( "{}: {}, ", adt_field.ident.as_str(), match field_pretty { Ok(field_pretty) => field_pretty, Err(_err) => "<err>".to_string(), } )); if should_collapse { pretty.push_str("
"); } } if should_collapse { pretty.push_str("
"); } pretty.push_str("}"); println!("pretty adt: {}", pretty); return Ok(pretty); } _ => {} } if op_ty.layout.size.bytes() == 0 { Err(err())?; } if let Abi::Scalar(_) = op_ty.layout.abi { } else { Err(err())?; } let scalar = ecx.read_scalar(&op_ty)?; if let ScalarMaybeUninit::Scalar(Scalar::Ptr(_)) = &scalar { return Ok(print_scalar_maybe_undef(scalar)); // If the value is a ptr, print it } match op_ty.layout.ty.kind() { TyKind::Bool => { if scalar.to_bool()? { Ok("true".to_string()) } else { Ok("false".to_string()) } } TyKind::Char => { let chr = scalar.to_char()?; if chr.is_ascii() { Ok(format!("'{}'", chr)) } else { Err(err().into()) } } TyKind::Uint(_) => Ok(format!("{0}", scalar.to_u64()?)), TyKind::Int(_) => Ok(format!("{0}", scalar.to_i64()?)), TyKind::Float(float_ty) => match float_ty { rustc_type_ir::FloatTy::F32 => Ok(format!("{}", scalar.to_f32()?)), rustc_type_ir::FloatTy::F64 => Ok(format!("{}", scalar.to_f64()?)), }, _ => Err(err().into()), } } pub fn print_operand<'a, 'tcx: 'a>( ecx: &InterpCx<'tcx>, op_ty: OpTy<'tcx, miri::Tag>, ) -> Result<(Option, String), ()> { let pretty = pp_operand(ecx, op_ty); let (alloc, txt) = match *op_ty { Operand::Indirect(place) => { let size: u64 = op_ty.layout.size.bytes(); if place.meta == MemPlaceMeta::None { let ptr = place.to_ref().to_scalar().unwrap(); if ptr.is_ptr() { let (alloc, txt, _len) = print_ptr(ecx, ptr.assert_ptr(), Some(size))?; (alloc, txt) } else { (None, format!("{:?}", ptr)) } } else { (None, format!("{:?}", place)) // FIXME better printing for unsized locals } } Operand::Immediate(Immediate::Scalar(scalar)) => (None, print_scalar_maybe_undef(scalar)), Operand::Immediate(Immediate::ScalarPair(val, extra)) => ( None, format!( "{}, {}", print_scalar_maybe_undef(val), print_scalar_maybe_undef(extra) ), ), }; let txt = if let Ok(pretty) = pretty { format!("{} ({})", pretty, txt) } else { txt }; Ok((alloc, txt)) } pub fn print_ptr( ecx: &InterpCx<'_>, ptr: Pointer, size: Option, ) -> Result<(Option, String, u64), ()> { if let Ok(alloc) = ecx.memory.get_raw(ptr.alloc_id) { let s = print_alloc(ecx.tcx.data_layout.pointer_size.bytes(), ptr, alloc, size); debug_assert!(ecx.memory.get_fn(ptr.into()).is_err()); Ok((Some(ptr.alloc_id.0), s, alloc.len() as u64)) } else if let Ok(_) = ecx.memory.get_fn(ptr.into()) { // FIXME: print function name Ok((None, "function pointer".to_string(), 16)) } else { Err(()) } } pub fn print_alloc( ptr_size: u64, ptr: Pointer, alloc: &Allocation, size: Option, ) -> String { use std::fmt::Write; let end = size .map(|s| s + ptr.offset.bytes()) .unwrap_or(alloc.len() as u64); let mut s = String::new(); let mut i = ptr.offset.bytes(); while i < end { if let Some((_tag, reloc)) = alloc.relocations().get(&Size::from_bytes(i)) { i += ptr_size; write!(&mut s, "┠{nil:─", alloc = reloc, offset = ptr.offset.bytes(), nil = "", wdt = (ptr_size * 2 - 2) as usize, ).unwrap(); } else { if alloc .init_mask() .is_range_initialized(Size::from_bytes(i), Size::from_bytes(i + 1)) .is_ok() { let byte = alloc .inspect_with_uninit_and_ptr_outside_interpreter(i as usize..i as usize + 1)[0]; write!(&mut s, "{:02x}", byte).unwrap(); } else { let ub_chars = [ '∅', '∆', '∇', '∓', '∞', '⊙', '⊠', '⊘', '⊗', '⊛', '⊝', '⊡', '⊠', ]; let c1 = (ptr.alloc_id.0 * 769 + i as u64 * 5689) as usize % ub_chars.len(); let c2 = (ptr.alloc_id.0 * 997 + i as u64 * 7193) as usize % ub_chars.len(); write!(&mut s, "{}{}", ub_chars[c1], ub_chars[c2]).unwrap(); } i += 1; } } s } ================================================ FILE: src/render/mod.rs ================================================ mod graphviz; pub mod locals; mod source; pub use source::initialise_statics; use rustc_hir::definitions::DefPathData; use rustc_mir::interpret::{AllocId, Machine, Pointer}; use rustc_target::abi::Size; use horrorshow::{Raw, Template}; use rocket::response::content::Html; use crate::step::Breakpoint; use crate::PrirodaContext; pub fn template(pcx: &PrirodaContext<'_, '_>, title: String, t: impl Template) -> Html { let mut buf = String::new(); (horrorshow::html! { html { head { title { : title } meta(charset = "UTF-8") {} script(src="/resources/svg-pan-zoom.js") {} script(src="/resources/zoom_mir.js") {} : Raw(refresh_script(pcx)) } body(onload="enable_mir_mousewheel()") { link(rel="stylesheet", href="/resources/positioning.css"); link(rel="stylesheet", href=format!("/resources/style-{}.css", pcx.config.theme)); : t } } }) .write_to_string(&mut buf) .unwrap(); Html(buf) } pub fn refresh_script(pcx: &PrirodaContext<'_, '_>) -> String { if pcx.config.auto_refresh { r#""# .replace("#step_count#", &format!("{}", pcx.step_count)) } else { String::new() } } pub fn render_main_window( pcx: &PrirodaContext<'_, '_>, display_frame: Option, message: String, ) -> Html { let is_active_stack_frame = match display_frame { Some(n) => n == Machine::stack(&pcx.ecx).len() - 1, None => true, }; let frame = display_frame .and_then(|frame| Machine::stack(&pcx.ecx).get(frame)) .or_else(|| Machine::stack(&pcx.ecx).last()); let stack: Vec<(String, String, String)> = Machine::stack(&pcx.ecx) .iter() .map(|frame| { let instance = &frame.instance; let span = frame.current_source_info().unwrap().span; let name = if pcx .ecx .tcx .def_key(instance.def_id()) .disambiguated_data .data == DefPathData::ClosureExpr { "inside call to closure".to_string() } else { instance.to_string() }; let span = self::source::pretty_src_path(span); (name, span, format!("{:?}", instance.def_id())) }) .collect(); let rendered_breakpoints: Vec = pcx .config .bptree .iter() .map(|&Breakpoint(def_id, bb, stmt)| format!("{:?}@{}:{}", def_id, bb.index(), stmt)) .collect(); let rendered_locals = frame .map(|frame| locals::render_locals(&pcx.ecx, frame)) .unwrap_or_else(String::new); let rendered_source = source::render_source(pcx.ecx.tcx.tcx, frame); let mir_graph = frame.map(|frame| { graphviz::render_html(frame, pcx.config.bptree.for_def_id(frame.instance.def_id())) }); let filename = pcx .ecx .tcx .sess .local_crate_source_file .as_ref() .map(|f| f.display().to_string()) .unwrap_or_else(|| "no file name".to_string()); template( pcx, filename, horrorshow::html! { div(id="left") { div(id="commands") { @ if is_active_stack_frame { a(href="/step/single") { div(title="Execute next MIR statement/terminator") { : "Step" } } a(href="/step/next") { div(title="Run until after the next MIR statement/terminator") { : "Next" } } a(href="/step/return") { div(title="Run until the function returns") { : "Return" } } a(href="/step/single_back") { div(title="Execute previous MIR statement/terminator (restarts and steps till one stmt before the current stmt)") { : "Step back (slow)" } } a(href="/step/continue") { div(title="Run until termination or breakpoint") { : "Continue" } } a(href="/step/restart") { div(title="Abort execution and restart") { : "Restart" } } a(href="/breakpoints/add_here") { div(title="Add breakpoint at current location") { : "Add breakpoint here"} } a(href="/breakpoints/remove_all") { div(title="Remove all breakpoints") { : "Remove all breakpoints"} } } else { a(href="/") { div(title="Go to active stack frame") { : "Go back to active stack frame" } } } } div(id="messages") { p { : message } } div(id="mir") { : Raw(mir_graph.unwrap_or_else(|| "no current function".to_string())) } } div(id="right") { div { : format!("Step count: {}", pcx.step_count); } div(id="stack") { table(border="1") { @ for (i, &(ref s, ref span, ref def_id)) in stack.iter().enumerate().rev() { tr { @ if i == display_frame.unwrap_or(stack.len() - 1) { td { : Raw("→") } } else { td; } td { : s } td { : span } td { : def_id } @ if i == display_frame.unwrap_or(stack.len() - 1) { td; } else { td { a(href=format!("/frame/{}", i)) { : "View" } } } } } } } div(id="breakpoints") { : "Breakpoints: "; br; table(border="1") { @ for bp in rendered_breakpoints { tr { td { : &bp } td { a(href=format!("/breakpoints/remove/{}", bp)) { : "remove" } } } } } } div(id="locals") { : Raw(rendered_locals) } div(id="source") { : rendered_source } } }, ) } pub fn render_reverse_ptr(pcx: &PrirodaContext<'_, '_>, alloc_id: u64) -> Html { let allocs: Vec<_> = pcx.ecx.memory.alloc_map().iter(|values| { values .filter_map(|(&id, (_kind, alloc))| { alloc .relocations() .values() .find(|&&(_tag, reloc)| reloc == id) .map(|_| id) }) .collect() }); template( pcx, format!("Allocations with pointers to Allocation {}", alloc_id), horrorshow::html! { @for id in allocs { a(href=format!("/ptr/{}", id)) { : format!("Allocation {}", id) } br; } }, ) } pub fn render_ptr_memory( pcx: &PrirodaContext<'_, '_>, alloc_id: AllocId, offset: u64, ) -> Html { let (mem, offset, rest) = if let Ok((_, mem, bytes)) = locals::print_ptr( &pcx.ecx, Pointer::new(alloc_id, Size::from_bytes(offset)) .with_tag(miri::Tag::Untagged) .into(), None, ) { if bytes * 2 > offset { (mem, offset, (bytes * 2 - offset - 1) as usize) } else if bytes * 2 == 0 && offset == 0 { (mem, 0, 0) } else { ("out of bounds offset".to_string(), 0, 0) } } else { ("unknown memory".to_string(), 0, 0) }; template( pcx, format!("Allocation {}", alloc_id), horrorshow::html! { span(style="font-family: monospace") { : format!("{nil:. ::rocket::request::FromRequest<'a, 'r> for FlashString { type Error = !; fn from_request(request: &'a rocket::Request<'r>) -> rocket::request::Outcome { rocket::Outcome::Success(FlashString( Option::>::from_request(request)? .map(|flash| flash.msg().to_string()) .unwrap_or_else(String::new), )) } } pub mod routes { use super::*; use crate::*; pub fn routes() -> Vec<::rocket::Route> { routes![index, frame, frame_invalid, ptr, reverse_ptr] } #[get("/")] pub fn index( sender: rocket::State<'_, crate::PrirodaSender>, flash: FlashString, ) -> crate::RResult> { sender.do_work(move |pcx| render::render_main_window(pcx, None, flash.0)) } #[get("/frame/")] pub fn frame( sender: rocket::State<'_, crate::PrirodaSender>, flash: FlashString, frame: usize, ) -> crate::RResult> { sender.do_work(move |pcx| render::render_main_window(pcx, Some(frame), flash.0)) } #[get("/frame/", rank = 42)] // Error handler fn frame_invalid(frame: String) -> BadRequest { BadRequest(Some(format!( "not a number: {:?}", frame.parse::().unwrap_err() ))) } #[get("/ptr//")] pub fn ptr( sender: rocket::State<'_, crate::PrirodaSender>, alloc_id: u64, offset: u64, ) -> crate::RResult> { sender.do_work(move |pcx| render::render_ptr_memory(pcx, AllocId(alloc_id), offset)) } #[get("/reverse_ptr/")] fn reverse_ptr( sender: rocket::State<'_, crate::PrirodaSender>, ptr: u64, ) -> crate::RResult> { sender.do_work(move |pcx| render::render_reverse_ptr(pcx, ptr)) } } ================================================ FILE: src/render/source.rs ================================================ use std::collections::HashMap; use std::{cell::RefCell, ops::Range}; use miri::{FrameData, Tag}; use rustc_middle::ty::TyCtxt; use rustc_mir::interpret::Frame; use rustc_span::Span; use horrorshow::prelude::*; use syntect::easy::HighlightLines; use syntect::highlighting::{Style, ThemeSet}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::parsing::SyntaxSet; use syntect::util::{split_at, LinesWithEndings}; lazy_static::lazy_static! { static ref SYNTAX_SET: SyntaxSet = SyntaxSet::load_defaults_nonewlines(); static ref THEME_SET: ThemeSet = ThemeSet::load_defaults(); static ref RUST_SOURCE: regex::Regex = regex::Regex::new("/rustc/\\w+/").unwrap(); static ref STD_SRC: Option = { if let Ok(output) = std::process::Command::new("rustc").arg("--print").arg("sysroot").output() { if let Ok(sysroot) = String::from_utf8(output.stdout) { Some(sysroot.trim().to_string() + "/lib/rustlib/src/rust/") } else { None } } else { None } }; } pub fn initialise_statics() { let _ = (&*SYNTAX_SET, &*THEME_SET); } pub fn pretty_src_path(span: Span) -> String { let span = format!("{:?}", span); let span = RUST_SOURCE.replace(span.as_ref(), "/").to_string(); if let Some(std_src) = &*STD_SRC { span.replace(std_src, "/") } else { span } } thread_local! { // This is a thread local, because a `Span` is only valid within one thread static CACHED_HIGHLIGHTED_FILES: RefCell> = { RefCell::new(HashMap::new()) }; } pub struct HighlightCacheEntry { pub string: String, pub highlighted: Vec<(Style, Range)>, } pub fn render_source( tcx: TyCtxt<'_>, frame: Option<&Frame<'_, '_, Tag, FrameData<'_>>>, ) -> Box { let before_time = ::std::time::Instant::now(); if frame.is_none() { return Box::new(FnRenderer::new(|_| {})); } let frame = frame.unwrap(); let mut instr_spans = if let Some(location) = frame.current_loc().ok() { let stmt = location.statement_index; let block = location.block; if stmt == frame.body[block].statements.len() { vec![frame.body[block].terminator().source_info.span] } else { vec![frame.body[block].statements[stmt].source_info.span] } } else { vec![frame.body.span] }; // Get the original macro caller while let Some(span) = instr_spans .last() .unwrap() .macro_backtrace() .next() .map(|b| b.call_site) { instr_spans.push(span); } let highlighted_sources = instr_spans .into_iter() .rev() .map(|sp| { let (src, lo, hi) = match get_file_source_for_span(tcx, sp) { Ok(res) => res, Err(err) => return (format!("{:?}", sp), err), }; CACHED_HIGHLIGHTED_FILES.with(|highlight_cache| { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); src.hash(&mut hasher); let hash = hasher.finish(); let mut cache = highlight_cache.borrow_mut(); let entry = cache.entry(hash).or_insert_with(|| { let before_time = ::std::time::Instant::now(); let highlighted = syntax_highlight(&src); let after_time = ::std::time::Instant::now(); println!("h: {:?}", after_time - before_time); HighlightCacheEntry { string: src, highlighted, } }); ( pretty_src_path(sp), mark_span(&entry.string, &entry.highlighted, lo, hi), ) }) }) .collect::>(); let after_time = ::std::time::Instant::now(); println!("s: {:?}", after_time - before_time); let style = if let Some(bg_color) = THEME_SET.themes["Solarized (dark)"].settings.background { format!( "background-color: #{:02x}{:02x}{:02x}; display: block;", bg_color.r, bg_color.g, bg_color.b ) } else { String::new() }; horrorshow::box_html! { pre { code(id="the_code", style=style) { @ for (sp, source) in highlighted_sources { span(style = "color: aqua;") { :sp; br; } : Raw(source); br; br; } } } } } fn get_file_source_for_span(tcx: TyCtxt<'_>, sp: Span) -> Result<(String, usize, usize), String> { let source_map = tcx.sess.source_map(); let _ = source_map.span_to_snippet(sp); // Ensure file src is loaded let src = if let Ok(file_lines) = source_map.span_to_lines(sp) { if let Some(ref src) = file_lines.file.src { src.to_string() } else if let Some(src) = file_lines.file.external_src.borrow().get_source() { src.to_string() } else { return Err("".to_string()); } } else { return Err("".to_string()); }; let lo = source_map.bytepos_to_file_charpos(sp.lo()).0; let hi = source_map.bytepos_to_file_charpos(sp.hi()).0; Ok((src, lo, hi)) } fn syntax_highlight<'a, 's>(src: &'s str) -> Vec<(Style, Range)> { let theme = &THEME_SET.themes["Solarized (dark)"]; let mut h = HighlightLines::new( &SYNTAX_SET .find_syntax_by_extension("rs") .unwrap() .to_owned(), theme, ); let mut index = 0; let mut highlighted = Vec::new(); for line in LinesWithEndings::from(src) { highlighted.extend( h.highlight(line, &SYNTAX_SET) .into_iter() .map(|(style, str)| { let idx = index; index += str.len(); (style, idx..index) }), ); } highlighted } fn mark_span(file_contents: &str, src: &[(Style, Range)], lo: usize, hi: usize) -> String { let src = src .iter() .map(|(style, range)| (*style, &file_contents[range.clone()])) .collect::>(); let (before, with) = split_at(&src, lo); let (it, after) = split_at(&with, hi - lo); let before = styled_line_to_highlighted_html(&before, IncludeBackground::No); let it = styled_line_to_highlighted_html(&it, IncludeBackground::No); let after = styled_line_to_highlighted_html(&after, IncludeBackground::No); if lo == hi { assert_eq!(it.len(), 0); format!("{}{}", before, after) } else { assert_ne!(it.len(), 0); format!("{}{}{}", before, it, after) } } ================================================ FILE: src/step.rs ================================================ use rustc_hir::def_id::{CrateNum, DefId, DefIndex}; use rustc_index::vec::Idx; use rustc_middle::mir; use rustc_mir::interpret::Machine; use std::collections::{HashMap, HashSet}; use std::iter::Iterator; use miri::*; use serde::de::{Deserialize, Deserializer, Error as SerdeError}; use crate::{InterpCx, PrirodaContext}; pub enum ShouldContinue { Continue, Stop, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct Breakpoint(pub DefId, pub mir::BasicBlock, pub usize); #[derive(Default)] pub struct BreakpointTree(HashMap>); impl<'de> Deserialize<'de> for BreakpointTree { fn deserialize>(deser: D) -> Result { let mut map = HashMap::new(); for (k, v) in HashMap::>::deserialize(deser)? { let def_id = parse_def_id(&k).map_err(SerdeError::custom)?; map.insert( def_id, v.into_iter() .map(|(bb, instr)| Breakpoint(def_id, mir::BasicBlock::new(bb), instr)) .collect::>(), ); } Ok(BreakpointTree(map)) } } impl BreakpointTree { pub fn add_breakpoint(&mut self, bp: Breakpoint) { self.0.entry(bp.0).or_insert_with(HashSet::new).insert(bp); } pub fn remove_breakpoint(&mut self, bp: Breakpoint) -> bool { self.0 .get_mut(&bp.0) .map(|local| local.remove(&bp)) .unwrap_or(false) } pub fn remove_all(&mut self) { self.0.clear(); } pub fn for_def_id(&self, def_id: DefId) -> LocalBreakpoints<'_> { if let Some(bps) = self.0.get(&def_id) { LocalBreakpoints::SomeBps(bps) } else { LocalBreakpoints::NoBp } } pub fn is_at_breakpoint(&self, ecx: &InterpCx<'_>) -> bool { let frame = ecx.frame(); self.for_def_id(frame.instance.def_id()) .breakpoint_exists(frame.current_loc().ok()) } pub fn iter(&self) -> impl Iterator { self.0.values().flat_map(|local| local.iter()) } } #[derive(Copy, Clone)] pub enum LocalBreakpoints<'a> { NoBp, SomeBps(&'a HashSet), } impl<'a> LocalBreakpoints<'a> { pub fn breakpoint_exists(self, location: Option) -> bool { if let Some(location) = location { match self { LocalBreakpoints::NoBp => false, LocalBreakpoints::SomeBps(bps) => bps .iter() .any(|bp| bp.1 == location.block && bp.2 == location.statement_index), } } else { // Unwinding, but no cleanup for this frame // FIXME make this configurable false } } } pub fn step(pcx: &mut PrirodaContext<'_, '_>, continue_while: F) -> String where F: Fn(&InterpCx<'_>) -> ShouldContinue, { let mut message = None; let ret: InterpResult<'_, _> = try { loop { let is_main_thread_active = pcx.ecx.get_active_thread() == 0.into(); if is_main_thread_active && Machine::stack(&pcx.ecx).len() <= 1 && is_ret(&pcx.ecx) { // When the main thread exists, the program terminates. However, // we want to prevent stepping out of the program. break; } match pcx.ecx.schedule()? { SchedulingAction::ExecuteStep => {} SchedulingAction::ExecuteTimeoutCallback => { pcx.ecx.run_timeout_callback()?; continue; } SchedulingAction::ExecuteDtors => { // This will either enable the thread again (so we go back // to `ExecuteStep`), or determine that this thread is done // for good. pcx.ecx.schedule_next_tls_dtor_for_active_thread()?; continue; } SchedulingAction::Stop => { message = Some("interpretation finished".to_string()); break; } } let info = pcx.ecx.preprocess_diagnostics(); if !pcx.ecx.step()? { message = Some("a terminated thread was scheduled for execution".to_string()); break; } pcx.ecx.process_diagnostics(info); *pcx.step_count += 1; crate::watch::step_callback(pcx); if let Some(frame) = Machine::stack(&pcx.ecx).last() { if let Some(location) = frame.current_loc().ok() { let blck = &frame.body.basic_blocks()[location.block]; if location.statement_index != blck.statements.len() && crate::should_hide_stmt(&blck.statements[location.statement_index]) && !pcx.config.bptree.is_at_breakpoint(&pcx.ecx) { continue; } } else { // Unwinding, but no cleanup for this frame // FIXME make step behaviour configurable } } if let ShouldContinue::Stop = continue_while(&pcx.ecx) { break; } if pcx.config.bptree.is_at_breakpoint(&pcx.ecx) { break; } } }; match ret { Err(e) => { message = Some(format!("{:?}", e)); } Ok(_) => {} } message.unwrap_or_else(String::new) } pub fn is_ret(ecx: &InterpCx<'_>) -> bool { if let Some(frame) = Machine::stack(&ecx).last() { if let Some(location) = frame.current_loc().ok() { let basic_block = &frame.body.basic_blocks()[location.block]; match basic_block.terminator().kind { rustc_middle::mir::TerminatorKind::Return | rustc_middle::mir::TerminatorKind::Resume => { location.statement_index >= basic_block.statements.len() } _ => false, } } else { true // Unwinding, but no cleanup necessary for current frame } } else { true } } fn parse_breakpoint_from_url(s: &str) -> Result { let regex = ::regex::Regex::new(r#"([^@]+)@(\d+):(\d+)"#).unwrap(); // DefId(1:14824 ~ mycrate::main)@1:3 // ^ ^ ^ ^ // | | | statement // | | BasicBlock // | DefIndex::as_array_index() // CrateNum let s = s.replace("%20", " "); let caps = regex .captures(&s) .ok_or_else(|| format!("Invalid breakpoint {}", s))?; // Parse DefId let def_id = parse_def_id(caps.get(1).unwrap().as_str())?; // Parse block and stmt let bb = mir::BasicBlock::new( caps.get(2) .unwrap() .as_str() .parse::() .map_err(|_| "block id is not a positive integer")?, ); let stmt = caps .get(3) .unwrap() .as_str() .parse::() .map_err(|_| "stmt id is not a positive integer")?; Ok(Breakpoint(def_id, bb, stmt)) } fn parse_def_id(s: &str) -> Result { let regex = ::regex::Regex::new(r#"DefId\((\d+):(\d+) ~ [^\)]+\)"#).unwrap(); let caps = regex .captures(&s) .ok_or_else(|| format!("Invalid def_id {}", s))?; let crate_num = CrateNum::new(caps.get(1).unwrap().as_str().parse::().unwrap()); let index = caps .get(2) .unwrap() .as_str() .parse::() .map_err(|_| "index is not a positive integer".to_string())?; let def_index = DefIndex::from_usize(index); Ok(DefId { krate: crate_num, index: def_index, }) } pub mod step_routes { use rocket::response; use super::*; pub fn routes() -> Vec<::rocket::Route> { routes![restart, single, single_back, next, return_, continue_] } #[get("/restart")] fn restart( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { pcx.restart(); response::Flash::success(response::Redirect::to("/"), "restarted") }) } #[get("/single")] fn single( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { response::Flash::success( response::Redirect::to("/"), step(pcx, |_ecx| ShouldContinue::Stop), ) }) } #[get("/single_back")] fn single_back( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { let orig_step_count = *pcx.step_count; pcx.restart(); *pcx.step_count = orig_step_count; let msg = if *pcx.step_count > 0 { *pcx.step_count -= 1; for _ in 0..*pcx.step_count { match pcx.ecx.step() { Ok(true) => crate::watch::step_callback(pcx), // Rebuild traces till the current instruction res => { return response::Flash::warning( response::Redirect::to("/"), format!("Miri is not deterministic causing error {:?}", res), ) } } } "stepped back".to_string() } else { "already at the start".to_string() }; response::Flash::success(response::Redirect::to("/"), msg) }) } #[get("/next")] fn next( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { let frame = Machine::stack(&pcx.ecx).len(); let (block, stmt): (Option, _) = if let Some(location) = pcx.ecx.frame().current_loc().ok() { (Some(location.block), Some(location.statement_index)) } else { (None, None) }; let msg = step(pcx, move |ecx| { let (curr_block, curr_stmt) = if let Some(location) = ecx.frame().current_loc().ok() { (Some(location.block), Some(location.statement_index)) } else { (None, None) }; if Machine::stack(&ecx).len() <= frame && (block < curr_block || stmt < curr_stmt) { ShouldContinue::Stop } else { ShouldContinue::Continue } }); response::Flash::success(response::Redirect::to("/"), msg) }) } #[get("/return")] fn return_( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { let frame = Machine::stack(&pcx.ecx).len(); let msg = step(pcx, |ecx| { if Machine::stack(&ecx).len() <= frame && is_ret(&ecx) { ShouldContinue::Stop } else { ShouldContinue::Continue } }); response::Flash::success(response::Redirect::to("/"), msg) }) } #[get("/continue")] fn continue_( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { response::Flash::success( response::Redirect::to("/"), step(pcx, |_ecx| ShouldContinue::Continue), ) }) } } pub mod bp_routes { use super::*; use std::path::PathBuf; pub fn routes() -> Vec<::rocket::Route> { routes![add_here, add, remove, remove_all] } #[get("/add_here")] pub fn add_here( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { let frame = pcx.ecx.frame(); let msg = if let Some(location) = frame.current_loc().ok() { pcx.config.bptree.add_breakpoint(Breakpoint( frame.instance.def_id(), location.block, location.statement_index, )); format!( "Breakpoint added for {:?}@{}:{}", frame.instance.def_id(), location.block.index(), location.statement_index ) } else { format!("Can't set breakpoint for unwinding without cleanup yet") }; rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg) }) } #[get("/add/")] pub fn add( sender: rocket::State<'_, crate::PrirodaSender>, path: PathBuf, ) -> crate::RResult> { sender.do_work(move |pcx| { let path = path.to_string_lossy(); let res = parse_breakpoint_from_url(&path); let msg = match res { Ok(breakpoint) => { pcx.config.bptree.add_breakpoint(breakpoint); format!( "Breakpoint added for {:?}@{}:{}", breakpoint.0, breakpoint.1.index(), breakpoint.2 ) } Err(e) => e, }; rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg) }) } #[get("/remove/")] pub fn remove( sender: rocket::State<'_, crate::PrirodaSender>, path: PathBuf, ) -> crate::RResult> { sender.do_work(move |pcx| { let path = path.to_string_lossy(); let res = parse_breakpoint_from_url(&path); let msg = match res { Ok(breakpoint) => { if pcx.config.bptree.remove_breakpoint(breakpoint) { format!( "Breakpoint removed for {:?}@{}:{}", breakpoint.0, breakpoint.1.index(), breakpoint.2 ) } else { format!( "No breakpoint for for {:?}@{}:{}", breakpoint.0, breakpoint.1.index(), breakpoint.2 ) } } Err(e) => e, }; rocket::response::Flash::success(rocket::response::Redirect::to("/"), msg) }) } #[get("/remove_all")] pub fn remove_all( sender: rocket::State<'_, crate::PrirodaSender>, ) -> crate::RResult> { sender.do_work(move |pcx| { pcx.config.bptree.remove_all(); rocket::response::Flash::success( rocket::response::Redirect::to("/"), "All breakpoints removed", ) }) } } ================================================ FILE: src/watch/mod.rs ================================================ use std::collections::HashMap; use std::fmt::Write; use rustc_middle::mir::interpret::{Allocation, Pointer, PointerArithmetic}; use rustc_middle::ty::Instance; use rustc_mir::interpret::AllocId; use rustc_target::abi::Size; use crate::*; mod stack_trace; #[derive(Debug)] pub struct Traces<'tcx> { alloc_traces: HashMap, stack_traces_cpu: Vec<(Vec<(Instance<'tcx>,)>, u128)>, stack_traces_mem: Vec<(Vec<(Instance<'tcx>,)>, u128)>, } impl<'tcx> Traces<'tcx> { pub fn new() -> Self { let alloc_traces = HashMap::new(); //for i in 0..700 { // alloc_traces.insert(AllocId(i), AllocTrace::new()); //} Traces { alloc_traces, stack_traces_cpu: Vec::new(), stack_traces_mem: Vec::new(), } } /// Clear the traces. This should be called before restarting the evaluation. pub fn clear(&mut self) { // We have to replace all values of alloc_traces by empty AllocTraces, // because stepping back will change the alloc id's self.alloc_traces.clear(); // We can just empty the stack traces, because they will be rebuild during stepping self.stack_traces_cpu.clear(); self.stack_traces_mem.clear(); } } #[derive(Debug)] struct AllocTrace { trace_points: Vec<(u128, AllocTracePoint)>, } impl AllocTrace { fn new() -> Self { AllocTrace { trace_points: Vec::new(), } } } #[derive(Debug)] enum AllocTracePoint { Changed(Allocation), Deallocated, } fn eq_alloc( a: &Allocation, b: &Allocation, ) -> bool { let Allocation { align: a_align, mutability: a_mut, extra: _, size: a_size, .. } = a; let Allocation { align: b_align, mutability: b_mut, extra: _, size: b_size, .. } = b; a_align == b_align && a_mut == b_mut && a_size == b_size && a.inspect_with_uninit_and_ptr_outside_interpreter(0..a.len()) == b.inspect_with_uninit_and_ptr_outside_interpreter(0..b.len()) && a.relocations() == b.relocations() && a.init_mask() == b.init_mask() } pub fn step_callback(pcx: &mut PrirodaContext<'_, '_>) { { let ecx = &pcx.ecx; let traces = &mut pcx.traces; // Collect alloc traces for (alloc_id, alloc_trace) in &mut traces.alloc_traces { if let Ok(alloc) = ecx.memory.get_raw(*alloc_id) { if let Some(&(prev_step_count, AllocTracePoint::Changed(ref prev_alloc))) = alloc_trace.trace_points.last() { if eq_alloc(alloc, prev_alloc) || *pcx.step_count == prev_step_count { continue; } } alloc_trace .trace_points .push((*pcx.step_count, AllocTracePoint::Changed(alloc.clone()))); } else if !matches!( alloc_trace.trace_points.last(), Some(&(_, AllocTracePoint::Deallocated)) ) && !alloc_trace.trace_points.is_empty() { alloc_trace .trace_points .push((*pcx.step_count, AllocTracePoint::Deallocated)); } } } stack_trace::step_callback(pcx); } pub fn routes() -> Vec<::rocket::Route> { routes![watch::show, watch::continue_and_show, watch::add] } #[get("/show")] fn show(sender: rocket::State<'_, crate::PrirodaSender>) -> crate::RResult> { sender.do_work(|pcx| { let mut buf = String::new(); stack_trace::show(pcx, &mut buf).unwrap(); let mut alloc_traces = pcx.traces.alloc_traces.iter().collect::>(); alloc_traces.sort_by_key(|(id, _)| id.0); for (alloc_id, alloc_trace) in alloc_traces { if alloc_trace.trace_points.is_empty() { writeln!(buf, "

Alloc {} has never existed

", alloc_id.0).unwrap(); continue; } writeln!(buf, "

Alloc {}

\n", alloc_id.0).unwrap(); for (step_count, trace_point) in &alloc_trace.trace_points { let content = match trace_point { AllocTracePoint::Changed(alloc) => crate::render::locals::print_alloc( pcx.ecx.memory.pointer_size().bytes(), Pointer::new(*alloc_id, Size::from_bytes(0)).with_tag(miri::Tag::Untagged), alloc, None, ), AllocTracePoint::Deallocated => "Dealloc".to_string(), }; writeln!( buf, "\n\n\n", step_count, content ) .unwrap(); } writeln!(buf, "
{}{}
\n").unwrap(); } Html(buf) }) } #[get("/continue_and_show")] pub fn continue_and_show(sender: State<'_, PrirodaSender>) -> RResult> { sender.do_work(move |pcx| { crate::step::step(pcx, |_ecx| crate::step::ShouldContinue::Continue); })?; show(sender) } #[get("/add/")] pub fn add( sender: rocket::State<'_, crate::PrirodaSender>, id: u64, ) -> crate::RResult { sender.do_work(move |pcx| { pcx.traces .alloc_traces .insert(AllocId(id), AllocTrace::new()); step_callback(pcx); rocket::response::Redirect::to("/") }) } ================================================ FILE: src/watch/stack_trace.rs ================================================ use std::fmt::Write; use std::io::{self, Write as IoWrite}; use std::process::{Command, Stdio}; use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv}; use rustc_mir::interpret::Machine; use crate::*; pub(super) fn step_callback(pcx: &mut PrirodaContext<'_, '_>) { let ecx = &pcx.ecx; let traces = &mut pcx.traces; let stack_trace = Machine::stack(ecx) .iter() .map(|frame| (frame.instance,)) .collect::>(); insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1); let location = if let Some(location) = ecx.frame().current_loc().ok() { location } else { return; // Unwinding, but no cleanup for current frame needed }; let mir::Location { block, statement_index: stmt, } = location; let blck = &ecx.frame().body.basic_blocks()[block]; if stmt == blck.statements.len() { use rustc_middle::mir::TerminatorKind::*; match &blck.terminator().kind { Call { func, args, .. } => { if let Some(instance) = instance_for_call_operand(ecx, &func) { insert_stack_traces_for_instance(pcx, stack_trace, instance, Some(&args)); } } Drop { place, .. } => { let location_ty = place.ty(ecx.frame().body, ecx.tcx.tcx).ty; let location_ty = ecx.tcx.subst_and_normalize_erasing_regions( ecx.frame().instance.substs, ParamEnv::reveal_all(), location_ty, ); let instance = Instance::resolve_drop_in_place(ecx.tcx.tcx, location_ty); insert_stack_traces_for_instance(pcx, stack_trace, instance, None); } _ => {} } } } fn instance_for_call_operand<'a, 'tcx: 'a>( ecx: &InterpCx<'tcx>, func: &'tcx rustc_middle::mir::Operand<'_>, ) -> Option> { let res: ::miri::InterpResult<'_, Instance<'_>> = try { let func = ecx.eval_operand(func, None)?; match func.layout.ty.kind() { ty::FnPtr(_) => { let fn_ptr = ecx.read_scalar(&func)?.check_init()?; if let Ok(instance) = ecx.memory.get_fn(fn_ptr)?.as_instance() { instance } else { return None; } } ty::FnDef(def_id, substs) => { let substs = ecx.tcx.subst_and_normalize_erasing_regions( ecx.frame().instance.substs, ParamEnv::reveal_all(), *substs, ); ty::Instance::resolve(*ecx.tcx, ParamEnv::reveal_all(), *def_id, substs) .unwrap() .unwrap() } _ => { panic!("can't handle callee of type {:?}", func.layout.ty); } } }; Some(res.unwrap()) } fn insert_stack_traces_for_instance<'a, 'tcx: 'a>( pcx: &mut PrirodaContext<'a, 'tcx>, mut stack_trace: Vec<(Instance<'tcx>,)>, instance: Instance<'tcx>, args: Option<&[mir::Operand<'tcx>]>, ) { let ecx = &pcx.ecx; let traces = &mut pcx.traces; let item_path = ecx.tcx.def_path_str(instance.def_id()); stack_trace.push((instance,)); insert_stack_trace(&mut traces.stack_traces_cpu, stack_trace.clone(), 1); let _: ::miri::InterpResult<'_> = try { let args = if let Some(args) = args { args.into_iter() .map(|op| ecx.eval_operand(op, None)) .collect::, _>>()? } else { return; }; match &item_path[..] { "alloc::alloc::::__rust_alloc" | "alloc::alloc::::__rust_alloc_zeroed" => { let size = ecx.read_scalar(&args[0])?.to_machine_usize(&ecx.tcx.tcx)?; insert_stack_trace(&mut traces.stack_traces_mem, stack_trace, size as u128); } "alloc::alloc::::__rust_realloc" => { let old_size = ecx.read_scalar(&args[1])?.to_machine_usize(&ecx.tcx.tcx)?; let new_size = ecx.read_scalar(&args[3])?.to_machine_usize(&ecx.tcx.tcx)?; if new_size > old_size { insert_stack_trace( &mut traces.stack_traces_mem, stack_trace, (new_size - old_size) as u128, ); } } _ => {} } }; } fn insert_stack_trace(traces: &mut Vec<(T, u128)>, trace: T, count: u128) { if let Some(t) = traces.last_mut() { if t.0 == trace { t.1 += count; return; } } traces.push((trace, count)); } pub(super) fn show(pcx: &PrirodaContext<'_, '_>, buf: &mut impl Write) -> io::Result<()> { writeln!(buf, "{}\n", crate::render::refresh_script(pcx)).unwrap(); create_flame_graph( &pcx.ecx, &mut *buf, &pcx.traces.stack_traces_cpu, "Cpu usage", "instructions", "java", "flame_graph_cpu", )?; create_flame_graph( &pcx.ecx, &mut *buf, &pcx.traces.stack_traces_mem, "Memory usage", "bytes", "mem", "flame_graph_mem", )?; print_stack_traces(&pcx.ecx, &mut *buf, &pcx.traces.stack_traces_cpu).unwrap(); Ok(()) } fn create_flame_graph<'a, 'tcx: 'a>( ecx: &InterpCx<'tcx>, mut buf: impl Write, traces: &[(Vec<(Instance<'tcx>,)>, u128)], name: &str, count_name: &str, color_scheme: &str, _file_name: &str, ) -> io::Result<()> { let mut flame_data = String::new(); for (stack_trace, count) in traces { let mut last_crate = rustc_hir::def_id::LOCAL_CRATE; writeln!( flame_data, "{} {}", stack_trace .iter() .map(|(instance,)| { let mut name = ecx.tcx.def_path_str(instance.def_id()); match instance.def { InstanceDef::Intrinsic(..) => name.push_str("_[k]"), InstanceDef::DropGlue(..) => name.push_str("_[k]"), _ => { if instance.def_id().is_local() { name.push_str("_[j]"); } } } if last_crate != instance.def_id().krate { name = "-;".to_string() + &name; last_crate = instance.def_id().krate; } name }) .collect::>() .join(";"), count ) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; } //::std::fs::write(format!("./resources/{}.txt", _file_name), flame_data.as_bytes())?; let child = Command::new("../FlameGraph/flamegraph.pl") .arg("-") .arg("--title") .arg(name) .arg("--countname") .arg(count_name) .arg("--colors") .arg(color_scheme) .arg("--minwidth") .arg("0.01") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn(); match child { Ok(mut child) => { child .stdin .as_mut() .unwrap() .write_all(flame_data.as_bytes())?; match child.wait_with_output() { Ok(output) => { let flame_graph = String::from_utf8(output.stdout).unwrap(); //::std::fs::write(format!("./resources/{}.svg", _file_name), flame_graph.as_bytes())?; writeln!(buf, "{}", flame_graph).unwrap() } Err(err) => writeln!(buf, "

Wait error: {:?}

", err).unwrap(), } } Err(err) => writeln!(buf, "

Spawn error: {:?}

", err).unwrap(), } Ok(()) } fn print_stack_traces<'a, 'tcx: 'a>( ecx: &InterpCx<'tcx>, mut buf: impl Write, traces: &[(Vec<(Instance<'tcx>,)>, u128)], ) -> ::std::fmt::Result { let name_for_instance = |i: Instance<'_>| { ecx.tcx .def_path_str(i.def_id()) .replace("<", "<") .replace(">", ">") }; writeln!(buf, "

Stack trace

\n
    \n")?; for (stack_trace, count) in traces { writeln!( buf, "
  • {2}{0} ({1})
  • \n", name_for_instance(stack_trace.last().unwrap().0), count, format!( "{nil: ")?; Ok(()) }