Trevor Good
Trevor Good

Reputation: 33

C Assembly Code

Here is some code I was given, but its the first time I've seen the function asm. I'm not too familiar with assembly. I was hoping someone could just explain what the asm function is doing.

/* stack.c */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

unsigned long int sp;


int cp(char *str)
{
    char buffer[12];
    asm("movl %%ebp, %0" : "=r" (sp));
    printf("$ebp is 0X%lx\n",sp);

    strcpy(buffer, str);

    printf("Buffer is at address %p\n",(void*)(&buffer));
    return 1;
}

int main(int argc, char **argv)
{
    char str[517];
    FILE *badfile;

    badfile = fopen("badfile", "r");
    fread(str, sizeof(char), 517, badfile);
    cp(str);

    printf("Returned Properly\n");
    return 1;
}

Could someone just explain what the following does?

asm("movl %%ebp, %0" : "=r" (sp));
printf("$ebp is 0X%lx\n",sp);

Upvotes: 0

Views: 1958

Answers (2)

user3344003
user3344003

Reputation: 21647

asm("movl %%ebp, %0" : "=r" (sp));

This substitutes whatever the compiler is using to address sp for %0. It then becomes something like

MOVE EBP, sp

Be clear I mean something like this. If your environment prefixes _ to global variables, it could translate into

MOVE EBP, _sp

(Other substitutions are possible.) Thus it moves the value of the hardware EBP register into your C variable sp.

printf("$ebp is 0X%lx\n",sp);

This prints the value of sp which is the value of the EBP register.

Upvotes: 0

SoronelHaetir
SoronelHaetir

Reputation: 15172

"asm" in this code is not a function, it is a gcc extension (also inherited by clang) that allows inlining assembly code. You can read about it here: https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Using-Assembly-Language-with-C.html

Upvotes: 2

Related Questions