簡體   English   中英

8086 Assembley-在大型模型中調用Printf

[英]8086 Assembley - call Printf in model large

我試圖在大型模型的匯編代碼中使用printf,並且出現修復程序溢出,我需要對此代碼進行哪些更改才能使其正常工作?

.MODEL LARGE
.STACK 100h
.DATA
int     DW "%d"
.CODE
.386

extrn   _printf:far
PUBLIC _stack_protection
_stack_protection PROC FAR
push    bp          
mov bp,sp           
push    es
mov     ax,10
push    ax
push    word ptr int
call    _printf
add sp,4
pop es  
pop bp          
ret 
_stack_protection ENDP
    END

您需要更改此:

int     DW "%d"

對此:

_int     DB "%d",0

因為printf()需要以NUL終止的普通C字符串,因為C字符串由字節而不是字組成,並且因為int可能是保留字(至少在TASM中是保留字)。

您還需要更改此設置:

push    word ptr int
...
add sp,4

對此:

push    seg _int
push    offset _int
...
add sp,6

因為在大內存模型中,所有指針都是很遠的,也就是說,由一個段和一個偏移量組成。

所以,這就是我最終得到的...

ASM文件:

; file: larg.asm
; how to assemble: tasm.exe /ml larg.asm
.MODEL LARGE

;.STACK 100h ; unnecessary and too small anyway,
; let the C compiler take care of it

DATA segment word public 'DATA' ; make sure class='DATA' (default)
;int     DW "%d" ; 'int' is a reserved word,
; C strings must consist of bytes/chars and end with byte 0
_int    DB "%d", 0
DATA ends

extrn   _printf:far ; for some reason this must be
; outside of the code segment

CODE segment byte public 'CODE' USE16 ; make sure it's
; 16-bit code, class='CODE' (default)
assume cs:CODE
.386

PUBLIC _stack_protection
_stack_protection PROC FAR
push    bp
mov     bp,sp
push    es
mov     ax,10
push    ax
;push    word ptr int ; must be the far address of '_int'
; because in the 'large' memory model all pointers are 'far'
push    seg _int
push    offset _int
call    _printf
;add sp,4 ; must account for the far address size on stack
add     sp,6
pop     es
pop     bp
ret
_stack_protection ENDP
CODE ends

    END

C文件:

// file: large.c
// how to compile: tcc.exe -mlarge large.c larg.obj

#include <stdio.h>

extern void stack_protection(void);

int main(void)
{
  stack_protection();
  printf("\n");
  return 0;
}

然后,我編譯程序(使用Turbo C ++ 1.01和TASM 3.2):

tasm.exe /ml larg.asm
tcc.exe -mlarge large.c larg.obj

並運行它:

c:\large.exe
10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM