asm in C question

closed account (zwA4jE8b)
I have this example code

I am using eclipse Indigo with mingw GCC and AMDx64 processor
In my console "0x0" is always shown. I think this is an old example. Can anyone tell me if the syntax is incorrect or what? This should return the address of the stack pointer.

1
2
3
4
5
6
7
unsigned long get_sp(void) {
   __asm__("movl %esp,%eax");
}
int main() {
  printf("0x%x\n", get_sp());
  return 0;
}


example taken from

http://destroy.net/machines/security/P49-14-Aleph-One
closed account (o1vk4iN6)
Are you getting compiler errors?

To me if I remember my at&t syntax correctly, you are moving EAX -> ESP. You should also force a specific calling convection on your function call.

I don't really see why you would want to do this, after that function returns the stack pointer is already going to be different, not to mention this will only work on 32-bit programs.

Last edited on
closed account (zwA4jE8b)
If you check that link you can see the whole stack exploit. the function is to get the address of the stack in order to overflow a buffer onto it.

It compiles, but it only prints '0x0' not the stack address.
Last edited on
closed account (o1vk4iN6)
Well there might be a problem with calling convention, I'm not entirely sure what the default is for the GCC compiler, or what options you have set. I'm also unfamiliar with what calling conventions C supports.

I did run this through the mscv compiler and it appear to return the stack pointer.

1
2
3
4
5
6
7
8
9
10
11
unsigned int sp()
{
	__asm mov eax, esp
}

int main()
{
	printf("%x\n", sp());

	return 0;
}


Your best bet would be to look through and see exactly what's going wrong with some sort of debugger. The compiler can be doing anything really which is why I prefer to do something like this instead:

1
2
3
4
5
6
unsigned int sp()
{
      unsigned int p;
      __asm mov p, esp
      return p;
}


This way you don't have to worry about EAX containing a value or not, and it'll follow any calling convection / optimizations the compiler will do. Again this is Intel and MSVC syntax.
Last edited on
closed account (zwA4jE8b)
Thanks xerzi. I have amd but I do have MSVC so I will try it in that.

EDIT: Works great in msvc. That is the IDE I started with. One of my teachers wants us to use eclipse with SDL so I am trying to get used to that.
Last edited on
MSVC inline assembler does not support 64bit platform.
Topic archived. No new replies allowed.