1

I have this simple code:

#include <sys/types.h>
    #include <netinet/in.h>

    #include <stdio.h>
    #include <ctype.h>

    main(argc, argv)
        char *argv[];
    {
        char line[512];
        gets(line);

    }

my goal is to find the distance between the end of the buffer and the return address of the stack.

So if my buffer (line) is 512 bytes, I could find the starting address, and add 512 and know where the start of that distance would be.. but how would I find the return address of the stack?

Basically I am just trying to figure out how to find the return address of the stack and the buffers start address.. I couldn't find it when disassembling main

6
  • You'll need to use inline assembly to reliably get the stack base pointer. (In particular it's not going to be a fixed value for every program/function/execution point). Commented Apr 18, 2019 at 14:09
  • (Also: not all return values are even returned on the stack! I'll stop short of asking you why you could possibly want to do this. :) ) Commented Apr 18, 2019 at 14:10
  • You have to analyze the calling method of your compiler/platform. Then you can apply that to your question. Commented Apr 18, 2019 at 14:11
  • Possible duplicate of How does the gcc determine stack size the function based on C will use? Commented Apr 18, 2019 at 14:44
  • @PaulOgilvie how do i do that? Really confused on where to start Commented Apr 18, 2019 at 14:50

1 Answer 1

2
#include <stdio.h>

int main()
{
    long l, k;

    asm("mov %%rsp,%0" : "=r"(l));
    asm("mov %%rbp,%0" : "=r"(k));
    printf("Stack pointer: 0x%16.16lX\n", l);
    printf("Stack frame base: 0x0%16.16lX\n", k);
    printf("Distance to return address: %ld\n", k-l);
}
snow ~ $ ./test
Stack pointer: 0x00007FFC95B793C0
Stack frame base: 0x000007FFC95B793D0
Distance to return address: 16

Obviously this is not portable, I'm assuming x64 and gcc here.

Caveat: BP isn't always going to point to the return address. Sometimes it's not used as a stack frame pointer, and some functions may not return their values on the stack. Register optimizations will break it. Local variables may break it. Variable word alignments may break it. Basically, don't count on it working. (I believe depending on the compiler/compile-time options you may need to add a constant offset to this, as well.)

I do really wonder if there isn't a better way to do whatever it is that you are trying to do... =)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.