get the caller's lr from subroutine into C variable - arm

前端 未结 2 449
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 06:55

I\'ve got a C function that\'s supposed to get the value of the caller\'s lr register into a local variable.

I\'ve tried the following code:

volatile         


        
2条回答
  •  青春惊慌失措
    2021-01-03 07:55

    Your code will get the value at the address SP+4. Whether that location contains the initial LR depends on the compiler, optimization settings, specific function, or the place in the function where you put this code. In short, it would probably work only by accident.

    EDIT: your code is not even reading anything relevant, it's just storing a value of uninitialized variable on the stack (hint: naming your variable lr doesn't make it magically take the value of the register LR). In the best case it won't do anything, in the worst you'll overwrite something important and it will crash.

    I'll assume that you actually want to get the function's return address, not LR specifically. There exist compiler-specific options for that.

    1. GCC offers the __builtin_return_address() intrinsic which returns the return address of the current function (if called with 0) or, possibly, other functions in the call stack (though I wouldn't rely on the latter).

    2. Visual C++ has _ReturnAddress() and even _AddressOfReturnAddress() intrinsics.

    I would recommend using one of the above (assuming you're using GCC or VC) and not rely on tricks which may stop working at any time.

提交回复
热议问题