user5406450
user5406450

Reputation: 63

Function calling w/ parameters

I am struggling with creating functions and calling them in assembly.

The function gfx_draw_h(color, x_1, y_1, x_2) should be drawing a line from (x_1, y_1) to (x_2, y_1), but I can't get the value of x_2 to compare with the current position inside gfx_draw_h.repeat.

Also, is the other piece of code correct (no stack corruptions)?

This is my code:

    BITS 16

; ----------------------------------------------------------------------

_start:
    mov ax, 07C0h
    add ax, 288
    mov ss, ax              ; SS = stack space
    mov sp, 4096            ; SP = stack pointer

    mov ax, 07C0h
    mov ds, ax              ; DS = data segment

    call gfx_init

    push 50                 ; x_2
    push 30                 ; y_1
    push 30                 ; x_1
    push 1000b              ; color

    call gfx_draw_h

    add esp, 16

    jmp $                   ; infinite loop

; ----------------------------------------------------------------------
; Initializes graphics.
;
; Sets the video mode.
;
; INPUT:
;   none
;
; OUTPUT:
;   none
;
gfx_init:
    mov ah, 00h             ; set video mode
    mov al, 12h             ; AL = graphical mode
    int 10h                 ; INT 10h / AH = 00h
    ret

; ----------------------------------------------------------------------
; Draws a horizontal line.
;
; INPUT:
;   color
;   x_1
;   y_1
;   x_2
;
; OUTPUT:
;   none
;
gfx_draw_h:
    pop ax                  ; color
    pop cx                  ; x
    pop dx                  ; y

    mov ah, 0Ch             ; change color for a single pixel

.repeat:
    cmp cx, [ebp + 20]      ; !!! THIS IS THE ISSUE !!!
    je  .done

    inc cx
    int 10h

    jmp .repeat

.done:
    ret

; ----------------------------------------------------------------------

times 510 - ($ - $$) db 0   ; padding with 0 at the end
dw 0xAA55                   ; PC boot signature

Upvotes: 2

Views: 76

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

add esp, 16

Since this is 16-bit code pushing 4 parameters on the stack would only require you to pop off 8 bytes.

gfx_draw_h:
 pop ax                  ; color
 pop cx                  ; x
 pop dx                  ; y

Since gfx_draw_h is a sub-routine (it was called) there is a return address on the stack. Your first pop ax removes this! You could write the following:

gfx_draw_h:
 mov bp, sp
 mov ax, [bp+2] ;color
 mov cx, [bp+4] ;x
 mov dx, [bp+6] ;y

Following this logic change the problem line like (don't use EBP !):

cmp cx, [bp + 8]      ; !!! THIS IS THE ISSUE !!!

Upvotes: 2

Related Questions