Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15196

Call Cdecl by VB Function why Stack was trashed by 4 bytes?

$
0
0
Call Cdecl by VB Function
why Stack was trashed by 4 bytes?

Code:


Function VB_CdeclAPI_Sum(ByVal a As Long, ByVal b As Long) As Long

MsgBox 1
MsgBox 2
MsgBox 2
MsgBox 2
MsgBox 2
End Function

Sub FixCdecl(VbFunction As Long, CdeclApi As Long, args As Long)
'ESP堆栈不平衡 Stack was trashed by 4 bytes

Dim asm() As String, stub() As Byte
Dim i As Long, argSize As Long
    argSize = args * 4
    '  0: 58                  pop        eax
    '  1: 89 84 24 XX XX XX XX mov        dword ptr [esp+Xh],eax
   
    push asm(), "58 89 84 24 " & lng2Hex(argSize + 0) '&H24848958

    push asm(), "B8 " & lng2Hex(CdeclApi)        'B8 90807000    MOV EAX,708090
    push asm(), "FF D0"                      'FFD0          CALL EAX
    push asm(), "83 C4 " & Hex(argSize + 0) '83 C4 XX      add esp, XX    'cleanup args
    'push asm(), "C2 10 00"
    push asm(), "C3"
    stub() = toBytes(Join(asm, " "))
   
Dim THUNK_SIZE As Long
THUNK_SIZE = UBound(stub) + 1
VirtualProtect2 VbFunction, THUNK_SIZE, PAGE_EXECUTE_READWRITE, 0    '更改函数地址所在页面属性
WriteProcessMemory2 -1, VbFunction, VarPtr(stub(0)), THUNK_SIZE, 0
'Vblegend.VirtualProtect VbFunction, THUNK_SIZE, PAGE_EXECUTE_READWRITE, 0    '更改函数地址所在页面属性
'Vblegend.WriteProcessMemory -1, VbFunction, stub(0), THUNK_SIZE, 0
End Sub

form1 code:
Code:

Dim startESP As Long, endEsp As Long
startESP = getESP

Dim h As Long, ret As Long
Dim CdeclApi As Long, lpfnAdd As Long, lpfnVoid As Long, lpfnSub As Long
h = LoadLibrary("cdecl.dll")
CdeclApi = GetProcAddress(h, "Add")

Dim a As Long, b As Long, c As Long
a = 44
b = 55

FixCdecl AddressOf VB_CdeclAPI_Sum, CdeclApi, 2
' FixCdecl AddressOf VB_CdeclAPI_Sum, CdeclApi, 8
startESP = getESP
c = VB_CdeclAPI_Sum(a, b)
endEsp = getESP
MsgBox "c=" & c

'ESP堆栈不平衡
MsgBox "Stack was trashed by " & (endEsp - startESP) & " bytes"

Attached Files

Viewing all articles
Browse latest Browse all 15196

Trending Articles