[英]C Assembly Code
Here is some code I was given, but its the first time I've seen the function asm . 这是我得到的一些代码,但这是我第一次看到函数asm 。 I'm not too familiar with assembly.
我对组装不太熟悉。 I was hoping someone could just explain what the asm function is doing.
我希望有人能解释一下asm函数的功能。
/* 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);
"asm" in this code is not a function, it is a gcc extension (also inherited by clang) that allows inlining assembly code. 此代码中的“ asm”不是函数,它是gcc扩展(也由clang继承),允许内联汇编代码。 You can read about it here: https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Using-Assembly-Language-with-C.html
您可以在这里阅读有关内容: https : //gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Using-Assembly-Language-with-C.html
asm("movl %%ebp, %0" : "=r" (sp));
This substitutes whatever the compiler is using to address sp for %0. 这将替代编译器用来为%0寻址sp的任何对象。 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. (可以使用其他替代方法。)因此,它将硬件EBP寄存器的值移到C变量sp中。
printf("$ebp is 0X%lx\n",sp);
This prints the value of sp which is the value of the EBP register. 这将打印sp的值,该值是EBP寄存器的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.