C到ASM的增量导致Segfault



我有以下C程序:

#include <stdio.h>
int main() {
int i = 0;
int N = 10;
while(i < N) {
printf("counting to %d: %d", N, i);
//i = i + 1;
}
return 0;
}

我想先把它编译成汇编,然后再编译成二进制,用于教学目的。因此,我发出以下命令:

$ gcc -S count.c -o count.s
$ as -o count.o count.s
$ ld -o count -e main -dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib/x86_64-linux-gnu/libc.so count.o -lc

它们分别将C编译为程序集,将程序集编译为二进制,然后链接包含printf函数的库。

这是有效的。输出:

counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0counting to 10: 0

等,直到我按下程序。

但是,当我取消注释i = i + 1行时:

Segmentation fault (core dumped)

这里出了什么问题?

更新:这是count.s(包括i = i + 1行(

.file   "count.c"
.text
.section    .rodata
.LC0:
.string "counting to %d: %d"
.text
.globl  main
.type   main, @function
main:
.LFB0:
.cfi_startproc
pushq   %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq    %rsp, %rbp
.cfi_def_cfa_register 6
subq    $16, %rsp
movl    $0, -8(%rbp)
movl    $10, -4(%rbp)
jmp .L2
.L3:
movl    -8(%rbp), %edx
movl    -4(%rbp), %eax
movl    %eax, %esi
leaq    .LC0(%rip), %rdi
movl    $0, %eax
call    printf@PLT
addl    $1, -8(%rbp)
.L2:
movl    -8(%rbp), %eax
cmpl    -4(%rbp), %eax
jl  .L3
movl    $0, %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size   main, .-main
.ident  "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
.section    .note.GNU-stack,"",@progbits

以下内容在Ubuntu 20上对我来说非常适用(取自Ciro Santilli在将C程序与ld直接链接失败时的回答,未定义引用`__libc_csu_fini`(。

gcc -S count.c -o count.s
as -o count.o count.s
ld -o count -dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o -L/usr/lib/gcc/x86_64-linux-gnu/4.8/ -lc count.o /usr/lib/x86_64-linux-gnu/crtn.o

如果您在Linux 64上,在主函数的末尾添加:

mov eax, 60   
xor edi, edi  
syscall      

在linux 32 上

mov  eax  1
xor ebx,ebx  
int 0x80 

相关内容

  • 没有找到相关文章

最新更新