我最近继承的一个Delphi项目在ASM中有一个过程。我是一个完全的ASM新手,所以我不明白。我已经阅读了各种ASM指令,试图破译程序流程,但我仍然不明白。
有ASM经验的人能帮助我理解并将下面的过程翻译成英语(然后我可以翻译回Delphi,这样以后的代码就更容易阅读了!)
Mem1的声明是Byte;的0..15数组。Mem2是LongInt。
下面是程序:
procedure TForm1.XorMem(var Mem1; const Mem2; Count : Cardinal); register;
begin
asm
push esi
push edi
mov esi, eax //esi = Mem1
mov edi, edx //edi = Mem2
push ecx //save byte count
shr ecx, 2 //convert to dwords
jz @Continue
cld
@Loop1: //xor dwords at a time
mov eax, [edi]
xor [esi], eax
add esi, 4
add edi, 4
dec ecx
jnz @Loop1
@Continue: //handle remaining bytes (3 or less)
pop ecx
and ecx, 3
jz @Done
@Loop2: //xor remaining bytes
mov al, [edi]
xor [esi], al
inc esi
inc edi
dec ecx
jnz @Loop2
@Done:
pop edi
pop esi
end;
end;
编辑:多亏了Roman,我把ASM转换回了Delphi
procedure TForm1.XorMem2(var Mem1; const Mem2 :LongInt; Count : Cardinal);
var
Key : array [0..3] of byte absolute Mem1;
Num : array [0..3] of byte absolute Mem2;
idx : byte;
begin
for Idx := 0 to Count -1 do Key[idx] := Key[idx] Xor Num[idx];
end;
发布于 2011-10-25 05:56:35
函数接受两个指针(指向任何数组)及其长度(以字节为单位)。该函数使用第二个数组字节( XOR
)对第一个数组字节(Mem1)执行字节对字节的Mem1操作。伪码:
for Index = 0 to Count - 1
(Mem1 as Byte Array) [Index] = (Mem1 as Byte Array) [Index] Xor (Mem2 as Byte Array) [Index]
发布于 2011-10-25 12:58:42
下面是一个实用的、简单的纯pascal版本:
procedure TForm1.XorMem(var Mem1; const Mem2; Count : Cardinal);
var i: integer;
M1: TByteArray absolute Mem1;
M2: TByteArray absolute Mem2;
begin
for i := 0 to Count-1 do
M1[i] := M1[i] xor M2[i];
end;
下面是使用DWORD读取的优化版本:
procedure TForm1.XorMem(var Mem1; const Mem2; Count : Cardinal);
var i, n: integer;
M1: TByteArray absolute Mem1;
M2: TByteArray absolute Mem2;
I1: TIntegerArray absolute Mem1;
I2: TIntegerArray absolute Mem2;
begin
n := Count shr 2;
for i := 0 to n-1 do
I1[i] := I1[i] xor I2[i];
n := n shl 2;
for i := 0 to (Count and 3)-1 do
M1[n+i] := M1[n+i] xor M2[n+i];
end;
第二版不是强制性的。如果数据是对齐的,那么立即读取DWORD是有意义的。否则,它可以有效地慢下来。对于少量的数据,一个小型的Delphi循环将足够快,并且清晰易懂。最新的CPU(如核心i5或i7)在使用小代码循环时会产生奇迹(不再需要展开循环)。
https://stackoverflow.com/questions/7885162
复制相似问题