feat: 增加事件通信代码

This commit is contained in:
381848900@qq.com 2025-03-14 00:11:07 +08:00
parent cef75c0adf
commit e3d29b1183
11 changed files with 341 additions and 140 deletions

View File

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.13.35825.156 d17.13 VisualStudioVersion = 17.13.35825.156
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "KernelCommunication", "KernelCommunication\KernelCommunication.vcxproj", "{B1740CFB-94A0-BAA6-1165-49A4F96703C3}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "KernelCommunication", "KernelCommunication\KernelCommunication.vcxproj", "{B1740CFB-94A0-BAA6-1165-49A4F96703C3}"
EndProject EndProject

View File

@ -48,11 +48,11 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion> <TargetVersion>Windows10</TargetVersion>
<UseDebugLibraries>true</UseDebugLibraries> <UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
<ConfigurationType>Driver</ConfigurationType> <ConfigurationType>Driver</ConfigurationType>
<DriverType>WDM</DriverType> <DriverType>WDM</DriverType>
<DriverTargetPlatform>Desktop</DriverTargetPlatform> <DriverTargetPlatform>Desktop</DriverTargetPlatform>
<CharacterSet>Unicode</CharacterSet> <CharacterSet>Unicode</CharacterSet>
<PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<TargetVersion>Windows10</TargetVersion> <TargetVersion>Windows10</TargetVersion>
@ -132,11 +132,11 @@
<FilesToPackage Include="$(TargetPath)" /> <FilesToPackage Include="$(TargetPath)" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="main.cpp" /> <ClCompile Include="kernel.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="ioctl.h" /> <ClInclude Include="ioctl.h" />
<ClInclude Include="main.h" /> <ClInclude Include="kernel.h" />
<ClInclude Include="MyDriverGuids.h" /> <ClInclude Include="MyDriverGuids.h" />
</ItemGroup> </ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

View File

@ -19,12 +19,12 @@
</Filter> </Filter>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="main.cpp"> <ClCompile Include="kernel.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="main.h"> <ClInclude Include="kernel.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="ioctl.h"> <ClInclude Include="ioctl.h">

View File

@ -1,5 +1,40 @@
#pragma once #pragma once
#define MY_DRVICE_NAME L"YhyDrvice" #define MY_DRVICE_NAME L"YhyDrvice"
#define KERNEL_REG_DRVICE_NAME L"\\Device\\" MY_DRVICE_NAME
#define SYMBOLIC_LINK L"\\??\\" MY_DRVICE_NAME #define SYMBOLIC_LINK L"\\??\\" MY_DRVICE_NAME
// 内核注册的同步事件对象
#define NOTIFICATION_OBJECT_NAME L"\\BaseNamedObjects\\YhyDrvice"
#define KERNEL_TO_USER_EVENT_NAME L"Global\\YhyDrvice"
#define KERNEL_FILE_NAME L"\\\\.\\" MY_DRVICE_NAME
#define IOCTL_READ_MEMORY CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) #define DEFINE_IOCTL(function_code) \
CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800 + function_code, METHOD_BUFFERED, FILE_ANY_ACCESS)
// 读取任意内存地址数据
#define IOCTL_READ_MEMORY DEFINE_IOCTL(1)
typedef struct ReadMemoryModel {
void* address;
int len;
} ReadMemoryModel;
// 写入内存地址数据
#define IOCTL_WRITE_MEMORY DEFINE_IOCTL(2)
typedef struct WriteMemoryModel {
void* address; // 目标地址
int len; // 写入数据量
char buffer[1]; // 缓冲区
} WriteMemoryModel;
// 枚举进程
#define IOCTL_ENUMERATION_PROCESS DEFINE_IOCTL(3)
typedef struct EnumerationProcessModel {
// TODO: ...
} EnumerationProcessModel;
// 内核驱动创建命名的事件同步对象,用来让应用层接收事件
#define IOCTL_KERNEL_CREATE_EVENT_OBJECT CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800 + 4, METHOD_NEITHER , FILE_ANY_ACCESS)
// 通知内核驱动关闭命名的事件对象
#define IOCTL_CLOSE_EVENT_OBJECT CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800 + 5, METHOD_NEITHER , FILE_ANY_ACCESS)

View File

@ -0,0 +1,228 @@
#include "kernel.h"
// 接收三环传递来的通讯线程
HANDLE gThreadHandle = NULL;
bool gWorkThreadFlags = false;
HANDLE gEventHandle = NULL;
PKEVENT gKernelEvent = NULL;
VOID onUnload(_In_ struct _DRIVER_OBJECT* DriverObject) {
UNREFERENCED_PARAMETER(DriverObject);
KdPrint(("[yhy]: %s", __FUNCTION__));
// 删除驱动符号链接
UNICODE_STRING symLink;
RtlInitUnicodeString(&symLink, SYMBOLIC_LINK);
NTSTATUS status = IoDeleteSymbolicLink(&symLink);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] [Error]: IoDeleteSymbolicLink Error! errorCode:%08x\n", status));
return;
}
// 删除设备
if (DriverObject->DeviceObject != NULL) {
IoDeleteDevice(DriverObject->DeviceObject);
}
KdPrint(("[yhy]: onUnload Success!\n"));
KdPrint(("[yhy]: Bye!\n"));
}
NTSTATUS DispatchCreate(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCTION__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
return status;
}
NTSTATUS DispatchClose(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCTION__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
return status;
}
NTSTATUS DispatchRead(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
UNREFERENCED_PARAMETER(DeviceObject);
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCTION__));
// 需要把数据写入缓冲区
PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(Irp);
// 需要缓冲区地址+请求读写的长度
const char* text = "hello world!";
//PVOID pBuffer = Irp->AssociatedIrp.SystemBuffer;
PVOID pBuffer = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority);
ULONG nBufferSize = pIrpStack->Parameters.Read.Length;
// 拷贝字符串
ULONG len = min(nBufferSize, (ULONG)strlen(text));
KdPrint(("[yhy]: DispatchRead() text: %s pBuffer:%p nBufferSize:%d len:%d", text, pBuffer, nBufferSize, len));
RtlCopyMemory(pBuffer, text, len);
// 发送一个测试
KeSetEvent(gKernelEvent, IO_NO_INCREMENT, FALSE);
// 完成请求
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = len;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS DispatchWrite(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCTION__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
KdPrint(("[yhy]: DeviceObject->StackSize: %d\n", DeviceObject->StackSize));
return status;
}
NTSTATUS handleOnCtlReadMemory(PIO_STACK_LOCATION pIrpStack, _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
PVOID inBuffer = Irp->AssociatedIrp.SystemBuffer;
PVOID outBuffer = Irp->AssociatedIrp.SystemBuffer;
// 先解
ReadMemoryModel* readModel = (ReadMemoryModel*)inBuffer;
ULONG bufferLen = max((ULONG)readModel->len, pIrpStack->Parameters.DeviceIoControl.OutputBufferLength);
// 读取目标内存
KdPrint(("[yhy]: DispatchControl inBuffer:%p targetAddress:%p\n", inBuffer, readModel->address));
RtlCopyMemory(outBuffer, readModel->address, bufferLen);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = bufferLen;
return status;
}
NTSTATUS handleOnCtlWriteMemory(PIO_STACK_LOCATION pIrpStack, _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
PVOID inBuffer = Irp->AssociatedIrp.SystemBuffer;
//PVOID outBuffer = Irp->AssociatedIrp.SystemBuffer;
UNREFERENCED_PARAMETER(pIrpStack);
WriteMemoryModel* writeModel = (WriteMemoryModel*)inBuffer;
ULONG bufferLen = writeModel->len;
RtlCopyMemory(writeModel->address, writeModel->buffer, bufferLen);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = bufferLen;
return status;
}
NTSTATUS handleOnCtlEnumProc(PIO_STACK_LOCATION pIrpStack, _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
// TODO...
UNREFERENCED_PARAMETER(pIrpStack);
UNREFERENCED_PARAMETER(Irp);
return status;
}
/*
*
*/
NTSTATUS handleCreateNotificationEvent() {
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING EventName = { 0 };
RtlInitUnicodeString(&EventName, NOTIFICATION_OBJECT_NAME);
gKernelEvent = IoCreateNotificationEvent(&EventName, &gEventHandle);
KdPrint(("[yhy] createNotificationEvent! gKernelEvent: %p gEventHandle: %p\n", gKernelEvent, gEventHandle));
if (gKernelEvent == NULL) {
KdPrint(("[yhy] createNotificationEvent Fail!\n"));
status = STATUS_UNSUCCESSFUL;
}
return status;
}
NTSTATUS handleCloseNotificationEvent() {
KdPrint(("[yhy]: %s\n", __FUNCTION__));
NTSTATUS status = STATUS_SUCCESS;
// 关闭事件对象
// 唤醒事件
KeSetEvent(gKernelEvent, IO_NO_INCREMENT, FALSE);
KdPrint(("[yhy] [Error]: NtClose! gEventHandle:%p\n", gEventHandle));
status = NtClose(gEventHandle);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] [Error]: NtClose Error! errorCode:%08x\n", status));
}
return status;
}
NTSTATUS DispatchControl(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
UNREFERENCED_PARAMETER(DeviceObject);
PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG ControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode;
switch (ControlCode) {
case IOCTL_READ_MEMORY: {
status = handleOnCtlReadMemory(pIrpStack, Irp);
break;
}
case IOCTL_WRITE_MEMORY: {
status = handleOnCtlWriteMemory(pIrpStack, Irp);
break;
}
case IOCTL_ENUMERATION_PROCESS: {
status = handleOnCtlEnumProc(pIrpStack, Irp);
break;
}
case IOCTL_KERNEL_CREATE_EVENT_OBJECT: {
status = handleCreateNotificationEvent();
break;
}
case IOCTL_CLOSE_EVENT_OBJECT: {
status = handleCloseNotificationEvent();
break;
}
}
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
UNREFERENCED_PARAMETER(RegistryPath);
// NTSTATUS variable to record success or failure
NTSTATUS status = STATUS_SUCCESS;
DriverObject->DriverUnload = onUnload;
// 1. 绑定IRP 处理Dispatch例程
DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchClose;
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchRead;
DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchWrite;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchControl;
// 2. 创建设备对象
UNICODE_STRING deviceName;
PDEVICE_OBJECT pDevice = NULL;
RtlInitUnicodeString(&deviceName, KERNEL_REG_DRVICE_NAME);
KdPrint(("[yhy] deviceName: %wZ", &deviceName));
status = IoCreateDevice(DriverObject, 0, &deviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE /*非独占*/,
&pDevice);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] DriverEntry IoCreateDevice ErrorCode:%08x\n", status));
return status;
}
// 使用缓冲区IO方式
//pDevice->Flags |= DO_BUFFERED_IO;
pDevice->Flags |= DO_DIRECT_IO;
// 3. 创建符号
UNICODE_STRING symbolName;
RtlInitUnicodeString(&symbolName, SYMBOLIC_LINK);
status = IoCreateSymbolicLink(&symbolName, &deviceName);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] DriverEntry IoCreateSymbolicLink ErrorCode:%08x\n", status));
return status;
}
KdPrint(("[yhy] DriverEntry IoCreateSymbolicLink Success! symbolName is :%wZ", &symbolName));
return status;
}

View File

@ -1,4 +1,5 @@
#pragma once #pragma once
#include <ntifs.h>
#include <ntddk.h> #include <ntddk.h>
#include "ioctl.h" #include "ioctl.h"

View File

@ -1,110 +0,0 @@
#include "main.h"
VOID onUnload(_In_ struct _DRIVER_OBJECT* DriverObject) {
UNREFERENCED_PARAMETER(DriverObject);
KdPrint(("[yhy]: %s", __FUNCDNAME__));
UNICODE_STRING symLink;
RtlInitUnicodeString(&symLink, SYMBOLIC_LINK);
NTSTATUS status = IoDeleteSymbolicLink(&symLink); // 删除符号链接
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] [Error]: IoDeleteSymbolicLink Error! rrorCode:%08x\n", status));
return;
}
// 删除设备
if (DriverObject->DeviceObject != NULL) {
IoDeleteDevice(DriverObject->DeviceObject);
}
KdPrint(("[yhy]: onUnload Success!\n"));
KdPrint(("[yhy]: Bye!\n"));
}
NTSTATUS DispatchCreate(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCDNAME__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
return status;
}
NTSTATUS DispatchClose(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCDNAME__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
return status;
}
NTSTATUS DispatchRead(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCDNAME__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
return status;
}
NTSTATUS DispatchWrite(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
KdPrint(("[yhy]: %s\n", __FUNCDNAME__));
IoCompleteRequest(Irp, IO_NO_INCREMENT);
UNREFERENCED_PARAMETER(DeviceObject);
return status;
}
NTSTATUS DispatchControl(_In_ struct _DEVICE_OBJECT* DeviceObject, _Inout_ struct _IRP* Irp) {
NTSTATUS status = STATUS_SUCCESS;
UNREFERENCED_PARAMETER(DeviceObject);
KdPrint(("[yhy]: %s\n", __FUNCDNAME__));
PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(Irp);
if (pIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_READ_MEMORY) {
PVOID ioBuffer = Irp->AssociatedIrp.SystemBuffer;
//ULONG bufferLen = max(pIrpStack->Parameters.DeviceIoControl.InputBufferLength, pIrpStack->Parameters.DeviceIoControl.OutputBufferLength);
// 读取目标内存
void* targetAddress = *(void**)ioBuffer;
KdPrint(("[yhy]: DispatchControl ioBuffer:%p targetAddress:%p\n", ioBuffer, targetAddress));
int newValue = 0x12341234;
RtlCopyMemory(ioBuffer, &newValue, 4);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 4;
}
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
UNREFERENCED_PARAMETER(RegistryPath);
// NTSTATUS variable to record success or failure
NTSTATUS status = STATUS_SUCCESS;
DriverObject->DriverUnload = onUnload;
// 1. 绑定IRP 处理Dispatch例程
DriverObject->MajorFunction[IRP_MJ_CREATE] = DispatchCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DispatchClose;
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchRead;
DriverObject->MajorFunction[IRP_MJ_WRITE] = DispatchWrite;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchControl;
// 2. 创建设备对象
UNICODE_STRING deviceName;
PDEVICE_OBJECT pDevice = NULL;
RtlInitUnicodeString(&deviceName, L"\\Device\\" MY_DRVICE_NAME);
KdPrint(("[yhy] deviceName: %wZ", &deviceName));
status = IoCreateDevice(DriverObject, 0, &deviceName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE /*非独占*/,
&pDevice);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] DriverEntry IoCreateDevice ErrorCode:%08x\n", status));
return status;
}
// 3. 创建符号
UNICODE_STRING symbolName;
// L"\\DosDevices\\MY_DRVICE_NAME"
RtlInitUnicodeString(&symbolName, SYMBOLIC_LINK);
status = IoCreateSymbolicLink(&symbolName, &deviceName);
if (!NT_SUCCESS(status)) {
KdPrint(("[yhy] DriverEntry IoCreateSymbolicLink ErrorCode:%08x\n", status));
return status;
}
KdPrint(("[yhy] DriverEntry IoCreateSymbolicLink Success! symbolName is :%wZ", &symbolName));
return status;
}

View File

@ -1,11 +1,21 @@
#include <iostream> #include "TestDrvice.h"
#include <cstdlib>
#include <Windows.h>
#include "../KernelCommunication/ioctl.h"
#include <memory>
#define TEST_SERVICE_NAME "aaayhytestservice" #define TEST_SERVICE_NAME "aaayhytestservice"
std::thread gWorkThread;
bool gThreadFlags = false;
void workThread(HANDLE eventHandle) {
while (gThreadFlags) {
WaitForSingleObject(eventHandle, INFINITE);
// TODO: 处理内核通知
printf("Kernel Event!\n");
ResetEvent(eventHandle); // 重置事件以便下次触发
}
// 退出线程时,关闭句柄
printf("Exit WorkThread! eventHandle: %08x", eventHandle);
if (eventHandle != NULL) { CloseHandle(eventHandle); }
return;
}
void ShowError(const char* szName) { void ShowError(const char* szName) {
DWORD dwErrorCode = GetLastError(); DWORD dwErrorCode = GetLastError();
@ -126,32 +136,46 @@ int UnLoadDriver(const char* szServiceName) {
void UseDriver() { void UseDriver() {
HANDLE hFile = CreateFileW(L"\\\\.\\" MY_DRVICE_NAME, unique_handle hFile = make_unique_handle(CreateFileW(KERNEL_FILE_NAME,
GENERIC_READ | GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE,
0, 0,
NULL, NULL,
OPEN_EXISTING, OPEN_EXISTING,
0, 0,
NULL); NULL));
printf("CreateFile hFile:%p ErrCode:%08x\n", hFile, GetLastError()); printf("CreateFile hFile:%p ErrCode:%08x\n", hFile.get(), GetLastError());
DWORD dwBytes = 0;
// 1. 发送让驱动创建事件对象的消息
bool result = DeviceIoControl(hFile.get(), IOCTL_KERNEL_CREATE_EVENT_OBJECT, NULL, 0, NULL, 0, &dwBytes, NULL);
if (!result) {
printf("IOCTL_KERNEL_CREATE_EVENT_OBJECT False!\n");
return;
}
// 2. 打开内核驱动的命名同步对象
HANDLE eventHandle = OpenEventW(EVENT_ALL_ACCESS, FALSE, KERNEL_TO_USER_EVENT_NAME);
printf("eventHandle: %08x\n", eventHandle);
gWorkThread = std::thread([=] {
gThreadFlags = true;
workThread(eventHandle);
});
// 测试ReadFile 功能 // 测试ReadFile 功能
char Buffer[MAXBYTE] = { 0 }; char Buffer[MAXBYTE] = { 0 };
DWORD dwBytes = 0; BOOL Result = ReadFile(hFile.get(), Buffer, 6, &dwBytes, NULL);
BOOL Result = ReadFile(hFile, Buffer, sizeof(Buffer), &dwBytes, NULL);
printf("ReadFile Result:%d dwBytes:%d Buffer:%s ErrCode:%08x\n", Result, dwBytes, Buffer, GetLastError()); printf("ReadFile Result:%d dwBytes:%d Buffer:%s ErrCode:%08x\n", Result, dwBytes, Buffer, GetLastError());
// 测试WriteFile 功能
WriteFile(hFile, Buffer, sizeof(Buffer), &dwBytes, NULL);
printf("WriteFile Result:%d dwBytes:%d Buffer:%s ErrCode:%08x\n", Result, dwBytes, Buffer, GetLastError());
// 测试DeviceIoControl 功能
char data[4] = { 0x78, 0x56, 0x34, 0x12 };
printf("Data value: %p\n", *(int*)data);
DeviceIoControl(hFile, IOCTL_READ_MEMORY, &data, sizeof(data),
data, sizeof(data), &dwBytes, NULL);
printf("DeviceIoControl Result:%d dwBytes:%d Data:%s ErrCode:%08x\n", Result, dwBytes, data, GetLastError());
printf("Data newValue: %p\n", *(int*)data);
// 关闭文件 //// 测试WriteFile 功能
CloseHandle(hFile); //WriteFile(hFile, Buffer, sizeof(Buffer), &dwBytes, NULL);
//printf("WriteFile Result:%d dwBytes:%d Buffer:%s ErrCode:%08x\n", Result, dwBytes, Buffer, GetLastError());
// 退出
gThreadFlags = false;
result = DeviceIoControl(hFile.get(), IOCTL_CLOSE_EVENT_OBJECT, NULL, 0, NULL, 0, &dwBytes, NULL);
gWorkThread.join();
return; return;
} }
@ -175,7 +199,6 @@ int main(int argc, char* argv[])
// TODO: 做一些事情 // TODO: 做一些事情
UseDriver(); UseDriver();
if (UnLoadDriver(TEST_SERVICE_NAME) != 0) { if (UnLoadDriver(TEST_SERVICE_NAME) != 0) {
cerr << "[x] UnLoadDriver Faile! " << endl; cerr << "[x] UnLoadDriver Faile! " << endl;
system("pause"); system("pause");

16
TestDrvice/TestDrvice.h Normal file
View File

@ -0,0 +1,16 @@
#pragma once
#include <iostream>
#include <cstdlib>
#include <Windows.h>
#include "../KernelCommunication/ioctl.h"
#include <memory>
#include <thread>
using unique_handle = std::unique_ptr<
std::remove_pointer_t<HANDLE>, // 类型为 void
BOOL(WINAPI*)(HANDLE) // 函数指针类型
>;
unique_handle make_unique_handle(HANDLE h = INVALID_HANDLE_VALUE) {
return unique_handle(h, &CloseHandle);
}

View File

@ -131,6 +131,9 @@
<ItemGroup> <ItemGroup>
<ClCompile Include="TestDrvice.cpp" /> <ClCompile Include="TestDrvice.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ClInclude Include="TestDrvice.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">
</ImportGroup> </ImportGroup>

View File

@ -19,4 +19,9 @@
<Filter>源文件</Filter> <Filter>源文件</Filter>
</ClCompile> </ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ClInclude Include="TestDrvice.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project> </Project>