I have the following C program:
#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;
}
I would like to compile this first to assembly, then to binary for instructional purposes. So, I issue the following commands:
$ 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
These compile the C to assembly, assemble the assembly to binary, and then link the library containing the printf
function, respectively.
This works. Output:
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
etc until I ctrl-c the program.
However, when I uncomment the i = i + 1
line:
Segmentation fault (core dumped)
What is going wrong here?
UPDATE: Here is count.s
(with the i = i + 1
line included)
.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
The below works perfectly fine for me on Ubuntu 20 (taken from Ciro Santilli's answer at Linking a C program directly with ld fails with undefined reference to `__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