Hacking on assembly code: Dynamic memory allocation on stack?

So I started dabbling with assembly language programming a couple of days ago. This was the next logical step in the “going lower down” move I have been doing ever since I started writing programs in Visual Basic some years ago (there, I admitted it). Since then I went through C#, Java, C++, C, and now finally assembly. And it is fun to watch a program die in so many innovative ways. It is helping me understand the internals of a program much better.

One of the first things I learned about assembly programming was that I needed to use completely different syscall numbers and instructions for x86_64 as compared to i386. For example, the syscall number for exit on i386 is 1 while on x86_64 it is 60. Same goes for write — 4 on i386 and 1 on x86_64. I spent half hour trying to figure out why my program was calling fstat on x86_64 while a similar program built with –32 would work fine.

Crossing all these hurdles, I finally wrote a slightly more complicated (but still useless) program than a hello world. This is a program that takes in an integer string through the command line, converts it to an integer, converts it back to string and prints it back out. Pretty useful huh :)

Now for the interesting part in the code. I always thought of dynamic memory allocation as something you can only go through the OS using the brk() and/or mmap() syscalls. Generally, we do this indirectly through malloc() and friends. But what I ended up doing in my program is allocating memory on the stack on the fly. Here’s the code snippet:

The complete code along with the makefile is at the end of this post. You can build it if you have an x86_64 installation. What I do above is simply:

  1. Read a digit from the number
  2. Move the stack pointer ahead to make room for a byte
  3. Store the ASCII representation of that number into that byte

I could not use the push instruction itself since it can only push 16, 32 or 64-bit stuff on to the stack (with pushw, pushl, pushq). If you push a single byte value, it will be stored in one of the above sizes, not in just 1 byte. What I wanted was to create a string on the fly without limiting myself to a fixed size array, so this seemed to be the only approach. While this works, I still need to find out a few more things about this:

  1. Is it safe?
  2. If it is safe, then is there a similar way to do this in C without embedding assembly code? This would be really cool, especially in usage scenarios such as the above. Admitted that the above scenario is pretty useless in itself, but I’m sure there must be similar examples out there that are at least a little more useful.

The code:

The makefile:

If you save the source as foo.s, you can build it with:

Written by Siddhesh Poyarekar

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.