5

我继承的一个最近的 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 R,我已将 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;
4

2 回答 2

8

该函数接受两个指针(指向数组)及其以字节为单位的长度。XOR该函数使用第二个数组字节 (Mem2) 对第一个数组字节 (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-25T05:56:35.977 回答
4

这是一个工作且简单的纯帕斯卡版本:

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 对齐的,则一次读取 DWORD 是有意义的。否则,它可以有效地变慢。对于少量数据,一个小的 Delphi 循环将足够快,并且易于阅读。最新的 CPU(如 Core i5 或 i7)在使用小代码循环时会产生奇迹(不再需要展开循环)。

于 2011-10-25T12:58:42.570 回答