I came across a pop esp in real code, which I think is a kind of confusing instruction. i.e. What is the value of esp after the following?

push    0x0400
pop     esp

What does pop esp do? People who look at x86 asm more than me no doubt know. But to understand let’s look at what pop eax basically does.

add esp, 4       ;"instruction" 1
mov eax, [esp]   ;"instruction" 2

What is the order of operations here? There could be two solutions – it could be 0x0400 (if it increments esp first – instruction 1 then 2) – or esp could be 0x0404 (if the increment is second – instruction 2 then 1).

It turns out the second is what happens. So if you guessed that esp is 0x0400, you’re right!

print shell code

From the book “Buffer Overflow Attacks” by Foster and others, I came across this very handy tool for testing developing shellcode.  It takes your assembly and puts it into a well commented C array to be tested by execution or simply printing to the screen.

To compile thes program, type gcc -o printshell printshellcode.c

Now, if you want to try out your shellcode assembly,

  • Type the instructions in a .S file
  • Execute nasm -o <filename> <filename>.S
    • To print the shellcode use printshellcode -p <filename>.
    • To execute the shellcode use printshellcode -e <filename>

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
/*Print message function*/
static void croak(const char *msg){
    fprintf(stderr, "%s\n", msg);

/*Usage funcion*/
static void usage(const char *prgnam){
    fprintf(stderr, "\nExecute code : %s -e \n", prgnam);

/*Signal error and bail out*/
 static void barf(const char *msg){

int main(int argc, char **argv){

    FILE	*fp;
    void	*code;
    int		i,l,arg;
    int		m=15; /* max number of bytes on a line*/

    struct stat sbuf;
    long	flen; /*assume files are &lt; 2**32*/
    void	(*fptr)(void);

    if(argc &lt; 3) usage(argv[0]);
    if(stat(argv[2], &amp;sbuf)) barf(&quot;failed to stat file&quot;);
    flen = (long) sbuf.st_size;
    if(!(code = malloc(flen))) barf(&quot;failed to grab enough memory&quot;);
    if(!(fp = fopen(argv[2], &quot;rb&quot;))) barf(&quot;failed to open file&quot;);
    if(fclose(fp)) barf(&quot;failed to close file&quot;);

    while ((arg = getopt (argc, argv, &quot;e:p:&quot;)) != 1){
        case 'e':
          croak(&quot;Calling code ...&quot;);
          fptr = (void (*)(void)) code;
        case 'p':
          printf(&quot;\n/* The following shellcode is %d bytes long: */\n&quot;,flen);
          printf(&quot;\nchar shellcode[] = \n&quot;);
          l = m;
          for(i = 0; i= m){
              if(i) printf("\"\n");
              printf( "\t\"");
              l = 0;
            printf("\\x%02x", ((unsigned char *)code)[i]);

    return 0;