Results 1 to 3 of 3

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

Threaded View

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Jan 2020
    Posts
    5,541

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

    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, Optional NullArg As Long) As Long
    ' now it'S OK,how to remove 【Optional NullArg As Long】?
    MsgBox 1
    MsgBox 2
    End Function
    
    Function VB_Sum(ByVal a As Long, ByVal b As Long) As Long
    'can't bind here
    
    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 Attached Files
    Last edited by xiaoyao; Mar 2nd, 2021 at 05:30 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width