unicorn icon indicating copy to clipboard operation
unicorn copied to clipboard

riscv: Expose privilege level as pseudo-register "priv"

Open apparentlymart opened this issue 1 year ago • 0 comments

Unlike some other architectures, RISC-V does not expose the current privilege mode in any architecturally-defined register. That is intentional to make it easier to implement virtualization in software, but a Unicorn caller operates outside of the emulated hart and so it can and should be able to observe and change the current privilege mode in order to properly emulate certain behaviors of a real CPU.

This PR therefore now exposes a new pseudo-register using the name "priv", defined to match the virtual register "priv" defined in the RISC-V Debug Specification, section 4.10.1. This design assumes that the Unicorn API is providing an abstraction similar to that of a debugger and so it's reasonable to take design cues from the Debug specification, rather than inventing something entirely Unicorn-specific.

The register read/write is currently implemented directly inside the Unicorn code because QEMU doesn't have explicit support for the CSRs from the debug specification. If a future QEMU release supports "dcsr" then this implementation could potentially change to wrap reading and writing that CSR and then projecting the "prv" and "v" bitfields into the correct locations for the virtual register, but for now I prioritize pragmatism since Unicorn previously offered no way to directly get/set the privilege mode from outside the emulated hart.

I've updated all of the bindings that already had the RISC-V register constants, but some of them do not currently have any defined and so I left them alone: vb6 and haskell. Of the remaining ones I only know how to test the rust bindings, and I've confirmed that this works when called from my own Rust-based Unicorn client that motivated this addition.

(I discovered a need for this while I was investigating over in https://github.com/unicorn-engine/unicorn/pull/1988, but this is an orthogonal change and so submitted as a separate PR.)

apparentlymart avatar Aug 27 '24 15:08 apparentlymart