0
unsigned int read_reg(char *reg_name)
{
   unsigned int result;

    __asm__ __volatile__ ("sw xxx, %0" : : "r"(result));

    return result;
}

The above is a piece of RISC-V code. reg_name is got from CLI, and it's a string, such as "ra" or "x1", etc.

Is there a way to pass the reg_name to the assembly template so that the same function can handle different registers?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Wanghz
  • 305
  • 2
  • 12
  • 1
    The problem is that you have to encode the register name into the instruction. So you can't generate the correct instruction until you have the register name. It might be possible to do this by generating instructions at runtime then jumping to that code, but it's a pretty ugly solution (also it looks like a virus to av checkers). You could have a (very) big case statement that switches on the desired register. But ultimately, this code almost certainly isn't going to do what you want. What's your actual goal here? – David Wohlferd Oct 21 '21 at 21:43
  • @DavidWohlferd I want to input `view reg_name` command from CLI and get the register's value. As there are a cluster of registers, for example `x1~x31` for integer registers in RISC-V, a `switch` statement with many `case` branch is an obvious solution. But it's a little ugly and every `case` uses almost the same code except the register name. So I want to know if there's a better way. – Wanghz Oct 22 '21 at 01:25
  • The process of calling `read_reg` will end up *changing* the values of certain registers. Which means that if you're trying to see what's in a register, you could end up changing it by calling this code, which would kinda defeat the purpose. Also, you could change a lot more registers if you attempt to output the value. And doing this from the command line just seems... odd. Are you trying to debug something? – David Wohlferd Oct 22 '21 at 01:33
  • @DavidWohlferd Yes, I want to show register value from CLI as a debugging tool. Interger registers are just examples for clarifying the problem, and the register targets are some cared CSRs(Control and State Register). – Wanghz Oct 22 '21 at 01:38
  • You might want to try defining this function inside a preprocessor macro and invoke it with each register name. – mkayaalp Oct 22 '21 at 03:23
  • 1
    For debug usage, probably just dump the registers to an array and index them. Of course, any compiler-generated code will write some registers, so we normally use debuggers to inspect a process without having to modify it to add support for debug output, if we just want asm-level debugging like register values. If you're trying to write your own bare-metal debugger, you'll probably want to separate it from the code its debugging, so it can single-step other code. Although I guess some basic reading of control regs could make sense without that. – Peter Cordes Oct 22 '21 at 05:20

0 Answers0