David
David

Reputation: 753

How to get the value of stack pointer? (MIPS GCC)

I am trying to get the call stack, for some reason the following code returns a wrong stack pointer:

        unsigned int stack_pointer = 0;
        __asm("la  $26,  %[spAddr]\n\t"
              "or  $27,  $0,  $sp\n\t"
              "sw  $27,  0($26)\n\t"
              "nop"::[spAddr] "m" (stack_pointer));
        return stack_pointer;

What am I missing here?

Upvotes: 1

Views: 1652

Answers (1)

Jester
Jester

Reputation: 58762

To get the stack pointer use the proper output constraint like so:

register unsigned sp asm("29");
asm("" : "=r" (sp));

Note that mips uses a register for the return address, but of course non-leaf functions might store it on the stack.

To implement a backtrace, you can however use the builtins __builtin_return_address and __builtin_extract_return_addr as described in the gcc manual.

Also, if glibc is available, it already has backtrace function, see man backtrace.

Upvotes: 3

Related Questions