2.5 OpenEuler 中C与汇编的混合编程(选做)
一、X86_64实践内容
2.5.1
1.代码如下:
/************a.c*************/
#include<stdio.h>
extern int B();
int A(int x,int y)
{
int d,e,f;
d =4; e =5; f=6;
d=B(d,e);
}
经过汇编命令gcc -m32 -S a.c -o a.s
得到汇编文件
/************a.s*************/
.file "a.c"
.text
.globl A
.type A, @function
A:
.LFB0:
.cfi_startproc
endbr32
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
pushl %ebx
subl $20, %esp
.cfi_offset 3, -12
call __x86.get_pc_thunk.ax
addl $_GLOBAL_OFFSET_TABLE_, %eax
movl $4, -20(%ebp)
movl $5, -16(%ebp)
movl $6, -12(%ebp)
subl $8, %esp
pushl -16(%ebp)
pushl -20(%ebp)
movl %eax, %ebx
call B@PLT
addl $16, %esp
movl %eax, -20(%ebp)
nop
movl -4(%ebp), %ebx
leave
.cfi_restore 5
.cfi_restore 3
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size A, .-A
.section .text.__x86.get_pc_thunk.ax,"axG",@progbits,__x86.get_pc_thunk.ax,comdat
.globl __x86.get_pc_thunk.ax
.hidden __x86.get_pc_thunk.ax
.type __x86.get_pc_thunk.ax, @function
__x86.get_pc_thunk.ax:
.LFB1:
.cfi_startproc
movl (%esp), %eax
ret
.cfi_endproc
.LFE1:
.ident "GCC: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0"
.section .note.GNU-stack,"",@progbits
.section .note.gnu.property,"a"
.align 4
.long 1f - 0f
.long 4f - 1f
.long 5
0:
.string "GNU"
1:
.align 4
.long 0xc0000002
.long 3f - 2f
2:
.long 0x3
3:
.align 4
4:
2.5.2
1.代码如下:
/************s.c*************/
#include <stdio.h>
extern int get_ebp();
extern int get_esp();
int main()
{
int ebp, esp;
ebp = get_ebp();
esp = get_esp();
printf("ebp=%8x esp=%8x\n",ebp,esp);
}
/************s.s*************/
.global get_esp,get_ebp
get_esp:
movl %esp,%eax
ret
get_ebp:
movl %ebp,%eax
ret
经过汇编命令gcc -m32 s.s s.c -o s.out
得到汇编文件
2.5.3
/************smysum.s*************/
.text
.global mysum,printf
mysum:
#(1)Entry:
pushl $ebp
movl %esp,%ebp
#(2)Function Body code
movl 8(%ebp),%eax
addl 12(%ebp),%eax
#(3)Exit Code
movl %ebp,%esp
pop %ebp
ret
/************smysum.c*************/
#include<stdio.h>
int main()
{
int a,b,c;
a = 123;b = 456;
c = mysum(a,b);
printf("c=%d\n",c);
}
汇编指令:gcc -m32 -o mysum.out mysum.s mysum.c
2.5.4
/************prt.c*************/
int a,b;
int main()
{
a = 100;b = 200;
sub();
}
/************prt.s*************/
.text
.global sub,a,b,printf
sub:
pushl %ebp
movl %esp,%ebp
pushl b
pushl a
pushl $fmt
call printf
addl $12,%esp
movl %ebp,%esp
popl %ebp
ret
.data
fmt: .asciz "a=%d b=%d\n"
汇编命令:gcc -m32 prt.c prt.s -o prt.out