Build NASM in a loop

I am writing a while loop in an assembly to compile on a Linux terminal with nasm and gcc. The program compares x and y to y> = x and reports the number of cycles at the end. Here is the code:

segment .data

out1    db "It took ", 10, 0
out2    db "iterations to complete loop. That seems like a lot.", 10, 0
x       db 10
y       db 2
count   db 0

segment .bss

segment .text

global main
extern printf

main:
    mov    eax, x
    mov    ebx, y
    mov    ecx, count
    jmp    lp         ;jump to loop lp

lp:
    cmp    ebx, eax   ;compare x and y
    jge    end        ;jump to end if y >= x
    inc    eax        ;add 1 to x
    inc    ebx        ;add 2 to y
    inc    ebx
    inc    ecx        ;add 1 to count
    jp     lp         ;repeat loop

end:

    push    out1      ;print message part 1
    call    printf

    push    count     ;print count
    call    printf

    push    out2      ;print message part 2
    call    printf

    ;mov    edx, out1               ;
    ;call   print_string            ;
                                    ;
    ;mov    edx, ecx                ;these were other attempts to print
    ;call   print_int               ;using an included file
                                    ;
    ;mov    edx, out2               ;
    ;call   print_string            ;

This is compiled and run in the terminal with:

nasm -f elf test.asm
gcc -o test test.o
./test

The terminal output is displayed as:

It took
iterations to complete loop. That seems like a lot.
Segmentation fault (core dumped)

I do not see anything wrong with logic. I think it is syntactic, but we just started to learn assembly, and I tried all kinds of syntaxes like brackets around variables, and using retat the end of the segment, but nothing works. I also looked for segmentation errors, but I did not find anything useful. Any help would be appreciated because I'm an absolute beginner.

+4
source share
2

, , , , main ret. eax 0 :

xor     eax, eax ; or `mov eax, 0` if you're more comfortable with that
ret

, , . mov eax, x eax x. , - ( ).

, printf :

push    count     ;print count
call    printf

, "%i". count , . :

out3    db "%i ", 0

; snip

push    ecx
push    out3
call    printf
+6

, , , . nasm , . , [label]:

 segment .data
     x      dw 42
 segment .text
     global main
     extern printf
 main:
     mov    eax, x
     push   eax
     call   printf   ; will print address of x (like doing cout<<&x in C++)
     mov    eax, [x]
     push   eax
     call   printf   ; will print 42
     sub    esp, 8
     xor    eax, eax
     ret

PS: , - , (C ++ ), , , "" , asm . , , , , , , (call printf) ( ! ) , . :

  • , gcc your_c_file.c -S, your_c_file.s , C . ( , , , , Mangling, , func.)

  • , , , , LIFO.

  • PUSHA POPA, .

3 NASM, : http://www.csie.ntu.edu.tw/~comp03/nasm/nasmdoc3.html

, .

0

All Articles