-1

我必须在这个程序中实现一个 cdecl 调用约定,该程序最初使用的是非标准化约定。据我所知,它看起来是正确的,但是我收到一个未处理的异常错误,说“访问违规写入位置 0x00000066,当程序到达“not byte ptr [eax]”行或至少这是打破程序后的箭头指向。

谁能告诉我我的程序出了什么问题以及如何解决它?谢谢你。

void encrypt_chars (int length, char EKey)
{   char temp_char;                     

for (int i = 0; i < length; i++)    
{
    temp_char = OChars [i];         
    __asm {
            push   eax
            movzx  eax, temp_char
            push   eax
            lea    eax, EKey
            push   eax
            call   encrypt
            mov    temp_char, al

            pop    eax
    }
    EChars[i] = temp_char;          
return;


// Inputs: register EAX = 32-bit address of Ekey,
//                  ECX = the character to be encrypted (in the low 8-bit field, CL).
// Output: register EAX = the encrypted value of the source character (in the low 8-bit field, AL).

__asm {          

encrypt:

        push ebp
        mov ebp, esp
        mov ecx, 8[ebp] 
        mov eax, 12[ebp]
        push edi                  
        push ecx                  
        not byte ptr[eax]         
        add byte ptr[eax], 0x04   
        movzx edi, byte ptr[eax]  
        pop eax                   
        xor eax, edi              
        pop edi                   
        rol al, 1                 
        rol al, 1                 
        add al, 0x04              
        mov esp, ebp
        pop ebp
        ret                       
}
4

1 回答 1

3

通过检查,加密功能的注释是错误的。请记住:堆栈向下增长,因此当参数被压入堆栈时,首先压入的参数具有更高的地址,因此与堆栈帧中的基指针的偏移量更大。

评论encrypt说:

// Inputs: register EAX = 32-bit address of Ekey,
//                  ECX = the character to be encrypted

但是,您的调用顺序是:

movzx  eax, temp_char    ; push the char to encrypt FIRST
push   eax
lea    eax, EKey         ; push the encryption key SECOND
push   eax
call   encrypt

所以角色是push first。所以要加密的字符但是encrypt以这种方式加载它们:

; On function entry, the old Instruction Pointer (4 bytes) is pushed onto the stack
; so now the EKey is +4 bytes from the stack pointer
; and the character is +8 bytes from the stack pointer
;

push ebp
mov ebp, esp

; We just pushed another 4 bytes onto the stack (the esp register)
; and THEN we put the stack pointer (esp) into ebp as base pointer
; to the stack frame.
;
; That means EKey is now +8 bytes off of the base pointer
; and the char to encrypt is +12 off of the base pointer
;
mov ecx, 8[ebp]            ; This loads EKey pointer to ECX
mov eax, 12[ebp]           ; This loads char-to-encrypt to EAX

然后代码继续尝试EAX作为指针引用(因为它认为是EKey),这将导致访问冲突,因为它是你的角色在第一次尝试EAX作为指针引用时进行加密,这里是:

not byte ptr[eax]

所以你的调试器指针是对的!:)

您可以通过交换这两个寄存器来修复它:

mov eax, 8[ebp]            ; This loads EKey pointer to EAX
mov ecx, 12[ebp]           ; This loads char-to-encrypt to ECX

最后,您对 encrypt 的调用在完成时不会清理堆栈指针。由于您在调用之前将 8 个字节的数据压入堆栈encrypt,并且由于执行了没有堆栈清理encrypt的标准,因此您需要在调用之后进行清理:ret

...
call   encrypt
add    esp, 8
...
于 2015-03-19T15:53:58.153 回答