Why does this subtraction in NASM not set the sign flag?

51 Views Asked by At

I'm attempting to locate the minimum value in an array in NASM. My array is set up fine, but I keep running into this problem where the sign flag is not set, even though a negative result is produced.

Here's the GDB debugger for the problem. R8 is the current value in the array, R14 is the location of the minimum value, R9 is the output of [rbx] - r14(which should be negative if a new min value is found).

This is the array definition.

%define ARRAY_SIZE  5

segment .bss
    myArray:    resd ARRAY_SIZE

The array is populated by user input, heres the code that does that:

inputLoop:
    add         r12, 1 ;used to count number of elements
    push        rcx
    push        rdi
    mov         rdi, inputPrompt
    call        printf

    mov     rdi, intFormat
    mov     rsi, intInput
    call        scanf

    add     r13, [intInput] ;this is for the sum of all inputs

    xor     rax, rax
    mov     eax, [intInput]
    pop     rdi
    stosd
    pop     rcx
    loop        inputLoop

    ;;set up array access
    mov     rbx, myArray
    mov     rcx, r12

    ;;set up max and min
    xor     r14, r14
    xor     r15, r15
    mov     r14, [rbx]
    mov     r15, [rbx]

This is the loop that handles finding min and max(only concerned with min right now)

    minMaxLoop:
    push        rcx
    push        rsi
    xor         r9, r9
    mov         r8, [rbx] ;used for debugging

    ;;comparisons - min
    mov         r9, [rbx]
    sub         r9, r14
    jns         returnMin
    mov         r14, [rbx]

returnMin:  ;;-max
    cmp        r15, [rbx]
    jge        returnMax
    mov        r15, [rbx]
returnMax:
    pop        rsi
    pop        rcx
    add        rbx, 4
    loop       minMaxLoop
    jmp        printStuff

GDB debugger output

The input that I gave for the example in the debugger is: 100, 75, 50, 80, 110

I tried using both cmp [rbx], r14 and the subtraction method stated above. I expect the sign flag to be set and to set 50 as a new minimum value, but the sign flag is never set so it skips the mov r14, [rbx]

Update: It seems I've fixed it. I wrongly put 32 bit values in the 64 bit registers. Once I did

movsx (dest), DWORD [rbx]

it worked. Thank you

0

There are 0 best solutions below