My assembler is YASM and I am coding on 64-bit Linux.
I assemble using yasm -f elf -m amd64 -g dwarf2 filename.asm and link using ld
I’m trying to implement selection sort. rdi and rsi are pointing to various parts of a strbuf2 resb 10 array. What could possibly be the reason for this segmentation fault? Lines 105 and 106 do the exact same type of operation, so why does it crash on line 106 but not line 105?
I’ve included the relevant portion of the code, and the gdbtui screenshot when it crashes.
UPDATE: Counters fixed
; ====== Sorting begins here ======
; Register uses:
; bpl holds the current minimum value
; r8 holds the memory address of the current minimum value
; rdi points to the boundary of the "outer loop"
; rsi points to the boundary of the "inner loop"
sorting:
mov rdi, strbuf2 ; outer loop pointer
mov rsi, strbuf2+1 ; inner loop pointer
mov rax, 1 ; inner loop counter
mov rbx, 0 ; outer loop counter
innerloop:
mov bpl, [rdi] ; assume beginning element of unsorted array is minimum
; store the value of first element of unsorted array
mov dl, [rdi]
; compare the current small value with the value in rsi
mov cl, [rsi]
cmp bpl, cl
jg new_small
inc rsi
inc rax
cmp rax, 9
jle innerloop
jg innerloop_done
new_small:
inc rax
mov bpl, cl; save the new small value
mov r8, rsi ; save its index
inc rsi
cmp rax, 9
jle innerloop
innerloop_done:
; When the inner loop is completed...
; First, do the swap
; to swap r8 (target memory address) with [rdi] (outer array boundary)
mov dl, 0 ; initialise
mov dl, [rdi]
mov [rdi], bpl
mov [r8], dl
inc rdi ; move the outer loop pointer forward
inc rsi ; move the inner loop pointer forward
inc rbx ; increment the outer loop counter (the unsorted array becomes smaller)
; set the inner loop counter to the appropriate position
mov rax, 1
add rax, rbx ; now rax (inner loop counter)
; will always be rbx+1 (outer loop counter + 1)
cmp rbx, 9
jle innerloop
; ====== Sorting ends here ======
Segmentation fault gdb output
I think you’re getting lost in the details of the implementation and forgetting what the code should do. I suggest that you first implement the code in C and then gradually change it to become ASM-like until the point when you can write it in ASM fully.
Note the progression from the small, clean and easy to understand implementation in C in
sortC1()to the somewhat messy but completely equivalent ASM-like implementation insortAsm(). Use your favorite file comparison tool to see what changes between the implementations.The code:
The output: