汇编如何保存和恢复寄存器

时间:2017-08-13 06:00:06

标签: assembly restore cpu-registers preserve hla

我写了这段代码,但我的教授一直告诉我保存和恢复我的寄存器。我以为我是通过向空寄存器声明一个值。

program middleFinder;
#include( "stdlib.hhf" ); // imports the input and output library
static
iDataX : int16 := 0;
iDataY : int16 := 0;
iDataZ : int16 := 0;


procedure middleFindernow( x: int16; y : int16; z : int16 ); @nodisplay; @noframe; 
// this caller must free up DH
static
iReturnAddress : dword;
iMid : int16;
iTemporary : int16;
iRegisterValue : dword;


begin middleFindernow;


mov( EBX, iRegisterValue );
// acquire parameters on the stack
pop( iReturnAddress );
pop(iTemporary);
pop(iTemporary);
mov(iTemporary, BX);
mov( BX, z );
pop( iTemporary ); // this is Y
mov( iTemporary, BX );
mov( BX, y );
pop( iTemporary ); // this is X
mov( iTemporary, BX );
mov( BX, x );
// push back the return
push( iReturnAddress );
push( iRegisterValue );

// calculate x - y
mov(x, DX);
cmp(y, DX);
je XYequal;
cmp(y, DX);
jl YisMax;
cmp(y, DX);
jg XisMax;

XYequal:
mov(y, BX);
cmp(z, BX);
je equal;
jmp ExitSequence;

equal:
stdout.put("All three values are equal");
stdout.put("AL=1");
jmp ExitSequence;

XisMax:
// calculate x - z
mov(0,BX);
mov(z,BX);
cmp(x,BX);
jl PutXinDX;
jg PutZinDX;


YisMax:
// calculate y - z
mov(0, BX);
mov(y, BX);
cmp(z, BX); 
jl PutYinDX;
jg PutZinDX;


PutXinDX:
mov(x, DX);
jmp ExitSequence;

PutYinDX:
mov(y, DX);
jmp ExitSequence;

PutZinDX:
mov(z, DX);
jmp ExitSequence;

ExitSequence:
// exit sequence
// pop all preserved registers --- BX
pop( EBX );
ret();


end middleFindernow;
begin middleFinder;
stdout.put( "gimme a X value: " );
stdin.get( iDataX);
stdout.put( "gimme a Y value: " );
stdin.get( iDataY );
stdout.put( "gimme a Z value: " );
stdin.get( iDataZ ); 
stdout.put( "Calling Mid number " , nl );
mov( 0, BX );
mov( iDataX, BX );
push( BX );
mov( 0, BX );
mov( iDataY, BX );
push( BX );
mov( 0, BX );
mov( iDataZ, BX );
push( BX );
mov( 0, BX );
push( BX );
call middleFindernow;
stdout.put( "The value in the middle is " );
stdout.puti16( DX );
stdout.newln();

end middleFinder;

2 个答案:

答案 0 :(得分:0)

你使用了一些像BX这样的寄存器,但最后你没有从你的程序开始之前恢复它们的初始值,这可能是你教授的意思

答案 1 :(得分:0)

我想教授想要的是,在你的函数开始时你将推送所有寄存器,该函数正在改变到堆栈,在返回之前你将恢复这些寄存器的实际值。这是必需的,因为稍后将调用您的函数的代码可以使用这些值,并且不希望值被更改。