公共模块代码
Option Explicit
'//////////////////////////////////////////////////////////////
'//// callback 函数是个虚函数,代码无意义只为分配内存空间 ////
'//// 参数布局 模仿 callwindowproc 的参数格式 ////
'//////////////////////////////////////////////////////////////
Public Function Callback(ByVal addr As Long, ByVal a As Long, ByVal b As Long, _
ByVal c As Long, ByVal d As Long) As Long
Dim r As Long
r = a + b + c + d
r = a + b + c + d
r = a + b + c + d
Callback = r
End Function
'/// 测试范例: 加法 /////
Public Function FAdd(ByVal a As Long, ByVal b As Long, _
ByVal c As Long, ByVal d As Long) As Long
Dim r As Long
r = a + b + c + d
MsgBox "加法:" & a & " + " & b & " + " & c & " + " & d & " = " & r
FAdd = r
End Function
'/// 测试范例: 乘法 /////
Public Function FMul(ByVal a As Long, ByVal b As Long, _
ByVal c As Long, ByVal d As Long) As Long
Dim r As Long
r = a * b * c * d
MsgBox "乘法:" & a & " * " & b & " * " & c & " * " & d & " = " & r
FMul = r
End Function
'////// 返回通过 addressof 传入的函数指针 ////
Public Function GetAddr(ByVal addr As Long) As Long
GetAddr = addr
End Function
类模块ClsInjectCode代码:
Option Explicit
' 修改内存保护属性(使代码段可写)
Private Declare Function VirtualProtect Lib "kernel32" ( _
ByVal lpAddress As Long, _
ByVal dwSize As Long, _
ByVal flNewProtect As Long, _
lpflOldProtect As Long) As Long
' 拷贝内存(用于写入机器码)
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As Long, _
ByRef Source As Any, _
ByVal Length As Long)
' 记录最后一次注入地址和机器码
Private mLastAddress As Long
Private mLastHexCode As String
Private Const PAGE_EXECUTE_READWRITE As Long = &H40
'//// 代码注入接口 //////
Public Sub InjectCode(ByVal addr As Long, ByVal hexStr As String)
Dim patch() As Byte
patch = HexStringToBytes(hexStr)
Call ModifyFun(addr, patch)
mLastAddress = addr
mLastHexCode = hexStr
End Sub
'//////// 机器码字符串转成byte数组 /////
Private Function HexStringToBytes(hexStr As String) As Byte()
Dim parts() As String
Dim result() As Byte
Dim i As Long
parts = Split(Trim$(hexStr))
ReDim result(0 To UBound(parts))
For i = 0 To UBound(parts)
result(i) = CByte("&H" & parts(i))
Next
HexStringToBytes = result
End Function
'////// 机器码注入 //////
Private Sub ModifyFun(ByVal addr As Long, patch() As Byte)
Dim patchLength As Long
patchLength = UBound(patch) - LBound(patch) + 1
Dim oldProtect As Long
Call VirtualProtect(addr, patchLength, &H40, oldProtect)
Call CopyMemory(ByVal addr, ByVal VarPtr(patch(LBound(patch))), patchLength)
Call VirtualProtect(addr, patchLength, oldProtect, oldProtect)
End Sub
配合IDE模式下调试的回调函数Dll库C代码,可自己编译:
编译后在VB的声明格式:
Private Declare Sub Callback Lib "Callback.dll" Alias "_Callback@20" _
(ByVal addr As Long, ByVal a As Long, ByVal b As Long, ByVal c As Long, ByVal d As Long)